@hown/djinn 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +66 -64
  2. package/package.json +19 -7
package/dist/index.js CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __djinnCreateRequire } from "node:module"; const require = __djinnCreateRequire(import.meta.url);
3
- var Gh=Object.create;var di=Object.defineProperty;var Yh=Object.getOwnPropertyDescriptor;var Jh=Object.getOwnPropertyNames;var Zh=Object.getPrototypeOf,Kh=Object.prototype.hasOwnProperty;var se=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var mt=(t,e)=>()=>(t&&(e=t(t=0)),e);var q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ns=(t,e)=>{for(var r in e)di(t,r,{get:e[r],enumerable:!0})},Xh=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jh(e))!Kh.call(t,i)&&i!==r&&di(t,i,{get:()=>e[i],enumerable:!(s=Yh(e,i))||s.enumerable});return t};var Be=(t,e,r)=>(r=t!=null?Gh(Zh(t)):{},Xh(e||!t||!t.__esModule?di(r,"default",{value:t,enumerable:!0}):r,t));import{chmodSync as ou,existsSync as au,lstatSync as cu,mkdirSync as lu,statSync as hu}from"fs";import{join as Oe}from"path";function Zt(t){return Oe(t,"run")}function os(t,e){return Oe(Zt(t),`${e}.json`)}function Tr(t,e){return Oe(Zt(t),`${e}.sock`)}function Kt(t){return Oe(t,"sessions")}function fi(t,e){return Oe(Kt(t),`${e}.json`)}function qe(t){return Oe(t,"daemon.sock")}function pi(t){return Oe(t,"daemon.pid")}function ao(t){return Oe(t,"daemon.log")}function co(t,e){return Oe(Zt(t),`${e}.log`)}function _i(t){return Oe(t,"projects.json")}function Qe(t){for(let e of[t,Zt(t),Kt(t)]){Ar(e),lu(e,{recursive:!0,mode:448}),ou(e,448);let r=hu(e).mode&511;if(r!==448)throw new Error(`state dir ${e} could not be tightened to 0700 (got ${r.toString(8)})`)}}function Ar(t){if(au(t)&&cu(t).isSymbolicLink())throw new Error(`refusing to use ${t}: it is a symlink`)}function as(){return!0}var ye=mt(()=>{"use strict"});var yi=q((T0,go)=>{"use strict";go.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var tt=q(gt=>{"use strict";var bi,Eu=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];gt.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};gt.getSymbolTotalCodewords=function(e){return Eu[e]};gt.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};gt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');bi=e};gt.isKanjiModeEnabled=function(){return typeof bi<"u"};gt.toSJIS=function(e){return bi(e)}});var hs=q(we=>{"use strict";we.L={bit:1};we.M={bit:0};we.Q={bit:3};we.H={bit:2};function xu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return we.L;case"m":case"medium":return we.M;case"q":case"quartile":return we.Q;case"h":case"high":return we.H;default:throw new Error("Unknown EC Level: "+t)}}we.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};we.from=function(e,r){if(we.isValid(e))return e;try{return xu(e)}catch{return r}}});var bo=q((P0,yo)=>{"use strict";function vo(){this.buffer=[],this.length=0}vo.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};yo.exports=vo});var So=q((L0,wo)=>{"use strict";function Ir(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Ir.prototype.set=function(t,e,r,s){let i=t*this.size+e;this.data[i]=r,s&&(this.reservedBit[i]=!0)};Ir.prototype.get=function(t,e){return this.data[t*this.size+e]};Ir.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Ir.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};wo.exports=Ir});var Co=q(us=>{"use strict";var ku=tt().getSymbolSize;us.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,s=ku(e),i=s===145?26:Math.ceil((s-13)/(2*r-2))*2,o=[s-7];for(let a=1;a<r-1;a++)o[a]=o[a-1]-i;return o.push(6),o.reverse()};us.getPositions=function(e){let r=[],s=us.getRowColCoords(e),i=s.length;for(let o=0;o<i;o++)for(let a=0;a<i;a++)o===0&&a===0||o===0&&a===i-1||o===i-1&&a===0||r.push([s[o],s[a]]);return r}});var ko=q(xo=>{"use strict";var Tu=tt().getSymbolSize,Eo=7;xo.getPositions=function(e){let r=Tu(e);return[[0,0],[r-Eo,0],[0,r-Eo]]}});var To=q(ae=>{"use strict";ae.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var vt={N1:3,N2:3,N3:40,N4:10};ae.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};ae.from=function(e){return ae.isValid(e)?parseInt(e,10):void 0};ae.getPenaltyN1=function(e){let r=e.size,s=0,i=0,o=0,a=null,n=null;for(let l=0;l<r;l++){i=o=0,a=n=null;for(let u=0;u<r;u++){let y=e.get(l,u);y===a?i++:(i>=5&&(s+=vt.N1+(i-5)),a=y,i=1),y=e.get(u,l),y===n?o++:(o>=5&&(s+=vt.N1+(o-5)),n=y,o=1)}i>=5&&(s+=vt.N1+(i-5)),o>=5&&(s+=vt.N1+(o-5))}return s};ae.getPenaltyN2=function(e){let r=e.size,s=0;for(let i=0;i<r-1;i++)for(let o=0;o<r-1;o++){let a=e.get(i,o)+e.get(i,o+1)+e.get(i+1,o)+e.get(i+1,o+1);(a===4||a===0)&&s++}return s*vt.N2};ae.getPenaltyN3=function(e){let r=e.size,s=0,i=0,o=0;for(let a=0;a<r;a++){i=o=0;for(let n=0;n<r;n++)i=i<<1&2047|e.get(a,n),n>=10&&(i===1488||i===93)&&s++,o=o<<1&2047|e.get(n,a),n>=10&&(o===1488||o===93)&&s++}return s*vt.N3};ae.getPenaltyN4=function(e){let r=0,s=e.data.length;for(let o=0;o<s;o++)r+=e.data[o];return Math.abs(Math.ceil(r*100/s/5)-10)*vt.N4};function Au(t,e,r){switch(t){case ae.Patterns.PATTERN000:return(e+r)%2===0;case ae.Patterns.PATTERN001:return e%2===0;case ae.Patterns.PATTERN010:return r%3===0;case ae.Patterns.PATTERN011:return(e+r)%3===0;case ae.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case ae.Patterns.PATTERN101:return e*r%2+e*r%3===0;case ae.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case ae.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}ae.applyMask=function(e,r){let s=r.size;for(let i=0;i<s;i++)for(let o=0;o<s;o++)r.isReserved(o,i)||r.xor(o,i,Au(e,o,i))};ae.getBestMask=function(e,r){let s=Object.keys(ae.Patterns).length,i=0,o=1/0;for(let a=0;a<s;a++){r(a),ae.applyMask(a,e);let n=ae.getPenaltyN1(e)+ae.getPenaltyN2(e)+ae.getPenaltyN3(e)+ae.getPenaltyN4(e);ae.applyMask(a,e),n<o&&(o=n,i=a)}return i}});var Si=q(wi=>{"use strict";var rt=hs(),ds=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],fs=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];wi.getBlocksCount=function(e,r){switch(r){case rt.L:return ds[(e-1)*4+0];case rt.M:return ds[(e-1)*4+1];case rt.Q:return ds[(e-1)*4+2];case rt.H:return ds[(e-1)*4+3];default:return}};wi.getTotalCodewordsCount=function(e,r){switch(r){case rt.L:return fs[(e-1)*4+0];case rt.M:return fs[(e-1)*4+1];case rt.Q:return fs[(e-1)*4+2];case rt.H:return fs[(e-1)*4+3];default:return}}});var Ao=q(_s=>{"use strict";var Pr=new Uint8Array(512),ps=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Pr[r]=e,ps[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Pr[r]=Pr[r-255]})();_s.log=function(e){if(e<1)throw new Error("log("+e+")");return ps[e]};_s.exp=function(e){return Pr[e]};_s.mul=function(e,r){return e===0||r===0?0:Pr[ps[e]+ps[r]]}});var Io=q(Lr=>{"use strict";var Ci=Ao();Lr.mul=function(e,r){let s=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let o=0;o<r.length;o++)s[i+o]^=Ci.mul(e[i],r[o]);return s};Lr.mod=function(e,r){let s=new Uint8Array(e);for(;s.length-r.length>=0;){let i=s[0];for(let a=0;a<r.length;a++)s[a]^=Ci.mul(r[a],i);let o=0;for(;o<s.length&&s[o]===0;)o++;s=s.slice(o)}return s};Lr.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let s=0;s<e;s++)r=Lr.mul(r,new Uint8Array([1,Ci.exp(s)]));return r}});var Ro=q((H0,Lo)=>{"use strict";var Po=Io();function Ei(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ei.prototype.initialize=function(e){this.degree=e,this.genPoly=Po.generateECPolynomial(this.degree)};Ei.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let s=Po.mod(r,this.genPoly),i=this.degree-s.length;if(i>0){let o=new Uint8Array(this.degree);return o.set(s,i),o}return s};Lo.exports=Ei});var xi=q(Bo=>{"use strict";Bo.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var ki=q($e=>{"use strict";var Oo="[0-9]+",Iu="[A-Z $%*+\\-./:]+",Rr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Rr=Rr.replace(/u/g,"\\u");var Pu="(?:(?![A-Z0-9 $%*+\\-./:]|"+Rr+`)(?:.|[\r
4
- ]))+`;$e.KANJI=new RegExp(Rr,"g");$e.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");$e.BYTE=new RegExp(Pu,"g");$e.NUMERIC=new RegExp(Oo,"g");$e.ALPHANUMERIC=new RegExp(Iu,"g");var Lu=new RegExp("^"+Rr+"$"),Ru=new RegExp("^"+Oo+"$"),Bu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");$e.testKanji=function(e){return Lu.test(e)};$e.testNumeric=function(e){return Ru.test(e)};$e.testAlphanumeric=function(e){return Bu.test(e)}});var st=q(le=>{"use strict";var Ou=xi(),Ti=ki();le.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};le.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};le.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};le.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};le.MIXED={bit:-1};le.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Ou.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};le.getBestModeForData=function(e){return Ti.testNumeric(e)?le.NUMERIC:Ti.testAlphanumeric(e)?le.ALPHANUMERIC:Ti.testKanji(e)?le.KANJI:le.BYTE};le.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};le.isValid=function(e){return e&&e.bit&&e.ccBits};function Du(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return le.NUMERIC;case"alphanumeric":return le.ALPHANUMERIC;case"kanji":return le.KANJI;case"byte":return le.BYTE;default:throw new Error("Unknown mode: "+t)}}le.from=function(e,r){if(le.isValid(e))return e;try{return Du(e)}catch{return r}}});var Uo=q(yt=>{"use strict";var ms=tt(),Mu=Si(),Do=hs(),it=st(),Ai=xi(),No=7973,Mo=ms.getBCHDigit(No);function Nu(t,e,r){for(let s=1;s<=40;s++)if(e<=yt.getCapacity(s,r,t))return s}function Ho(t,e){return it.getCharCountIndicator(t,e)+4}function Hu(t,e){let r=0;return t.forEach(function(s){let i=Ho(s.mode,e);r+=i+s.getBitsLength()}),r}function Uu(t,e){for(let r=1;r<=40;r++)if(Hu(t,r)<=yt.getCapacity(r,e,it.MIXED))return r}yt.from=function(e,r){return Ai.isValid(e)?parseInt(e,10):r};yt.getCapacity=function(e,r,s){if(!Ai.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=it.BYTE);let i=ms.getSymbolTotalCodewords(e),o=Mu.getTotalCodewordsCount(e,r),a=(i-o)*8;if(s===it.MIXED)return a;let n=a-Ho(s,e);switch(s){case it.NUMERIC:return Math.floor(n/10*3);case it.ALPHANUMERIC:return Math.floor(n/11*2);case it.KANJI:return Math.floor(n/13);case it.BYTE:default:return Math.floor(n/8)}};yt.getBestVersionForData=function(e,r){let s,i=Do.from(r,Do.M);if(Array.isArray(e)){if(e.length>1)return Uu(e,i);if(e.length===0)return 1;s=e[0]}else s=e;return Nu(s.mode,s.getLength(),i)};yt.getEncodedBits=function(e){if(!Ai.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;ms.getBCHDigit(r)-Mo>=0;)r^=No<<ms.getBCHDigit(r)-Mo;return e<<12|r}});var qo=q(Wo=>{"use strict";var Ii=tt(),jo=1335,Fu=21522,Fo=Ii.getBCHDigit(jo);Wo.getEncodedBits=function(e,r){let s=e.bit<<3|r,i=s<<10;for(;Ii.getBCHDigit(i)-Fo>=0;)i^=jo<<Ii.getBCHDigit(i)-Fo;return(s<<10|i)^Fu}});var zo=q(($0,$o)=>{"use strict";var ju=st();function Qt(t){this.mode=ju.NUMERIC,this.data=t.toString()}Qt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Qt.prototype.getLength=function(){return this.data.length};Qt.prototype.getBitsLength=function(){return Qt.getBitsLength(this.data.length)};Qt.prototype.write=function(e){let r,s,i;for(r=0;r+3<=this.data.length;r+=3)s=this.data.substr(r,3),i=parseInt(s,10),e.put(i,10);let o=this.data.length-r;o>0&&(s=this.data.substr(r),i=parseInt(s,10),e.put(i,o*3+1))};$o.exports=Qt});var Go=q((z0,Vo)=>{"use strict";var Wu=st(),Pi=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function er(t){this.mode=Wu.ALPHANUMERIC,this.data=t}er.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};er.prototype.getLength=function(){return this.data.length};er.prototype.getBitsLength=function(){return er.getBitsLength(this.data.length)};er.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let s=Pi.indexOf(this.data[r])*45;s+=Pi.indexOf(this.data[r+1]),e.put(s,11)}this.data.length%2&&e.put(Pi.indexOf(this.data[r]),6)};Vo.exports=er});var Jo=q((V0,Yo)=>{"use strict";var qu=st();function tr(t){this.mode=qu.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}tr.getBitsLength=function(e){return e*8};tr.prototype.getLength=function(){return this.data.length};tr.prototype.getBitsLength=function(){return tr.getBitsLength(this.data.length)};tr.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};Yo.exports=tr});var Ko=q((G0,Zo)=>{"use strict";var $u=st(),zu=tt();function rr(t){this.mode=$u.KANJI,this.data=t}rr.getBitsLength=function(e){return e*13};rr.prototype.getLength=function(){return this.data.length};rr.prototype.getBitsLength=function(){return rr.getBitsLength(this.data.length)};rr.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=zu.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
5
- Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};Zo.exports=rr});var Xo=q((Y0,Li)=>{"use strict";var Br={single_source_shortest_paths:function(t,e,r){var s={},i={};i[e]=0;var o=Br.PriorityQueue.make();o.push(e,0);for(var a,n,l,u,y,h,_,d,p;!o.empty();){a=o.pop(),n=a.value,u=a.cost,y=t[n]||{};for(l in y)y.hasOwnProperty(l)&&(h=y[l],_=u+h,d=i[l],p=typeof i[l]>"u",(p||d>_)&&(i[l]=_,o.push(l,_),s[l]=n))}if(typeof r<"u"&&typeof i[r]>"u"){var b=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(b)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],s=e,i;s;)r.push(s),i=t[s],s=t[s];return r.reverse(),r},find_path:function(t,e,r){var s=Br.single_source_shortest_paths(t,e,r);return Br.extract_shortest_path_from_predecessor_list(s,r)},PriorityQueue:{make:function(t){var e=Br.PriorityQueue,r={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(r[s]=e[s]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Li<"u"&&(Li.exports=Br)});var oa=q(sr=>{"use strict";var oe=st(),ta=zo(),ra=Go(),sa=Jo(),ia=Ko(),Or=ki(),gs=tt(),Vu=Xo();function Qo(t){return unescape(encodeURIComponent(t)).length}function Dr(t,e,r){let s=[],i;for(;(i=t.exec(r))!==null;)s.push({data:i[0],index:i.index,mode:e,length:i[0].length});return s}function na(t){let e=Dr(Or.NUMERIC,oe.NUMERIC,t),r=Dr(Or.ALPHANUMERIC,oe.ALPHANUMERIC,t),s,i;return gs.isKanjiModeEnabled()?(s=Dr(Or.BYTE,oe.BYTE,t),i=Dr(Or.KANJI,oe.KANJI,t)):(s=Dr(Or.BYTE_KANJI,oe.BYTE,t),i=[]),e.concat(r,s,i).sort(function(a,n){return a.index-n.index}).map(function(a){return{data:a.data,mode:a.mode,length:a.length}})}function Ri(t,e){switch(e){case oe.NUMERIC:return ta.getBitsLength(t);case oe.ALPHANUMERIC:return ra.getBitsLength(t);case oe.KANJI:return ia.getBitsLength(t);case oe.BYTE:return sa.getBitsLength(t)}}function Gu(t){return t.reduce(function(e,r){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Yu(t){let e=[];for(let r=0;r<t.length;r++){let s=t[r];switch(s.mode){case oe.NUMERIC:e.push([s,{data:s.data,mode:oe.ALPHANUMERIC,length:s.length},{data:s.data,mode:oe.BYTE,length:s.length}]);break;case oe.ALPHANUMERIC:e.push([s,{data:s.data,mode:oe.BYTE,length:s.length}]);break;case oe.KANJI:e.push([s,{data:s.data,mode:oe.BYTE,length:Qo(s.data)}]);break;case oe.BYTE:e.push([{data:s.data,mode:oe.BYTE,length:Qo(s.data)}])}}return e}function Ju(t,e){let r={},s={start:{}},i=["start"];for(let o=0;o<t.length;o++){let a=t[o],n=[];for(let l=0;l<a.length;l++){let u=a[l],y=""+o+l;n.push(y),r[y]={node:u,lastCount:0},s[y]={};for(let h=0;h<i.length;h++){let _=i[h];r[_]&&r[_].node.mode===u.mode?(s[_][y]=Ri(r[_].lastCount+u.length,u.mode)-Ri(r[_].lastCount,u.mode),r[_].lastCount+=u.length):(r[_]&&(r[_].lastCount=u.length),s[_][y]=Ri(u.length,u.mode)+4+oe.getCharCountIndicator(u.mode,e))}}i=n}for(let o=0;o<i.length;o++)s[i[o]].end=0;return{map:s,table:r}}function ea(t,e){let r,s=oe.getBestModeForData(t);if(r=oe.from(e,s),r!==oe.BYTE&&r.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+oe.toString(r)+`.
6
- Suggested mode is: `+oe.toString(s));switch(r===oe.KANJI&&!gs.isKanjiModeEnabled()&&(r=oe.BYTE),r){case oe.NUMERIC:return new ta(t);case oe.ALPHANUMERIC:return new ra(t);case oe.KANJI:return new ia(t);case oe.BYTE:return new sa(t)}}sr.fromArray=function(e){return e.reduce(function(r,s){return typeof s=="string"?r.push(ea(s,null)):s.data&&r.push(ea(s.data,s.mode)),r},[])};sr.fromString=function(e,r){let s=na(e,gs.isKanjiModeEnabled()),i=Yu(s),o=Ju(i,r),a=Vu.find_path(o.map,"start","end"),n=[];for(let l=1;l<a.length-1;l++)n.push(o.table[a[l]].node);return sr.fromArray(Gu(n))};sr.rawSplit=function(e){return sr.fromArray(na(e,gs.isKanjiModeEnabled()))}});var Hi=q(aa=>{"use strict";var ys=tt(),Bi=hs(),Zu=bo(),Ku=So(),Xu=Co(),Qu=ko(),Mi=To(),Ni=Si(),ed=Ro(),vs=Uo(),td=qo(),rd=st(),Oi=oa();function sd(t,e){let r=t.size,s=Qu.getPositions(e);for(let i=0;i<s.length;i++){let o=s[i][0],a=s[i][1];for(let n=-1;n<=7;n++)if(!(o+n<=-1||r<=o+n))for(let l=-1;l<=7;l++)a+l<=-1||r<=a+l||(n>=0&&n<=6&&(l===0||l===6)||l>=0&&l<=6&&(n===0||n===6)||n>=2&&n<=4&&l>=2&&l<=4?t.set(o+n,a+l,!0,!0):t.set(o+n,a+l,!1,!0))}}function id(t){let e=t.size;for(let r=8;r<e-8;r++){let s=r%2===0;t.set(r,6,s,!0),t.set(6,r,s,!0)}}function nd(t,e){let r=Xu.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-2;a<=2;a++)for(let n=-2;n<=2;n++)a===-2||a===2||n===-2||n===2||a===0&&n===0?t.set(i+a,o+n,!0,!0):t.set(i+a,o+n,!1,!0)}}function od(t,e){let r=t.size,s=vs.getEncodedBits(e),i,o,a;for(let n=0;n<18;n++)i=Math.floor(n/3),o=n%3+r-8-3,a=(s>>n&1)===1,t.set(i,o,a,!0),t.set(o,i,a,!0)}function Di(t,e,r){let s=t.size,i=td.getEncodedBits(e,r),o,a;for(o=0;o<15;o++)a=(i>>o&1)===1,o<6?t.set(o,8,a,!0):o<8?t.set(o+1,8,a,!0):t.set(s-15+o,8,a,!0),o<8?t.set(8,s-o-1,a,!0):o<9?t.set(8,15-o-1+1,a,!0):t.set(8,15-o-1,a,!0);t.set(s-8,8,1,!0)}function ad(t,e){let r=t.size,s=-1,i=r-1,o=7,a=0;for(let n=r-1;n>0;n-=2)for(n===6&&n--;;){for(let l=0;l<2;l++)if(!t.isReserved(i,n-l)){let u=!1;a<e.length&&(u=(e[a]>>>o&1)===1),t.set(i,n-l,u),o--,o===-1&&(a++,o=7)}if(i+=s,i<0||r<=i){i-=s,s=-s;break}}}function cd(t,e,r){let s=new Zu;r.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),rd.getCharCountIndicator(l.mode,t)),l.write(s)});let i=ys.getSymbolTotalCodewords(t),o=Ni.getTotalCodewordsCount(t,e),a=(i-o)*8;for(s.getLengthInBits()+4<=a&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let n=(a-s.getLengthInBits())/8;for(let l=0;l<n;l++)s.put(l%2?17:236,8);return ld(s,t,e)}function ld(t,e,r){let s=ys.getSymbolTotalCodewords(e),i=Ni.getTotalCodewordsCount(e,r),o=s-i,a=Ni.getBlocksCount(e,r),n=s%a,l=a-n,u=Math.floor(s/a),y=Math.floor(o/a),h=y+1,_=u-y,d=new ed(_),p=0,b=new Array(a),c=new Array(a),v=0,g=new Uint8Array(t.buffer);for(let k=0;k<a;k++){let A=k<l?y:h;b[k]=g.slice(p,p+A),c[k]=d.encode(b[k]),p+=A,v=Math.max(v,A)}let f=new Uint8Array(s),m=0,w,C;for(w=0;w<v;w++)for(C=0;C<a;C++)w<b[C].length&&(f[m++]=b[C][w]);for(w=0;w<_;w++)for(C=0;C<a;C++)f[m++]=c[C][w];return f}function hd(t,e,r,s){let i;if(Array.isArray(t))i=Oi.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let y=Oi.rawSplit(t);u=vs.getBestVersionForData(y,r)}i=Oi.fromString(t,u||40)}else throw new Error("Invalid data");let o=vs.getBestVersionForData(i,r);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
3
+ var eu=Object.create;var mi=Object.defineProperty;var tu=Object.getOwnPropertyDescriptor;var ru=Object.getOwnPropertyNames;var su=Object.getPrototypeOf,iu=Object.prototype.hasOwnProperty;var se=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var bt=(t,e)=>()=>(t&&(e=t(t=0)),e);var $=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),os=(t,e)=>{for(var r in e)mi(t,r,{get:e[r],enumerable:!0})},nu=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ru(e))!iu.call(t,i)&&i!==r&&mi(t,i,{get:()=>e[i],enumerable:!(s=tu(e,i))||s.enumerable});return t};var Be=(t,e,r)=>(r=t!=null?eu(su(t)):{},nu(e||!t||!t.__esModule?mi(r,"default",{value:t,enumerable:!0}):r,t));import{chmodSync as fu,existsSync as pu,lstatSync as _u,mkdirSync as mu,statSync as gu}from"fs";import{join as De}from"path";function et(t){return De(t,"run")}function as(t,e){return De(et(t),`${e}.json`)}function Pr(t,e){return De(et(t),`${e}.sock`)}function tt(t){return De(t,"sessions")}function gi(t,e){return De(tt(t),`${e}.json`)}function $e(t){return De(t,"daemon.sock")}function Lr(t){return De(t,"daemon.pid")}function uo(t){return De(t,"daemon.log")}function fo(t,e){return De(et(t),`${e}.log`)}function vi(t){return De(t,"projects.json")}function rt(t){for(let e of[t,et(t),tt(t)]){qe(e),mu(e,{recursive:!0,mode:448}),fu(e,448);let r=gu(e).mode&511;if(r!==448)throw new Error(`state dir ${e} could not be tightened to 0700 (got ${r.toString(8)})`)}}function qe(t){if(pu(t)&&_u(t).isSymbolicLink())throw new Error(`refusing to use ${t}: it is a symlink`)}function cs(){return!0}var me=bt(()=>{"use strict"});var Si=$((U0,wo)=>{"use strict";wo.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var it=$(wt=>{"use strict";var Ci,Lu=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];wt.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};wt.getSymbolTotalCodewords=function(e){return Lu[e]};wt.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};wt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Ci=e};wt.isKanjiModeEnabled=function(){return typeof Ci<"u"};wt.toSJIS=function(e){return Ci(e)}});var us=$(we=>{"use strict";we.L={bit:1};we.M={bit:0};we.Q={bit:3};we.H={bit:2};function Ru(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return we.L;case"m":case"medium":return we.M;case"q":case"quartile":return we.Q;case"h":case"high":return we.H;default:throw new Error("Unknown EC Level: "+t)}}we.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};we.from=function(e,r){if(we.isValid(e))return e;try{return Ru(e)}catch{return r}}});var Eo=$((j0,Co)=>{"use strict";function So(){this.buffer=[],this.length=0}So.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Co.exports=So});var ko=$((W0,xo)=>{"use strict";function Rr(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Rr.prototype.set=function(t,e,r,s){let i=t*this.size+e;this.data[i]=r,s&&(this.reservedBit[i]=!0)};Rr.prototype.get=function(t,e){return this.data[t*this.size+e]};Rr.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Rr.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};xo.exports=Rr});var To=$(ds=>{"use strict";var Bu=it().getSymbolSize;ds.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,s=Bu(e),i=s===145?26:Math.ceil((s-13)/(2*r-2))*2,o=[s-7];for(let a=1;a<r-1;a++)o[a]=o[a-1]-i;return o.push(6),o.reverse()};ds.getPositions=function(e){let r=[],s=ds.getRowColCoords(e),i=s.length;for(let o=0;o<i;o++)for(let a=0;a<i;a++)o===0&&a===0||o===0&&a===i-1||o===i-1&&a===0||r.push([s[o],s[a]]);return r}});var Po=$(Io=>{"use strict";var Du=it().getSymbolSize,Ao=7;Io.getPositions=function(e){let r=Du(e);return[[0,0],[r-Ao,0],[0,r-Ao]]}});var Lo=$(ae=>{"use strict";ae.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var St={N1:3,N2:3,N3:40,N4:10};ae.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};ae.from=function(e){return ae.isValid(e)?parseInt(e,10):void 0};ae.getPenaltyN1=function(e){let r=e.size,s=0,i=0,o=0,a=null,n=null;for(let l=0;l<r;l++){i=o=0,a=n=null;for(let u=0;u<r;u++){let y=e.get(l,u);y===a?i++:(i>=5&&(s+=St.N1+(i-5)),a=y,i=1),y=e.get(u,l),y===n?o++:(o>=5&&(s+=St.N1+(o-5)),n=y,o=1)}i>=5&&(s+=St.N1+(i-5)),o>=5&&(s+=St.N1+(o-5))}return s};ae.getPenaltyN2=function(e){let r=e.size,s=0;for(let i=0;i<r-1;i++)for(let o=0;o<r-1;o++){let a=e.get(i,o)+e.get(i,o+1)+e.get(i+1,o)+e.get(i+1,o+1);(a===4||a===0)&&s++}return s*St.N2};ae.getPenaltyN3=function(e){let r=e.size,s=0,i=0,o=0;for(let a=0;a<r;a++){i=o=0;for(let n=0;n<r;n++)i=i<<1&2047|e.get(a,n),n>=10&&(i===1488||i===93)&&s++,o=o<<1&2047|e.get(n,a),n>=10&&(o===1488||o===93)&&s++}return s*St.N3};ae.getPenaltyN4=function(e){let r=0,s=e.data.length;for(let o=0;o<s;o++)r+=e.data[o];return Math.abs(Math.ceil(r*100/s/5)-10)*St.N4};function Ou(t,e,r){switch(t){case ae.Patterns.PATTERN000:return(e+r)%2===0;case ae.Patterns.PATTERN001:return e%2===0;case ae.Patterns.PATTERN010:return r%3===0;case ae.Patterns.PATTERN011:return(e+r)%3===0;case ae.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case ae.Patterns.PATTERN101:return e*r%2+e*r%3===0;case ae.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case ae.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}ae.applyMask=function(e,r){let s=r.size;for(let i=0;i<s;i++)for(let o=0;o<s;o++)r.isReserved(o,i)||r.xor(o,i,Ou(e,o,i))};ae.getBestMask=function(e,r){let s=Object.keys(ae.Patterns).length,i=0,o=1/0;for(let a=0;a<s;a++){r(a),ae.applyMask(a,e);let n=ae.getPenaltyN1(e)+ae.getPenaltyN2(e)+ae.getPenaltyN3(e)+ae.getPenaltyN4(e);ae.applyMask(a,e),n<o&&(o=n,i=a)}return i}});var xi=$(Ei=>{"use strict";var nt=us(),fs=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],ps=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Ei.getBlocksCount=function(e,r){switch(r){case nt.L:return fs[(e-1)*4+0];case nt.M:return fs[(e-1)*4+1];case nt.Q:return fs[(e-1)*4+2];case nt.H:return fs[(e-1)*4+3];default:return}};Ei.getTotalCodewordsCount=function(e,r){switch(r){case nt.L:return ps[(e-1)*4+0];case nt.M:return ps[(e-1)*4+1];case nt.Q:return ps[(e-1)*4+2];case nt.H:return ps[(e-1)*4+3];default:return}}});var Ro=$(ms=>{"use strict";var Br=new Uint8Array(512),_s=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Br[r]=e,_s[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Br[r]=Br[r-255]})();ms.log=function(e){if(e<1)throw new Error("log("+e+")");return _s[e]};ms.exp=function(e){return Br[e]};ms.mul=function(e,r){return e===0||r===0?0:Br[_s[e]+_s[r]]}});var Bo=$(Dr=>{"use strict";var ki=Ro();Dr.mul=function(e,r){let s=new Uint8Array(e.length+r.length-1);for(let i=0;i<e.length;i++)for(let o=0;o<r.length;o++)s[i+o]^=ki.mul(e[i],r[o]);return s};Dr.mod=function(e,r){let s=new Uint8Array(e);for(;s.length-r.length>=0;){let i=s[0];for(let a=0;a<r.length;a++)s[a]^=ki.mul(r[a],i);let o=0;for(;o<s.length&&s[o]===0;)o++;s=s.slice(o)}return s};Dr.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let s=0;s<e;s++)r=Dr.mul(r,new Uint8Array([1,ki.exp(s)]));return r}});var Mo=$((J0,Oo)=>{"use strict";var Do=Bo();function Ti(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ti.prototype.initialize=function(e){this.degree=e,this.genPoly=Do.generateECPolynomial(this.degree)};Ti.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let s=Do.mod(r,this.genPoly),i=this.degree-s.length;if(i>0){let o=new Uint8Array(this.degree);return o.set(s,i),o}return s};Oo.exports=Ti});var Ai=$(No=>{"use strict";No.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Ii=$(ze=>{"use strict";var Uo="[0-9]+",Mu="[A-Z $%*+\\-./:]+",Or="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Or=Or.replace(/u/g,"\\u");var Nu="(?:(?![A-Z0-9 $%*+\\-./:]|"+Or+`)(?:.|[\r
4
+ ]))+`;ze.KANJI=new RegExp(Or,"g");ze.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ze.BYTE=new RegExp(Nu,"g");ze.NUMERIC=new RegExp(Uo,"g");ze.ALPHANUMERIC=new RegExp(Mu,"g");var Uu=new RegExp("^"+Or+"$"),Hu=new RegExp("^"+Uo+"$"),Fu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ze.testKanji=function(e){return Uu.test(e)};ze.testNumeric=function(e){return Hu.test(e)};ze.testAlphanumeric=function(e){return Fu.test(e)}});var ot=$(le=>{"use strict";var ju=Ai(),Pi=Ii();le.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};le.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};le.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};le.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};le.MIXED={bit:-1};le.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!ju.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};le.getBestModeForData=function(e){return Pi.testNumeric(e)?le.NUMERIC:Pi.testAlphanumeric(e)?le.ALPHANUMERIC:Pi.testKanji(e)?le.KANJI:le.BYTE};le.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};le.isValid=function(e){return e&&e.bit&&e.ccBits};function Wu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return le.NUMERIC;case"alphanumeric":return le.ALPHANUMERIC;case"kanji":return le.KANJI;case"byte":return le.BYTE;default:throw new Error("Unknown mode: "+t)}}le.from=function(e,r){if(le.isValid(e))return e;try{return Wu(e)}catch{return r}}});var $o=$(Ct=>{"use strict";var gs=it(),$u=xi(),Ho=us(),at=ot(),Li=Ai(),jo=7973,Fo=gs.getBCHDigit(jo);function qu(t,e,r){for(let s=1;s<=40;s++)if(e<=Ct.getCapacity(s,r,t))return s}function Wo(t,e){return at.getCharCountIndicator(t,e)+4}function zu(t,e){let r=0;return t.forEach(function(s){let i=Wo(s.mode,e);r+=i+s.getBitsLength()}),r}function Vu(t,e){for(let r=1;r<=40;r++)if(zu(t,r)<=Ct.getCapacity(r,e,at.MIXED))return r}Ct.from=function(e,r){return Li.isValid(e)?parseInt(e,10):r};Ct.getCapacity=function(e,r,s){if(!Li.isValid(e))throw new Error("Invalid QR Code version");typeof s>"u"&&(s=at.BYTE);let i=gs.getSymbolTotalCodewords(e),o=$u.getTotalCodewordsCount(e,r),a=(i-o)*8;if(s===at.MIXED)return a;let n=a-Wo(s,e);switch(s){case at.NUMERIC:return Math.floor(n/10*3);case at.ALPHANUMERIC:return Math.floor(n/11*2);case at.KANJI:return Math.floor(n/13);case at.BYTE:default:return Math.floor(n/8)}};Ct.getBestVersionForData=function(e,r){let s,i=Ho.from(r,Ho.M);if(Array.isArray(e)){if(e.length>1)return Vu(e,i);if(e.length===0)return 1;s=e[0]}else s=e;return qu(s.mode,s.getLength(),i)};Ct.getEncodedBits=function(e){if(!Li.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;gs.getBCHDigit(r)-Fo>=0;)r^=jo<<gs.getBCHDigit(r)-Fo;return e<<12|r}});var Go=$(Vo=>{"use strict";var Ri=it(),zo=1335,Gu=21522,qo=Ri.getBCHDigit(zo);Vo.getEncodedBits=function(e,r){let s=e.bit<<3|r,i=s<<10;for(;Ri.getBCHDigit(i)-qo>=0;)i^=zo<<Ri.getBCHDigit(i)-qo;return(s<<10|i)^Gu}});var Jo=$((tv,Yo)=>{"use strict";var Yu=ot();function er(t){this.mode=Yu.NUMERIC,this.data=t.toString()}er.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};er.prototype.getLength=function(){return this.data.length};er.prototype.getBitsLength=function(){return er.getBitsLength(this.data.length)};er.prototype.write=function(e){let r,s,i;for(r=0;r+3<=this.data.length;r+=3)s=this.data.substr(r,3),i=parseInt(s,10),e.put(i,10);let o=this.data.length-r;o>0&&(s=this.data.substr(r),i=parseInt(s,10),e.put(i,o*3+1))};Yo.exports=er});var Ko=$((rv,Zo)=>{"use strict";var Ju=ot(),Bi=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function tr(t){this.mode=Ju.ALPHANUMERIC,this.data=t}tr.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};tr.prototype.getLength=function(){return this.data.length};tr.prototype.getBitsLength=function(){return tr.getBitsLength(this.data.length)};tr.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let s=Bi.indexOf(this.data[r])*45;s+=Bi.indexOf(this.data[r+1]),e.put(s,11)}this.data.length%2&&e.put(Bi.indexOf(this.data[r]),6)};Zo.exports=tr});var Qo=$((sv,Xo)=>{"use strict";var Zu=ot();function rr(t){this.mode=Zu.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}rr.getBitsLength=function(e){return e*8};rr.prototype.getLength=function(){return this.data.length};rr.prototype.getBitsLength=function(){return rr.getBitsLength(this.data.length)};rr.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};Xo.exports=rr});var ta=$((iv,ea)=>{"use strict";var Ku=ot(),Xu=it();function sr(t){this.mode=Ku.KANJI,this.data=t}sr.getBitsLength=function(e){return e*13};sr.prototype.getLength=function(){return this.data.length};sr.prototype.getBitsLength=function(){return sr.getBitsLength(this.data.length)};sr.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Xu.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
5
+ Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};ea.exports=sr});var ra=$((nv,Di)=>{"use strict";var Mr={single_source_shortest_paths:function(t,e,r){var s={},i={};i[e]=0;var o=Mr.PriorityQueue.make();o.push(e,0);for(var a,n,l,u,y,h,_,d,p;!o.empty();){a=o.pop(),n=a.value,u=a.cost,y=t[n]||{};for(l in y)y.hasOwnProperty(l)&&(h=y[l],_=u+h,d=i[l],p=typeof i[l]>"u",(p||d>_)&&(i[l]=_,o.push(l,_),s[l]=n))}if(typeof r<"u"&&typeof i[r]>"u"){var b=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(b)}return s},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],s=e,i;s;)r.push(s),i=t[s],s=t[s];return r.reverse(),r},find_path:function(t,e,r){var s=Mr.single_source_shortest_paths(t,e,r);return Mr.extract_shortest_path_from_predecessor_list(s,r)},PriorityQueue:{make:function(t){var e=Mr.PriorityQueue,r={},s;t=t||{};for(s in e)e.hasOwnProperty(s)&&(r[s]=e[s]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Di<"u"&&(Di.exports=Mr)});var ha=$(ir=>{"use strict";var oe=ot(),na=Jo(),oa=Ko(),aa=Qo(),ca=ta(),Nr=Ii(),vs=it(),Qu=ra();function sa(t){return unescape(encodeURIComponent(t)).length}function Ur(t,e,r){let s=[],i;for(;(i=t.exec(r))!==null;)s.push({data:i[0],index:i.index,mode:e,length:i[0].length});return s}function la(t){let e=Ur(Nr.NUMERIC,oe.NUMERIC,t),r=Ur(Nr.ALPHANUMERIC,oe.ALPHANUMERIC,t),s,i;return vs.isKanjiModeEnabled()?(s=Ur(Nr.BYTE,oe.BYTE,t),i=Ur(Nr.KANJI,oe.KANJI,t)):(s=Ur(Nr.BYTE_KANJI,oe.BYTE,t),i=[]),e.concat(r,s,i).sort(function(a,n){return a.index-n.index}).map(function(a){return{data:a.data,mode:a.mode,length:a.length}})}function Oi(t,e){switch(e){case oe.NUMERIC:return na.getBitsLength(t);case oe.ALPHANUMERIC:return oa.getBitsLength(t);case oe.KANJI:return ca.getBitsLength(t);case oe.BYTE:return aa.getBitsLength(t)}}function ed(t){return t.reduce(function(e,r){let s=e.length-1>=0?e[e.length-1]:null;return s&&s.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function td(t){let e=[];for(let r=0;r<t.length;r++){let s=t[r];switch(s.mode){case oe.NUMERIC:e.push([s,{data:s.data,mode:oe.ALPHANUMERIC,length:s.length},{data:s.data,mode:oe.BYTE,length:s.length}]);break;case oe.ALPHANUMERIC:e.push([s,{data:s.data,mode:oe.BYTE,length:s.length}]);break;case oe.KANJI:e.push([s,{data:s.data,mode:oe.BYTE,length:sa(s.data)}]);break;case oe.BYTE:e.push([{data:s.data,mode:oe.BYTE,length:sa(s.data)}])}}return e}function rd(t,e){let r={},s={start:{}},i=["start"];for(let o=0;o<t.length;o++){let a=t[o],n=[];for(let l=0;l<a.length;l++){let u=a[l],y=""+o+l;n.push(y),r[y]={node:u,lastCount:0},s[y]={};for(let h=0;h<i.length;h++){let _=i[h];r[_]&&r[_].node.mode===u.mode?(s[_][y]=Oi(r[_].lastCount+u.length,u.mode)-Oi(r[_].lastCount,u.mode),r[_].lastCount+=u.length):(r[_]&&(r[_].lastCount=u.length),s[_][y]=Oi(u.length,u.mode)+4+oe.getCharCountIndicator(u.mode,e))}}i=n}for(let o=0;o<i.length;o++)s[i[o]].end=0;return{map:s,table:r}}function ia(t,e){let r,s=oe.getBestModeForData(t);if(r=oe.from(e,s),r!==oe.BYTE&&r.bit<s.bit)throw new Error('"'+t+'" cannot be encoded with mode '+oe.toString(r)+`.
6
+ Suggested mode is: `+oe.toString(s));switch(r===oe.KANJI&&!vs.isKanjiModeEnabled()&&(r=oe.BYTE),r){case oe.NUMERIC:return new na(t);case oe.ALPHANUMERIC:return new oa(t);case oe.KANJI:return new ca(t);case oe.BYTE:return new aa(t)}}ir.fromArray=function(e){return e.reduce(function(r,s){return typeof s=="string"?r.push(ia(s,null)):s.data&&r.push(ia(s.data,s.mode)),r},[])};ir.fromString=function(e,r){let s=la(e,vs.isKanjiModeEnabled()),i=td(s),o=rd(i,r),a=Qu.find_path(o.map,"start","end"),n=[];for(let l=1;l<a.length-1;l++)n.push(o.table[a[l]].node);return ir.fromArray(ed(n))};ir.rawSplit=function(e){return ir.fromArray(la(e,vs.isKanjiModeEnabled()))}});var ji=$(ua=>{"use strict";var bs=it(),Mi=us(),sd=Eo(),id=ko(),nd=To(),od=Po(),Hi=Lo(),Fi=xi(),ad=Mo(),ys=$o(),cd=Go(),ld=ot(),Ni=ha();function hd(t,e){let r=t.size,s=od.getPositions(e);for(let i=0;i<s.length;i++){let o=s[i][0],a=s[i][1];for(let n=-1;n<=7;n++)if(!(o+n<=-1||r<=o+n))for(let l=-1;l<=7;l++)a+l<=-1||r<=a+l||(n>=0&&n<=6&&(l===0||l===6)||l>=0&&l<=6&&(n===0||n===6)||n>=2&&n<=4&&l>=2&&l<=4?t.set(o+n,a+l,!0,!0):t.set(o+n,a+l,!1,!0))}}function ud(t){let e=t.size;for(let r=8;r<e-8;r++){let s=r%2===0;t.set(r,6,s,!0),t.set(6,r,s,!0)}}function dd(t,e){let r=nd.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-2;a<=2;a++)for(let n=-2;n<=2;n++)a===-2||a===2||n===-2||n===2||a===0&&n===0?t.set(i+a,o+n,!0,!0):t.set(i+a,o+n,!1,!0)}}function fd(t,e){let r=t.size,s=ys.getEncodedBits(e),i,o,a;for(let n=0;n<18;n++)i=Math.floor(n/3),o=n%3+r-8-3,a=(s>>n&1)===1,t.set(i,o,a,!0),t.set(o,i,a,!0)}function Ui(t,e,r){let s=t.size,i=cd.getEncodedBits(e,r),o,a;for(o=0;o<15;o++)a=(i>>o&1)===1,o<6?t.set(o,8,a,!0):o<8?t.set(o+1,8,a,!0):t.set(s-15+o,8,a,!0),o<8?t.set(8,s-o-1,a,!0):o<9?t.set(8,15-o-1+1,a,!0):t.set(8,15-o-1,a,!0);t.set(s-8,8,1,!0)}function pd(t,e){let r=t.size,s=-1,i=r-1,o=7,a=0;for(let n=r-1;n>0;n-=2)for(n===6&&n--;;){for(let l=0;l<2;l++)if(!t.isReserved(i,n-l)){let u=!1;a<e.length&&(u=(e[a]>>>o&1)===1),t.set(i,n-l,u),o--,o===-1&&(a++,o=7)}if(i+=s,i<0||r<=i){i-=s,s=-s;break}}}function _d(t,e,r){let s=new sd;r.forEach(function(l){s.put(l.mode.bit,4),s.put(l.getLength(),ld.getCharCountIndicator(l.mode,t)),l.write(s)});let i=bs.getSymbolTotalCodewords(t),o=Fi.getTotalCodewordsCount(t,e),a=(i-o)*8;for(s.getLengthInBits()+4<=a&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(0);let n=(a-s.getLengthInBits())/8;for(let l=0;l<n;l++)s.put(l%2?17:236,8);return md(s,t,e)}function md(t,e,r){let s=bs.getSymbolTotalCodewords(e),i=Fi.getTotalCodewordsCount(e,r),o=s-i,a=Fi.getBlocksCount(e,r),n=s%a,l=a-n,u=Math.floor(s/a),y=Math.floor(o/a),h=y+1,_=u-y,d=new ad(_),p=0,b=new Array(a),c=new Array(a),v=0,g=new Uint8Array(t.buffer);for(let k=0;k<a;k++){let A=k<l?y:h;b[k]=g.slice(p,p+A),c[k]=d.encode(b[k]),p+=A,v=Math.max(v,A)}let f=new Uint8Array(s),m=0,w,C;for(w=0;w<v;w++)for(C=0;C<a;C++)w<b[C].length&&(f[m++]=b[C][w]);for(w=0;w<_;w++)for(C=0;C<a;C++)f[m++]=c[C][w];return f}function gd(t,e,r,s){let i;if(Array.isArray(t))i=Ni.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){let y=Ni.rawSplit(t);u=ys.getBestVersionForData(y,r)}i=Ni.fromString(t,u||40)}else throw new Error("Invalid data");let o=ys.getBestVersionForData(i,r);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
7
7
  The chosen QR Code version cannot contain this amount of data.
8
8
  Minimum version required to store current data is: `+o+`.
9
- `);let a=cd(e,r,i),n=ys.getSymbolSize(e),l=new Ku(n);return sd(l,e),id(l),nd(l,e),Di(l,r,0),e>=7&&od(l,e),ad(l,a),isNaN(s)&&(s=Mi.getBestMask(l,Di.bind(null,l,r))),Mi.applyMask(s,l),Di(l,r,s),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:s,segments:i}}aa.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let s=Bi.M,i,o;return typeof r<"u"&&(s=Bi.from(r.errorCorrectionLevel,Bi.M),i=vs.from(r.version),o=Mi.from(r.maskPattern),r.toSJISFunc&&ys.setToSJISFunction(r.toSJISFunc)),hd(e,i,s,o)}});var Ui=q((K0,la)=>{"use strict";var ud=se("util"),ca=se("stream"),Pe=la.exports=function(){ca.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ud.inherits(Pe,ca);Pe.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Pe.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Pe.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Pe.prototype.destroySoon=Pe.prototype.end;Pe.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Pe.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Pe.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Pe.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,s=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],o=Math.min(i.length,t.length-e);i.copy(s,e,0,o),e+=o,o!==i.length&&(this._buffers[--r]=i.slice(o))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,s)};Pe.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var ji=q(Fi=>{"use strict";var nt=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Fi.getImagePasses=function(t,e){let r=[],s=t%8,i=e%8,o=(t-s)/8,a=(e-i)/8;for(let n=0;n<nt.length;n++){let l=nt[n],u=o*l.x.length,y=a*l.y.length;for(let h=0;h<l.x.length&&l.x[h]<s;h++)u++;for(let h=0;h<l.y.length&&l.y[h]<i;h++)y++;u>0&&y>0&&r.push({width:u,height:y,index:n})}return r};Fi.getInterlaceIterator=function(t){return function(e,r,s){let i=e%nt[s].x.length,o=(e-i)/nt[s].x.length*8+nt[s].x[i],a=r%nt[s].y.length,n=(r-a)/nt[s].y.length*8+nt[s].y[a];return o*4+n*t*4}}});var Wi=q((Q0,ha)=>{"use strict";ha.exports=function(e,r,s){let i=e+r-s,o=Math.abs(i-e),a=Math.abs(i-r),n=Math.abs(i-s);return o<=a&&o<=n?e:a<=n?r:s}});var qi=q((ev,da)=>{"use strict";var dd=ji(),fd=Wi();function ua(t,e,r){let s=t*e;return r!==8&&(s=Math.ceil(s/(8/r))),s}var ir=da.exports=function(t,e){let r=t.width,s=t.height,i=t.interlace,o=t.bpp,a=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let n=dd.getImagePasses(r,s);for(let l=0;l<n.length;l++)this._images.push({byteWidth:ua(n[l].width,o,a),height:n[l].height,lineIndex:0})}else this._images.push({byteWidth:ua(r,o,a),height:s,lineIndex:0});a===8?this._xComparison=o:a===16?this._xComparison=o*2:this._xComparison=1};ir.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ir.prototype._unFilterType1=function(t,e,r){let s=this._xComparison,i=s-1;for(let o=0;o<r;o++){let a=t[1+o],n=o>i?e[o-s]:0;e[o]=a+n}};ir.prototype._unFilterType2=function(t,e,r){let s=this._lastLine;for(let i=0;i<r;i++){let o=t[1+i],a=s?s[i]:0;e[i]=o+a}};ir.prototype._unFilterType3=function(t,e,r){let s=this._xComparison,i=s-1,o=this._lastLine;for(let a=0;a<r;a++){let n=t[1+a],l=o?o[a]:0,u=a>i?e[a-s]:0,y=Math.floor((u+l)/2);e[a]=n+y}};ir.prototype._unFilterType4=function(t,e,r){let s=this._xComparison,i=s-1,o=this._lastLine;for(let a=0;a<r;a++){let n=t[1+a],l=o?o[a]:0,u=a>i?e[a-s]:0,y=a>i&&o?o[a-s]:0,h=fd(u,l,y);e[a]=n+h}};ir.prototype._reverseFilterLine=function(t){let e=t[0],r,s=this._images[this._imageIndex],i=s.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=r,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var _a=q((tv,pa)=>{"use strict";var pd=se("util"),fa=Ui(),_d=qi(),md=pa.exports=function(t){fa.call(this);let e=[],r=this;this._filter=new _d(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};pd.inherits(md,fa)});var nr=q((rv,ma)=>{"use strict";ma.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Vi=q((sv,ga)=>{"use strict";var $i=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;$i[t]=e}})();var zi=ga.exports=function(){this._crc=-1};zi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=$i[(this._crc^t[e])&255]^this._crc>>>8;return!0};zi.prototype.crc32=function(){return this._crc^-1};zi.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=$i[(e^t[r])&255]^e>>>8;return e^-1}});var Gi=q((iv,va)=>{"use strict";var he=nr(),gd=Vi(),ue=va.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[he.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[he.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[he.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[he.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[he.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[he.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};ue.prototype.start=function(){this.read(he.PNG_SIGNATURE.length,this._parseSignature.bind(this))};ue.prototype._parseSignature=function(t){let e=he.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),s="";for(let o=4;o<8;o++)s+=String.fromCharCode(t[o]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==he.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new gd,this._crc.write(Buffer.from(s)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};ue.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};ue.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};ue.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),s=t[8],i=t[9],o=t[10],a=t[11],n=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(i in he.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(o!==0){this.error(new Error("Unsupported compression method"));return}if(a!==0){this.error(new Error("Unsupported filter method"));return}if(n!==0&&n!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let l=he.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:s,interlace:!!n,palette:!!(i&he.COLORTYPE_PALETTE),color:!!(i&he.COLORTYPE_COLOR),alpha:!!(i&he.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};ue.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};ue.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};ue.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};ue.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===he.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===he.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===he.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};ue.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};ue.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/he.GAMMA_DIVISION),this._handleChunkEnd()};ue.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};ue.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===he.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};ue.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};ue.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Yi=q(ba=>{"use strict";var ya=ji(),vd=[function(){},function(t,e,r,s){if(s===e.length)throw new Error("Ran out of data");let i=e[s];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,s){if(s+1>=e.length)throw new Error("Ran out of data");let i=e[s];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[s+1]},function(t,e,r,s){if(s+2>=e.length)throw new Error("Ran out of data");t[r]=e[s],t[r+1]=e[s+1],t[r+2]=e[s+2],t[r+3]=255},function(t,e,r,s){if(s+3>=e.length)throw new Error("Ran out of data");t[r]=e[s],t[r+1]=e[s+1],t[r+2]=e[s+2],t[r+3]=e[s+3]}],yd=[function(){},function(t,e,r,s){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=s},function(t,e,r){let s=e[0];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=e[1]},function(t,e,r,s){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=s},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function bd(t,e){let r=[],s=0;function i(){if(s===t.length)throw new Error("Ran out of data");let o=t[s];s++;let a,n,l,u,y,h,_,d;switch(e){default:throw new Error("unrecognised depth");case 16:_=t[s],s++,r.push((o<<8)+_);break;case 4:_=o&15,d=o>>4,r.push(d,_);break;case 2:y=o&3,h=o>>2&3,_=o>>4&3,d=o>>6&3,r.push(d,_,h,y);break;case 1:a=o&1,n=o>>1&1,l=o>>2&1,u=o>>3&1,y=o>>4&1,h=o>>5&1,_=o>>6&1,d=o>>7&1,r.push(d,_,h,y,u,l,n,a);break}}return{get:function(o){for(;r.length<o;)i();let a=r.slice(0,o);return r=r.slice(o),a},resetAfterLine:function(){r.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function wd(t,e,r,s,i,o){let a=t.width,n=t.height,l=t.index;for(let u=0;u<n;u++)for(let y=0;y<a;y++){let h=r(y,u,l);vd[s](e,i,h,o),o+=s}return o}function Sd(t,e,r,s,i,o){let a=t.width,n=t.height,l=t.index;for(let u=0;u<n;u++){for(let y=0;y<a;y++){let h=i.get(s),_=r(y,u,l);yd[s](e,h,_,o)}i.resetAfterLine()}}ba.dataToBitMap=function(t,e){let r=e.width,s=e.height,i=e.depth,o=e.bpp,a=e.interlace,n;i!==8&&(n=bd(t,i));let l;i<=8?l=Buffer.alloc(r*s*4):l=new Uint16Array(r*s*4);let u=Math.pow(2,i)-1,y=0,h,_;if(a)h=ya.getImagePasses(r,s),_=ya.getInterlaceIterator(r,s);else{let d=0;_=function(){let p=d;return d+=4,p},h=[{width:r,height:s}]}for(let d=0;d<h.length;d++)i===8?y=wd(h[d],l,_,o,t,y):Sd(h[d],l,_,o,n,u);if(i===8){if(y!==t.length)throw new Error("extra data found")}else n.end();return l}});var Ji=q((ov,wa)=>{"use strict";function Cd(t,e,r,s,i){let o=0;for(let a=0;a<s;a++)for(let n=0;n<r;n++){let l=i[t[o]];if(!l)throw new Error("index "+t[o]+" not in palette");for(let u=0;u<4;u++)e[o+u]=l[u];o+=4}}function Ed(t,e,r,s,i){let o=0;for(let a=0;a<s;a++)for(let n=0;n<r;n++){let l=!1;if(i.length===1?i[0]===t[o]&&(l=!0):i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2]&&(l=!0),l)for(let u=0;u<4;u++)e[o+u]=0;o+=4}}function xd(t,e,r,s,i){let o=255,a=Math.pow(2,i)-1,n=0;for(let l=0;l<s;l++)for(let u=0;u<r;u++){for(let y=0;y<4;y++)e[n+y]=Math.floor(t[n+y]*o/a+.5);n+=4}}wa.exports=function(t,e){let r=e.depth,s=e.width,i=e.height,o=e.colorType,a=e.transColor,n=e.palette,l=t;return o===3?Cd(t,l,s,i,n):(a&&Ed(t,l,s,i,a),r!==8&&(r===16&&(l=Buffer.alloc(s*i*4)),xd(t,l,s,i,r))),l}});var Ea=q((av,Ca)=>{"use strict";var kd=se("util"),Zi=se("zlib"),Sa=Ui(),Td=_a(),Ad=Gi(),Id=Yi(),Pd=Ji(),De=Ca.exports=function(t){Sa.call(this),this._parser=new Ad(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};kd.inherits(De,Sa);De.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};De.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Zi.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(r,Zi.Z_MIN_CHUNK);this._inflate=Zi.createInflate({chunkSize:s});let i=r,o=this.emit.bind(this,"error");this._inflate.on("error",function(n){i&&o(n)}),this._filter.on("complete",this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on("data",function(n){i&&(n.length>i&&(n=n.slice(0,i)),i-=n.length,a(n))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};De.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Td(this._bitmapInfo)};De.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};De.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};De.prototype._simpleTransparency=function(){this._metaData.alpha=!0};De.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};De.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};De.prototype._complete=function(t){if(this.errord)return;let e;try{let r=Id.dataToBitMap(t,this._bitmapInfo);e=Pd(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var ka=q((cv,xa)=>{"use strict";var Se=nr();xa.exports=function(t,e,r,s){let i=[Se.COLORTYPE_COLOR_ALPHA,Se.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let p=(function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&p)return t}let o=s.bitDepth!==16?t:new Uint16Array(t.buffer),a=255,n=Se.COLORTYPE_TO_BPP_MAP[s.inputColorType];n===4&&!s.inputHasAlpha&&(n=3);let l=Se.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(a=65535,l*=2);let u=Buffer.alloc(e*r*l),y=0,h=0,_=s.bgColor||{};_.red===void 0&&(_.red=a),_.green===void 0&&(_.green=a),_.blue===void 0&&(_.blue=a);function d(){let p,b,c,v=a;switch(s.inputColorType){case Se.COLORTYPE_COLOR_ALPHA:v=o[y+3],p=o[y],b=o[y+1],c=o[y+2];break;case Se.COLORTYPE_COLOR:p=o[y],b=o[y+1],c=o[y+2];break;case Se.COLORTYPE_ALPHA:v=o[y+1],p=o[y],b=p,c=p;break;case Se.COLORTYPE_GRAYSCALE:p=o[y],b=p,c=p;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(i||(v/=a,p=Math.min(Math.max(Math.round((1-v)*_.red+v*p),0),a),b=Math.min(Math.max(Math.round((1-v)*_.green+v*b),0),a),c=Math.min(Math.max(Math.round((1-v)*_.blue+v*c),0),a))),{red:p,green:b,blue:c,alpha:v}}for(let p=0;p<r;p++)for(let b=0;b<e;b++){let c=d(o,y);switch(s.colorType){case Se.COLORTYPE_COLOR_ALPHA:case Se.COLORTYPE_COLOR:s.bitDepth===8?(u[h]=c.red,u[h+1]=c.green,u[h+2]=c.blue,i&&(u[h+3]=c.alpha)):(u.writeUInt16BE(c.red,h),u.writeUInt16BE(c.green,h+2),u.writeUInt16BE(c.blue,h+4),i&&u.writeUInt16BE(c.alpha,h+6));break;case Se.COLORTYPE_ALPHA:case Se.COLORTYPE_GRAYSCALE:{let v=(c.red+c.green+c.blue)/3;s.bitDepth===8?(u[h]=v,i&&(u[h+1]=c.alpha)):(u.writeUInt16BE(v,h),i&&u.writeUInt16BE(c.alpha,h+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}y+=n,h+=l}return u}});var Ia=q((lv,Aa)=>{"use strict";var Ta=Wi();function Ld(t,e,r,s,i){for(let o=0;o<r;o++)s[i+o]=t[e+o]}function Rd(t,e,r){let s=0,i=e+r;for(let o=e;o<i;o++)s+=Math.abs(t[o]);return s}function Bd(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=t[e+a]-n;s[i+a]=l}}function Od(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=t[e+o]-a;i+=Math.abs(n)}return i}function Dd(t,e,r,s,i){for(let o=0;o<r;o++){let a=e>0?t[e+o-r]:0,n=t[e+o]-a;s[i+o]=n}}function Md(t,e,r){let s=0,i=e+r;for(let o=e;o<i;o++){let a=e>0?t[o-r]:0,n=t[o]-a;s+=Math.abs(n)}return s}function Nd(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=e>0?t[e+a-r]:0,u=t[e+a]-(n+l>>1);s[i+a]=u}}function Hd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=e>0?t[e+o-r]:0,l=t[e+o]-(a+n>>1);i+=Math.abs(l)}return i}function Ud(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=e>0?t[e+a-r]:0,u=e>0&&a>=o?t[e+a-(r+o)]:0,y=t[e+a]-Ta(n,l,u);s[i+a]=y}}function Fd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=e>0?t[e+o-r]:0,l=e>0&&o>=s?t[e+o-(r+s)]:0,u=t[e+o]-Ta(a,n,l);i+=Math.abs(u)}return i}var jd={0:Ld,1:Bd,2:Dd,3:Nd,4:Ud},Wd={0:Rd,1:Od,2:Md,3:Hd,4:Fd};Aa.exports=function(t,e,r,s,i){let o;if(!("filterType"in s)||s.filterType===-1)o=[0,1,2,3,4];else if(typeof s.filterType=="number")o=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(i*=2);let a=e*i,n=0,l=0,u=Buffer.alloc((a+1)*r),y=o[0];for(let h=0;h<r;h++){if(o.length>1){let _=1/0;for(let d=0;d<o.length;d++){let p=Wd[o[d]](t,l,a,i);p<_&&(y=o[d],_=p)}}u[n]=y,n++,jd[y](t,l,a,u,n,i),n+=a,l+=a}return u}});var Ki=q((hv,Pa)=>{"use strict";var pe=nr(),qd=Vi(),$d=ka(),zd=Ia(),Vd=se("zlib"),ot=Pa.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Vd.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:pe.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:pe.COLORTYPE_COLOR_ALPHA,[pe.COLORTYPE_GRAYSCALE,pe.COLORTYPE_COLOR,pe.COLORTYPE_COLOR_ALPHA,pe.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([pe.COLORTYPE_GRAYSCALE,pe.COLORTYPE_COLOR,pe.COLORTYPE_COLOR_ALPHA,pe.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};ot.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ot.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ot.prototype.filterData=function(t,e,r){let s=$d(t,e,r,this._options),i=pe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return zd(s,e,r,this._options,i)};ot.prototype._packChunk=function(t,e){let r=e?e.length:0,s=Buffer.alloc(r+12);return s.writeUInt32BE(r,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(qd.crc32(s.slice(4,s.length-4)),s.length-4),s};ot.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*pe.GAMMA_DIVISION),0),this._packChunk(pe.TYPE_gAMA,e)};ot.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(pe.TYPE_IHDR,r)};ot.prototype.packIDAT=function(t){return this._packChunk(pe.TYPE_IDAT,t)};ot.prototype.packIEND=function(){return this._packChunk(pe.TYPE_IEND,null)}});var Oa=q((uv,Ba)=>{"use strict";var Gd=se("util"),La=se("stream"),Yd=nr(),Jd=Ki(),Ra=Ba.exports=function(t){La.call(this);let e=t||{};this._packer=new Jd(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Gd.inherits(Ra,La);Ra.prototype.pack=function(t,e,r,s){this.emit("data",Buffer.from(Yd.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),s&&this.emit("data",this._packer.packGAMA(s));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Fa=q((Mr,Ua)=>{"use strict";var Da=se("assert").ok,or=se("zlib"),Zd=se("util"),Ma=se("buffer").kMaxLength;function bt(t){if(!(this instanceof bt))return new bt(t);t&&t.chunkSize<or.Z_MIN_CHUNK&&(t.chunkSize=or.Z_MIN_CHUNK),or.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Kd(t){return new bt(t)}function Na(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}bt.prototype._processChunk=function(t,e,r){if(typeof r=="function")return or.Inflate._processChunk.call(this,t,e,r);let s=this,i=t&&t.length,o=this._chunkSize-this._offset,a=this._maxLength,n=0,l=[],u=0,y;this.on("error",function(p){y=p});function h(p,b){if(s._hadError)return;let c=o-b;if(Da(c>=0,"have should not go down"),c>0){let v=s._buffer.slice(s._offset,s._offset+c);if(s._offset+=c,v.length>a&&(v=v.slice(0,a)),l.push(v),u+=v.length,a-=v.length,a===0)return!1}return(b===0||s._offset>=s._chunkSize)&&(o=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),b===0?(n+=i-p,i=p,!0):!1}Da(this._handle,"zlib binding closed");let _;do _=this._handle.writeSync(e,t,n,i,this._buffer,this._offset,o),_=_||this._writeState;while(!this._hadError&&h(_[0],_[1]));if(this._hadError)throw y;if(u>=Ma)throw Na(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ma.toString(16)+" bytes");let d=Buffer.concat(l,u);return Na(this),d};Zd.inherits(bt,or.Inflate);function Xd(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=or.Z_FINISH),t._processChunk(e,r)}function Ha(t,e){return Xd(new bt(e),t)}Ua.exports=Mr=Ha;Mr.Inflate=bt;Mr.createInflate=Kd;Mr.inflateSync=Ha});var Xi=q((dv,Wa)=>{"use strict";var ja=Wa.exports=function(t){this._buffer=t,this._reads=[]};ja.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};ja.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var $a=q(qa=>{"use strict";var Qd=Xi(),ef=qi();qa.process=function(t,e){let r=[],s=new Qd(t);return new ef(e,{read:s.read.bind(s),write:function(o){r.push(o)},complete:function(){}}).start(),s.process(),Buffer.concat(r)}});var Ya=q((pv,Ga)=>{"use strict";var za=!0,Va=se("zlib"),tf=Fa();Va.deflateSync||(za=!1);var rf=Xi(),sf=$a(),nf=Gi(),of=Yi(),af=Ji();Ga.exports=function(t,e){if(!za)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function s(m){r=m}let i;function o(m){i=m}function a(m){i.transColor=m}function n(m){i.palette=m}function l(){i.alpha=!0}let u;function y(m){u=m}let h=[];function _(m){h.push(m)}let d=new rf(t);if(new nf(e,{read:d.read.bind(d),error:s,metadata:o,gamma:y,palette:n,transColor:a,inflateData:_,simpleTransparency:l}).start(),d.process(),r)throw r;let b=Buffer.concat(h);h.length=0;let c;if(i.interlace)c=Va.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;c=tf(b,{chunkSize:w,maxLength:w})}if(b=null,!c||!c.length)throw new Error("bad png - invalid inflate data response");let v=sf.process(c,i);b=null;let g=of.dataToBitMap(v,i);v=null;let f=af(g,i);return i.data=f,i.gamma=u||0,i}});var Xa=q((_v,Ka)=>{"use strict";var Ja=!0,Za=se("zlib");Za.deflateSync||(Ja=!1);var cf=nr(),lf=Ki();Ka.exports=function(t,e){if(!Ja)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},s=new lf(r),i=[];i.push(Buffer.from(cf.PNG_SIGNATURE)),i.push(s.packIHDR(t.width,t.height)),t.gamma&&i.push(s.packGAMA(t.gamma));let o=s.filterData(t.data,t.width,t.height),a=Za.deflateSync(o,s.getDeflateOptions());if(o=null,!a||!a.length)throw new Error("bad png - invalid compressed data response");return i.push(s.packIDAT(a)),i.push(s.packIEND()),Buffer.concat(i)}});var Qa=q(Qi=>{"use strict";var hf=Ya(),uf=Xa();Qi.read=function(t,e){return hf(t,e||{})};Qi.write=function(t,e){return uf(t,e)}});var rc=q(tc=>{"use strict";var df=se("util"),ec=se("stream"),ff=Ea(),pf=Oa(),_f=Qa(),me=tc.PNG=function(t){ec.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new ff(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new pf(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};df.inherits(me,ec);me.sync=_f;me.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};me.prototype.parse=function(t,e){if(e){let r,s;r=function(i){this.removeListener("error",s),this.data=i,e(null,this)}.bind(this),s=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",s)}return this.end(t),this};me.prototype.write=function(t){return this._parser.write(t),!0};me.prototype.end=function(t){this._parser.end(t)};me.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};me.prototype._gamma=function(t){this.gamma=t};me.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};me.bitblt=function(t,e,r,s,i,o,a,n){if(r|=0,s|=0,i|=0,o|=0,a|=0,n|=0,r>t.width||s>t.height||r+i>t.width||s+o>t.height)throw new Error("bitblt reading outside image");if(a>e.width||n>e.height||a+i>e.width||n+o>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<o;l++)t.data.copy(e.data,(n+l)*e.width+a<<2,(s+l)*t.width+r<<2,(s+l)*t.width+r+i<<2)};me.prototype.bitblt=function(t,e,r,s,i,o,a){return me.bitblt(this,t,e,r,s,i,o,a),this};me.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let s=t.width*e+r<<2;for(let i=0;i<3;i++){let o=t.data[s+i]/255;o=Math.pow(o,1/2.2/t.gamma),t.data[s+i]=Math.round(o*255)}}t.gamma=0}};me.prototype.adjustGamma=function(){me.adjustGamma(this)}});var Nr=q(wt=>{"use strict";function sc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(s){return[s,s]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}wt.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:s,scale:s?4:i,margin:r,color:{dark:sc(e.color.dark||"#000000ff"),light:sc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};wt.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};wt.getImageWidth=function(e,r){let s=wt.getScale(e,r);return Math.floor((e+r.margin*2)*s)};wt.qrToImageData=function(e,r,s){let i=r.modules.size,o=r.modules.data,a=wt.getScale(i,s),n=Math.floor((i+s.margin*2)*a),l=s.margin*a,u=[s.color.light,s.color.dark];for(let y=0;y<n;y++)for(let h=0;h<n;h++){let _=(y*n+h)*4,d=s.color.light;if(y>=l&&h>=l&&y<n-l&&h<n-l){let p=Math.floor((y-l)/a),b=Math.floor((h-l)/a);d=u[o[p*i+b]?1:0]}e[_++]=d.r,e[_++]=d.g,e[_++]=d.b,e[_]=d.a}}});var ic=q(Me=>{"use strict";var mf=se("fs"),gf=rc().PNG,en=Nr();Me.render=function(e,r){let s=en.getOptions(r),i=s.rendererOpts,o=en.getImageWidth(e.modules.size,s);i.width=o,i.height=o;let a=new gf(i);return en.qrToImageData(a.data,e,s),a};Me.renderToDataURL=function(e,r,s){typeof s>"u"&&(s=r,r=void 0),Me.renderToBuffer(e,r,function(i,o){i&&s(i);let a="data:image/png;base64,";a+=o.toString("base64"),s(null,a)})};Me.renderToBuffer=function(e,r,s){typeof s>"u"&&(s=r,r=void 0);let i=Me.render(e,r),o=[];i.on("error",s),i.on("data",function(a){o.push(a)}),i.on("end",function(){s(null,Buffer.concat(o))}),i.pack()};Me.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=!1,a=(...l)=>{o||(o=!0,i.apply(null,l))},n=mf.createWriteStream(e);n.on("error",a),n.on("close",a),Me.renderToFileStream(n,r,s)};Me.renderToFileStream=function(e,r,s){Me.render(r,s).pack().pipe(e)}});var nc=q(bs=>{"use strict";var vf=Nr(),yf={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},bf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function wf(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}bs.render=function(t,e,r){let s=vf.getOptions(e),i=yf;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(i=bf);let o=t.modules.size,a=t.modules.data,n="",l=Array(o+s.margin*2+1).join(i.WW);l=Array(s.margin/2+1).join(l+`
10
- `);let u=Array(s.margin+1).join(i.WW);n+=l;for(let y=0;y<o;y+=2){n+=u;for(let h=0;h<o;h++){let _=a[y*o+h],d=a[(y+1)*o+h];n+=wf(_,d,i)}n+=u+`
11
- `}return n+=l.slice(0,-1),typeof r=="function"&&r(null,n),n};bs.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=se("fs"),a=bs.render(r,s);o.writeFile(e,a,i)}});var ac=q(oc=>{"use strict";oc.render=function(t,e,r){let s=t.modules.size,i=t.modules.data,o="\x1B[40m \x1B[0m",a="\x1B[47m \x1B[0m",n="",l=Array(s+3).join(a),u=Array(2).join(a);n+=l+`
9
+ `);let a=_d(e,r,i),n=bs.getSymbolSize(e),l=new id(n);return hd(l,e),ud(l),dd(l,e),Ui(l,r,0),e>=7&&fd(l,e),pd(l,a),isNaN(s)&&(s=Hi.getBestMask(l,Ui.bind(null,l,r))),Hi.applyMask(s,l),Ui(l,r,s),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:s,segments:i}}ua.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let s=Mi.M,i,o;return typeof r<"u"&&(s=Mi.from(r.errorCorrectionLevel,Mi.M),i=ys.from(r.version),o=Hi.from(r.maskPattern),r.toSJISFunc&&bs.setToSJISFunction(r.toSJISFunc)),gd(e,i,s,o)}});var Wi=$((cv,fa)=>{"use strict";var vd=se("util"),da=se("stream"),Pe=fa.exports=function(){da.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};vd.inherits(Pe,da);Pe.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};Pe.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Pe.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};Pe.prototype.destroySoon=Pe.prototype.end;Pe.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Pe.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Pe.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};Pe.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,s=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[r++],o=Math.min(i.length,t.length-e);i.copy(s,e,0,o),e+=o,o!==i.length&&(this._buffers[--r]=i.slice(o))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,s)};Pe.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var qi=$($i=>{"use strict";var ct=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];$i.getImagePasses=function(t,e){let r=[],s=t%8,i=e%8,o=(t-s)/8,a=(e-i)/8;for(let n=0;n<ct.length;n++){let l=ct[n],u=o*l.x.length,y=a*l.y.length;for(let h=0;h<l.x.length&&l.x[h]<s;h++)u++;for(let h=0;h<l.y.length&&l.y[h]<i;h++)y++;u>0&&y>0&&r.push({width:u,height:y,index:n})}return r};$i.getInterlaceIterator=function(t){return function(e,r,s){let i=e%ct[s].x.length,o=(e-i)/ct[s].x.length*8+ct[s].x[i],a=r%ct[s].y.length,n=(r-a)/ct[s].y.length*8+ct[s].y[a];return o*4+n*t*4}}});var zi=$((hv,pa)=>{"use strict";pa.exports=function(e,r,s){let i=e+r-s,o=Math.abs(i-e),a=Math.abs(i-r),n=Math.abs(i-s);return o<=a&&o<=n?e:a<=n?r:s}});var Vi=$((uv,ma)=>{"use strict";var yd=qi(),bd=zi();function _a(t,e,r){let s=t*e;return r!==8&&(s=Math.ceil(s/(8/r))),s}var nr=ma.exports=function(t,e){let r=t.width,s=t.height,i=t.interlace,o=t.bpp,a=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let n=yd.getImagePasses(r,s);for(let l=0;l<n.length;l++)this._images.push({byteWidth:_a(n[l].width,o,a),height:n[l].height,lineIndex:0})}else this._images.push({byteWidth:_a(r,o,a),height:s,lineIndex:0});a===8?this._xComparison=o:a===16?this._xComparison=o*2:this._xComparison=1};nr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};nr.prototype._unFilterType1=function(t,e,r){let s=this._xComparison,i=s-1;for(let o=0;o<r;o++){let a=t[1+o],n=o>i?e[o-s]:0;e[o]=a+n}};nr.prototype._unFilterType2=function(t,e,r){let s=this._lastLine;for(let i=0;i<r;i++){let o=t[1+i],a=s?s[i]:0;e[i]=o+a}};nr.prototype._unFilterType3=function(t,e,r){let s=this._xComparison,i=s-1,o=this._lastLine;for(let a=0;a<r;a++){let n=t[1+a],l=o?o[a]:0,u=a>i?e[a-s]:0,y=Math.floor((u+l)/2);e[a]=n+y}};nr.prototype._unFilterType4=function(t,e,r){let s=this._xComparison,i=s-1,o=this._lastLine;for(let a=0;a<r;a++){let n=t[1+a],l=o?o[a]:0,u=a>i?e[a-s]:0,y=a>i&&o?o[a-s]:0,h=bd(u,l,y);e[a]=n+h}};nr.prototype._reverseFilterLine=function(t){let e=t[0],r,s=this._images[this._imageIndex],i=s.byteWidth;if(e===0)r=t.slice(1,i+1);else switch(r=Buffer.alloc(i),e){case 1:this._unFilterType1(t,r,i);break;case 2:this._unFilterType2(t,r,i);break;case 3:this._unFilterType3(t,r,i);break;case 4:this._unFilterType4(t,r,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=r,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var ya=$((dv,va)=>{"use strict";var wd=se("util"),ga=Wi(),Sd=Vi(),Cd=va.exports=function(t){ga.call(this);let e=[],r=this;this._filter=new Sd(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};wd.inherits(Cd,ga)});var or=$((fv,ba)=>{"use strict";ba.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Ji=$((pv,wa)=>{"use strict";var Gi=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;Gi[t]=e}})();var Yi=wa.exports=function(){this._crc=-1};Yi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Gi[(this._crc^t[e])&255]^this._crc>>>8;return!0};Yi.prototype.crc32=function(){return this._crc^-1};Yi.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=Gi[(e^t[r])&255]^e>>>8;return e^-1}});var Zi=$((_v,Sa)=>{"use strict";var he=or(),Ed=Ji(),ue=Sa.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[he.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[he.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[he.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[he.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[he.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[he.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};ue.prototype.start=function(){this.read(he.PNG_SIGNATURE.length,this._parseSignature.bind(this))};ue.prototype._parseSignature=function(t){let e=he.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),s="";for(let o=4;o<8;o++)s+=String.fromCharCode(t[o]);let i=!!(t[4]&32);if(!this._hasIHDR&&r!==he.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Ed,this._crc.write(Buffer.from(s)),this._chunks[r])return this._chunks[r](e);if(!i){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};ue.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};ue.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};ue.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};ue.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),s=t[8],i=t[9],o=t[10],a=t[11],n=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(i in he.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(o!==0){this.error(new Error("Unsupported compression method"));return}if(a!==0){this.error(new Error("Unsupported filter method"));return}if(n!==0&&n!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let l=he.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:s,interlace:!!n,palette:!!(i&he.COLORTYPE_PALETTE),color:!!(i&he.COLORTYPE_COLOR),alpha:!!(i&he.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};ue.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};ue.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};ue.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};ue.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===he.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===he.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===he.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};ue.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};ue.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/he.GAMMA_DIVISION),this._handleChunkEnd()};ue.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};ue.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===he.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};ue.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};ue.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ki=$(Ea=>{"use strict";var Ca=qi(),xd=[function(){},function(t,e,r,s){if(s===e.length)throw new Error("Ran out of data");let i=e[s];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,s){if(s+1>=e.length)throw new Error("Ran out of data");let i=e[s];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[s+1]},function(t,e,r,s){if(s+2>=e.length)throw new Error("Ran out of data");t[r]=e[s],t[r+1]=e[s+1],t[r+2]=e[s+2],t[r+3]=255},function(t,e,r,s){if(s+3>=e.length)throw new Error("Ran out of data");t[r]=e[s],t[r+1]=e[s+1],t[r+2]=e[s+2],t[r+3]=e[s+3]}],kd=[function(){},function(t,e,r,s){let i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=s},function(t,e,r){let s=e[0];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=e[1]},function(t,e,r,s){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=s},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function Td(t,e){let r=[],s=0;function i(){if(s===t.length)throw new Error("Ran out of data");let o=t[s];s++;let a,n,l,u,y,h,_,d;switch(e){default:throw new Error("unrecognised depth");case 16:_=t[s],s++,r.push((o<<8)+_);break;case 4:_=o&15,d=o>>4,r.push(d,_);break;case 2:y=o&3,h=o>>2&3,_=o>>4&3,d=o>>6&3,r.push(d,_,h,y);break;case 1:a=o&1,n=o>>1&1,l=o>>2&1,u=o>>3&1,y=o>>4&1,h=o>>5&1,_=o>>6&1,d=o>>7&1,r.push(d,_,h,y,u,l,n,a);break}}return{get:function(o){for(;r.length<o;)i();let a=r.slice(0,o);return r=r.slice(o),a},resetAfterLine:function(){r.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function Ad(t,e,r,s,i,o){let a=t.width,n=t.height,l=t.index;for(let u=0;u<n;u++)for(let y=0;y<a;y++){let h=r(y,u,l);xd[s](e,i,h,o),o+=s}return o}function Id(t,e,r,s,i,o){let a=t.width,n=t.height,l=t.index;for(let u=0;u<n;u++){for(let y=0;y<a;y++){let h=i.get(s),_=r(y,u,l);kd[s](e,h,_,o)}i.resetAfterLine()}}Ea.dataToBitMap=function(t,e){let r=e.width,s=e.height,i=e.depth,o=e.bpp,a=e.interlace,n;i!==8&&(n=Td(t,i));let l;i<=8?l=Buffer.alloc(r*s*4):l=new Uint16Array(r*s*4);let u=Math.pow(2,i)-1,y=0,h,_;if(a)h=Ca.getImagePasses(r,s),_=Ca.getInterlaceIterator(r,s);else{let d=0;_=function(){let p=d;return d+=4,p},h=[{width:r,height:s}]}for(let d=0;d<h.length;d++)i===8?y=Ad(h[d],l,_,o,t,y):Id(h[d],l,_,o,n,u);if(i===8){if(y!==t.length)throw new Error("extra data found")}else n.end();return l}});var Xi=$((gv,xa)=>{"use strict";function Pd(t,e,r,s,i){let o=0;for(let a=0;a<s;a++)for(let n=0;n<r;n++){let l=i[t[o]];if(!l)throw new Error("index "+t[o]+" not in palette");for(let u=0;u<4;u++)e[o+u]=l[u];o+=4}}function Ld(t,e,r,s,i){let o=0;for(let a=0;a<s;a++)for(let n=0;n<r;n++){let l=!1;if(i.length===1?i[0]===t[o]&&(l=!0):i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2]&&(l=!0),l)for(let u=0;u<4;u++)e[o+u]=0;o+=4}}function Rd(t,e,r,s,i){let o=255,a=Math.pow(2,i)-1,n=0;for(let l=0;l<s;l++)for(let u=0;u<r;u++){for(let y=0;y<4;y++)e[n+y]=Math.floor(t[n+y]*o/a+.5);n+=4}}xa.exports=function(t,e){let r=e.depth,s=e.width,i=e.height,o=e.colorType,a=e.transColor,n=e.palette,l=t;return o===3?Pd(t,l,s,i,n):(a&&Ld(t,l,s,i,a),r!==8&&(r===16&&(l=Buffer.alloc(s*i*4)),Rd(t,l,s,i,r))),l}});var Aa=$((vv,Ta)=>{"use strict";var Bd=se("util"),Qi=se("zlib"),ka=Wi(),Dd=ya(),Od=Zi(),Md=Ki(),Nd=Xi(),Oe=Ta.exports=function(t){ka.call(this),this._parser=new Od(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Bd.inherits(Oe,ka);Oe.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Oe.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Qi.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(r,Qi.Z_MIN_CHUNK);this._inflate=Qi.createInflate({chunkSize:s});let i=r,o=this.emit.bind(this,"error");this._inflate.on("error",function(n){i&&o(n)}),this._filter.on("complete",this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on("data",function(n){i&&(n.length>i&&(n=n.slice(0,i)),i-=n.length,a(n))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Oe.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Dd(this._bitmapInfo)};Oe.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Oe.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Oe.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Oe.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Oe.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Oe.prototype._complete=function(t){if(this.errord)return;let e;try{let r=Md.dataToBitMap(t,this._bitmapInfo);e=Nd(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var Pa=$((yv,Ia)=>{"use strict";var Se=or();Ia.exports=function(t,e,r,s){let i=[Se.COLORTYPE_COLOR_ALPHA,Se.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let p=(function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&p)return t}let o=s.bitDepth!==16?t:new Uint16Array(t.buffer),a=255,n=Se.COLORTYPE_TO_BPP_MAP[s.inputColorType];n===4&&!s.inputHasAlpha&&(n=3);let l=Se.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(a=65535,l*=2);let u=Buffer.alloc(e*r*l),y=0,h=0,_=s.bgColor||{};_.red===void 0&&(_.red=a),_.green===void 0&&(_.green=a),_.blue===void 0&&(_.blue=a);function d(){let p,b,c,v=a;switch(s.inputColorType){case Se.COLORTYPE_COLOR_ALPHA:v=o[y+3],p=o[y],b=o[y+1],c=o[y+2];break;case Se.COLORTYPE_COLOR:p=o[y],b=o[y+1],c=o[y+2];break;case Se.COLORTYPE_ALPHA:v=o[y+1],p=o[y],b=p,c=p;break;case Se.COLORTYPE_GRAYSCALE:p=o[y],b=p,c=p;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(i||(v/=a,p=Math.min(Math.max(Math.round((1-v)*_.red+v*p),0),a),b=Math.min(Math.max(Math.round((1-v)*_.green+v*b),0),a),c=Math.min(Math.max(Math.round((1-v)*_.blue+v*c),0),a))),{red:p,green:b,blue:c,alpha:v}}for(let p=0;p<r;p++)for(let b=0;b<e;b++){let c=d(o,y);switch(s.colorType){case Se.COLORTYPE_COLOR_ALPHA:case Se.COLORTYPE_COLOR:s.bitDepth===8?(u[h]=c.red,u[h+1]=c.green,u[h+2]=c.blue,i&&(u[h+3]=c.alpha)):(u.writeUInt16BE(c.red,h),u.writeUInt16BE(c.green,h+2),u.writeUInt16BE(c.blue,h+4),i&&u.writeUInt16BE(c.alpha,h+6));break;case Se.COLORTYPE_ALPHA:case Se.COLORTYPE_GRAYSCALE:{let v=(c.red+c.green+c.blue)/3;s.bitDepth===8?(u[h]=v,i&&(u[h+1]=c.alpha)):(u.writeUInt16BE(v,h),i&&u.writeUInt16BE(c.alpha,h+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}y+=n,h+=l}return u}});var Ba=$((bv,Ra)=>{"use strict";var La=zi();function Ud(t,e,r,s,i){for(let o=0;o<r;o++)s[i+o]=t[e+o]}function Hd(t,e,r){let s=0,i=e+r;for(let o=e;o<i;o++)s+=Math.abs(t[o]);return s}function Fd(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=t[e+a]-n;s[i+a]=l}}function jd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=t[e+o]-a;i+=Math.abs(n)}return i}function Wd(t,e,r,s,i){for(let o=0;o<r;o++){let a=e>0?t[e+o-r]:0,n=t[e+o]-a;s[i+o]=n}}function $d(t,e,r){let s=0,i=e+r;for(let o=e;o<i;o++){let a=e>0?t[o-r]:0,n=t[o]-a;s+=Math.abs(n)}return s}function qd(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=e>0?t[e+a-r]:0,u=t[e+a]-(n+l>>1);s[i+a]=u}}function zd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=e>0?t[e+o-r]:0,l=t[e+o]-(a+n>>1);i+=Math.abs(l)}return i}function Vd(t,e,r,s,i,o){for(let a=0;a<r;a++){let n=a>=o?t[e+a-o]:0,l=e>0?t[e+a-r]:0,u=e>0&&a>=o?t[e+a-(r+o)]:0,y=t[e+a]-La(n,l,u);s[i+a]=y}}function Gd(t,e,r,s){let i=0;for(let o=0;o<r;o++){let a=o>=s?t[e+o-s]:0,n=e>0?t[e+o-r]:0,l=e>0&&o>=s?t[e+o-(r+s)]:0,u=t[e+o]-La(a,n,l);i+=Math.abs(u)}return i}var Yd={0:Ud,1:Fd,2:Wd,3:qd,4:Vd},Jd={0:Hd,1:jd,2:$d,3:zd,4:Gd};Ra.exports=function(t,e,r,s,i){let o;if(!("filterType"in s)||s.filterType===-1)o=[0,1,2,3,4];else if(typeof s.filterType=="number")o=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(i*=2);let a=e*i,n=0,l=0,u=Buffer.alloc((a+1)*r),y=o[0];for(let h=0;h<r;h++){if(o.length>1){let _=1/0;for(let d=0;d<o.length;d++){let p=Jd[o[d]](t,l,a,i);p<_&&(y=o[d],_=p)}}u[n]=y,n++,Yd[y](t,l,a,u,n,i),n+=a,l+=a}return u}});var en=$((wv,Da)=>{"use strict";var pe=or(),Zd=Ji(),Kd=Pa(),Xd=Ba(),Qd=se("zlib"),lt=Da.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Qd.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:pe.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:pe.COLORTYPE_COLOR_ALPHA,[pe.COLORTYPE_GRAYSCALE,pe.COLORTYPE_COLOR,pe.COLORTYPE_COLOR_ALPHA,pe.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([pe.COLORTYPE_GRAYSCALE,pe.COLORTYPE_COLOR,pe.COLORTYPE_COLOR_ALPHA,pe.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};lt.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};lt.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};lt.prototype.filterData=function(t,e,r){let s=Kd(t,e,r,this._options),i=pe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Xd(s,e,r,this._options,i)};lt.prototype._packChunk=function(t,e){let r=e?e.length:0,s=Buffer.alloc(r+12);return s.writeUInt32BE(r,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(Zd.crc32(s.slice(4,s.length-4)),s.length-4),s};lt.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*pe.GAMMA_DIVISION),0),this._packChunk(pe.TYPE_gAMA,e)};lt.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(pe.TYPE_IHDR,r)};lt.prototype.packIDAT=function(t){return this._packChunk(pe.TYPE_IDAT,t)};lt.prototype.packIEND=function(){return this._packChunk(pe.TYPE_IEND,null)}});var Ua=$((Sv,Na)=>{"use strict";var ef=se("util"),Oa=se("stream"),tf=or(),rf=en(),Ma=Na.exports=function(t){Oa.call(this);let e=t||{};this._packer=new rf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};ef.inherits(Ma,Oa);Ma.prototype.pack=function(t,e,r,s){this.emit("data",Buffer.from(tf.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),s&&this.emit("data",this._packer.packGAMA(s));let i=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var qa=$((Hr,$a)=>{"use strict";var Ha=se("assert").ok,ar=se("zlib"),sf=se("util"),Fa=se("buffer").kMaxLength;function Et(t){if(!(this instanceof Et))return new Et(t);t&&t.chunkSize<ar.Z_MIN_CHUNK&&(t.chunkSize=ar.Z_MIN_CHUNK),ar.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function nf(t){return new Et(t)}function ja(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Et.prototype._processChunk=function(t,e,r){if(typeof r=="function")return ar.Inflate._processChunk.call(this,t,e,r);let s=this,i=t&&t.length,o=this._chunkSize-this._offset,a=this._maxLength,n=0,l=[],u=0,y;this.on("error",function(p){y=p});function h(p,b){if(s._hadError)return;let c=o-b;if(Ha(c>=0,"have should not go down"),c>0){let v=s._buffer.slice(s._offset,s._offset+c);if(s._offset+=c,v.length>a&&(v=v.slice(0,a)),l.push(v),u+=v.length,a-=v.length,a===0)return!1}return(b===0||s._offset>=s._chunkSize)&&(o=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),b===0?(n+=i-p,i=p,!0):!1}Ha(this._handle,"zlib binding closed");let _;do _=this._handle.writeSync(e,t,n,i,this._buffer,this._offset,o),_=_||this._writeState;while(!this._hadError&&h(_[0],_[1]));if(this._hadError)throw y;if(u>=Fa)throw ja(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Fa.toString(16)+" bytes");let d=Buffer.concat(l,u);return ja(this),d};sf.inherits(Et,ar.Inflate);function of(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=ar.Z_FINISH),t._processChunk(e,r)}function Wa(t,e){return of(new Et(e),t)}$a.exports=Hr=Wa;Hr.Inflate=Et;Hr.createInflate=nf;Hr.inflateSync=Wa});var tn=$((Cv,Va)=>{"use strict";var za=Va.exports=function(t){this._buffer=t,this._reads=[]};za.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};za.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Ya=$(Ga=>{"use strict";var af=tn(),cf=Vi();Ga.process=function(t,e){let r=[],s=new af(t);return new cf(e,{read:s.read.bind(s),write:function(o){r.push(o)},complete:function(){}}).start(),s.process(),Buffer.concat(r)}});var Xa=$((xv,Ka)=>{"use strict";var Ja=!0,Za=se("zlib"),lf=qa();Za.deflateSync||(Ja=!1);var hf=tn(),uf=Ya(),df=Zi(),ff=Ki(),pf=Xi();Ka.exports=function(t,e){if(!Ja)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function s(m){r=m}let i;function o(m){i=m}function a(m){i.transColor=m}function n(m){i.palette=m}function l(){i.alpha=!0}let u;function y(m){u=m}let h=[];function _(m){h.push(m)}let d=new hf(t);if(new df(e,{read:d.read.bind(d),error:s,metadata:o,gamma:y,palette:n,transColor:a,inflateData:_,simpleTransparency:l}).start(),d.process(),r)throw r;let b=Buffer.concat(h);h.length=0;let c;if(i.interlace)c=Za.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;c=lf(b,{chunkSize:w,maxLength:w})}if(b=null,!c||!c.length)throw new Error("bad png - invalid inflate data response");let v=uf.process(c,i);b=null;let g=ff.dataToBitMap(v,i);v=null;let f=pf(g,i);return i.data=f,i.gamma=u||0,i}});var rc=$((kv,tc)=>{"use strict";var Qa=!0,ec=se("zlib");ec.deflateSync||(Qa=!1);var _f=or(),mf=en();tc.exports=function(t,e){if(!Qa)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},s=new mf(r),i=[];i.push(Buffer.from(_f.PNG_SIGNATURE)),i.push(s.packIHDR(t.width,t.height)),t.gamma&&i.push(s.packGAMA(t.gamma));let o=s.filterData(t.data,t.width,t.height),a=ec.deflateSync(o,s.getDeflateOptions());if(o=null,!a||!a.length)throw new Error("bad png - invalid compressed data response");return i.push(s.packIDAT(a)),i.push(s.packIEND()),Buffer.concat(i)}});var sc=$(rn=>{"use strict";var gf=Xa(),vf=rc();rn.read=function(t,e){return gf(t,e||{})};rn.write=function(t,e){return vf(t,e)}});var oc=$(nc=>{"use strict";var yf=se("util"),ic=se("stream"),bf=Aa(),wf=Ua(),Sf=sc(),ge=nc.PNG=function(t){ic.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new bf(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new wf(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};yf.inherits(ge,ic);ge.sync=Sf;ge.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};ge.prototype.parse=function(t,e){if(e){let r,s;r=function(i){this.removeListener("error",s),this.data=i,e(null,this)}.bind(this),s=function(i){this.removeListener("parsed",r),e(i,null)}.bind(this),this.once("parsed",r),this.once("error",s)}return this.end(t),this};ge.prototype.write=function(t){return this._parser.write(t),!0};ge.prototype.end=function(t){this._parser.end(t)};ge.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};ge.prototype._gamma=function(t){this.gamma=t};ge.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};ge.bitblt=function(t,e,r,s,i,o,a,n){if(r|=0,s|=0,i|=0,o|=0,a|=0,n|=0,r>t.width||s>t.height||r+i>t.width||s+o>t.height)throw new Error("bitblt reading outside image");if(a>e.width||n>e.height||a+i>e.width||n+o>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<o;l++)t.data.copy(e.data,(n+l)*e.width+a<<2,(s+l)*t.width+r<<2,(s+l)*t.width+r+i<<2)};ge.prototype.bitblt=function(t,e,r,s,i,o,a){return ge.bitblt(this,t,e,r,s,i,o,a),this};ge.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let s=t.width*e+r<<2;for(let i=0;i<3;i++){let o=t.data[s+i]/255;o=Math.pow(o,1/2.2/t.gamma),t.data[s+i]=Math.round(o*255)}}t.gamma=0}};ge.prototype.adjustGamma=function(){ge.adjustGamma(this)}});var Fr=$(xt=>{"use strict";function ac(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(s){return[s,s]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}xt.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,s=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:s,scale:s?4:i,margin:r,color:{dark:ac(e.color.dark||"#000000ff"),light:ac(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};xt.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};xt.getImageWidth=function(e,r){let s=xt.getScale(e,r);return Math.floor((e+r.margin*2)*s)};xt.qrToImageData=function(e,r,s){let i=r.modules.size,o=r.modules.data,a=xt.getScale(i,s),n=Math.floor((i+s.margin*2)*a),l=s.margin*a,u=[s.color.light,s.color.dark];for(let y=0;y<n;y++)for(let h=0;h<n;h++){let _=(y*n+h)*4,d=s.color.light;if(y>=l&&h>=l&&y<n-l&&h<n-l){let p=Math.floor((y-l)/a),b=Math.floor((h-l)/a);d=u[o[p*i+b]?1:0]}e[_++]=d.r,e[_++]=d.g,e[_++]=d.b,e[_]=d.a}}});var cc=$(Me=>{"use strict";var Cf=se("fs"),Ef=oc().PNG,sn=Fr();Me.render=function(e,r){let s=sn.getOptions(r),i=s.rendererOpts,o=sn.getImageWidth(e.modules.size,s);i.width=o,i.height=o;let a=new Ef(i);return sn.qrToImageData(a.data,e,s),a};Me.renderToDataURL=function(e,r,s){typeof s>"u"&&(s=r,r=void 0),Me.renderToBuffer(e,r,function(i,o){i&&s(i);let a="data:image/png;base64,";a+=o.toString("base64"),s(null,a)})};Me.renderToBuffer=function(e,r,s){typeof s>"u"&&(s=r,r=void 0);let i=Me.render(e,r),o=[];i.on("error",s),i.on("data",function(a){o.push(a)}),i.on("end",function(){s(null,Buffer.concat(o))}),i.pack()};Me.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=!1,a=(...l)=>{o||(o=!0,i.apply(null,l))},n=Cf.createWriteStream(e);n.on("error",a),n.on("close",a),Me.renderToFileStream(n,r,s)};Me.renderToFileStream=function(e,r,s){Me.render(r,s).pack().pipe(e)}});var lc=$(ws=>{"use strict";var xf=Fr(),kf={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Tf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Af(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}ws.render=function(t,e,r){let s=xf.getOptions(e),i=kf;(s.color.dark.hex==="#ffffff"||s.color.light.hex==="#000000")&&(i=Tf);let o=t.modules.size,a=t.modules.data,n="",l=Array(o+s.margin*2+1).join(i.WW);l=Array(s.margin/2+1).join(l+`
10
+ `);let u=Array(s.margin+1).join(i.WW);n+=l;for(let y=0;y<o;y+=2){n+=u;for(let h=0;h<o;h++){let _=a[y*o+h],d=a[(y+1)*o+h];n+=Af(_,d,i)}n+=u+`
11
+ `}return n+=l.slice(0,-1),typeof r=="function"&&r(null,n),n};ws.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=se("fs"),a=ws.render(r,s);o.writeFile(e,a,i)}});var uc=$(hc=>{"use strict";hc.render=function(t,e,r){let s=t.modules.size,i=t.modules.data,o="\x1B[40m \x1B[0m",a="\x1B[47m \x1B[0m",n="",l=Array(s+3).join(a),u=Array(2).join(a);n+=l+`
12
12
  `;for(let y=0;y<s;++y){n+=a;for(let h=0;h<s;h++)n+=i[y*s+h]?o:a;n+=u+`
13
13
  `}return n+=l+`
14
- `,typeof r=="function"&&r(null,n),n}});var uc=q(hc=>{"use strict";var Sf="\x1B[47m",Cf="\x1B[40m",tn="\x1B[37m",rn="\x1B[30m",St="\x1B[0m",Ef=Sf+rn,xf=Cf+tn,kf=function(t,e,r){return{"00":St+" "+t,"01":St+e+"\u2584"+t,"02":St+r+"\u2584"+t,10:St+e+"\u2580"+t,11:" ",12:"\u2584",20:St+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},cc=function(t,e,r,s){let i=e+1;if(r>=i||s>=i||s<-1||r<-1)return"0";if(r>=e||s>=e||s<0||r<0)return"1";let o=s*e+r;return t[o]?"2":"1"},lc=function(t,e,r,s){return cc(t,e,r,s)+cc(t,e,r,s+1)};hc.render=function(t,e,r){let s=t.modules.size,i=t.modules.data,o=!!(e&&e.inverse),a=e&&e.inverse?xf:Ef,u=kf(a,o?rn:tn,o?tn:rn),y=St+`
15
- `+a,h=a;for(let _=-1;_<s+1;_+=2){for(let d=-1;d<s;d++)h+=u[lc(i,s,d,_)];h+=u[lc(i,s,s,_)]+y}return h+=St,typeof r=="function"&&r(null,h),h}});var fc=q(dc=>{"use strict";var Tf=ac(),Af=uc();dc.render=function(t,e,r){return e&&e.small?Af.render(t,e,r):Tf.render(t,e,r)}});var nn=q(_c=>{"use strict";var If=Nr();function pc(t,e){let r=t.a/255,s=e+'="'+t.hex+'"';return r<1?s+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':s}function sn(t,e,r){let s=t+e;return typeof r<"u"&&(s+=" "+r),s}function Pf(t,e,r){let s="",i=0,o=!1,a=0;for(let n=0;n<t.length;n++){let l=Math.floor(n%e),u=Math.floor(n/e);!l&&!o&&(o=!0),t[n]?(a++,n>0&&l>0&&t[n-1]||(s+=o?sn("M",l+r,.5+u+r):sn("m",i,0),i=0,o=!1),l+1<e&&t[n+1]||(s+=sn("h",a),a=0)):i++}return s}_c.render=function(e,r,s){let i=If.getOptions(r),o=e.modules.size,a=e.modules.data,n=o+i.margin*2,l=i.color.light.a?"<path "+pc(i.color.light,"fill")+' d="M0 0h'+n+"v"+n+'H0z"/>':"",u="<path "+pc(i.color.dark,"stroke")+' d="'+Pf(a,o,i.margin)+'"/>',y='viewBox="0 0 '+n+" "+n+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+y+' shape-rendering="crispEdges">'+l+u+`</svg>
16
- `;return typeof s=="function"&&s(null,_),_}});var mc=q(ws=>{"use strict";var Lf=nn();ws.render=Lf.render;ws.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=se("fs"),n='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+ws.render(r,s);o.writeFile(e,n,i)}});var gc=q(Ss=>{"use strict";var on=Nr();function Rf(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function Bf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ss.render=function(e,r,s){let i=s,o=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(o=Bf()),i=on.getOptions(i);let a=on.getImageWidth(e.modules.size,i),n=o.getContext("2d"),l=n.createImageData(a,a);return on.qrToImageData(l.data,e,i),Rf(n,o,a),n.putImageData(l,0,0),o};Ss.renderToDataURL=function(e,r,s){let i=s;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let o=Ss.render(e,r,i),a=i.type||"image/png",n=i.rendererOpts||{};return o.toDataURL(a,n.quality)}});var yc=q(Hr=>{"use strict";var Of=yi(),an=Hi(),vc=gc(),Df=nn();function cn(t,e,r,s,i){let o=[].slice.call(arguments,1),a=o.length,n=typeof o[a-1]=="function";if(!n&&!Of())throw new Error("Callback required as last argument");if(n){if(a<2)throw new Error("Too few arguments provided");a===2?(i=r,r=e,e=s=void 0):a===3&&(e.getContext&&typeof i>"u"?(i=s,s=void 0):(i=s,s=r,r=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(r=e,e=s=void 0):a===2&&!e.getContext&&(s=r,r=e,e=void 0),new Promise(function(l,u){try{let y=an.create(r,s);l(t(y,e,s))}catch(y){u(y)}})}try{let l=an.create(r,s);i(null,t(l,e,s))}catch(l){i(l)}}Hr.create=an.create;Hr.toCanvas=cn.bind(null,vc.render);Hr.toDataURL=cn.bind(null,vc.renderToDataURL);Hr.toString=cn.bind(null,function(t,e,r){return Df.render(t,r)})});var Cc=q(at=>{"use strict";var bc=yi(),ln=Hi(),Mf=ic(),wc=nc(),Nf=fc(),Sc=mc();function Ur(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(bc())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function Hf(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Cs(t){switch(t){case"svg":return Sc;case"txt":case"utf8":return wc;default:return Mf}}function Uf(t){switch(t){case"svg":return Sc;case"terminal":return Nf;default:return wc}}function Fr(t,e,r){if(!r.cb)return new Promise(function(s,i){try{let o=ln.create(e,r.opts);return t(o,r.opts,function(a,n){return a?i(a):s(n)})}catch(o){i(o)}});try{let s=ln.create(e,r.opts);return t(s,r.opts,r.cb)}catch(s){r.cb(s)}}at.create=ln.create;at.toCanvas=yc().toCanvas;at.toString=function(e,r,s){let i=Ur(e,r,s),o=i.opts?i.opts.type:void 0,a=Uf(o);return Fr(a.render,e,i)};at.toDataURL=function(e,r,s){let i=Ur(e,r,s),o=Cs(i.opts.type);return Fr(o.renderToDataURL,e,i)};at.toBuffer=function(e,r,s){let i=Ur(e,r,s),o=Cs(i.opts.type);return Fr(o.renderToBuffer,e,i)};at.toFile=function(e,r,s,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!bc())throw new Error("Too few arguments provided");let o=Ur(r,s,i),a=o.opts.type||Hf(e),l=Cs(a).renderToFile.bind(null,e);return Fr(l,r,o)};at.toFileStream=function(e,r,s){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Ur(r,s,e.emit.bind(e,"error")),a=Cs("png").renderToFileStream.bind(null,e);Fr(a,r,i)}});var xc=q((Iv,Ec)=>{"use strict";Ec.exports=Cc()});import{readFileSync as Ac,writeFileSync as Gf,renameSync as Yf,readdirSync as Jf,existsSync as Ic,rmSync as Zf}from"fs";function Pc(t,e){Qe(t);let r=os(t,e.sessionId),s=`${r}.${process.pid}.tmp`;Gf(s,JSON.stringify(e,null,2),{mode:384}),Yf(s,r)}function Ct(t,e){let r=os(t,e);if(Ic(r))return JSON.parse(Ac(r,"utf8"))}function dn(t){let e=Zt(t);return Ic(e)?Jf(e).filter(r=>r.endsWith(".json")).map(r=>JSON.parse(Ac(`${e}/${r}`,"utf8"))):[]}function Es(t,e){Zf(os(t,e),{force:!0})}function Et(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var jr=mt(()=>{"use strict";ye()});import{spawn as Kf}from"child_process";import{openSync as Xf,closeSync as Qf}from"fs";import{randomUUID as ep}from"crypto";function tp(t){let e=["__worker","--session-id",t.sessionId,"--cwd",t.cwd,"--adapter",t.adapterId,"--mode",t.mode,"--origin",t.origin];return t.label&&e.push("--label",t.label),t.aiCliArgs.length>0&&e.push("--",...t.aiCliArgs),e}function ip(t){return new Promise(e=>setTimeout(e,t))}function ar(t,e){let r=[...process.execArgv],s=r.some(i=>i.includes("tsx"));return t.endsWith(".ts")&&!s&&r.push("--import","tsx"),[...r,t,...e]}async function fn(t,e){let r=e.sessionId??ep(),s=tp({sessionId:r,cwd:e.cwd,adapterId:e.adapterId,mode:e.mode,origin:e.origin,aiCliArgs:e.aiCliArgs,label:e.label}),i=t.timeoutMs??rp,o=Date.now(),a=Xf(co(t.dir,r),"a"),n;try{n=Kf(process.execPath,ar(t.entry,s),{detached:!0,stdio:["ignore",a,a],env:process.env}),n.unref()}finally{Qf(a)}let l,u=y=>{l=y};n.on("exit",u);try{let y=o+i;for(;;){if(l!==void 0)throw new Error(`worker exited during startup (code ${l})`);let h=Ct(t.dir,r);if(h&&h.pid===n.pid&&h.startedAtMs>=o)return{sessionId:r};if(Date.now()>=y)return process.stderr.write(`[djinn] forkWorker: worker ${r} readiness unverified after ${i}ms (best-effort, treating as started)
17
- `),{sessionId:r};await ip(sp)}}finally{n.off("exit",u)}}var rp,sp,xs=mt(()=>{"use strict";ye();jr();rp=2500,sp=50});var Je=q((f1,rl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");rl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Jr=q((p1,Hs)=>{"use strict";var{EMPTY_BUFFER:X_}=Je(),yn=Buffer[Symbol.species];function Q_(t,e){if(t.length===0)return X_;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,s),s+=o.length}return s<e?new yn(r.buffer,r.byteOffset,s):r}function sl(t,e,r,s,i){for(let o=0;o<i;o++)r[s+o]=t[o]^e[o&3]}function il(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function em(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function bn(t){if(bn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new yn(t):ArrayBuffer.isView(t)?e=new yn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),bn.readOnly=!1),e}Hs.exports={concat:Q_,mask:sl,toArrayBuffer:em,toBuffer:bn,unmask:il};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=se("bufferutil");Hs.exports.mask=function(e,r,s,i,o){o<48?sl(e,r,s,i,o):t.mask(e,r,s,i,o)},Hs.exports.unmask=function(e,r){e.length<32?il(e,r):t.unmask(e,r)}}catch{}});var al=q((_1,ol)=>{"use strict";var nl=Symbol("kDone"),wn=Symbol("kRun"),Sn=class{constructor(e){this[nl]=()=>{this.pending--,this[wn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wn]()}[wn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[nl])}}};ol.exports=Sn});var yr=q((m1,ul)=>{"use strict";var Zr=se("zlib"),cl=Jr(),tm=al(),{kStatusCode:ll}=Je(),rm=Buffer[Symbol.species],sm=Buffer.from([0,0,255,255]),Fs=Symbol("permessage-deflate"),Ze=Symbol("total-length"),gr=Symbol("callback"),ft=Symbol("buffers"),vr=Symbol("error"),Us,Cn=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Us){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Us=new tm(r)}}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[gr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let i=r[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 o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else if(s==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=o}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}"`);r[s]=i})}),e}decompress(e,r,s){Us.add(i=>{this._decompress(e,r,(o,a)=>{i(),s(o,a)})})}compress(e,r,s){Us.add(i=>{this._compress(e,r,(o,a)=>{i(),s(o,a)})})}_decompress(e,r,s){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Zr.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Zr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Fs]=this,this._inflate[Ze]=0,this._inflate[ft]=[],this._inflate.on("error",nm),this._inflate.on("data",hl)}this._inflate[gr]=s,this._inflate.write(e),r&&this._inflate.write(sm),this._inflate.flush(()=>{let o=this._inflate[vr];if(o){this._inflate.close(),this._inflate=null,s(o);return}let a=cl.concat(this._inflate[ft],this._inflate[Ze]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ze]=0,this._inflate[ft]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),s(null,a)})}_compress(e,r,s){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Zr.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Zr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Ze]=0,this._deflate[ft]=[],this._deflate.on("data",im)}this._deflate[gr]=s,this._deflate.write(e),this._deflate.flush(Zr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=cl.concat(this._deflate[ft],this._deflate[Ze]);r&&(o=new rm(o.buffer,o.byteOffset,o.length-4)),this._deflate[gr]=null,this._deflate[Ze]=0,this._deflate[ft]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};ul.exports=Cn;function im(t){this[ft].push(t),this[Ze]+=t.length}function hl(t){if(this[Ze]+=t.length,this[Fs]._maxPayload<1||this[Ze]<=this[Fs]._maxPayload){this[ft].push(t);return}this[vr]=new RangeError("Max payload size exceeded"),this[vr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[vr][ll]=1009,this.removeListener("data",hl),this.reset()}function nm(t){if(this[Fs]._inflate=null,this[vr]){this[gr](this[vr]);return}t[ll]=1007,this[gr](t)}});var br=q((g1,js)=>{"use strict";var{isUtf8:dl}=se("buffer"),{hasBlob:om}=Je(),am=[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 cm(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function En(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function lm(t){return om&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}js.exports={isBlob:lm,isValidStatusCode:cm,isValidUTF8:En,tokenChars:am};if(dl)js.exports.isValidUTF8=function(t){return t.length<24?En(t):dl(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=se("utf-8-validate");js.exports.isValidUTF8=function(e){return e.length<32?En(e):t(e)}}catch{}});var In=q((v1,yl)=>{"use strict";var{Writable:hm}=se("stream"),fl=yr(),{BINARY_TYPES:um,EMPTY_BUFFER:pl,kStatusCode:dm,kWebSocket:fm}=Je(),{concat:xn,toArrayBuffer:pm,unmask:_m}=Jr(),{isValidStatusCode:mm,isValidUTF8:_l}=br(),Ws=Buffer[Symbol.species],ke=0,ml=1,gl=2,vl=3,kn=4,Tn=5,qs=6,An=class extends hm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||um[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[fm]=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=ke}_write(e,r,s){if(this._opcode===8&&this._state==ke)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 Ws(s.buffer,s.byteOffset+e,s.length-e),new Ws(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],i=r.length-e;e>=s.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),i),this._buffers[0]=new Ws(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ke:this.getInfo(e);break;case ml:this.getPayloadLength16(e);break;case gl:this.getPayloadLength64(e);break;case vl:this.getMask();break;case kn:this.getData(e);break;case Tn:case qs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[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=(r[0]&64)===64;if(s&&!this._extensions[fl.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[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=(r[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=ml:this._payloadLength===127?this._state=gl: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 r=this.consume(8),s=r.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)+r.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 r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=vl:this._state=kn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=kn}getData(e){let r=pl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&_m(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Tn,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[fl.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return r(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(o)}this.dataMessage(r),this._state===ke&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ke;return}let r=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=xn(s,r):this._binaryType==="arraybuffer"?i=pm(xn(s,r)):this._binaryType==="blob"?i=new Blob(s):i=s,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=ke):(this._state=qs,setImmediate(()=>{this.emit("message",i,!0),this._state=ke,this.startLoop(e)}))}else{let i=xn(s,r);if(!this._skipUTF8Validation&&!_l(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Tn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=ke):(this._state=qs,setImmediate(()=>{this.emit("message",i,!1),this._state=ke,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pl),this.end();else{let s=e.readUInt16BE(0);if(!mm(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let i=new Ws(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_l(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,i),this.end()}this._state=ke;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ke):(this._state=qs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ke,this.startLoop(r)}))}createError(e,r,s,i,o){this._loop=!1,this._errored=!0;let a=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=o,a[dm]=i,a}};yl.exports=An});var Rn=q((b1,Sl)=>{"use strict";var{Duplex:y1}=se("stream"),{randomFillSync:gm}=se("crypto"),bl=yr(),{EMPTY_BUFFER:vm,kWebSocket:ym,NOOP:bm}=Je(),{isBlob:wr,isValidStatusCode:wm}=br(),{mask:wl,toBuffer:Wt}=Jr(),Te=Symbol("kByteLength"),Sm=Buffer.alloc(4),$s=8*1024,qt,Sr=$s,Re=0,Cm=1,Em=2,Pn=class t{constructor(e,r,s){this._extensions=r||{},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=Re,this.onerror=bm,this[ym]=void 0}static frame(e,r){let s,i=!1,o=2,a=!1;r.mask&&(s=r.maskBuffer||Sm,r.generateMask?r.generateMask(s):(Sr===$s&&(qt===void 0&&(qt=Buffer.alloc($s)),gm(qt,0,$s),Sr=0),s[0]=qt[Sr++],s[1]=qt[Sr++],s[2]=qt[Sr++],s[3]=qt[Sr++]),a=(s[0]|s[1]|s[2]|s[3])===0,o=6);let n;typeof e=="string"?(!r.mask||a)&&r[Te]!==void 0?n=r[Te]:(e=Buffer.from(e),n=e.length):(n=e.length,i=r.mask&&r.readOnly&&!a);let l=n;n>=65536?(o+=8,l=127):n>125&&(o+=2,l=126);let u=Buffer.allocUnsafe(i?n+o:o);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(n,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(n,4,6)),r.mask?(u[1]|=128,u[o-4]=s[0],u[o-3]=s[1],u[o-2]=s[2],u[o-1]=s[3],a?[u,e]:i?(wl(e,s,u,o,n),[u]):(wl(e,s,e,0,n),[u,e])):[u,e]}close(e,r,s,i){let o;if(e===void 0)o=vm;else{if(typeof e!="number"||!wm(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let n=Buffer.byteLength(r);if(n>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+n),o.writeUInt16BE(e,0),typeof r=="string"?o.write(r,2):o.set(r,2)}}let a={[Te]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Re?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(t.frame(o,a),i)}ping(e,r,s){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):wr(e)?(i=e.size,o=!1):(e=Wt(e),i=e.length,o=Wt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Te]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};wr(e)?this._state!==Re?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Re?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(t.frame(e,a),s)}pong(e,r,s){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):wr(e)?(i=e.size,o=!1):(e=Wt(e),i=e.length,o=Wt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Te]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};wr(e)?this._state!==Re?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Re?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(t.frame(e,a),s)}send(e,r,s){let i=this._extensions[bl.extensionName],o=r.binary?2:1,a=r.compress,n,l;typeof e=="string"?(n=Buffer.byteLength(e),l=!1):wr(e)?(n=e.size,l=!1):(e=Wt(e),n=e.length,l=Wt.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=i._threshold),this._compress=a):(a=!1,o=0),r.fin&&(this._firstFragment=!0);let u={[Te]:n,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:l,rsv1:a};wr(e)?this._state!==Re?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==Re?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,r,s,i){this._bufferedBytes+=s[Te],this._state=Em,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let n=new Error("The socket was closed while the blob was being read");process.nextTick(Ln,this,n,i);return}this._bufferedBytes-=s[Te];let a=Wt(o);r?this.dispatch(a,r,s,i):(this._state=Re,this.sendFrame(t.frame(a,s),i),this.dequeue())}).catch(o=>{process.nextTick(xm,this,o,i)})}dispatch(e,r,s,i){if(!r){this.sendFrame(t.frame(e,s),i);return}let o=this._extensions[bl.extensionName];this._bufferedBytes+=s[Te],this._state=Cm,o.compress(e,s.fin,(a,n)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ln(this,l,i);return}this._bufferedBytes-=s[Te],this._state=Re,s.readOnly=!1,this.sendFrame(t.frame(n,s),i),this.dequeue()})}dequeue(){for(;this._state===Re&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Te],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Te],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Sl.exports=Pn;function Ln(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let i=t._queue[s],o=i[i.length-1];typeof o=="function"&&o(e)}}function xm(t,e,r){Ln(t,e,r),t.onerror(e)}});var Ll=q((w1,Pl)=>{"use strict";var{kForOnEventAttribute:Kr,kListener:Bn}=Je(),Cl=Symbol("kCode"),El=Symbol("kData"),xl=Symbol("kError"),kl=Symbol("kMessage"),Tl=Symbol("kReason"),Cr=Symbol("kTarget"),Al=Symbol("kType"),Il=Symbol("kWasClean"),Ke=class{constructor(e){this[Cr]=null,this[Al]=e}get target(){return this[Cr]}get type(){return this[Al]}};Object.defineProperty(Ke.prototype,"target",{enumerable:!0});Object.defineProperty(Ke.prototype,"type",{enumerable:!0});var $t=class extends Ke{constructor(e,r={}){super(e),this[Cl]=r.code===void 0?0:r.code,this[Tl]=r.reason===void 0?"":r.reason,this[Il]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Cl]}get reason(){return this[Tl]}get wasClean(){return this[Il]}};Object.defineProperty($t.prototype,"code",{enumerable:!0});Object.defineProperty($t.prototype,"reason",{enumerable:!0});Object.defineProperty($t.prototype,"wasClean",{enumerable:!0});var Er=class extends Ke{constructor(e,r={}){super(e),this[xl]=r.error===void 0?null:r.error,this[kl]=r.message===void 0?"":r.message}get error(){return this[xl]}get message(){return this[kl]}};Object.defineProperty(Er.prototype,"error",{enumerable:!0});Object.defineProperty(Er.prototype,"message",{enumerable:!0});var Xr=class extends Ke{constructor(e,r={}){super(e),this[El]=r.data===void 0?null:r.data}get data(){return this[El]}};Object.defineProperty(Xr.prototype,"data",{enumerable:!0});var km={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[Kr]&&i[Bn]===e&&!i[Kr])return;let s;if(t==="message")s=function(o,a){let n=new Xr("message",{data:a?o:o.toString()});n[Cr]=this,zs(e,this,n)};else if(t==="close")s=function(o,a){let n=new $t("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[Cr]=this,zs(e,this,n)};else if(t==="error")s=function(o){let a=new Er("error",{error:o,message:o.message});a[Cr]=this,zs(e,this,a)};else if(t==="open")s=function(){let o=new Ke("open");o[Cr]=this,zs(e,this,o)};else return;s[Kr]=!!r[Kr],s[Bn]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Bn]===e&&!r[Kr]){this.removeListener(t,r);break}}};Pl.exports={CloseEvent:$t,ErrorEvent:Er,Event:Ke,EventTarget:km,MessageEvent:Xr};function zs(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Vs=q((S1,Rl)=>{"use strict";var{tokenChars:Qr}=br();function je(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Tm(t){let e=Object.create(null),r=Object.create(null),s=!1,i=!1,o=!1,a,n,l=-1,u=-1,y=-1,h=0;for(;h<t.length;h++)if(u=t.charCodeAt(h),a===void 0)if(y===-1&&Qr[u]===1)l===-1&&(l=h);else if(h!==0&&(u===32||u===9))y===-1&&l!==-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h);let d=t.slice(l,y);u===44?(je(e,d,r),r=Object.create(null)):a=d,l=y=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(n===void 0)if(y===-1&&Qr[u]===1)l===-1&&(l=h);else if(u===32||u===9)y===-1&&l!==-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h),je(r,t.slice(l,y),!0),u===44&&(je(e,a,r),r=Object.create(null),a=void 0),l=y=-1}else if(u===61&&l!==-1&&y===-1)n=t.slice(l,h),l=y=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(i){if(Qr[u]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:s||(s=!0),i=!1}else if(o)if(Qr[u]===1)l===-1&&(l=h);else if(u===34&&l!==-1)o=!1,y=h;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(u===34&&t.charCodeAt(h-1)===61)o=!0;else if(y===-1&&Qr[u]===1)l===-1&&(l=h);else if(l!==-1&&(u===32||u===9))y===-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h);let d=t.slice(l,y);s&&(d=d.replace(/\\/g,""),s=!1),je(r,n,d),u===44&&(je(e,a,r),r=Object.create(null),a=void 0),n=void 0,l=y=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(l===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");y===-1&&(y=h);let _=t.slice(l,y);return a===void 0?je(e,_,r):(n===void 0?je(r,_,!0):s?je(r,n,_.replace(/\\/g,"")):je(r,n,_),je(e,a,r)),e}function Am(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(i=>{let o=s[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Rl.exports={format:Am,parse:Tm}});var Zs=q((x1,$l)=>{"use strict";var Im=se("events"),Pm=se("https"),Lm=se("http"),Dl=se("net"),Rm=se("tls"),{randomBytes:Bm,createHash:Om}=se("crypto"),{Duplex:C1,Readable:E1}=se("stream"),{URL:On}=se("url"),pt=yr(),Dm=In(),Mm=Rn(),{isBlob:Nm}=br(),{BINARY_TYPES:Bl,CLOSE_TIMEOUT:Hm,EMPTY_BUFFER:Gs,GUID:Um,kForOnEventAttribute:Dn,kListener:Fm,kStatusCode:jm,kWebSocket:de,NOOP:Ml}=Je(),{EventTarget:{addEventListener:Wm,removeEventListener:qm}}=Ll(),{format:$m,parse:zm}=Vs(),{toBuffer:Vm}=Jr(),Nl=Symbol("kAborted"),Mn=[8,13],Xe=["CONNECTING","OPEN","CLOSING","CLOSED"],Gm=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ce=class t extends Im{constructor(e,r,s){super(),this._binaryType=Bl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Gs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),Hl(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Bl.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,r,s){let i=new Dm({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new Mm(e,this._extensions,s.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[de]=this,o[de]=this,e[de]=this,i.on("conclude",Zm),i.on("drain",Km),i.on("error",Xm),i.on("message",Qm),i.on("ping",eg),i.on("pong",tg),o.onerror=rg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",jl),e.on("data",Js),e.on("end",Wl),e.on("error",ql),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){be(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Fl(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Nn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Gs,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Nn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Gs,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Nn(this,e,s);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[pt.extensionName]||(i.compress=!1),this._sender.send(e||Gs,i,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){be(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ce,"CONNECTING",{enumerable:!0,value:Xe.indexOf("CONNECTING")});Object.defineProperty(ce.prototype,"CONNECTING",{enumerable:!0,value:Xe.indexOf("CONNECTING")});Object.defineProperty(ce,"OPEN",{enumerable:!0,value:Xe.indexOf("OPEN")});Object.defineProperty(ce.prototype,"OPEN",{enumerable:!0,value:Xe.indexOf("OPEN")});Object.defineProperty(ce,"CLOSING",{enumerable:!0,value:Xe.indexOf("CLOSING")});Object.defineProperty(ce.prototype,"CLOSING",{enumerable:!0,value:Xe.indexOf("CLOSING")});Object.defineProperty(ce,"CLOSED",{enumerable:!0,value:Xe.indexOf("CLOSED")});Object.defineProperty(ce.prototype,"CLOSED",{enumerable:!0,value:Xe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ce.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ce.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Dn])return e[Fm];return null},set(e){for(let r of this.listeners(t))if(r[Dn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Dn]:!0})}})});ce.prototype.addEventListener=Wm;ce.prototype.removeEventListener=qm;$l.exports=ce;function Hl(t,e,r,s){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Hm,protocolVersion:Mn[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(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Mn.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Mn.join(", ")})`);let o;if(e instanceof On)o=e;else try{o=new On(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let a=o.protocol==="wss:",n=o.protocol==="ws+unix:",l;if(o.protocol!=="ws:"&&!a&&!n?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:n&&!o.pathname?l="The URL's pathname is empty":o.hash&&(l="The URL contains a fragment identifier"),l){let b=new SyntaxError(l);if(t._redirects===0)throw b;Ys(t,b);return}let u=a?443:80,y=Bm(16).toString("base64"),h=a?Pm.request:Lm.request,_=new Set,d;if(i.createConnection=i.createConnection||(a?Jm:Ym),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":y,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new pt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=$m({[pt.extensionName]:d.offer()})),r.length){for(let b of r){if(typeof b!="string"||!Gm.test(b)||_.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(b)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),n){let b=i.path.split(":");i.socketPath=b[0],i.path=b[1]}let p;if(i.followRedirects){if(t._redirects===0){t._originalIpc=n,t._originalSecure=a,t._originalHostOrSocketPath=n?i.socketPath:o.host;let b=s&&s.headers;if(s={...s,headers:{}},b)for(let[c,v]of Object.entries(b))s.headers[c.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let b=n?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!b||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,b||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=t._req=h(i),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=h(i);i.timeout&&p.on("timeout",()=>{be(t,p,"Opening handshake has timed out")}),p.on("error",b=>{p===null||p[Nl]||(p=t._req=null,Ys(t,b))}),p.on("response",b=>{let c=b.headers.location,v=b.statusCode;if(c&&i.followRedirects&&v>=300&&v<400){if(++t._redirects>i.maxRedirects){be(t,p,"Maximum redirects exceeded");return}p.abort();let g;try{g=new On(c,e)}catch{let m=new SyntaxError(`Invalid URL: ${c}`);Ys(t,m);return}Hl(t,g,r,s)}else t.emit("unexpected-response",p,b)||be(t,p,`Unexpected server response: ${b.statusCode}`)}),p.on("upgrade",(b,c,v)=>{if(t.emit("upgrade",b),t.readyState!==ce.CONNECTING)return;p=t._req=null;let g=b.headers.upgrade;if(g===void 0||g.toLowerCase()!=="websocket"){be(t,c,"Invalid Upgrade header");return}let f=Om("sha1").update(y+Um).digest("base64");if(b.headers["sec-websocket-accept"]!==f){be(t,c,"Invalid Sec-WebSocket-Accept header");return}let m=b.headers["sec-websocket-protocol"],w;if(m!==void 0?_.size?_.has(m)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":_.size&&(w="Server sent no subprotocol"),w){be(t,c,w);return}m&&(t._protocol=m);let C=b.headers["sec-websocket-extensions"];if(C!==void 0){if(!d){be(t,c,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=zm(C)}catch{be(t,c,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(k);if(A.length!==1||A[0]!==pt.extensionName){be(t,c,"Server indicated an extension that was not requested");return}try{d.accept(k[pt.extensionName])}catch{be(t,c,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[pt.extensionName]=d}t.setSocket(c,v,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(p,t):p.end()}function Ys(t,e){t._readyState=ce.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ym(t){return t.path=t.socketPath,Dl.connect(t)}function Jm(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Dl.isIP(t.host)?"":t.host),Rm.connect(t)}function be(t,e,r){t._readyState=ce.CLOSING;let s=new Error(r);Error.captureStackTrace(s,be),e.setHeader?(e[Nl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ys,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Nn(t,e,r){if(e){let s=Nm(e)?e.size:Vm(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${Xe[t.readyState]})`);process.nextTick(r,s)}}function Zm(t,e){let r=this[de];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[de]!==void 0&&(r._socket.removeListener("data",Js),process.nextTick(Ul,r._socket),t===1005?r.close():r.close(t,e))}function Km(){let t=this[de];t.isPaused||t._socket.resume()}function Xm(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",Js),process.nextTick(Ul,e._socket),e.close(t[jm])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Ol(){this[de].emitClose()}function Qm(t,e){this[de].emit("message",t,e)}function eg(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,Ml),e.emit("ping",t)}function tg(t){this[de].emit("pong",t)}function Ul(t){t.resume()}function rg(t){let e=this[de];e.readyState!==ce.CLOSED&&(e.readyState===ce.OPEN&&(e._readyState=ce.CLOSING,Fl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Fl(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function jl(){let t=this[de];if(this.removeListener("close",jl),this.removeListener("data",Js),this.removeListener("end",Wl),t._readyState=ce.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Ol),t._receiver.on("finish",Ol))}function Js(t){this[de]._receiver.write(t)||this.pause()}function Wl(){let t=this[de];t._readyState=ce.CLOSING,t._receiver.end(),this.end()}function ql(){let t=this[de];this.removeListener("error",ql),this.on("error",Ml),t&&(t._readyState=ce.CLOSING,this.destroy())}});var Yl=q((T1,Gl)=>{"use strict";var k1=Zs(),{Duplex:sg}=se("stream");function zl(t){t.emit("close")}function ig(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(t){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function ng(t,e){let r=!0,s=new sg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,a){let n=!a&&s._readableState.objectMode?o.toString():o;s.push(n)||t.pause()}),t.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(zl,s);return}let a=!1;t.once("error",function(l){a=!0,o(l)}),t.once("close",function(){a||o(i),process.nextTick(zl,s)}),r&&t.terminate()},s._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(i,o,a){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(i,o,a)});return}t.send(i,a)},s.on("end",ig),s.on("error",Vl),s}Gl.exports=ng});var Hn=q((A1,Jl)=>{"use strict";var{tokenChars:og}=br();function ag(t){let e=new Set,r=-1,s=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(s===-1&&og[a]===1)r===-1&&(r=i);else if(i!==0&&(a===32||a===9))s===-1&&r!==-1&&(s=i);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);s===-1&&(s=i);let n=t.slice(r,s);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);e.add(n),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Jl.exports={parse:ag}});var rh=q((P1,th)=>{"use strict";var cg=se("events"),Ks=se("http"),{Duplex:I1}=se("stream"),{createHash:lg}=se("crypto"),Zl=Vs(),zt=yr(),hg=Hn(),ug=Zs(),{CLOSE_TIMEOUT:dg,GUID:fg,kWebSocket:pg}=Je(),_g=/^[+/0-9A-Za-z]{22}==$/,Kl=0,Xl=1,eh=2,Un=class extends cg{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:dg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ug,...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=Ks.createServer((s,i)=>{let o=Ks.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=mg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Kl}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===eh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(es,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(es,this):process.nextTick(es,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{es(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,i){r.on("error",Ql);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Vt(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Vt(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!_g.test(o)){Vt(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(n!==13&&n!==8){Vt(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ts(r,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=hg.parse(l)}catch{Vt(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let y=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&y!==void 0){let _=new zt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let d=Zl.parse(y);d[zt.extensionName]&&(_.accept(d[zt.extensionName]),h[zt.extensionName]=_)}catch{Vt(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${n===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(d,p,b,c)=>{if(!d)return ts(r,p||401,b,c);this.completeUpgrade(h,o,u,e,r,s,i)});return}if(!this.options.verifyClient(_))return ts(r,401)}this.completeUpgrade(h,o,u,e,r,s,i)}completeUpgrade(e,r,s,i,o,a,n){if(!o.readable||!o.writable)return o.destroy();if(o[pg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kl)return ts(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lg("sha1").update(r+fg).digest("base64")}`],y=new this.options.WebSocket(null,void 0,this.options);if(s.size){let h=this.options.handleProtocols?this.options.handleProtocols(s,i):s.values().next().value;h&&(u.push(`Sec-WebSocket-Protocol: ${h}`),y._protocol=h)}if(e[zt.extensionName]){let h=e[zt.extensionName].params,_=Zl.format({[zt.extensionName]:[h]});u.push(`Sec-WebSocket-Extensions: ${_}`),y._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
14
+ `,typeof r=="function"&&r(null,n),n}});var _c=$(pc=>{"use strict";var If="\x1B[47m",Pf="\x1B[40m",nn="\x1B[37m",on="\x1B[30m",kt="\x1B[0m",Lf=If+on,Rf=Pf+nn,Bf=function(t,e,r){return{"00":kt+" "+t,"01":kt+e+"\u2584"+t,"02":kt+r+"\u2584"+t,10:kt+e+"\u2580"+t,11:" ",12:"\u2584",20:kt+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},dc=function(t,e,r,s){let i=e+1;if(r>=i||s>=i||s<-1||r<-1)return"0";if(r>=e||s>=e||s<0||r<0)return"1";let o=s*e+r;return t[o]?"2":"1"},fc=function(t,e,r,s){return dc(t,e,r,s)+dc(t,e,r,s+1)};pc.render=function(t,e,r){let s=t.modules.size,i=t.modules.data,o=!!(e&&e.inverse),a=e&&e.inverse?Rf:Lf,u=Bf(a,o?on:nn,o?nn:on),y=kt+`
15
+ `+a,h=a;for(let _=-1;_<s+1;_+=2){for(let d=-1;d<s;d++)h+=u[fc(i,s,d,_)];h+=u[fc(i,s,s,_)]+y}return h+=kt,typeof r=="function"&&r(null,h),h}});var gc=$(mc=>{"use strict";var Df=uc(),Of=_c();mc.render=function(t,e,r){return e&&e.small?Of.render(t,e,r):Df.render(t,e,r)}});var cn=$(yc=>{"use strict";var Mf=Fr();function vc(t,e){let r=t.a/255,s=e+'="'+t.hex+'"';return r<1?s+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':s}function an(t,e,r){let s=t+e;return typeof r<"u"&&(s+=" "+r),s}function Nf(t,e,r){let s="",i=0,o=!1,a=0;for(let n=0;n<t.length;n++){let l=Math.floor(n%e),u=Math.floor(n/e);!l&&!o&&(o=!0),t[n]?(a++,n>0&&l>0&&t[n-1]||(s+=o?an("M",l+r,.5+u+r):an("m",i,0),i=0,o=!1),l+1<e&&t[n+1]||(s+=an("h",a),a=0)):i++}return s}yc.render=function(e,r,s){let i=Mf.getOptions(r),o=e.modules.size,a=e.modules.data,n=o+i.margin*2,l=i.color.light.a?"<path "+vc(i.color.light,"fill")+' d="M0 0h'+n+"v"+n+'H0z"/>':"",u="<path "+vc(i.color.dark,"stroke")+' d="'+Nf(a,o,i.margin)+'"/>',y='viewBox="0 0 '+n+" "+n+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+y+' shape-rendering="crispEdges">'+l+u+`</svg>
16
+ `;return typeof s=="function"&&s(null,_),_}});var bc=$(Ss=>{"use strict";var Uf=cn();Ss.render=Uf.render;Ss.renderToFile=function(e,r,s,i){typeof i>"u"&&(i=s,s=void 0);let o=se("fs"),n='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+Ss.render(r,s);o.writeFile(e,n,i)}});var wc=$(Cs=>{"use strict";var ln=Fr();function Hf(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function Ff(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Cs.render=function(e,r,s){let i=s,o=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(o=Ff()),i=ln.getOptions(i);let a=ln.getImageWidth(e.modules.size,i),n=o.getContext("2d"),l=n.createImageData(a,a);return ln.qrToImageData(l.data,e,i),Hf(n,o,a),n.putImageData(l,0,0),o};Cs.renderToDataURL=function(e,r,s){let i=s;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let o=Cs.render(e,r,i),a=i.type||"image/png",n=i.rendererOpts||{};return o.toDataURL(a,n.quality)}});var Cc=$(jr=>{"use strict";var jf=Si(),hn=ji(),Sc=wc(),Wf=cn();function un(t,e,r,s,i){let o=[].slice.call(arguments,1),a=o.length,n=typeof o[a-1]=="function";if(!n&&!jf())throw new Error("Callback required as last argument");if(n){if(a<2)throw new Error("Too few arguments provided");a===2?(i=r,r=e,e=s=void 0):a===3&&(e.getContext&&typeof i>"u"?(i=s,s=void 0):(i=s,s=r,r=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(r=e,e=s=void 0):a===2&&!e.getContext&&(s=r,r=e,e=void 0),new Promise(function(l,u){try{let y=hn.create(r,s);l(t(y,e,s))}catch(y){u(y)}})}try{let l=hn.create(r,s);i(null,t(l,e,s))}catch(l){i(l)}}jr.create=hn.create;jr.toCanvas=un.bind(null,Sc.render);jr.toDataURL=un.bind(null,Sc.renderToDataURL);jr.toString=un.bind(null,function(t,e,r){return Wf.render(t,r)})});var Tc=$(ht=>{"use strict";var Ec=Si(),dn=ji(),$f=cc(),xc=lc(),qf=gc(),kc=bc();function Wr(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(Ec())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function zf(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Es(t){switch(t){case"svg":return kc;case"txt":case"utf8":return xc;default:return $f}}function Vf(t){switch(t){case"svg":return kc;case"terminal":return qf;default:return xc}}function $r(t,e,r){if(!r.cb)return new Promise(function(s,i){try{let o=dn.create(e,r.opts);return t(o,r.opts,function(a,n){return a?i(a):s(n)})}catch(o){i(o)}});try{let s=dn.create(e,r.opts);return t(s,r.opts,r.cb)}catch(s){r.cb(s)}}ht.create=dn.create;ht.toCanvas=Cc().toCanvas;ht.toString=function(e,r,s){let i=Wr(e,r,s),o=i.opts?i.opts.type:void 0,a=Vf(o);return $r(a.render,e,i)};ht.toDataURL=function(e,r,s){let i=Wr(e,r,s),o=Es(i.opts.type);return $r(o.renderToDataURL,e,i)};ht.toBuffer=function(e,r,s){let i=Wr(e,r,s),o=Es(i.opts.type);return $r(o.renderToBuffer,e,i)};ht.toFile=function(e,r,s,i){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Ec())throw new Error("Too few arguments provided");let o=Wr(r,s,i),a=o.opts.type||zf(e),l=Es(a).renderToFile.bind(null,e);return $r(l,r,o)};ht.toFileStream=function(e,r,s){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Wr(r,s,e.emit.bind(e,"error")),a=Es("png").renderToFileStream.bind(null,e);$r(a,r,i)}});var Ic=$((Fv,Ac)=>{"use strict";Ac.exports=Tc()});import{readFileSync as Rc,writeFileSync as ep,renameSync as tp,readdirSync as rp,existsSync as Bc,rmSync as sp}from"fs";function Dc(t,e){rt(t);let r=as(t,e.sessionId),s=`${r}.${process.pid}.tmp`;ep(s,JSON.stringify(e,null,2),{mode:384}),tp(s,r)}function Tt(t,e){let r=as(t,e);if(Bc(r))return JSON.parse(Rc(r,"utf8"))}function xs(t){let e=et(t);return Bc(e)?rp(e).filter(r=>r.endsWith(".json")).map(r=>JSON.parse(Rc(`${e}/${r}`,"utf8"))):[]}function ks(t,e){sp(as(t,e),{force:!0})}function ut(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var cr=bt(()=>{"use strict";me()});import{spawn as ip}from"child_process";import{openSync as np,closeSync as op}from"fs";import{randomUUID as ap}from"crypto";function cp(t){let e=["__worker","--session-id",t.sessionId,"--cwd",t.cwd,"--adapter",t.adapterId,"--mode",t.mode,"--origin",t.origin];return t.label&&e.push("--label",t.label),t.aiCliArgs.length>0&&e.push("--",...t.aiCliArgs),e}function up(t){return new Promise(e=>setTimeout(e,t))}function lr(t,e){let r=[...process.execArgv],s=r.some(i=>i.includes("tsx"));return t.endsWith(".ts")&&!s&&r.push("--import","tsx"),[...r,t,...e]}async function _n(t,e){let r=e.sessionId??ap(),s=cp({sessionId:r,cwd:e.cwd,adapterId:e.adapterId,mode:e.mode,origin:e.origin,aiCliArgs:e.aiCliArgs,label:e.label}),i=t.timeoutMs??lp,o=Date.now(),a=np(fo(t.dir,r),"a"),n;try{n=ip(process.execPath,lr(t.entry,s),{detached:!0,stdio:["ignore",a,a],env:process.env}),n.unref()}finally{op(a)}let l,u=y=>{l=y};n.on("exit",u);try{let y=o+i;for(;;){if(l!==void 0)throw new Error(`worker exited during startup (code ${l})`);let h=Tt(t.dir,r);if(h&&h.pid===n.pid&&h.startedAtMs>=o)return{sessionId:r};if(Date.now()>=y)return process.stderr.write(`[djinn] forkWorker: worker ${r} readiness unverified after ${i}ms (best-effort, treating as started)
17
+ `),{sessionId:r};await up(hp)}}finally{n.off("exit",u)}}var lp,hp,Ts=bt(()=>{"use strict";me();cr();lp=2500,hp=50});var Ze=$((A1,nl)=>{"use strict";var sl=["nodebuffer","arraybuffer","fragments"],il=typeof Blob<"u";il&&sl.push("blob");nl.exports={BINARY_TYPES:sl,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:il,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Kr=$((I1,js)=>{"use strict";var{EMPTY_BUFFER:nm}=Ze(),wn=Buffer[Symbol.species];function om(t,e){if(t.length===0)return nm;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,s),s+=o.length}return s<e?new wn(r.buffer,r.byteOffset,s):r}function ol(t,e,r,s,i){for(let o=0;o<i;o++)r[s+o]=t[o]^e[o&3]}function al(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function am(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sn(t){if(Sn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new wn(t):ArrayBuffer.isView(t)?e=new wn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sn.readOnly=!1),e}js.exports={concat:om,mask:ol,toArrayBuffer:am,toBuffer:Sn,unmask:al};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=se("bufferutil");js.exports.mask=function(e,r,s,i,o){o<48?ol(e,r,s,i,o):t.mask(e,r,s,i,o)},js.exports.unmask=function(e,r){e.length<32?al(e,r):t.unmask(e,r)}}catch{}});var hl=$((P1,ll)=>{"use strict";var cl=Symbol("kDone"),Cn=Symbol("kRun"),En=class{constructor(e){this[cl]=()=>{this.pending--,this[Cn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Cn]()}[Cn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[cl])}}};ll.exports=En});var wr=$((L1,pl)=>{"use strict";var Xr=se("zlib"),ul=Kr(),cm=hl(),{kStatusCode:dl}=Ze(),lm=Buffer[Symbol.species],hm=Buffer.from([0,0,255,255]),$s=Symbol("permessage-deflate"),Ke=Symbol("total-length"),yr=Symbol("callback"),gt=Symbol("buffers"),br=Symbol("error"),Ws,xn=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ws){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ws=new cm(r)}}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[yr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let i=r[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 o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else if(s==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=o}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}"`);r[s]=i})}),e}decompress(e,r,s){Ws.add(i=>{this._decompress(e,r,(o,a)=>{i(),s(o,a)})})}compress(e,r,s){Ws.add(i=>{this._compress(e,r,(o,a)=>{i(),s(o,a)})})}_decompress(e,r,s){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Xr.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Xr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[$s]=this,this._inflate[Ke]=0,this._inflate[gt]=[],this._inflate.on("error",dm),this._inflate.on("data",fl)}this._inflate[yr]=s,this._inflate.write(e),r&&this._inflate.write(hm),this._inflate.flush(()=>{let o=this._inflate[br];if(o){this._inflate.close(),this._inflate=null,s(o);return}let a=ul.concat(this._inflate[gt],this._inflate[Ke]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ke]=0,this._inflate[gt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),s(null,a)})}_compress(e,r,s){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?Xr.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Xr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Ke]=0,this._deflate[gt]=[],this._deflate.on("data",um)}this._deflate[yr]=s,this._deflate.write(e),this._deflate.flush(Xr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=ul.concat(this._deflate[gt],this._deflate[Ke]);r&&(o=new lm(o.buffer,o.byteOffset,o.length-4)),this._deflate[yr]=null,this._deflate[Ke]=0,this._deflate[gt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),s(null,o)})}};pl.exports=xn;function um(t){this[gt].push(t),this[Ke]+=t.length}function fl(t){if(this[Ke]+=t.length,this[$s]._maxPayload<1||this[Ke]<=this[$s]._maxPayload){this[gt].push(t);return}this[br]=new RangeError("Max payload size exceeded"),this[br].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[br][dl]=1009,this.removeListener("data",fl),this.reset()}function dm(t){if(this[$s]._inflate=null,this[br]){this[yr](this[br]);return}t[dl]=1007,this[yr](t)}});var Sr=$((R1,qs)=>{"use strict";var{isUtf8:_l}=se("buffer"),{hasBlob:fm}=Ze(),pm=[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 _m(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function kn(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function mm(t){return fm&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}qs.exports={isBlob:mm,isValidStatusCode:_m,isValidUTF8:kn,tokenChars:pm};if(_l)qs.exports.isValidUTF8=function(t){return t.length<24?kn(t):_l(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=se("utf-8-validate");qs.exports.isValidUTF8=function(e){return e.length<32?kn(e):t(e)}}catch{}});var Ln=$((B1,Sl)=>{"use strict";var{Writable:gm}=se("stream"),ml=wr(),{BINARY_TYPES:vm,EMPTY_BUFFER:gl,kStatusCode:ym,kWebSocket:bm}=Ze(),{concat:Tn,toArrayBuffer:wm,unmask:Sm}=Kr(),{isValidStatusCode:Cm,isValidUTF8:vl}=Sr(),zs=Buffer[Symbol.species],ke=0,yl=1,bl=2,wl=3,An=4,In=5,Vs=6,Pn=class extends gm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||vm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[bm]=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=ke}_write(e,r,s){if(this._opcode===8&&this._state==ke)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 zs(s.buffer,s.byteOffset+e,s.length-e),new zs(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],i=r.length-e;e>=s.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),i),this._buffers[0]=new zs(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ke:this.getInfo(e);break;case yl:this.getPayloadLength16(e);break;case bl:this.getPayloadLength64(e);break;case wl:this.getMask();break;case An:this.getData(e);break;case In:case Vs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[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=(r[0]&64)===64;if(s&&!this._extensions[ml.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[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=(r[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=yl:this._payloadLength===127?this._state=bl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),s=r.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)+r.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 r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=wl:this._state=An}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=An}getData(e){let r=gl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Sm(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=In,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[ml.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return r(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(o)}this.dataMessage(r),this._state===ke&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ke;return}let r=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=Tn(s,r):this._binaryType==="arraybuffer"?i=wm(Tn(s,r)):this._binaryType==="blob"?i=new Blob(s):i=s,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=ke):(this._state=Vs,setImmediate(()=>{this.emit("message",i,!0),this._state=ke,this.startLoop(e)}))}else{let i=Tn(s,r);if(!this._skipUTF8Validation&&!vl(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===In||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=ke):(this._state=Vs,setImmediate(()=>{this.emit("message",i,!1),this._state=ke,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,gl),this.end();else{let s=e.readUInt16BE(0);if(!Cm(s)){let o=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let i=new zs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!vl(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",s,i),this.end()}this._state=ke;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ke):(this._state=Vs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ke,this.startLoop(r)}))}createError(e,r,s,i,o){this._loop=!1,this._errored=!0;let a=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=o,a[ym]=i,a}};Sl.exports=Pn});var Dn=$((O1,xl)=>{"use strict";var{Duplex:D1}=se("stream"),{randomFillSync:Em}=se("crypto"),Cl=wr(),{EMPTY_BUFFER:xm,kWebSocket:km,NOOP:Tm}=Ze(),{isBlob:Cr,isValidStatusCode:Am}=Sr(),{mask:El,toBuffer:zt}=Kr(),Te=Symbol("kByteLength"),Im=Buffer.alloc(4),Gs=8*1024,Vt,Er=Gs,Re=0,Pm=1,Lm=2,Rn=class t{constructor(e,r,s){this._extensions=r||{},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=Re,this.onerror=Tm,this[km]=void 0}static frame(e,r){let s,i=!1,o=2,a=!1;r.mask&&(s=r.maskBuffer||Im,r.generateMask?r.generateMask(s):(Er===Gs&&(Vt===void 0&&(Vt=Buffer.alloc(Gs)),Em(Vt,0,Gs),Er=0),s[0]=Vt[Er++],s[1]=Vt[Er++],s[2]=Vt[Er++],s[3]=Vt[Er++]),a=(s[0]|s[1]|s[2]|s[3])===0,o=6);let n;typeof e=="string"?(!r.mask||a)&&r[Te]!==void 0?n=r[Te]:(e=Buffer.from(e),n=e.length):(n=e.length,i=r.mask&&r.readOnly&&!a);let l=n;n>=65536?(o+=8,l=127):n>125&&(o+=2,l=126);let u=Buffer.allocUnsafe(i?n+o:o);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(n,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(n,4,6)),r.mask?(u[1]|=128,u[o-4]=s[0],u[o-3]=s[1],u[o-2]=s[2],u[o-1]=s[3],a?[u,e]:i?(El(e,s,u,o,n),[u]):(El(e,s,e,0,n),[u,e])):[u,e]}close(e,r,s,i){let o;if(e===void 0)o=xm;else{if(typeof e!="number"||!Am(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let n=Buffer.byteLength(r);if(n>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+n),o.writeUInt16BE(e,0),typeof r=="string"?o.write(r,2):o.set(r,2)}}let a={[Te]:o.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Re?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(t.frame(o,a),i)}ping(e,r,s){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Cr(e)?(i=e.size,o=!1):(e=zt(e),i=e.length,o=zt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Te]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Cr(e)?this._state!==Re?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Re?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(t.frame(e,a),s)}pong(e,r,s){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Cr(e)?(i=e.size,o=!1):(e=zt(e),i=e.length,o=zt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Te]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Cr(e)?this._state!==Re?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Re?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(t.frame(e,a),s)}send(e,r,s){let i=this._extensions[Cl.extensionName],o=r.binary?2:1,a=r.compress,n,l;typeof e=="string"?(n=Buffer.byteLength(e),l=!1):Cr(e)?(n=e.size,l=!1):(e=zt(e),n=e.length,l=zt.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=n>=i._threshold),this._compress=a):(a=!1,o=0),r.fin&&(this._firstFragment=!0);let u={[Te]:n,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:l,rsv1:a};Cr(e)?this._state!==Re?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):this._state!==Re?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,r,s,i){this._bufferedBytes+=s[Te],this._state=Lm,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let n=new Error("The socket was closed while the blob was being read");process.nextTick(Bn,this,n,i);return}this._bufferedBytes-=s[Te];let a=zt(o);r?this.dispatch(a,r,s,i):(this._state=Re,this.sendFrame(t.frame(a,s),i),this.dequeue())}).catch(o=>{process.nextTick(Rm,this,o,i)})}dispatch(e,r,s,i){if(!r){this.sendFrame(t.frame(e,s),i);return}let o=this._extensions[Cl.extensionName];this._bufferedBytes+=s[Te],this._state=Pm,o.compress(e,s.fin,(a,n)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Bn(this,l,i);return}this._bufferedBytes-=s[Te],this._state=Re,s.readOnly=!1,this.sendFrame(t.frame(n,s),i),this.dequeue()})}dequeue(){for(;this._state===Re&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Te],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Te],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};xl.exports=Rn;function Bn(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let i=t._queue[s],o=i[i.length-1];typeof o=="function"&&o(e)}}function Rm(t,e,r){Bn(t,e,r),t.onerror(e)}});var Dl=$((M1,Bl)=>{"use strict";var{kForOnEventAttribute:Qr,kListener:On}=Ze(),kl=Symbol("kCode"),Tl=Symbol("kData"),Al=Symbol("kError"),Il=Symbol("kMessage"),Pl=Symbol("kReason"),xr=Symbol("kTarget"),Ll=Symbol("kType"),Rl=Symbol("kWasClean"),Xe=class{constructor(e){this[xr]=null,this[Ll]=e}get target(){return this[xr]}get type(){return this[Ll]}};Object.defineProperty(Xe.prototype,"target",{enumerable:!0});Object.defineProperty(Xe.prototype,"type",{enumerable:!0});var Gt=class extends Xe{constructor(e,r={}){super(e),this[kl]=r.code===void 0?0:r.code,this[Pl]=r.reason===void 0?"":r.reason,this[Rl]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[kl]}get reason(){return this[Pl]}get wasClean(){return this[Rl]}};Object.defineProperty(Gt.prototype,"code",{enumerable:!0});Object.defineProperty(Gt.prototype,"reason",{enumerable:!0});Object.defineProperty(Gt.prototype,"wasClean",{enumerable:!0});var kr=class extends Xe{constructor(e,r={}){super(e),this[Al]=r.error===void 0?null:r.error,this[Il]=r.message===void 0?"":r.message}get error(){return this[Al]}get message(){return this[Il]}};Object.defineProperty(kr.prototype,"error",{enumerable:!0});Object.defineProperty(kr.prototype,"message",{enumerable:!0});var es=class extends Xe{constructor(e,r={}){super(e),this[Tl]=r.data===void 0?null:r.data}get data(){return this[Tl]}};Object.defineProperty(es.prototype,"data",{enumerable:!0});var Bm={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[Qr]&&i[On]===e&&!i[Qr])return;let s;if(t==="message")s=function(o,a){let n=new es("message",{data:a?o:o.toString()});n[xr]=this,Ys(e,this,n)};else if(t==="close")s=function(o,a){let n=new Gt("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[xr]=this,Ys(e,this,n)};else if(t==="error")s=function(o){let a=new kr("error",{error:o,message:o.message});a[xr]=this,Ys(e,this,a)};else if(t==="open")s=function(){let o=new Xe("open");o[xr]=this,Ys(e,this,o)};else return;s[Qr]=!!r[Qr],s[On]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[On]===e&&!r[Qr]){this.removeListener(t,r);break}}};Bl.exports={CloseEvent:Gt,ErrorEvent:kr,Event:Xe,EventTarget:Bm,MessageEvent:es};function Ys(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Js=$((N1,Ol)=>{"use strict";var{tokenChars:ts}=Sr();function je(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Dm(t){let e=Object.create(null),r=Object.create(null),s=!1,i=!1,o=!1,a,n,l=-1,u=-1,y=-1,h=0;for(;h<t.length;h++)if(u=t.charCodeAt(h),a===void 0)if(y===-1&&ts[u]===1)l===-1&&(l=h);else if(h!==0&&(u===32||u===9))y===-1&&l!==-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h);let d=t.slice(l,y);u===44?(je(e,d,r),r=Object.create(null)):a=d,l=y=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(n===void 0)if(y===-1&&ts[u]===1)l===-1&&(l=h);else if(u===32||u===9)y===-1&&l!==-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h),je(r,t.slice(l,y),!0),u===44&&(je(e,a,r),r=Object.create(null),a=void 0),l=y=-1}else if(u===61&&l!==-1&&y===-1)n=t.slice(l,h),l=y=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(i){if(ts[u]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:s||(s=!0),i=!1}else if(o)if(ts[u]===1)l===-1&&(l=h);else if(u===34&&l!==-1)o=!1,y=h;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(u===34&&t.charCodeAt(h-1)===61)o=!0;else if(y===-1&&ts[u]===1)l===-1&&(l=h);else if(l!==-1&&(u===32||u===9))y===-1&&(y=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);y===-1&&(y=h);let d=t.slice(l,y);s&&(d=d.replace(/\\/g,""),s=!1),je(r,n,d),u===44&&(je(e,a,r),r=Object.create(null),a=void 0),n=void 0,l=y=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(l===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");y===-1&&(y=h);let _=t.slice(l,y);return a===void 0?je(e,_,r):(n===void 0?je(r,_,!0):s?je(r,n,_.replace(/\\/g,"")):je(r,n,_),je(e,a,r)),e}function Om(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(i=>{let o=s[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ol.exports={format:Om,parse:Dm}});var Qs=$((F1,Gl)=>{"use strict";var Mm=se("events"),Nm=se("https"),Um=se("http"),Ul=se("net"),Hm=se("tls"),{randomBytes:Fm,createHash:jm}=se("crypto"),{Duplex:U1,Readable:H1}=se("stream"),{URL:Mn}=se("url"),vt=wr(),Wm=Ln(),$m=Dn(),{isBlob:qm}=Sr(),{BINARY_TYPES:Ml,CLOSE_TIMEOUT:zm,EMPTY_BUFFER:Zs,GUID:Vm,kForOnEventAttribute:Nn,kListener:Gm,kStatusCode:Ym,kWebSocket:de,NOOP:Hl}=Ze(),{EventTarget:{addEventListener:Jm,removeEventListener:Zm}}=Dl(),{format:Km,parse:Xm}=Js(),{toBuffer:Qm}=Kr(),Fl=Symbol("kAborted"),Un=[8,13],Qe=["CONNECTING","OPEN","CLOSING","CLOSED"],eg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ce=class t extends Mm{constructor(e,r,s){super(),this._binaryType=Ml[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Zs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),jl(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ml.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,r,s){let i=new Wm({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),o=new $m(e,this._extensions,s.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[de]=this,o[de]=this,e[de]=this,i.on("conclude",sg),i.on("drain",ig),i.on("error",ng),i.on("message",og),i.on("ping",ag),i.on("pong",cg),o.onerror=lg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",ql),e.on("data",Xs),e.on("end",zl),e.on("error",Vl),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[vt.extensionName]&&this._extensions[vt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){be(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$l(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Hn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Zs,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Hn(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Zs,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Hn(this,e,s);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[vt.extensionName]||(i.compress=!1),this._sender.send(e||Zs,i,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){be(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ce,"CONNECTING",{enumerable:!0,value:Qe.indexOf("CONNECTING")});Object.defineProperty(ce.prototype,"CONNECTING",{enumerable:!0,value:Qe.indexOf("CONNECTING")});Object.defineProperty(ce,"OPEN",{enumerable:!0,value:Qe.indexOf("OPEN")});Object.defineProperty(ce.prototype,"OPEN",{enumerable:!0,value:Qe.indexOf("OPEN")});Object.defineProperty(ce,"CLOSING",{enumerable:!0,value:Qe.indexOf("CLOSING")});Object.defineProperty(ce.prototype,"CLOSING",{enumerable:!0,value:Qe.indexOf("CLOSING")});Object.defineProperty(ce,"CLOSED",{enumerable:!0,value:Qe.indexOf("CLOSED")});Object.defineProperty(ce.prototype,"CLOSED",{enumerable:!0,value:Qe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ce.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ce.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nn])return e[Gm];return null},set(e){for(let r of this.listeners(t))if(r[Nn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Nn]:!0})}})});ce.prototype.addEventListener=Jm;ce.prototype.removeEventListener=Zm;Gl.exports=ce;function jl(t,e,r,s){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:zm,protocolVersion:Un[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(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Un.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Un.join(", ")})`);let o;if(e instanceof Mn)o=e;else try{o=new Mn(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let a=o.protocol==="wss:",n=o.protocol==="ws+unix:",l;if(o.protocol!=="ws:"&&!a&&!n?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:n&&!o.pathname?l="The URL's pathname is empty":o.hash&&(l="The URL contains a fragment identifier"),l){let b=new SyntaxError(l);if(t._redirects===0)throw b;Ks(t,b);return}let u=a?443:80,y=Fm(16).toString("base64"),h=a?Nm.request:Um.request,_=new Set,d;if(i.createConnection=i.createConnection||(a?rg:tg),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":y,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new vt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Km({[vt.extensionName]:d.offer()})),r.length){for(let b of r){if(typeof b!="string"||!eg.test(b)||_.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(b)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),n){let b=i.path.split(":");i.socketPath=b[0],i.path=b[1]}let p;if(i.followRedirects){if(t._redirects===0){t._originalIpc=n,t._originalSecure=a,t._originalHostOrSocketPath=n?i.socketPath:o.host;let b=s&&s.headers;if(s={...s,headers:{}},b)for(let[c,v]of Object.entries(b))s.headers[c.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let b=n?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!b||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,b||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=t._req=h(i),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=h(i);i.timeout&&p.on("timeout",()=>{be(t,p,"Opening handshake has timed out")}),p.on("error",b=>{p===null||p[Fl]||(p=t._req=null,Ks(t,b))}),p.on("response",b=>{let c=b.headers.location,v=b.statusCode;if(c&&i.followRedirects&&v>=300&&v<400){if(++t._redirects>i.maxRedirects){be(t,p,"Maximum redirects exceeded");return}p.abort();let g;try{g=new Mn(c,e)}catch{let m=new SyntaxError(`Invalid URL: ${c}`);Ks(t,m);return}jl(t,g,r,s)}else t.emit("unexpected-response",p,b)||be(t,p,`Unexpected server response: ${b.statusCode}`)}),p.on("upgrade",(b,c,v)=>{if(t.emit("upgrade",b),t.readyState!==ce.CONNECTING)return;p=t._req=null;let g=b.headers.upgrade;if(g===void 0||g.toLowerCase()!=="websocket"){be(t,c,"Invalid Upgrade header");return}let f=jm("sha1").update(y+Vm).digest("base64");if(b.headers["sec-websocket-accept"]!==f){be(t,c,"Invalid Sec-WebSocket-Accept header");return}let m=b.headers["sec-websocket-protocol"],w;if(m!==void 0?_.size?_.has(m)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":_.size&&(w="Server sent no subprotocol"),w){be(t,c,w);return}m&&(t._protocol=m);let C=b.headers["sec-websocket-extensions"];if(C!==void 0){if(!d){be(t,c,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=Xm(C)}catch{be(t,c,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(k);if(A.length!==1||A[0]!==vt.extensionName){be(t,c,"Server indicated an extension that was not requested");return}try{d.accept(k[vt.extensionName])}catch{be(t,c,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[vt.extensionName]=d}t.setSocket(c,v,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(p,t):p.end()}function Ks(t,e){t._readyState=ce.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function tg(t){return t.path=t.socketPath,Ul.connect(t)}function rg(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ul.isIP(t.host)?"":t.host),Hm.connect(t)}function be(t,e,r){t._readyState=ce.CLOSING;let s=new Error(r);Error.captureStackTrace(s,be),e.setHeader?(e[Fl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ks,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Hn(t,e,r){if(e){let s=qm(e)?e.size:Qm(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${Qe[t.readyState]})`);process.nextTick(r,s)}}function sg(t,e){let r=this[de];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[de]!==void 0&&(r._socket.removeListener("data",Xs),process.nextTick(Wl,r._socket),t===1005?r.close():r.close(t,e))}function ig(){let t=this[de];t.isPaused||t._socket.resume()}function ng(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",Xs),process.nextTick(Wl,e._socket),e.close(t[Ym])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Nl(){this[de].emitClose()}function og(t,e){this[de].emit("message",t,e)}function ag(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,Hl),e.emit("ping",t)}function cg(t){this[de].emit("pong",t)}function Wl(t){t.resume()}function lg(t){let e=this[de];e.readyState!==ce.CLOSED&&(e.readyState===ce.OPEN&&(e._readyState=ce.CLOSING,$l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $l(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ql(){let t=this[de];if(this.removeListener("close",ql),this.removeListener("data",Xs),this.removeListener("end",zl),t._readyState=ce.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Nl),t._receiver.on("finish",Nl))}function Xs(t){this[de]._receiver.write(t)||this.pause()}function zl(){let t=this[de];t._readyState=ce.CLOSING,t._receiver.end(),this.end()}function Vl(){let t=this[de];this.removeListener("error",Vl),this.on("error",Hl),t&&(t._readyState=ce.CLOSING,this.destroy())}});var Kl=$((W1,Zl)=>{"use strict";var j1=Qs(),{Duplex:hg}=se("stream");function Yl(t){t.emit("close")}function ug(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Jl(t){this.removeListener("error",Jl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function dg(t,e){let r=!0,s=new hg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,a){let n=!a&&s._readableState.objectMode?o.toString():o;s.push(n)||t.pause()}),t.once("error",function(o){s.destroyed||(r=!1,s.destroy(o))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(Yl,s);return}let a=!1;t.once("error",function(l){a=!0,o(l)}),t.once("close",function(){a||o(i),process.nextTick(Yl,s)}),r&&t.terminate()},s._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(i,o,a){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(i,o,a)});return}t.send(i,a)},s.on("end",ug),s.on("error",Jl),s}Zl.exports=dg});var Fn=$(($1,Xl)=>{"use strict";var{tokenChars:fg}=Sr();function pg(t){let e=new Set,r=-1,s=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(s===-1&&fg[a]===1)r===-1&&(r=i);else if(i!==0&&(a===32||a===9))s===-1&&r!==-1&&(s=i);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);s===-1&&(s=i);let n=t.slice(r,s);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);e.add(n),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Xl.exports={parse:pg}});var nh=$((z1,ih)=>{"use strict";var _g=se("events"),ei=se("http"),{Duplex:q1}=se("stream"),{createHash:mg}=se("crypto"),Ql=Js(),Yt=wr(),gg=Fn(),vg=Qs(),{CLOSE_TIMEOUT:yg,GUID:bg,kWebSocket:wg}=Ze(),Sg=/^[+/0-9A-Za-z]{22}==$/,eh=0,th=1,sh=2,jn=class extends _g{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:yg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:vg,...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=ei.createServer((s,i)=>{let o=ei.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=Cg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=eh}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===sh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(rs,this);return}if(e&&this.once("close",e),this._state!==th)if(this._state=th,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(rs,this):process.nextTick(rs,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{rs(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,i){r.on("error",rh);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,n=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Jt(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Jt(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!Sg.test(o)){Jt(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(n!==13&&n!==8){Jt(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ss(r,400);return}let l=e.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=gg.parse(l)}catch{Jt(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let y=e.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&y!==void 0){let _=new Yt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let d=Ql.parse(y);d[Yt.extensionName]&&(_.accept(d[Yt.extensionName]),h[Yt.extensionName]=_)}catch{Jt(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${n===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(d,p,b,c)=>{if(!d)return ss(r,p||401,b,c);this.completeUpgrade(h,o,u,e,r,s,i)});return}if(!this.options.verifyClient(_))return ss(r,401)}this.completeUpgrade(h,o,u,e,r,s,i)}completeUpgrade(e,r,s,i,o,a,n){if(!o.readable||!o.writable)return o.destroy();if(o[wg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>eh)return ss(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${mg("sha1").update(r+bg).digest("base64")}`],y=new this.options.WebSocket(null,void 0,this.options);if(s.size){let h=this.options.handleProtocols?this.options.handleProtocols(s,i):s.values().next().value;h&&(u.push(`Sec-WebSocket-Protocol: ${h}`),y._protocol=h)}if(e[Yt.extensionName]){let h=e[Yt.extensionName].params,_=Ql.format({[Yt.extensionName]:[h]});u.push(`Sec-WebSocket-Extensions: ${_}`),y._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
18
18
  `).join(`\r
19
- `)),o.removeListener("error",Ql),y.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(es,this)})),n(y,i)}};th.exports=Un;function mg(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function es(t){t._state=eh,t.emit("close")}function Ql(){this.destroy()}function ts(t,e,r,s){r=r||Ks.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Ks.STATUS_CODES[e]}\r
19
+ `)),o.removeListener("error",rh),y.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(rs,this)})),n(y,i)}};ih.exports=jn;function Cg(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function rs(t){t._state=sh,t.emit("close")}function rh(){this.destroy()}function ss(t,e,r,s){r=r||ei.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ei.STATUS_CODES[e]}\r
20
20
  `+Object.keys(s).map(i=>`${i}: ${s[i]}`).join(`\r
21
21
  `)+`\r
22
22
  \r
23
- `+r)}function Vt(t,e,r,s,i,o){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,Vt),t.emit("wsClientError",a,r,e)}else ts(r,s,i,o)}});var xh={};ns(xh,{MAC_LABEL:()=>Yt,SYSTEMD_UNIT_NAME:()=>xr,buildLaunchdPlist:()=>wh,buildSystemdUnit:()=>Sh,installSupervisor:()=>Yn,isSupervisorInstalled:()=>Dg,pingDaemonSocket:()=>ss,uninstallSupervisor:()=>Jn,verifySupervisorActive:()=>oi,waitForSocketGone:()=>is});import{homedir as Gn,userInfo as Bg}from"os";import{join as rs}from"path";import{connect as Og}from"net";import{existsSync as Vn}from"fs";function ni(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function bh(t){return/^[A-Za-z0-9_./:=-]+$/.test(t)?t:`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function wh(t){let r=[t.execPath,...ar(t.entry,["daemon","run"])].map(s=>` <string>${ni(s)}</string>`).join(`
23
+ `+r)}function Jt(t,e,r,s,i,o){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,Jt),t.emit("wsClientError",a,r,e)}else ss(r,s,i,o)}});var Ah={};os(Ah,{MAC_LABEL:()=>Kt,SYSTEMD_UNIT_NAME:()=>Ar,buildLaunchdPlist:()=>Eh,buildSystemdUnit:()=>xh,installSupervisor:()=>Kn,isSupervisorInstalled:()=>Zn,pingDaemonSocket:()=>Tr,uninstallSupervisor:()=>Xn,verifySupervisorActive:()=>li,waitForSocketGone:()=>ns});import{homedir as Jn,userInfo as Fg}from"os";import{join as is}from"path";import{connect as jg}from"net";import{existsSync as Yn}from"fs";function ci(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ch(t){return/^[A-Za-z0-9_./:=-]+$/.test(t)?t:`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Eh(t){let r=[t.execPath,...lr(t.entry,["daemon","run"])].map(s=>` <string>${ci(s)}</string>`).join(`
24
24
  `);return`<?xml version="1.0" encoding="UTF-8"?>
25
25
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
26
26
  <plist version="1.0">
27
27
  <dict>
28
28
  <key>Label</key>
29
- <string>${Yt}</string>
29
+ <string>${Kt}</string>
30
30
  <key>ProgramArguments</key>
31
31
  <array>
32
32
  ${r}
@@ -34,7 +34,7 @@ ${r}
34
34
  <key>EnvironmentVariables</key>
35
35
  <dict>
36
36
  <key>PATH</key>
37
- <string>${ni(t.path)}</string>
37
+ <string>${ci(t.path)}</string>
38
38
  </dict>
39
39
  <key>RunAtLoad</key>
40
40
  <true/>
@@ -44,36 +44,36 @@ ${r}
44
44
  <false/>
45
45
  </dict>
46
46
  <key>StandardOutPath</key>
47
- <string>${ni(t.logPath)}</string>
47
+ <string>${ci(t.logPath)}</string>
48
48
  <key>StandardErrorPath</key>
49
- <string>${ni(t.logPath)}</string>
49
+ <string>${ci(t.logPath)}</string>
50
50
  </dict>
51
51
  </plist>
52
- `}function Sh(t){let r=[t.execPath,...ar(t.entry,["daemon","run"])].map(bh).join(" ");return`[Unit]
52
+ `}function xh(t){let r=[t.execPath,...lr(t.entry,["daemon","run"])].map(Ch).join(" ");return`[Unit]
53
53
  Description=Djinn daemon
54
54
  StartLimitIntervalSec=0
55
55
 
56
56
  [Service]
57
- Environment=${bh(`PATH=${t.path}`)}
57
+ Environment=${Ch(`PATH=${t.path}`)}
58
58
  ExecStart=${r}
59
59
  Restart=on-failure
60
60
 
61
61
  [Install]
62
62
  WantedBy=default.target
63
- `}function Ch(){return rs(Gn(),"Library","LaunchAgents",`${Yt}.plist`)}function Eh(){return rs(Gn(),".config","systemd","user",xr)}function Dg(t,e=Gn()){return t==="darwin"?Vn(rs(e,"Library","LaunchAgents",`${Yt}.plist`)):t==="linux"?Vn(rs(e,".config","systemd","user",xr)):!1}async function Yn(t){if(t.platform!=="darwin"&&t.platform!=="linux")throw new Error(`unsupported platform for daemon install: ${t.platform}`);if(!t.loadIdentity())throw new Error("no identity found; run `djinn new --invite <CODE> --server <wss>` first");if(await t.pingDaemon()&&(await t.stopDaemon().catch(()=>{}),!await t.waitForSocketGone()))throw new Error("daemon socket did not disappear after stop; aborting install (please stop the daemon manually)");let e=process.env.PATH??"";if(t.platform==="darwin"){let r=Ch();await t.writeConfig(r,wh({execPath:t.execPath,entry:t.entry,logPath:rs(t.dir,"daemon.log"),path:e}));let s=process.getuid?.()??0;await t.runCommand("launchctl",["bootout",`gui/${s}/${Yt}`]).catch(()=>{}),await t.runCommand("launchctl",["bootstrap",`gui/${s}`,r])}else{let r=Eh();await t.writeConfig(r,Sh({execPath:t.execPath,entry:t.entry,path:e})),await t.runCommand("systemctl",["--user","daemon-reload"]),await t.runCommand("systemctl",["--user","enable","--now",xr]),await t.runCommand("loginctl",["enable-linger",Bg().username]).catch(()=>{})}if(!await t.verifySupervisorActive())throw new Error("daemon did not come up under the OS supervisor (a competing daemon may have grabbed the socket); please re-run `djinn daemon install`")}async function Jn(t){if(t.platform==="darwin"){let e=process.getuid?.()??0;await t.runCommand("launchctl",["bootout",`gui/${e}/${Yt}`]).catch(()=>{}),await t.removeConfig(Ch())}else if(t.platform==="linux")await t.runCommand("systemctl",["--user","disable","--now",xr]).catch(()=>{}),await t.removeConfig(Eh()),await t.runCommand("systemctl",["--user","daemon-reload"]).catch(()=>{});else throw new Error(`unsupported platform for daemon uninstall: ${t.platform}`)}function ss(t){return new Promise(e=>{let r=Og(qe(t)),s,i=o=>{clearTimeout(s),r.destroy(),e(o)};s=setTimeout(()=>i(!1),300),r.on("connect",()=>r.write(JSON.stringify({cmd:"ping"})+`
64
- `)),r.on("data",()=>i(!0)),r.on("error",()=>i(!1))})}async function is(t,e=3e3){let r=Date.now()+e;for(;Date.now()<r;){if(!Vn(qe(t))&&!await ss(t))return!0;await new Promise(s=>setTimeout(s,150))}return!await ss(t)}async function oi(t,e){let r=e.timeoutMs??3e3,s=e.sleep??(a=>new Promise(n=>setTimeout(n,a))),i=Date.now()+r,o=async()=>{if(t==="linux")return(await e.exec("systemctl",["--user","is-active","--quiet",xr])).ok;if(t==="darwin"){let a=await e.exec("launchctl",["print",`gui/${e.uid}/${Yt}`]);return a.ok&&/\bpid = \d+/.test(a.stdout)}return!1};for(;Date.now()<i;){if(await o())return!0;await s(150)}return o()}var Yt,xr,Zn=mt(()=>{"use strict";xs();ye();Yt="top.unit00.djinn.daemon",xr="djinn-daemon.service"});var Th=q(kh=>{"use strict";(()=>{"use strict";var t={5639:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CircularList=void 0;let u=l(7150),y=l(802);class h extends u.Disposable{constructor(d){super(),this._maxLength=d,this.onDeleteEmitter=this._register(new y.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new y.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new y.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(d){if(this._maxLength===d)return;let p=new Array(d);for(let b=0;b<Math.min(d,this.length);b++)p[b]=this._array[this._getCyclicIndex(b)];this._array=p,this._maxLength=d,this._startIndex=0}get length(){return this._length}set length(d){if(d>this._length)for(let p=this._length;p<d;p++)this._array[p]=void 0;this._length=d}get(d){return this._array[this._getCyclicIndex(d)]}set(d,p){this._array[this._getCyclicIndex(d)]=p}push(d){this._array[this._getCyclicIndex(this._length)]=d,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(d,p,...b){if(p){for(let c=d;c<this._length-p;c++)this._array[this._getCyclicIndex(c)]=this._array[this._getCyclicIndex(c+p)];this._length-=p,this.onDeleteEmitter.fire({index:d,amount:p})}for(let c=this._length-1;c>=d;c--)this._array[this._getCyclicIndex(c+b.length)]=this._array[this._getCyclicIndex(c)];for(let c=0;c<b.length;c++)this._array[this._getCyclicIndex(d+c)]=b[c];if(b.length&&this.onInsertEmitter.fire({index:d,amount:b.length}),this._length+b.length>this._maxLength){let c=this._length+b.length-this._maxLength;this._startIndex+=c,this._length=this._maxLength,this.onTrimEmitter.fire(c)}else this._length+=b.length}trimStart(d){d>this._length&&(d=this._length),this._startIndex+=d,this._length-=d,this.onTrimEmitter.fire(d)}shiftElements(d,p,b){if(!(p<=0)){if(d<0||d>=this._length)throw new Error("start argument out of range");if(d+b<0)throw new Error("Cannot shift elements in list beyond index 0");if(b>0){for(let v=p-1;v>=0;v--)this.set(d+v+b,this.get(d+v));let c=d+p+b-this._length;if(c>0)for(this._length+=c;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let c=0;c<p;c++)this.set(d+c+b,this.get(d+c))}}_getCyclicIndex(d){return(this._startIndex+d)%this._maxLength}}n.CircularList=h},7453:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.clone=function l(u,y=5){if(typeof u!="object")return u;let h=Array.isArray(u)?[]:{};for(let _ in u)h[_]=y<=1?u[_]:u[_]&&l(u[_],y-1);return h}},5777:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreTerminal=void 0;let u=l(6501),y=l(6025),h=l(7276),_=l(9640),d=l(56),p=l(4071),b=l(7792),c=l(6415),v=l(5746),g=l(5882),f=l(2486),m=l(3562),w=l(8811),C=l(802),k=l(7150),A=!1;class D extends k.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new C.Emitter),this._onScroll.event((L=>{this._onScrollApi?.fire(L.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(L){for(let R in L)this.optionsService.options[R]=L[R]}constructor(L){super(),this._windowsWrappingHeuristics=this._register(new k.MutableDisposable),this._onBinary=this._register(new C.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new C.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new C.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new C.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new C.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new C.Emitter),this._instantiationService=new y.InstantiationService,this.optionsService=this._register(new d.OptionsService(L)),this._instantiationService.setService(u.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(_.BufferService)),this._instantiationService.setService(u.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(h.LogService)),this._instantiationService.setService(u.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(p.CoreService)),this._instantiationService.setService(u.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(b.CoreMouseService)),this._instantiationService.setService(u.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(c.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(v.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(w.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new f.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(C.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(C.Event.forward(this._bufferService.onResize,this._onResize)),this._register(C.Event.forward(this.coreService.onData,this._onData)),this._register(C.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom(!0)))),this._register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this._register(this._bufferService.onScroll((()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this._register(new m.WriteBuffer(((R,P)=>this._inputHandler.parse(R,P)))),this._register(C.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(L,R){this._writeBuffer.write(L,R)}writeSync(L,R){this._logService.logLevel<=u.LogLevelEnum.WARN&&!A&&(this._logService.warn("writeSync is unreliable and will be removed soon."),A=!0),this._writeBuffer.writeSync(L,R)}input(L,R=!0){this.coreService.triggerDataEvent(L,R)}resize(L,R){isNaN(L)||isNaN(R)||(L=Math.max(L,_.MINIMUM_COLS),R=Math.max(R,_.MINIMUM_ROWS),this._bufferService.resize(L,R))}scroll(L,R=!1){this._bufferService.scroll(L,R)}scrollLines(L,R){this._bufferService.scrollLines(L,R)}scrollPages(L){this.scrollLines(L*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(L){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(L){let R=L-this._bufferService.buffer.ydisp;R!==0&&this.scrollLines(R)}registerEscHandler(L,R){return this._inputHandler.registerEscHandler(L,R)}registerDcsHandler(L,R){return this._inputHandler.registerDcsHandler(L,R)}registerCsiHandler(L,R){return this._inputHandler.registerCsiHandler(L,R)}registerOscHandler(L,R){return this._inputHandler.registerOscHandler(L,R)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let L=!1,R=this.optionsService.rawOptions.windowsPty;R&&R.buildNumber!==void 0&&R.buildNumber!==void 0?L=R.backend==="conpty"&&R.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(L=!0),L?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let L=[];L.push(this.onLineFeed(g.updateWindowsModeWrappedState.bind(null,this._bufferService))),L.push(this.registerCsiHandler({final:"H"},(()=>((0,g.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,k.toDisposable)((()=>{for(let R of L)R.dispose()}))}}}n.CoreTerminal=D},2486:function(a,n,l){var u=this&&this.__decorate||function(j,S,T,E){var x,M=arguments.length,N=M<3?S:E===null?E=Object.getOwnPropertyDescriptor(S,T):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(j,S,T,E);else for(var U=j.length-1;U>=0;U--)(x=j[U])&&(N=(M<3?x(N):M>3?x(S,T,N):x(S,T))||N);return M>3&&N&&Object.defineProperty(S,T,N),N},y=this&&this.__param||function(j,S){return function(T,E){S(T,E,j)}};Object.defineProperty(n,"__esModule",{value:!0}),n.InputHandler=n.WindowsOptionsReportType=void 0,n.isValidColorIndex=Y;let h=l(3534),_=l(6760),d=l(6717),p=l(7150),b=l(726),c=l(6107),v=l(8938),g=l(3055),f=l(5451),m=l(6501),w=l(6415),C=l(1346),k=l(9823),A=l(8693),D=l(802),O={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function R(j,S){if(j>24)return S.setWinLines||!1;switch(j){case 1:return!!S.restoreWin;case 2:return!!S.minimizeWin;case 3:return!!S.setWinPosition;case 4:return!!S.setWinSizePixels;case 5:return!!S.raiseWin;case 6:return!!S.lowerWin;case 7:return!!S.refreshWin;case 8:return!!S.setWinSizeChars;case 9:return!!S.maximizeWin;case 10:return!!S.fullscreenWin;case 11:return!!S.getWinState;case 13:return!!S.getWinPosition;case 14:return!!S.getWinSizePixels;case 15:return!!S.getScreenSizePixels;case 16:return!!S.getCellSizePixels;case 18:return!!S.getWinSizeChars;case 19:return!!S.getScreenSizeChars;case 20:return!!S.getIconTitle;case 21:return!!S.getWinTitle;case 22:return!!S.pushTitle;case 23:return!!S.popTitle;case 24:return!!S.setWinLines}return!1}var P;(function(j){j[j.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",j[j.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(P||(n.WindowsOptionsReportType=P={}));let F=0;class V extends p.Disposable{getAttrData(){return this._curAttrData}constructor(S,T,E,x,M,N,U,z,ne=new d.EscapeSequenceParser){super(),this._bufferService=S,this._charsetService=T,this._coreService=E,this._logService=x,this._optionsService=M,this._oscLinkService=N,this._coreMouseService=U,this._unicodeService=z,this._parser=ne,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new b.StringToUtf32,this._utf8Decoder=new b.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new D.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new D.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new D.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new D.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new D.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new D.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new D.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new D.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new D.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new D.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new D.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new D.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new D.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((I=>this._activeBuffer=I.activeBuffer))),this._parser.setCsiHandlerFallback(((I,Q)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(I),params:Q.toArray()})})),this._parser.setEscHandlerFallback((I=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(I)})})),this._parser.setExecuteHandlerFallback((I=>{this._logService.debug("Unknown EXECUTE code: ",{code:I})})),this._parser.setOscHandlerFallback(((I,Q,J)=>{this._logService.debug("Unknown OSC code: ",{identifier:I,action:Q,data:J})})),this._parser.setDcsHandlerFallback(((I,Q,J)=>{Q==="HOOK"&&(J=J.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(I),action:Q,payload:J})})),this._parser.setPrintHandler(((I,Q,J)=>this.print(I,Q,J))),this._parser.registerCsiHandler({final:"@"},(I=>this.insertChars(I))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(I=>this.scrollLeft(I))),this._parser.registerCsiHandler({final:"A"},(I=>this.cursorUp(I))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(I=>this.scrollRight(I))),this._parser.registerCsiHandler({final:"B"},(I=>this.cursorDown(I))),this._parser.registerCsiHandler({final:"C"},(I=>this.cursorForward(I))),this._parser.registerCsiHandler({final:"D"},(I=>this.cursorBackward(I))),this._parser.registerCsiHandler({final:"E"},(I=>this.cursorNextLine(I))),this._parser.registerCsiHandler({final:"F"},(I=>this.cursorPrecedingLine(I))),this._parser.registerCsiHandler({final:"G"},(I=>this.cursorCharAbsolute(I))),this._parser.registerCsiHandler({final:"H"},(I=>this.cursorPosition(I))),this._parser.registerCsiHandler({final:"I"},(I=>this.cursorForwardTab(I))),this._parser.registerCsiHandler({final:"J"},(I=>this.eraseInDisplay(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(I=>this.eraseInDisplay(I,!0))),this._parser.registerCsiHandler({final:"K"},(I=>this.eraseInLine(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(I=>this.eraseInLine(I,!0))),this._parser.registerCsiHandler({final:"L"},(I=>this.insertLines(I))),this._parser.registerCsiHandler({final:"M"},(I=>this.deleteLines(I))),this._parser.registerCsiHandler({final:"P"},(I=>this.deleteChars(I))),this._parser.registerCsiHandler({final:"S"},(I=>this.scrollUp(I))),this._parser.registerCsiHandler({final:"T"},(I=>this.scrollDown(I))),this._parser.registerCsiHandler({final:"X"},(I=>this.eraseChars(I))),this._parser.registerCsiHandler({final:"Z"},(I=>this.cursorBackwardTab(I))),this._parser.registerCsiHandler({final:"`"},(I=>this.charPosAbsolute(I))),this._parser.registerCsiHandler({final:"a"},(I=>this.hPositionRelative(I))),this._parser.registerCsiHandler({final:"b"},(I=>this.repeatPrecedingCharacter(I))),this._parser.registerCsiHandler({final:"c"},(I=>this.sendDeviceAttributesPrimary(I))),this._parser.registerCsiHandler({prefix:">",final:"c"},(I=>this.sendDeviceAttributesSecondary(I))),this._parser.registerCsiHandler({final:"d"},(I=>this.linePosAbsolute(I))),this._parser.registerCsiHandler({final:"e"},(I=>this.vPositionRelative(I))),this._parser.registerCsiHandler({final:"f"},(I=>this.hVPosition(I))),this._parser.registerCsiHandler({final:"g"},(I=>this.tabClear(I))),this._parser.registerCsiHandler({final:"h"},(I=>this.setMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(I=>this.setModePrivate(I))),this._parser.registerCsiHandler({final:"l"},(I=>this.resetMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(I=>this.resetModePrivate(I))),this._parser.registerCsiHandler({final:"m"},(I=>this.charAttributes(I))),this._parser.registerCsiHandler({final:"n"},(I=>this.deviceStatus(I))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(I=>this.deviceStatusPrivate(I))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(I=>this.softReset(I))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(I=>this.setCursorStyle(I))),this._parser.registerCsiHandler({final:"r"},(I=>this.setScrollRegion(I))),this._parser.registerCsiHandler({final:"s"},(I=>this.saveCursor(I))),this._parser.registerCsiHandler({final:"t"},(I=>this.windowOptions(I))),this._parser.registerCsiHandler({final:"u"},(I=>this.restoreCursor(I))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(I=>this.insertColumns(I))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(I=>this.deleteColumns(I))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(I=>this.selectProtected(I))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(I=>this.requestMode(I,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(I=>this.requestMode(I,!1))),this._parser.setExecuteHandler(h.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(h.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(h.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(h.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(h.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(h.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(h.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(h.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(h.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new C.OscHandler((I=>(this.setTitle(I),this.setIconName(I),!0)))),this._parser.registerOscHandler(1,new C.OscHandler((I=>this.setIconName(I)))),this._parser.registerOscHandler(2,new C.OscHandler((I=>this.setTitle(I)))),this._parser.registerOscHandler(4,new C.OscHandler((I=>this.setOrReportIndexedColor(I)))),this._parser.registerOscHandler(8,new C.OscHandler((I=>this.setHyperlink(I)))),this._parser.registerOscHandler(10,new C.OscHandler((I=>this.setOrReportFgColor(I)))),this._parser.registerOscHandler(11,new C.OscHandler((I=>this.setOrReportBgColor(I)))),this._parser.registerOscHandler(12,new C.OscHandler((I=>this.setOrReportCursorColor(I)))),this._parser.registerOscHandler(104,new C.OscHandler((I=>this.restoreIndexedColor(I)))),this._parser.registerOscHandler(110,new C.OscHandler((I=>this.restoreFgColor(I)))),this._parser.registerOscHandler(111,new C.OscHandler((I=>this.restoreBgColor(I)))),this._parser.registerOscHandler(112,new C.OscHandler((I=>this.restoreCursorColor(I)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(let I in _.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:I},(()=>this.selectCharset("("+I))),this._parser.registerEscHandler({intermediates:")",final:I},(()=>this.selectCharset(")"+I))),this._parser.registerEscHandler({intermediates:"*",final:I},(()=>this.selectCharset("*"+I))),this._parser.registerEscHandler({intermediates:"+",final:I},(()=>this.selectCharset("+"+I))),this._parser.registerEscHandler({intermediates:"-",final:I},(()=>this.selectCharset("-"+I))),this._parser.registerEscHandler({intermediates:".",final:I},(()=>this.selectCharset("."+I))),this._parser.registerEscHandler({intermediates:"/",final:I},(()=>this.selectCharset("/"+I)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((I=>(this._logService.error("Parsing error: ",I),I))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new k.DcsHandler(((I,Q)=>this.requestStatusString(I,Q))))}_preserveStack(S,T,E,x){this._parseStack.paused=!0,this._parseStack.cursorStartX=S,this._parseStack.cursorStartY=T,this._parseStack.decodedLength=E,this._parseStack.position=x}_logSlowResolvingAsync(S){this._logService.logLevel<=m.LogLevelEnum.WARN&&Promise.race([S,new Promise(((T,E)=>setTimeout((()=>E("#SLOW_TIMEOUT")),5e3)))]).catch((T=>{if(T!=="#SLOW_TIMEOUT")throw T;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(S,T){let E,x=this._activeBuffer.x,M=this._activeBuffer.y,N=0,U=this._parseStack.paused;if(U){if(E=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,T))return this._logSlowResolvingAsync(E),E;x=this._parseStack.cursorStartX,M=this._parseStack.cursorStartY,this._parseStack.paused=!1,S.length>L&&(N=this._parseStack.position+L)}if(this._logService.logLevel<=m.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+(typeof S=="string"?` "${S}"`:` "${Array.prototype.map.call(S,(I=>String.fromCharCode(I))).join("")}"`)),this._logService.logLevel===m.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)",typeof S=="string"?S.split("").map((I=>I.charCodeAt(0))):S),this._parseBuffer.length<S.length&&this._parseBuffer.length<L&&(this._parseBuffer=new Uint32Array(Math.min(S.length,L))),U||this._dirtyRowTracker.clearRange(),S.length>L)for(let I=N;I<S.length;I+=L){let Q=I+L<S.length?I+L:S.length,J=typeof S=="string"?this._stringDecoder.decode(S.substring(I,Q),this._parseBuffer):this._utf8Decoder.decode(S.subarray(I,Q),this._parseBuffer);if(E=this._parser.parse(this._parseBuffer,J))return this._preserveStack(x,M,J,I),this._logSlowResolvingAsync(E),E}else if(!U){let I=typeof S=="string"?this._stringDecoder.decode(S,this._parseBuffer):this._utf8Decoder.decode(S,this._parseBuffer);if(E=this._parser.parse(this._parseBuffer,I))return this._preserveStack(x,M,I,0),this._logSlowResolvingAsync(E),E}this._activeBuffer.x===x&&this._activeBuffer.y===M||this._onCursorMove.fire();let z=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),ne=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);ne<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(ne,this._bufferService.rows-1),end:Math.min(z,this._bufferService.rows-1)})}print(S,T,E){let x,M,N=this._charsetService.charset,U=this._optionsService.rawOptions.screenReaderMode,z=this._bufferService.cols,ne=this._coreService.decPrivateModes.wraparound,I=this._coreService.modes.insertMode,Q=this._curAttrData,J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&E-T>0&&J.getWidth(this._activeBuffer.x-1)===2&&J.setCellFromCodepoint(this._activeBuffer.x-1,0,1,Q);let te=this._parser.precedingJoinState;for(let Ae=T;Ae<E;++Ae){if(x=S[Ae],x<127&&N){let _t=N[String.fromCharCode(x)];_t&&(x=_t.charCodeAt(0))}let Ie=this._unicodeService.charProperties(x,te);M=w.UnicodeService.extractWidth(Ie);let Jt=w.UnicodeService.extractShouldJoin(Ie),We=Jt?w.UnicodeService.extractWidth(te):0;if(te=Ie,U&&this._onA11yChar.fire((0,b.stringFromCodePoint)(x)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+M-We>z){if(ne){let _t=J,kr=this._activeBuffer.x-We;for(this._activeBuffer.x=We,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),We>0&&J instanceof c.BufferLine&&J.copyCellsFrom(_t,kr,0,We,!1);kr<z;)_t.setCellFromCodepoint(kr++,0,1,Q)}else if(this._activeBuffer.x=z-1,M===2)continue}if(Jt&&this._activeBuffer.x){let _t=J.getWidth(this._activeBuffer.x-1)?1:2;J.addCodepointToCell(this._activeBuffer.x-_t,x,M);for(let kr=M-We;--kr>=0;)J.setCellFromCodepoint(this._activeBuffer.x++,0,0,Q)}else if(I&&(J.insertCells(this._activeBuffer.x,M-We,this._activeBuffer.getNullCell(Q)),J.getWidth(z-1)===2&&J.setCellFromCodepoint(z-1,v.NULL_CELL_CODE,v.NULL_CELL_WIDTH,Q)),J.setCellFromCodepoint(this._activeBuffer.x++,x,M,Q),M>0)for(;--M;)J.setCellFromCodepoint(this._activeBuffer.x++,0,0,Q)}this._parser.precedingJoinState=te,this._activeBuffer.x<z&&E-T>0&&J.getWidth(this._activeBuffer.x)===0&&!J.hasContent(this._activeBuffer.x)&&J.setCellFromCodepoint(this._activeBuffer.x,0,1,Q),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(S,T){return S.final!=="t"||S.prefix||S.intermediates?this._parser.registerCsiHandler(S,T):this._parser.registerCsiHandler(S,(E=>!R(E.params[0],this._optionsService.rawOptions.windowOptions)||T(E)))}registerDcsHandler(S,T){return this._parser.registerDcsHandler(S,new k.DcsHandler(T))}registerEscHandler(S,T){return this._parser.registerEscHandler(S,T)}registerOscHandler(S,T){return this._parser.registerOscHandler(S,new C.OscHandler(T))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let S=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);S.hasWidth(this._activeBuffer.x)&&!S.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let S=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-S),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(S=this._bufferService.cols-1){this._activeBuffer.x=Math.min(S,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(S,T){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=S,this._activeBuffer.y=this._activeBuffer.scrollTop+T):(this._activeBuffer.x=S,this._activeBuffer.y=T),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(S,T){this._restrictCursor(),this._setCursor(this._activeBuffer.x+S,this._activeBuffer.y+T)}cursorUp(S){let T=this._activeBuffer.y-this._activeBuffer.scrollTop;return T>=0?this._moveCursor(0,-Math.min(T,S.params[0]||1)):this._moveCursor(0,-(S.params[0]||1)),!0}cursorDown(S){let T=this._activeBuffer.scrollBottom-this._activeBuffer.y;return T>=0?this._moveCursor(0,Math.min(T,S.params[0]||1)):this._moveCursor(0,S.params[0]||1),!0}cursorForward(S){return this._moveCursor(S.params[0]||1,0),!0}cursorBackward(S){return this._moveCursor(-(S.params[0]||1),0),!0}cursorNextLine(S){return this.cursorDown(S),this._activeBuffer.x=0,!0}cursorPrecedingLine(S){return this.cursorUp(S),this._activeBuffer.x=0,!0}cursorCharAbsolute(S){return this._setCursor((S.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(S){return this._setCursor(S.length>=2?(S.params[1]||1)-1:0,(S.params[0]||1)-1),!0}charPosAbsolute(S){return this._setCursor((S.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(S){return this._moveCursor(S.params[0]||1,0),!0}linePosAbsolute(S){return this._setCursor(this._activeBuffer.x,(S.params[0]||1)-1),!0}vPositionRelative(S){return this._moveCursor(0,S.params[0]||1),!0}hVPosition(S){return this.cursorPosition(S),!0}tabClear(S){let T=S.params[0];return T===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:T===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(S){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=S.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(S){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=S.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(S){let T=S.params[0];return T===1&&(this._curAttrData.bg|=536870912),T!==2&&T!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(S,T,E,x=!1,M=!1){let N=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);N.replaceCells(T,E,this._activeBuffer.getNullCell(this._eraseAttrData()),M),x&&(N.isWrapped=!1)}_resetBufferLine(S,T=!1){let E=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);E&&(E.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),T),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+S),E.isWrapped=!1)}eraseInDisplay(S,T=!1){let E;switch(this._restrictCursor(this._bufferService.cols),S.params[0]){case 0:for(E=this._activeBuffer.y,this._dirtyRowTracker.markDirty(E),this._eraseInBufferLine(E++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);E<this._bufferService.rows;E++)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(E);break;case 1:for(E=this._activeBuffer.y,this._dirtyRowTracker.markDirty(E),this._eraseInBufferLine(E,0,this._activeBuffer.x+1,!0,T),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(E+1).isWrapped=!1);E--;)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(E=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,E-1);E--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+E)?.getTrimmedLength(););for(;E>=0;E--)this._bufferService.scroll(this._eraseAttrData())}else{for(E=this._bufferService.rows,this._dirtyRowTracker.markDirty(E-1);E--;)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(0)}break;case 3:let x=this._activeBuffer.lines.length-this._bufferService.rows;x>0&&(this._activeBuffer.lines.trimStart(x),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-x,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-x,0),this._onScroll.fire(0))}return!0}eraseInLine(S,T=!1){switch(this._restrictCursor(this._bufferService.cols),S.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,T);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,T)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(S){this._restrictCursor();let T=S.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let E=this._activeBuffer.ybase+this._activeBuffer.y,x=this._bufferService.rows-1-this._activeBuffer.scrollBottom,M=this._bufferService.rows-1+this._activeBuffer.ybase-x+1;for(;T--;)this._activeBuffer.lines.splice(M-1,1),this._activeBuffer.lines.splice(E,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(S){this._restrictCursor();let T=S.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let E=this._activeBuffer.ybase+this._activeBuffer.y,x;for(x=this._bufferService.rows-1-this._activeBuffer.scrollBottom,x=this._bufferService.rows-1+this._activeBuffer.ybase-x;T--;)this._activeBuffer.lines.splice(E,1),this._activeBuffer.lines.splice(x,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.insertCells(this._activeBuffer.x,S.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.deleteCells(this._activeBuffer.x,S.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(S){let T=S.params[0]||1;for(;T--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(S){let T=S.params[0]||1;for(;T--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(c.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.deleteCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.insertCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.insertCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.deleteCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(S.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(S){let T=this._parser.precedingJoinState;if(!T)return!0;let E=S.params[0]||1,x=w.UnicodeService.extractWidth(T),M=this._activeBuffer.x-x,N=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(M),U=new Uint32Array(N.length*E),z=0;for(let I=0;I<N.length;){let Q=N.codePointAt(I)||0;U[z++]=Q,I+=Q>65535?2:1}let ne=z;for(let I=1;I<E;++I)U.copyWithin(ne,0,z),ne+=z;return this.print(U,0,ne),!0}sendDeviceAttributesPrimary(S){return S.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(h.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(h.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(S){return S.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(h.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(h.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(S.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(h.C0.ESC+"[>83;40003;0c")),!0}_is(S){return(this._optionsService.rawOptions.termName+"").indexOf(S)===0}setMode(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),this._charsetService.setgCharset(1,_.DEFAULT_CHARSET),this._charsetService.setgCharset(2,_.DEFAULT_CHARSET),this._charsetService.setgCharset(3,_.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),S.params[T]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(S,T){let E=this._coreService.decPrivateModes,{activeProtocol:x,activeEncoding:M}=this._coreMouseService,N=this._coreService,{buffers:U,cols:z}=this._bufferService,{active:ne,alt:I}=U,Q=this._optionsService.rawOptions,J=Jt=>Jt?1:2,te=S.params[0];return Ae=te,Ie=T?te===2?4:te===4?J(N.modes.insertMode):te===12?3:te===20?J(Q.convertEol):0:te===1?J(E.applicationCursorKeys):te===3?Q.windowOptions.setWinLines?z===80?2:z===132?1:0:0:te===6?J(E.origin):te===7?J(E.wraparound):te===8?3:te===9?J(x==="X10"):te===12?J(Q.cursorBlink):te===25?J(!N.isCursorHidden):te===45?J(E.reverseWraparound):te===66?J(E.applicationKeypad):te===67?4:te===1e3?J(x==="VT200"):te===1002?J(x==="DRAG"):te===1003?J(x==="ANY"):te===1004?J(E.sendFocus):te===1005?4:te===1006?J(M==="SGR"):te===1015?4:te===1016?J(M==="SGR_PIXELS"):te===1048?1:te===47||te===1047||te===1049?J(ne===I):te===2004?J(E.bracketedPasteMode):te===2026?J(E.synchronizedOutput):0,N.triggerDataEvent(`${h.C0.ESC}[${T?"":"?"}${Ae};${Ie}$y`),!0;var Ae,Ie}_updateAttrColor(S,T,E,x,M){return T===2?(S|=50331648,S&=-16777216,S|=f.AttributeData.fromColorRGB([E,x,M])):T===5&&(S&=-50331904,S|=33554432|255&E),S}_extractColor(S,T,E){let x=[0,0,-1,0,0,0],M=0,N=0;do{if(x[N+M]=S.params[T+N],S.hasSubParams(T+N)){let U=S.getSubParams(T+N),z=0;do x[1]===5&&(M=1),x[N+z+1+M]=U[z];while(++z<U.length&&z+N+1+M<x.length);break}if(x[1]===5&&N+M>=2||x[1]===2&&N+M>=5)break;x[1]&&(M=1)}while(++N+T<S.length&&N+M<x.length);for(let U=2;U<x.length;++U)x[U]===-1&&(x[U]=0);switch(x[0]){case 38:E.fg=this._updateAttrColor(E.fg,x[1],x[3],x[4],x[5]);break;case 48:E.bg=this._updateAttrColor(E.bg,x[1],x[3],x[4],x[5]);break;case 58:E.extended=E.extended.clone(),E.extended.underlineColor=this._updateAttrColor(E.extended.underlineColor,x[1],x[3],x[4],x[5])}return N}_processUnderline(S,T){T.extended=T.extended.clone(),(!~S||S>5)&&(S=1),T.extended.underlineStyle=S,T.fg|=268435456,S===0&&(T.fg&=-268435457),T.updateExtended()}_processSGR0(S){S.fg=c.DEFAULT_ATTR_DATA.fg,S.bg=c.DEFAULT_ATTR_DATA.bg,S.extended=S.extended.clone(),S.extended.underlineStyle=0,S.extended.underlineColor&=-67108864,S.updateExtended()}charAttributes(S){if(S.length===1&&S.params[0]===0)return this._processSGR0(this._curAttrData),!0;let T=S.length,E,x=this._curAttrData;for(let M=0;M<T;M++)E=S.params[M],E>=30&&E<=37?(x.fg&=-50331904,x.fg|=16777216|E-30):E>=40&&E<=47?(x.bg&=-50331904,x.bg|=16777216|E-40):E>=90&&E<=97?(x.fg&=-50331904,x.fg|=16777224|E-90):E>=100&&E<=107?(x.bg&=-50331904,x.bg|=16777224|E-100):E===0?this._processSGR0(x):E===1?x.fg|=134217728:E===3?x.bg|=67108864:E===4?(x.fg|=268435456,this._processUnderline(S.hasSubParams(M)?S.getSubParams(M)[0]:1,x)):E===5?x.fg|=536870912:E===7?x.fg|=67108864:E===8?x.fg|=1073741824:E===9?x.fg|=2147483648:E===2?x.bg|=134217728:E===21?this._processUnderline(2,x):E===22?(x.fg&=-134217729,x.bg&=-134217729):E===23?x.bg&=-67108865:E===24?(x.fg&=-268435457,this._processUnderline(0,x)):E===25?x.fg&=-536870913:E===27?x.fg&=-67108865:E===28?x.fg&=-1073741825:E===29?x.fg&=2147483647:E===39?(x.fg&=-67108864,x.fg|=16777215&c.DEFAULT_ATTR_DATA.fg):E===49?(x.bg&=-67108864,x.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):E===38||E===48||E===58?M+=this._extractColor(S,M,x):E===53?x.bg|=1073741824:E===55?x.bg&=-1073741825:E===59?(x.extended=x.extended.clone(),x.extended.underlineColor=-1,x.updateExtended()):E===100?(x.fg&=-67108864,x.fg|=16777215&c.DEFAULT_ATTR_DATA.fg,x.bg&=-67108864,x.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",E);return!0}deviceStatus(S){switch(S.params[0]){case 5:this._coreService.triggerDataEvent(`${h.C0.ESC}[0n`);break;case 6:let T=this._activeBuffer.y+1,E=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[${T};${E}R`)}return!0}deviceStatusPrivate(S){if(S.params[0]===6){let T=this._activeBuffer.y+1,E=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[?${T};${E}R`)}return!0}softReset(S){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(S){let T=S.length===0?1:S.params[0];if(T===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(T){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}let E=T%2==1;this._coreService.decPrivateModes.cursorBlink=E}return!0}setScrollRegion(S){let T=S.params[0]||1,E;return(S.length<2||(E=S.params[1])>this._bufferService.rows||E===0)&&(E=this._bufferService.rows),E>T&&(this._activeBuffer.scrollTop=T-1,this._activeBuffer.scrollBottom=E-1,this._setCursor(0,0)),!0}windowOptions(S){if(!R(S.params[0],this._optionsService.rawOptions.windowOptions))return!0;let T=S.length>1?S.params[1]:0;switch(S.params[0]){case 14:T!==2&&this._onRequestWindowsOptionsReport.fire(P.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(P.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${h.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:T!==0&&T!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),T!==0&&T!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:T!==0&&T!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),T!==0&&T!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(S){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(S){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(S){return this._windowTitle=S,this._onTitleChange.fire(S),!0}setIconName(S){return this._iconName=S,!0}setOrReportIndexedColor(S){let T=[],E=S.split(";");for(;E.length>1;){let x=E.shift(),M=E.shift();if(/^\d+$/.exec(x)){let N=parseInt(x);if(Y(N))if(M==="?")T.push({type:0,index:N});else{let U=(0,A.parseColor)(M);U&&T.push({type:1,index:N,color:U})}}}return T.length&&this._onColor.fire(T),!0}setHyperlink(S){let T=S.indexOf(";");if(T===-1)return!0;let E=S.slice(0,T).trim(),x=S.slice(T+1);return x?this._createHyperlink(E,x):!E.trim()&&this._finishHyperlink()}_createHyperlink(S,T){this._getCurrentLinkId()&&this._finishHyperlink();let E=S.split(":"),x,M=E.findIndex((N=>N.startsWith("id=")));return M!==-1&&(x=E[M].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:x,uri:T}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(S,T){let E=S.split(";");for(let x=0;x<E.length&&!(T>=this._specialColors.length);++x,++T)if(E[x]==="?")this._onColor.fire([{type:0,index:this._specialColors[T]}]);else{let M=(0,A.parseColor)(E[x]);M&&this._onColor.fire([{type:1,index:this._specialColors[T],color:M}])}return!0}setOrReportFgColor(S){return this._setOrReportSpecialColor(S,0)}setOrReportBgColor(S){return this._setOrReportSpecialColor(S,1)}setOrReportCursorColor(S){return this._setOrReportSpecialColor(S,2)}restoreIndexedColor(S){if(!S)return this._onColor.fire([{type:2}]),!0;let T=[],E=S.split(";");for(let x=0;x<E.length;++x)if(/^\d+$/.exec(E[x])){let M=parseInt(E[x]);Y(M)&&T.push({type:2,index:M})}return T.length&&this._onColor.fire(T),!0}restoreFgColor(S){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(S){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(S){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),!0}selectCharset(S){return S.length!==2?(this.selectDefaultCharset(),!0):(S[0]==="/"||this._charsetService.setgCharset(O[S[0]],_.CHARSETS[S[1]]||_.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let S=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,S,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(S){return this._charsetService.setgLevel(S),!0}screenAlignmentPattern(){let S=new g.CellData;S.content=4194373,S.fg=this._curAttrData.fg,S.bg=this._curAttrData.bg,this._setCursor(0,0);for(let T=0;T<this._bufferService.rows;++T){let E=this._activeBuffer.ybase+this._activeBuffer.y+T,x=this._activeBuffer.lines.get(E);x&&(x.fill(S),x.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(S,T){let E=this._bufferService.buffer,x=this._optionsService.rawOptions;return(M=>(this._coreService.triggerDataEvent(`${h.C0.ESC}${M}${h.C0.ESC}\\`),!0))(S==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:S==='"p'?'P1$r61;1"p':S==="r"?`P1$r${E.scrollTop+1};${E.scrollBottom+1}r`:S==="m"?"P1$r0m":S===" q"?`P1$r${{block:2,underline:4,bar:6}[x.cursorStyle]-(x.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(S,T){this._dirtyRowTracker.markRangeDirty(S,T)}}n.InputHandler=V;let Z=class{constructor(j){this._bufferService=j,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(j){j<this.start?this.start=j:j>this.end&&(this.end=j)}markRangeDirty(j,S){j>S&&(F=j,j=S,S=F),j<this.start&&(this.start=j),S>this.end&&(this.end=S)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function Y(j){return 0<=j&&j<256}Z=u([y(0,m.IBufferService)],Z)},701:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isChromeOS=n.isLinux=n.isWindows=n.isIphone=n.isIpad=n.isMac=n.isSafari=n.isLegacyEdge=n.isFirefox=n.isNode=void 0,n.getSafariVersion=function(){if(!n.isSafari)return 0;let y=l.match(/Version\/(\d+)/);return y===null||y.length<2?0:parseInt(y[1])},n.isNode=typeof process<"u"&&"title"in process;let l=n.isNode?"node":navigator.userAgent,u=n.isNode?"node":navigator.platform;n.isFirefox=l.includes("Firefox"),n.isLegacyEdge=l.includes("Edge"),n.isSafari=/^((?!chrome|android).)*safari/i.test(l),n.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(u),n.isIpad=u==="iPad",n.isIphone=u==="iPhone",n.isWindows=["Windows","Win16","Win32","WinCE"].includes(u),n.isLinux=u.indexOf("Linux")>=0,n.isChromeOS=/\bCrOS\b/.test(l)},6168:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DebouncedIdleTask=n.IdleTaskQueue=n.PriorityTaskQueue=void 0;let u=l(701);class y{constructor(){this._tasks=[],this._i=0}enqueue(d){this._tasks.push(d),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(d){this._idleCallback=void 0;let p=0,b=0,c=d.timeRemaining(),v=0;for(;this._i<this._tasks.length;){if(p=performance.now(),this._tasks[this._i]()||this._i++,p=Math.max(1,performance.now()-p),b=Math.max(p,b),v=d.timeRemaining(),1.5*b>v)return c-p<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(c-p))}ms`),void this._start();c=v}this.clear()}}class h extends y{_requestCallback(d){return setTimeout((()=>d(this._createDeadline(16))))}_cancelCallback(d){clearTimeout(d)}_createDeadline(d){let p=performance.now()+d;return{timeRemaining:()=>Math.max(0,p-performance.now())}}}n.PriorityTaskQueue=h,n.IdleTaskQueue=!u.isNode&&"requestIdleCallback"in window?class extends y{_requestCallback(_){return requestIdleCallback(_)}_cancelCallback(_){cancelIdleCallback(_)}}:h,n.DebouncedIdleTask=class{constructor(){this._queue=new n.IdleTaskQueue}set(_){this._queue.clear(),this._queue.enqueue(_)}flush(){this._queue.flush()}}},5882:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateWindowsModeWrappedState=function(y){let h=y.buffer.lines.get(y.buffer.ybase+y.buffer.y-1),_=h?.get(y.cols-1),d=y.buffer.lines.get(y.buffer.ybase+y.buffer.y);d&&_&&(d.isWrapped=_[u.CHAR_DATA_CODE_INDEX]!==u.NULL_CELL_CODE&&_[u.CHAR_DATA_CODE_INDEX]!==u.WHITESPACE_CELL_CODE)};let u=l(8938)},5451:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExtendedAttrs=n.AttributeData=void 0;class l{constructor(){this.fg=0,this.bg=0,this.extended=new u}static toColorRGB(h){return[h>>>16&255,h>>>8&255,255&h]}static fromColorRGB(h){return(255&h[0])<<16|(255&h[1])<<8|255&h[2]}clone(){let h=new l;return h.fg=this.fg,h.bg=this.bg,h.extended=this.extended.clone(),h}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}n.AttributeData=l;class u{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(h){this._ext=h}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(h){this._ext&=-469762049,this._ext|=h<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(h){this._ext&=-67108864,this._ext|=67108863&h}get urlId(){return this._urlId}set urlId(h){this._urlId=h}get underlineVariantOffset(){let h=(3758096384&this._ext)>>29;return h<0?4294967288^h:h}set underlineVariantOffset(h){this._ext&=536870911,this._ext|=h<<29&3758096384}constructor(h=0,_=0){this._ext=0,this._urlId=0,this._ext=h,this._urlId=_}clone(){return new u(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}n.ExtendedAttrs=u},1073:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Buffer=n.MAX_BUFFER_SIZE=void 0;let u=l(5639),y=l(6168),h=l(5451),_=l(6107),d=l(732),p=l(3055),b=l(8938),c=l(8158),v=l(6760);n.MAX_BUFFER_SIZE=4294967295,n.Buffer=class{constructor(g,f,m){this._hasScrollback=g,this._optionsService=f,this._bufferService=m,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=_.DEFAULT_ATTR_DATA.clone(),this.savedCharset=v.DEFAULT_CHARSET,this.markers=[],this._nullCell=p.CellData.fromCharData([0,b.NULL_CELL_CHAR,b.NULL_CELL_WIDTH,b.NULL_CELL_CODE]),this._whitespaceCell=p.CellData.fromCharData([0,b.WHITESPACE_CELL_CHAR,b.WHITESPACE_CELL_WIDTH,b.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new y.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new u.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(g){return g?(this._nullCell.fg=g.fg,this._nullCell.bg=g.bg,this._nullCell.extended=g.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new h.ExtendedAttrs),this._nullCell}getWhitespaceCell(g){return g?(this._whitespaceCell.fg=g.fg,this._whitespaceCell.bg=g.bg,this._whitespaceCell.extended=g.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new h.ExtendedAttrs),this._whitespaceCell}getBlankLine(g,f){return new _.BufferLine(this._bufferService.cols,this.getNullCell(g),f)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let g=this.ybase+this.y-this.ydisp;return g>=0&&g<this._rows}_getCorrectBufferLength(g){if(!this._hasScrollback)return g;let f=g+this._optionsService.rawOptions.scrollback;return f>n.MAX_BUFFER_SIZE?n.MAX_BUFFER_SIZE:f}fillViewportRows(g){if(this.lines.length===0){g===void 0&&(g=_.DEFAULT_ATTR_DATA);let f=this._rows;for(;f--;)this.lines.push(this.getBlankLine(g))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new u.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(g,f){let m=this.getNullCell(_.DEFAULT_ATTR_DATA),w=0,C=this._getCorrectBufferLength(f);if(C>this.lines.maxLength&&(this.lines.maxLength=C),this.lines.length>0){if(this._cols<g)for(let A=0;A<this.lines.length;A++)w+=+this.lines.get(A).resize(g,m);let k=0;if(this._rows<f)for(let A=this._rows;A<f;A++)this.lines.length<f+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new _.BufferLine(g,m)):this.ybase>0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new _.BufferLine(g,m)));else for(let A=this._rows;A>f;A--)this.lines.length>f+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(C<this.lines.maxLength){let A=this.lines.length-C;A>0&&(this.lines.trimStart(A),this.ybase=Math.max(this.ybase-A,0),this.ydisp=Math.max(this.ydisp-A,0),this.savedY=Math.max(this.savedY-A,0)),this.lines.maxLength=C}this.x=Math.min(this.x,g-1),this.y=Math.min(this.y,f-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,g-1),this.scrollTop=0}if(this.scrollBottom=f-1,this._isReflowEnabled&&(this._reflow(g,f),this._cols>g))for(let k=0;k<this.lines.length;k++)w+=+this.lines.get(k).resize(g,m);this._cols=g,this._rows=f,this._memoryCleanupQueue.clear(),w>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let g=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,g=!1);let f=0;for(;this._memoryCleanupPosition<this.lines.length;)if(f+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),f>100)return!0;return g}get _isReflowEnabled(){let g=this._optionsService.rawOptions.windowsPty;return g&&g.buildNumber?this._hasScrollback&&g.backend==="conpty"&&g.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(g,f){this._cols!==g&&(g>this._cols?this._reflowLarger(g,f):this._reflowSmaller(g,f))}_reflowLarger(g,f){let m=this._optionsService.rawOptions.reflowCursorLine,w=(0,d.reflowLargerGetLinesToRemove)(this.lines,this._cols,g,this.ybase+this.y,this.getNullCell(_.DEFAULT_ATTR_DATA),m);if(w.length>0){let C=(0,d.reflowLargerCreateNewLayout)(this.lines,w);(0,d.reflowLargerApplyNewLayout)(this.lines,C.layout),this._reflowLargerAdjustViewport(g,f,C.countRemoved)}}_reflowLargerAdjustViewport(g,f,m){let w=this.getNullCell(_.DEFAULT_ATTR_DATA),C=m;for(;C-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<f&&this.lines.push(new _.BufferLine(g,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-m,0)}_reflowSmaller(g,f){let m=this._optionsService.rawOptions.reflowCursorLine,w=this.getNullCell(_.DEFAULT_ATTR_DATA),C=[],k=0;for(let A=this.lines.length-1;A>=0;A--){let D=this.lines.get(A);if(!D||!D.isWrapped&&D.getTrimmedLength()<=g)continue;let O=[D];for(;D.isWrapped&&A>0;)D=this.lines.get(--A),O.unshift(D);if(!m){let E=this.ybase+this.y;if(E>=A&&E<A+O.length)continue}let L=O[O.length-1].getTrimmedLength(),R=(0,d.reflowSmallerGetNewLineLengths)(O,this._cols,g),P=R.length-O.length,F;F=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+P):Math.max(0,this.lines.length-this.lines.maxLength+P);let V=[];for(let E=0;E<P;E++){let x=this.getBlankLine(_.DEFAULT_ATTR_DATA,!0);V.push(x)}V.length>0&&(C.push({start:A+O.length+k,newLines:V}),k+=V.length),O.push(...V);let Z=R.length-1,Y=R[Z];Y===0&&(Z--,Y=R[Z]);let j=O.length-P-1,S=L;for(;j>=0;){let E=Math.min(S,Y);if(O[Z]===void 0)break;if(O[Z].copyCellsFrom(O[j],S-E,Y-E,E,!0),Y-=E,Y===0&&(Z--,Y=R[Z]),S-=E,S===0){j--;let x=Math.max(j,0);S=(0,d.getWrappedLineTrimmedLength)(O,x,this._cols)}}for(let E=0;E<O.length;E++)R[E]<g&&O[E].setCell(R[E],w);let T=P-F;for(;T-- >0;)this.ybase===0?this.y<f-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+k)-f&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+P,this.ybase+f-1)}if(C.length>0){let A=[],D=[];for(let Y=0;Y<this.lines.length;Y++)D.push(this.lines.get(Y));let O=this.lines.length,L=O-1,R=0,P=C[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+k);let F=0;for(let Y=Math.min(this.lines.maxLength-1,O+k-1);Y>=0;Y--)if(P&&P.start>L+F){for(let j=P.newLines.length-1;j>=0;j--)this.lines.set(Y--,P.newLines[j]);Y++,A.push({index:L+1,amount:P.newLines.length}),F+=P.newLines.length,P=C[++R]}else this.lines.set(Y,D[L--]);let V=0;for(let Y=A.length-1;Y>=0;Y--)A[Y].index+=V,this.lines.onInsertEmitter.fire(A[Y]),V+=A[Y].amount;let Z=Math.max(0,O+k-this.lines.maxLength);Z>0&&this.lines.onTrimEmitter.fire(Z)}}translateBufferLineToString(g,f,m=0,w){let C=this.lines.get(g);return C?C.translateToString(f,m,w):""}getWrappedRangeForLine(g){let f=g,m=g;for(;f>0&&this.lines.get(f).isWrapped;)f--;for(;m+1<this.lines.length&&this.lines.get(m+1).isWrapped;)m++;return{first:f,last:m}}setupTabStops(g){for(g!=null?this.tabs[g]||(g=this.prevStop(g)):(this.tabs={},g=0);g<this._cols;g+=this._optionsService.rawOptions.tabStopWidth)this.tabs[g]=!0}prevStop(g){for(g==null&&(g=this.x);!this.tabs[--g]&&g>0;);return g>=this._cols?this._cols-1:g<0?0:g}nextStop(g){for(g==null&&(g=this.x);!this.tabs[++g]&&g<this._cols;);return g>=this._cols?this._cols-1:g<0?0:g}clearMarkers(g){this._isClearing=!0;for(let f=0;f<this.markers.length;f++)this.markers[f].line===g&&(this.markers[f].dispose(),this.markers.splice(f--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let g=0;g<this.markers.length;g++)this.markers[g].dispose();this.markers.length=0,this._isClearing=!1}addMarker(g){let f=new c.Marker(g);return this.markers.push(f),f.register(this.lines.onTrim((m=>{f.line-=m,f.line<0&&f.dispose()}))),f.register(this.lines.onInsert((m=>{f.line>=m.index&&(f.line+=m.amount)}))),f.register(this.lines.onDelete((m=>{f.line>=m.index&&f.line<m.index+m.amount&&f.dispose(),f.line>m.index&&(f.line-=m.amount)}))),f.register(f.onDispose((()=>this._removeMarker(f)))),f}_removeMarker(g){this._isClearing||this.markers.splice(this.markers.indexOf(g),1)}}},6107:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLine=n.DEFAULT_ATTR_DATA=void 0;let u=l(5451),y=l(3055),h=l(8938),_=l(726);n.DEFAULT_ATTR_DATA=Object.freeze(new u.AttributeData);let d=0;class p{constructor(c,v,g=!1){this.isWrapped=g,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*c);let f=v||y.CellData.fromCharData([0,h.NULL_CELL_CHAR,h.NULL_CELL_WIDTH,h.NULL_CELL_CODE]);for(let m=0;m<c;++m)this.setCell(m,f);this.length=c}get(c){let v=this._data[3*c+0],g=2097151&v;return[this._data[3*c+1],2097152&v?this._combined[c]:g?(0,_.stringFromCodePoint)(g):"",v>>22,2097152&v?this._combined[c].charCodeAt(this._combined[c].length-1):g]}set(c,v){this._data[3*c+1]=v[h.CHAR_DATA_ATTR_INDEX],v[h.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[c]=v[1],this._data[3*c+0]=2097152|c|v[h.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*c+0]=v[h.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|v[h.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(c){return this._data[3*c+0]>>22}hasWidth(c){return 12582912&this._data[3*c+0]}getFg(c){return this._data[3*c+1]}getBg(c){return this._data[3*c+2]}hasContent(c){return 4194303&this._data[3*c+0]}getCodePoint(c){let v=this._data[3*c+0];return 2097152&v?this._combined[c].charCodeAt(this._combined[c].length-1):2097151&v}isCombined(c){return 2097152&this._data[3*c+0]}getString(c){let v=this._data[3*c+0];return 2097152&v?this._combined[c]:2097151&v?(0,_.stringFromCodePoint)(2097151&v):""}isProtected(c){return 536870912&this._data[3*c+2]}loadCell(c,v){return d=3*c,v.content=this._data[d+0],v.fg=this._data[d+1],v.bg=this._data[d+2],2097152&v.content&&(v.combinedData=this._combined[c]),268435456&v.bg&&(v.extended=this._extendedAttrs[c]),v}setCell(c,v){2097152&v.content&&(this._combined[c]=v.combinedData),268435456&v.bg&&(this._extendedAttrs[c]=v.extended),this._data[3*c+0]=v.content,this._data[3*c+1]=v.fg,this._data[3*c+2]=v.bg}setCellFromCodepoint(c,v,g,f){268435456&f.bg&&(this._extendedAttrs[c]=f.extended),this._data[3*c+0]=v|g<<22,this._data[3*c+1]=f.fg,this._data[3*c+2]=f.bg}addCodepointToCell(c,v,g){let f=this._data[3*c+0];2097152&f?this._combined[c]+=(0,_.stringFromCodePoint)(v):2097151&f?(this._combined[c]=(0,_.stringFromCodePoint)(2097151&f)+(0,_.stringFromCodePoint)(v),f&=-2097152,f|=2097152):f=v|4194304,g&&(f&=-12582913,f|=g<<22),this._data[3*c+0]=f}insertCells(c,v,g){if((c%=this.length)&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length-c){let f=new y.CellData;for(let m=this.length-c-v-1;m>=0;--m)this.setCell(c+v+m,this.loadCell(c+m,f));for(let m=0;m<v;++m)this.setCell(c+m,g)}else for(let f=c;f<this.length;++f)this.setCell(f,g);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,g)}deleteCells(c,v,g){if(c%=this.length,v<this.length-c){let f=new y.CellData;for(let m=0;m<this.length-c-v;++m)this.setCell(c+m,this.loadCell(c+v+m,f));for(let m=this.length-v;m<this.length;++m)this.setCell(m,g)}else for(let f=c;f<this.length;++f)this.setCell(f,g);c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),this.getWidth(c)!==0||this.hasContent(c)||this.setCellFromCodepoint(c,0,1,g)}replaceCells(c,v,g,f=!1){if(f)for(c&&this.getWidth(c-1)===2&&!this.isProtected(c-1)&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length&&this.getWidth(v-1)===2&&!this.isProtected(v)&&this.setCellFromCodepoint(v,0,1,g);c<v&&c<this.length;)this.isProtected(c)||this.setCell(c,g),c++;else for(c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length&&this.getWidth(v-1)===2&&this.setCellFromCodepoint(v,0,1,g);c<v&&c<this.length;)this.setCell(c++,g)}resize(c,v){if(c===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let g=3*c;if(c>this.length){if(this._data.buffer.byteLength>=4*g)this._data=new Uint32Array(this._data.buffer,0,g);else{let f=new Uint32Array(g);f.set(this._data),this._data=f}for(let f=this.length;f<c;++f)this.setCell(f,v)}else{this._data=this._data.subarray(0,g);let f=Object.keys(this._combined);for(let w=0;w<f.length;w++){let C=parseInt(f[w],10);C>=c&&delete this._combined[C]}let m=Object.keys(this._extendedAttrs);for(let w=0;w<m.length;w++){let C=parseInt(m[w],10);C>=c&&delete this._extendedAttrs[C]}}return this.length=c,4*g*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let c=new Uint32Array(this._data.length);return c.set(this._data),this._data=c,1}return 0}fill(c,v=!1){if(v)for(let g=0;g<this.length;++g)this.isProtected(g)||this.setCell(g,c);else{this._combined={},this._extendedAttrs={};for(let g=0;g<this.length;++g)this.setCell(g,c)}}copyFrom(c){this.length!==c.length?this._data=new Uint32Array(c._data):this._data.set(c._data),this.length=c.length,this._combined={};for(let v in c._combined)this._combined[v]=c._combined[v];this._extendedAttrs={};for(let v in c._extendedAttrs)this._extendedAttrs[v]=c._extendedAttrs[v];this.isWrapped=c.isWrapped}clone(){let c=new p(0);c._data=new Uint32Array(this._data),c.length=this.length;for(let v in this._combined)c._combined[v]=this._combined[v];for(let v in this._extendedAttrs)c._extendedAttrs[v]=this._extendedAttrs[v];return c.isWrapped=this.isWrapped,c}getTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0])return c+(this._data[3*c+0]>>22);return 0}getNoBgTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0]||50331648&this._data[3*c+2])return c+(this._data[3*c+0]>>22);return 0}copyCellsFrom(c,v,g,f,m){let w=c._data;if(m)for(let k=f-1;k>=0;k--){for(let A=0;A<3;A++)this._data[3*(g+k)+A]=w[3*(v+k)+A];268435456&w[3*(v+k)+2]&&(this._extendedAttrs[g+k]=c._extendedAttrs[v+k])}else for(let k=0;k<f;k++){for(let A=0;A<3;A++)this._data[3*(g+k)+A]=w[3*(v+k)+A];268435456&w[3*(v+k)+2]&&(this._extendedAttrs[g+k]=c._extendedAttrs[v+k])}let C=Object.keys(c._combined);for(let k=0;k<C.length;k++){let A=parseInt(C[k],10);A>=v&&(this._combined[A-v+g]=c._combined[A])}}translateToString(c,v,g,f){v=v??0,g=g??this.length,c&&(g=Math.min(g,this.getTrimmedLength())),f&&(f.length=0);let m="";for(;v<g;){let w=this._data[3*v+0],C=2097151&w,k=2097152&w?this._combined[v]:C?(0,_.stringFromCodePoint)(C):h.WHITESPACE_CELL_CHAR;if(m+=k,f)for(let A=0;A<k.length;++A)f.push(v);v+=w>>22||1}return f&&f.push(v),m}}n.BufferLine=p},732:(a,n)=>{function l(u,y,h){if(y===u.length-1)return u[y].getTrimmedLength();let _=!u[y].hasContent(h-1)&&u[y].getWidth(h-1)===1,d=u[y+1].getWidth(0)===2;return _&&d?h-1:h}Object.defineProperty(n,"__esModule",{value:!0}),n.reflowLargerGetLinesToRemove=function(u,y,h,_,d,p){let b=[];for(let c=0;c<u.length-1;c++){let v=c,g=u.get(++v);if(!g.isWrapped)continue;let f=[u.get(c)];for(;v<u.length&&g.isWrapped;)f.push(g),g=u.get(++v);if(!p&&_>=c&&_<v){c+=f.length-1;continue}let m=0,w=l(f,m,y),C=1,k=0;for(;C<f.length;){let D=l(f,C,y),O=D-k,L=h-w,R=Math.min(O,L);f[m].copyCellsFrom(f[C],k,w,R,!1),w+=R,w===h&&(m++,w=0),k+=R,k===D&&(C++,k=0),w===0&&m!==0&&f[m-1].getWidth(h-1)===2&&(f[m].copyCellsFrom(f[m-1],h-1,w++,1,!1),f[m-1].setCell(h-1,d))}f[m].replaceCells(w,h,d);let A=0;for(let D=f.length-1;D>0&&(D>m||f[D].getTrimmedLength()===0);D--)A++;A>0&&(b.push(c+f.length-A),b.push(A)),c+=f.length-1}return b},n.reflowLargerCreateNewLayout=function(u,y){let h=[],_=0,d=y[_],p=0;for(let b=0;b<u.length;b++)if(d===b){let c=y[++_];u.onDeleteEmitter.fire({index:b-p,amount:c}),b+=c-1,p+=c,d=y[++_]}else h.push(b);return{layout:h,countRemoved:p}},n.reflowLargerApplyNewLayout=function(u,y){let h=[];for(let _=0;_<y.length;_++)h.push(u.get(y[_]));for(let _=0;_<h.length;_++)u.set(_,h[_]);u.length=y.length},n.reflowSmallerGetNewLineLengths=function(u,y,h){let _=[],d=u.map(((v,g)=>l(u,g,y))).reduce(((v,g)=>v+g)),p=0,b=0,c=0;for(;c<d;){if(d-c<h){_.push(d-c);break}p+=h;let v=l(u,b,y);p>v&&(p-=v,b++);let g=u[b].getWidth(p-1)===2;g&&p--;let f=g?h-1:h;_.push(f),c+=f}return _},n.getWrappedLineTrimmedLength=l},4097:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferSet=void 0;let u=l(7150),y=l(1073),h=l(802);class _ extends u.Disposable{constructor(p,b){super(),this._optionsService=p,this._bufferService=b,this._onBufferActivate=this._register(new h.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new y.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new y.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(p){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(p),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(p,b){this._normal.resize(p,b),this._alt.resize(p,b),this.setupTabStops(p)}setupTabStops(p){this._normal.setupTabStops(p),this._alt.setupTabStops(p)}}n.BufferSet=_},3055:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CellData=void 0;let u=l(726),y=l(8938),h=l(5451);class _ extends h.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new h.ExtendedAttrs,this.combinedData=""}static fromCharData(p){let b=new _;return b.setFromCharData(p),b}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,u.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(p){this.fg=p[y.CHAR_DATA_ATTR_INDEX],this.bg=0;let b=!1;if(p[y.CHAR_DATA_CHAR_INDEX].length>2)b=!0;else if(p[y.CHAR_DATA_CHAR_INDEX].length===2){let c=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=c&&c<=56319){let v=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=v&&v<=57343?this.content=1024*(c-55296)+v-56320+65536|p[y.CHAR_DATA_WIDTH_INDEX]<<22:b=!0}else b=!0}else this.content=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|p[y.CHAR_DATA_WIDTH_INDEX]<<22;b&&(this.combinedData=p[y.CHAR_DATA_CHAR_INDEX],this.content=2097152|p[y.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.CellData=_},8938:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WHITESPACE_CELL_CODE=n.WHITESPACE_CELL_WIDTH=n.WHITESPACE_CELL_CHAR=n.NULL_CELL_CODE=n.NULL_CELL_WIDTH=n.NULL_CELL_CHAR=n.CHAR_DATA_CODE_INDEX=n.CHAR_DATA_WIDTH_INDEX=n.CHAR_DATA_CHAR_INDEX=n.CHAR_DATA_ATTR_INDEX=n.DEFAULT_EXT=n.DEFAULT_ATTR=n.DEFAULT_COLOR=void 0,n.DEFAULT_COLOR=0,n.DEFAULT_ATTR=n.DEFAULT_COLOR<<9|256,n.DEFAULT_EXT=0,n.CHAR_DATA_ATTR_INDEX=0,n.CHAR_DATA_CHAR_INDEX=1,n.CHAR_DATA_WIDTH_INDEX=2,n.CHAR_DATA_CODE_INDEX=3,n.NULL_CELL_CHAR="",n.NULL_CELL_WIDTH=1,n.NULL_CELL_CODE=0,n.WHITESPACE_CELL_CHAR=" ",n.WHITESPACE_CELL_WIDTH=1,n.WHITESPACE_CELL_CODE=32},8158:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Marker=void 0;let u=l(802),y=l(7150);class h{get id(){return this._id}constructor(d){this.line=d,this.isDisposed=!1,this._disposables=[],this._id=h._nextId++,this._onDispose=this.register(new u.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,y.dispose)(this._disposables),this._disposables.length=0)}register(d){return this._disposables.push(d),d}}n.Marker=h,h._nextId=1},6760:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DEFAULT_CHARSET=n.CHARSETS=void 0,n.CHARSETS={},n.DEFAULT_CHARSET=n.CHARSETS.B,n.CHARSETS[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"},n.CHARSETS.A={"#":"\xA3"},n.CHARSETS.B=void 0,n.CHARSETS[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"},n.CHARSETS.C=n.CHARSETS[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},n.CHARSETS.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"},n.CHARSETS.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"},n.CHARSETS.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"},n.CHARSETS.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"},n.CHARSETS.E=n.CHARSETS[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"},n.CHARSETS.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"},n.CHARSETS.H=n.CHARSETS[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},n.CHARSETS["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"}},3534:(a,n)=>{var l,u,y;Object.defineProperty(n,"__esModule",{value:!0}),n.C1_ESCAPED=n.C1=n.C0=void 0,(function(h){h.NUL="\0",h.SOH="",h.STX="",h.ETX="",h.EOT="",h.ENQ="",h.ACK="",h.BEL="\x07",h.BS="\b",h.HT=" ",h.LF=`
65
- `,h.VT="\v",h.FF="\f",h.CR="\r",h.SO="",h.SI="",h.DLE="",h.DC1="",h.DC2="",h.DC3="",h.DC4="",h.NAK="",h.SYN="",h.ETB="",h.CAN="",h.EM="",h.SUB="",h.ESC="\x1B",h.FS="",h.GS="",h.RS="",h.US="",h.SP=" ",h.DEL="\x7F"})(l||(n.C0=l={})),(function(h){h.PAD="\x80",h.HOP="\x81",h.BPH="\x82",h.NBH="\x83",h.IND="\x84",h.NEL="\x85",h.SSA="\x86",h.ESA="\x87",h.HTS="\x88",h.HTJ="\x89",h.VTS="\x8A",h.PLD="\x8B",h.PLU="\x8C",h.RI="\x8D",h.SS2="\x8E",h.SS3="\x8F",h.DCS="\x90",h.PU1="\x91",h.PU2="\x92",h.STS="\x93",h.CCH="\x94",h.MW="\x95",h.SPA="\x96",h.EPA="\x97",h.SOS="\x98",h.SGCI="\x99",h.SCI="\x9A",h.CSI="\x9B",h.ST="\x9C",h.OSC="\x9D",h.PM="\x9E",h.APC="\x9F"})(u||(n.C1=u={})),(function(h){h.ST=`${l.ESC}\\`})(y||(n.C1_ESCAPED=y={}))},726:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=void 0,n.stringFromCodePoint=function(l){return l>65535?(l-=65536,String.fromCharCode(55296+(l>>10))+String.fromCharCode(l%1024+56320)):String.fromCharCode(l)},n.utf32ToString=function(l,u=0,y=l.length){let h="";for(let _=u;_<y;++_){let d=l[_];d>65535?(d-=65536,h+=String.fromCharCode(55296+(d>>10))+String.fromCharCode(d%1024+56320)):h+=String.fromCharCode(d)}return h},n.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(l,u){let y=l.length;if(!y)return 0;let h=0,_=0;if(this._interim){let d=l.charCodeAt(_++);56320<=d&&d<=57343?u[h++]=1024*(this._interim-55296)+d-56320+65536:(u[h++]=this._interim,u[h++]=d),this._interim=0}for(let d=_;d<y;++d){let p=l.charCodeAt(d);if(55296<=p&&p<=56319){if(++d>=y)return this._interim=p,h;let b=l.charCodeAt(d);56320<=b&&b<=57343?u[h++]=1024*(p-55296)+b-56320+65536:(u[h++]=p,u[h++]=b)}else p!==65279&&(u[h++]=p)}return h}},n.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(l,u){let y=l.length;if(!y)return 0;let h,_,d,p,b=0,c=0,v=0;if(this.interim[0]){let m=!1,w=this.interim[0];w&=(224&w)==192?31:(240&w)==224?15:7;let C,k=0;for(;(C=63&this.interim[++k])&&k<4;)w<<=6,w|=C;let A=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,D=A-k;for(;v<D;){if(v>=y)return 0;if(C=l[v++],(192&C)!=128){v--,m=!0;break}this.interim[k++]=C,w<<=6,w|=63&C}m||(A===2?w<128?v--:u[b++]=w:A===3?w<2048||w>=55296&&w<=57343||w===65279||(u[b++]=w):w<65536||w>1114111||(u[b++]=w)),this.interim.fill(0)}let g=y-4,f=v;for(;f<y;){for(;!(!(f<g)||128&(h=l[f])||128&(_=l[f+1])||128&(d=l[f+2])||128&(p=l[f+3]));)u[b++]=h,u[b++]=_,u[b++]=d,u[b++]=p,f+=4;if(h=l[f++],h<128)u[b++]=h;else if((224&h)==192){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(c=(31&h)<<6|63&_,c<128){f--;continue}u[b++]=c}else if((240&h)==224){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,b;if(d=l[f++],(192&d)!=128){f--;continue}if(c=(15&h)<<12|(63&_)<<6|63&d,c<2048||c>=55296&&c<=57343||c===65279)continue;u[b++]=c}else if((248&h)==240){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,b;if(d=l[f++],(192&d)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,this.interim[2]=d,b;if(p=l[f++],(192&p)!=128){f--;continue}if(c=(7&h)<<18|(63&_)<<12|(63&d)<<6|63&p,c<65536||c>1114111)continue;u[b++]=c}}return b}}},7428:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeV6=void 0;let u=l(6415),y=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],h=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],_;n.UnicodeV6=class{constructor(){if(this.version="6",!_){_=new Uint8Array(65536),_.fill(1),_[0]=0,_.fill(0,1,32),_.fill(0,127,160),_.fill(2,4352,4448),_[9001]=2,_[9002]=2,_.fill(2,11904,42192),_[12351]=1,_.fill(2,44032,55204),_.fill(2,63744,64256),_.fill(2,65040,65050),_.fill(2,65072,65136),_.fill(2,65280,65377),_.fill(2,65504,65511);for(let d=0;d<y.length;++d)_.fill(0,y[d][0],y[d][1]+1)}}wcwidth(d){return d<32?0:d<127?1:d<65536?_[d]:(function(p,b){let c,v=0,g=b.length-1;if(p<b[0][0]||p>b[g][1])return!1;for(;g>=v;)if(c=v+g>>1,p>b[c][1])v=c+1;else{if(!(p<b[c][0]))return!0;g=c-1}return!1})(d,h)?0:d>=131072&&d<=196605||d>=196608&&d<=262141?2:1}charProperties(d,p){let b=this.wcwidth(d),c=b===0&&p!==0;if(c){let v=u.UnicodeService.extractWidth(p);v===0?c=!1:v>b&&(b=v)}return u.UnicodeService.createPropertyValue(0,b,c)}}},3562:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WriteBuffer=void 0;let u=l(7150),y=l(802);class h extends u.Disposable{constructor(d){super(),this._action=d,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new y.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(d,p){if(p!==void 0&&this._syncCalls>p)return void(this._syncCalls=0);if(this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let b;for(this._isSyncWriting=!0;b=this._writeBuffer.shift();){this._action(b);let c=this._callbacks.shift();c&&c()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(d,p){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(p),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(p)}_innerWrite(d=0,p=!0){let b=d||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let c=this._writeBuffer[this._bufferOffset],v=this._action(c,p);if(v){let f=m=>performance.now()-b>=12?setTimeout((()=>this._innerWrite(0,m))):this._innerWrite(b,m);return void v.catch((m=>(queueMicrotask((()=>{throw m})),Promise.resolve(!1)))).then(f)}let g=this._callbacks[this._bufferOffset];if(g&&g(),this._bufferOffset++,this._pendingData-=c.length,performance.now()-b>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}n.WriteBuffer=h},8693:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseColor=function(h){if(!h)return;let _=h.toLowerCase();if(_.indexOf("rgb:")===0){_=_.slice(4);let d=l.exec(_);if(d){let p=d[1]?15:d[4]?255:d[7]?4095:65535;return[Math.round(parseInt(d[1]||d[4]||d[7]||d[10],16)/p*255),Math.round(parseInt(d[2]||d[5]||d[8]||d[11],16)/p*255),Math.round(parseInt(d[3]||d[6]||d[9]||d[12],16)/p*255)]}}else if(_.indexOf("#")===0&&(_=_.slice(1),u.exec(_)&&[3,6,9,12].includes(_.length))){let d=_.length/3,p=[0,0,0];for(let b=0;b<3;++b){let c=parseInt(_.slice(d*b,d*b+d),16);p[b]=d===1?c<<4:d===2?c:d===3?c>>4:c>>8}return p}},n.toRgbString=function(h,_=16){let[d,p,b]=h;return`rgb:${y(d,_)}/${y(p,_)}/${y(b,_)}`};let l=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,u=/^[\da-f]+$/;function y(h,_){let d=h.toString(16),p=d.length<2?"0"+d:d;switch(_){case 4:return d[0];case 8:return p;case 12:return(p+p).slice(0,3);default:return p+p}}},1263:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PAYLOAD_LIMIT=void 0,n.PAYLOAD_LIMIT=1e7},9823:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DcsHandler=n.DcsParser=void 0;let u=l(726),y=l(7262),h=l(1263),_=[];n.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=_,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_}registerHandler(p,b){this._handlers[p]===void 0&&(this._handlers[p]=[]);let c=this._handlers[p];return c.push(b),{dispose:()=>{let v=c.indexOf(b);v!==-1&&c.splice(v,1)}}}clearHandler(p){this._handlers[p]&&delete this._handlers[p]}setHandlerFallback(p){this._handlerFb=p}reset(){if(this._active.length)for(let p=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;p>=0;--p)this._active[p].unhook(!1);this._stack.paused=!1,this._active=_,this._ident=0}hook(p,b){if(this.reset(),this._ident=p,this._active=this._handlers[p]||_,this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].hook(b);else this._handlerFb(this._ident,"HOOK",b)}put(p,b,c){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(p,b,c);else this._handlerFb(this._ident,"PUT",(0,u.utf32ToString)(p,b,c))}unhook(p,b=!0){if(this._active.length){let c=!1,v=this._active.length-1,g=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,c=b,g=this._stack.fallThrough,this._stack.paused=!1),!g&&c===!1){for(;v>=0&&(c=this._active[v].unhook(p),c!==!0);v--)if(c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,c;v--}for(;v>=0;v--)if(c=this._active[v].unhook(!1),c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,c}else this._handlerFb(this._ident,"UNHOOK",p);this._active=_,this._ident=0}};let d=new y.Params;d.addParam(0),n.DcsHandler=class{constructor(p){this._handler=p,this._data="",this._params=d,this._hitLimit=!1}hook(p){this._params=p.length>1||p.params[0]?p.clone():d,this._data="",this._hitLimit=!1}put(p,b,c){this._hitLimit||(this._data+=(0,u.utf32ToString)(p,b,c),this._data.length>h.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(p){let b=!1;if(this._hitLimit)b=!1;else if(p&&(b=this._handler(this._data,this._params),b instanceof Promise))return b.then((c=>(this._params=d,this._data="",this._hitLimit=!1,c)));return this._params=d,this._data="",this._hitLimit=!1,b}}},6717:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.EscapeSequenceParser=n.VT500_TRANSITION_TABLE=n.TransitionTable=void 0;let u=l(7150),y=l(7262),h=l(1346),_=l(9823);class d{constructor(v){this.table=new Uint8Array(v)}setDefault(v,g){this.table.fill(v<<4|g)}add(v,g,f,m){this.table[g<<8|v]=f<<4|m}addMany(v,g,f,m){for(let w=0;w<v.length;w++)this.table[g<<8|v[w]]=f<<4|m}}n.TransitionTable=d;let p=160;n.VT500_TRANSITION_TABLE=(function(){let c=new d(4095),v=Array.apply(null,Array(256)).map(((k,A)=>A)),g=(k,A)=>v.slice(k,A),f=g(32,127),m=g(0,24);m.push(25),m.push.apply(m,g(28,32));let w=g(0,14),C;for(C in c.setDefault(1,0),c.addMany(f,0,2,0),w)c.addMany([24,26,153,154],C,3,0),c.addMany(g(128,144),C,3,0),c.addMany(g(144,152),C,3,0),c.add(156,C,0,0),c.add(27,C,11,1),c.add(157,C,4,8),c.addMany([152,158,159],C,0,7),c.add(155,C,11,3),c.add(144,C,11,9);return c.addMany(m,0,3,0),c.addMany(m,1,3,1),c.add(127,1,0,1),c.addMany(m,8,0,8),c.addMany(m,3,3,3),c.add(127,3,0,3),c.addMany(m,4,3,4),c.add(127,4,0,4),c.addMany(m,6,3,6),c.addMany(m,5,3,5),c.add(127,5,0,5),c.addMany(m,2,3,2),c.add(127,2,0,2),c.add(93,1,4,8),c.addMany(f,8,5,8),c.add(127,8,5,8),c.addMany([156,27,24,26,7],8,6,0),c.addMany(g(28,32),8,0,8),c.addMany([88,94,95],1,0,7),c.addMany(f,7,0,7),c.addMany(m,7,0,7),c.add(156,7,0,0),c.add(127,7,0,7),c.add(91,1,11,3),c.addMany(g(64,127),3,7,0),c.addMany(g(48,60),3,8,4),c.addMany([60,61,62,63],3,9,4),c.addMany(g(48,60),4,8,4),c.addMany(g(64,127),4,7,0),c.addMany([60,61,62,63],4,0,6),c.addMany(g(32,64),6,0,6),c.add(127,6,0,6),c.addMany(g(64,127),6,0,0),c.addMany(g(32,48),3,9,5),c.addMany(g(32,48),5,9,5),c.addMany(g(48,64),5,0,6),c.addMany(g(64,127),5,7,0),c.addMany(g(32,48),4,9,5),c.addMany(g(32,48),1,9,2),c.addMany(g(32,48),2,9,2),c.addMany(g(48,127),2,10,0),c.addMany(g(48,80),1,10,0),c.addMany(g(81,88),1,10,0),c.addMany([89,90,92],1,10,0),c.addMany(g(96,127),1,10,0),c.add(80,1,11,9),c.addMany(m,9,0,9),c.add(127,9,0,9),c.addMany(g(28,32),9,0,9),c.addMany(g(32,48),9,9,12),c.addMany(g(48,60),9,8,10),c.addMany([60,61,62,63],9,9,10),c.addMany(m,11,0,11),c.addMany(g(32,128),11,0,11),c.addMany(g(28,32),11,0,11),c.addMany(m,10,0,10),c.add(127,10,0,10),c.addMany(g(28,32),10,0,10),c.addMany(g(48,60),10,8,10),c.addMany([60,61,62,63],10,0,11),c.addMany(g(32,48),10,9,12),c.addMany(m,12,0,12),c.add(127,12,0,12),c.addMany(g(28,32),12,0,12),c.addMany(g(32,48),12,9,12),c.addMany(g(48,64),12,0,11),c.addMany(g(64,127),12,12,13),c.addMany(g(64,127),10,12,13),c.addMany(g(64,127),9,12,13),c.addMany(m,13,13,13),c.addMany(f,13,13,13),c.add(127,13,0,13),c.addMany([27,156,24,26],13,14,0),c.add(p,0,2,0),c.add(p,8,5,8),c.add(p,6,0,6),c.add(p,11,0,11),c.add(p,13,13,13),c})();class b extends u.Disposable{constructor(v=n.VT500_TRANSITION_TABLE){super(),this._transitions=v,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new y.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(g,f,m)=>{},this._executeHandlerFb=g=>{},this._csiHandlerFb=(g,f)=>{},this._escHandlerFb=g=>{},this._errorHandlerFb=g=>g,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,u.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this._register(new h.OscParser),this._dcsParser=this._register(new _.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(v,g=[64,126]){let f=0;if(v.prefix){if(v.prefix.length>1)throw new Error("only one byte as prefix supported");if(f=v.prefix.charCodeAt(0),f&&60>f||f>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(v.intermediates){if(v.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let w=0;w<v.intermediates.length;++w){let C=v.intermediates.charCodeAt(w);if(32>C||C>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");f<<=8,f|=C}}if(v.final.length!==1)throw new Error("final must be a single byte");let m=v.final.charCodeAt(0);if(g[0]>m||m>g[1])throw new Error(`final must be in range ${g[0]} .. ${g[1]}`);return f<<=8,f|=m,f}identToString(v){let g=[];for(;v;)g.push(String.fromCharCode(255&v)),v>>=8;return g.reverse().join("")}setPrintHandler(v){this._printHandler=v}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(v,g){let f=this._identifier(v,[48,126]);this._escHandlers[f]===void 0&&(this._escHandlers[f]=[]);let m=this._escHandlers[f];return m.push(g),{dispose:()=>{let w=m.indexOf(g);w!==-1&&m.splice(w,1)}}}clearEscHandler(v){this._escHandlers[this._identifier(v,[48,126])]&&delete this._escHandlers[this._identifier(v,[48,126])]}setEscHandlerFallback(v){this._escHandlerFb=v}setExecuteHandler(v,g){this._executeHandlers[v.charCodeAt(0)]=g}clearExecuteHandler(v){this._executeHandlers[v.charCodeAt(0)]&&delete this._executeHandlers[v.charCodeAt(0)]}setExecuteHandlerFallback(v){this._executeHandlerFb=v}registerCsiHandler(v,g){let f=this._identifier(v);this._csiHandlers[f]===void 0&&(this._csiHandlers[f]=[]);let m=this._csiHandlers[f];return m.push(g),{dispose:()=>{let w=m.indexOf(g);w!==-1&&m.splice(w,1)}}}clearCsiHandler(v){this._csiHandlers[this._identifier(v)]&&delete this._csiHandlers[this._identifier(v)]}setCsiHandlerFallback(v){this._csiHandlerFb=v}registerDcsHandler(v,g){return this._dcsParser.registerHandler(this._identifier(v),g)}clearDcsHandler(v){this._dcsParser.clearHandler(this._identifier(v))}setDcsHandlerFallback(v){this._dcsParser.setHandlerFallback(v)}registerOscHandler(v,g){return this._oscParser.registerHandler(v,g)}clearOscHandler(v){this._oscParser.clearHandler(v)}setOscHandlerFallback(v){this._oscParser.setHandlerFallback(v)}setErrorHandler(v){this._errorHandler=v}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(v,g,f,m,w){this._parseStack.state=v,this._parseStack.handlers=g,this._parseStack.handlerPos=f,this._parseStack.transition=m,this._parseStack.chunkPos=w}parse(v,g,f){let m,w=0,C=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(f===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let A=this._parseStack.handlers,D=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(f===!1&&D>-1){for(;D>=0&&(m=A[D](this._params),m!==!0);D--)if(m instanceof Promise)return this._parseStack.handlerPos=D,m}this._parseStack.handlers=[];break;case 4:if(f===!1&&D>-1){for(;D>=0&&(m=A[D](),m!==!0);D--)if(m instanceof Promise)return this._parseStack.handlerPos=D,m}this._parseStack.handlers=[];break;case 6:if(w=v[this._parseStack.chunkPos],m=this._dcsParser.unhook(w!==24&&w!==26,f),m)return m;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(w=v[this._parseStack.chunkPos],m=this._oscParser.end(w!==24&&w!==26,f),m)return m;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let A=k;A<g;++A){switch(w=v[A],C=this._transitions.table[this.currentState<<8|(w<160?w:p)],C>>4){case 2:for(let P=A+1;;++P){if(P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}}break;case 3:this._executeHandlers[w]?this._executeHandlers[w]():this._executeHandlerFb(w),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:A,code:w,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let D=this._csiHandlers[this._collect<<8|w],O=D?D.length-1:-1;for(;O>=0&&(m=D[O](this._params),m!==!0);O--)if(m instanceof Promise)return this._preserveStack(3,D,O,C,A),m;O<0&&this._csiHandlerFb(this._collect<<8|w,this._params),this.precedingJoinState=0;break;case 8:do switch(w){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(w-48)}while(++A<g&&(w=v[A])>47&&w<60);A--;break;case 9:this._collect<<=8,this._collect|=w;break;case 10:let L=this._escHandlers[this._collect<<8|w],R=L?L.length-1:-1;for(;R>=0&&(m=L[R](),m!==!0);R--)if(m instanceof Promise)return this._preserveStack(4,L,R,C,A),m;R<0&&this._escHandlerFb(this._collect<<8|w),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|w,this._params);break;case 13:for(let P=A+1;;++P)if(P>=g||(w=v[P])===24||w===26||w===27||w>127&&w<p){this._dcsParser.put(v,A,P),A=P-1;break}break;case 14:if(m=this._dcsParser.unhook(w!==24&&w!==26),m)return this._preserveStack(6,[],0,C,A),m;w===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let P=A+1;;P++)if(P>=g||(w=v[P])<32||w>127&&w<p){this._oscParser.put(v,A,P),A=P-1;break}break;case 6:if(m=this._oscParser.end(w!==24&&w!==26),m)return this._preserveStack(5,[],0,C,A),m;w===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&C}}}n.EscapeSequenceParser=b},1346:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OscHandler=n.OscParser=void 0;let u=l(1263),y=l(726),h=[];n.OscParser=class{constructor(){this._state=0,this._active=h,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(_,d){this._handlers[_]===void 0&&(this._handlers[_]=[]);let p=this._handlers[_];return p.push(d),{dispose:()=>{let b=p.indexOf(d);b!==-1&&p.splice(b,1)}}}clearHandler(_){this._handlers[_]&&delete this._handlers[_]}setHandlerFallback(_){this._handlerFb=_}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}reset(){if(this._state===2)for(let _=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;_>=0;--_)this._active[_].end(!1);this._stack.paused=!1,this._active=h,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||h,this._active.length)for(let _=this._active.length-1;_>=0;_--)this._active[_].start();else this._handlerFb(this._id,"START")}_put(_,d,p){if(this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].put(_,d,p);else this._handlerFb(this._id,"PUT",(0,y.utf32ToString)(_,d,p))}start(){this.reset(),this._state=1}put(_,d,p){if(this._state!==3){if(this._state===1)for(;d<p;){let b=_[d++];if(b===59){this._state=2,this._start();break}if(b<48||57<b)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+b-48}this._state===2&&p-d>0&&this._put(_,d,p)}}end(_,d=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let p=!1,b=this._active.length-1,c=!1;if(this._stack.paused&&(b=this._stack.loopPosition-1,p=d,c=this._stack.fallThrough,this._stack.paused=!1),!c&&p===!1){for(;b>=0&&(p=this._active[b].end(_),p!==!0);b--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!1,p;b--}for(;b>=0;b--)if(p=this._active[b].end(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!0,p}else this._handlerFb(this._id,"END",_);this._active=h,this._id=-1,this._state=0}}},n.OscHandler=class{constructor(_){this._handler=_,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(_,d,p){this._hitLimit||(this._data+=(0,y.utf32ToString)(_,d,p),this._data.length>u.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(_){let d=!1;if(this._hitLimit)d=!1;else if(_&&(d=this._handler(this._data),d instanceof Promise))return d.then((p=>(this._data="",this._hitLimit=!1,p)));return this._data="",this._hitLimit=!1,d}}},7262:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Params=void 0;let l=2147483647;class u{static fromArray(h){let _=new u;if(!h.length)return _;for(let d=Array.isArray(h[0])?1:0;d<h.length;++d){let p=h[d];if(Array.isArray(p))for(let b=0;b<p.length;++b)_.addSubParam(p[b]);else _.addParam(p)}return _}constructor(h=32,_=32){if(this.maxLength=h,this.maxSubParamsLength=_,_>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(h),this.length=0,this._subParams=new Int32Array(_),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(h),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let h=new u(this.maxLength,this.maxSubParamsLength);return h.params.set(this.params),h.length=this.length,h._subParams.set(this._subParams),h._subParamsLength=this._subParamsLength,h._subParamsIdx.set(this._subParamsIdx),h._rejectDigits=this._rejectDigits,h._rejectSubDigits=this._rejectSubDigits,h._digitIsSub=this._digitIsSub,h}toArray(){let h=[];for(let _=0;_<this.length;++_){h.push(this.params[_]);let d=this._subParamsIdx[_]>>8,p=255&this._subParamsIdx[_];p-d>0&&h.push(Array.prototype.slice.call(this._subParams,d,p))}return h}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(h){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=h>l?l:h}}addSubParam(h){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=h>l?l:h,this._subParamsIdx[this.length-1]++}}hasSubParams(h){return(255&this._subParamsIdx[h])-(this._subParamsIdx[h]>>8)>0}getSubParams(h){let _=this._subParamsIdx[h]>>8,d=255&this._subParamsIdx[h];return d-_>0?this._subParams.subarray(_,d):null}getSubParamsAll(){let h={};for(let _=0;_<this.length;++_){let d=this._subParamsIdx[_]>>8,p=255&this._subParamsIdx[_];p-d>0&&(h[_]=this._subParams.slice(d,p))}return h}addDigit(h){let _;if(this._rejectDigits||!(_=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let d=this._digitIsSub?this._subParams:this.params,p=d[_-1];d[_-1]=~p?Math.min(10*p+h,l):h}}n.Params=u},3027:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.AddonManager=void 0,n.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let l=this._addons.length-1;l>=0;l--)this._addons[l].instance.dispose()}loadAddon(l,u){let y={instance:u,dispose:u.dispose,isDisposed:!1};this._addons.push(y),u.dispose=()=>this._wrappedAddonDispose(y),u.activate(l)}_wrappedAddonDispose(l){if(l.isDisposed)return;let u=-1;for(let y=0;y<this._addons.length;y++)if(this._addons[y]===l){u=y;break}if(u===-1)throw new Error("Could not dispose an addon that has not been loaded");l.isDisposed=!0,l.dispose.apply(l.instance),this._addons.splice(u,1)}}},3235:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferApiView=void 0;let u=l(793),y=l(3055);n.BufferApiView=class{constructor(h,_){this._buffer=h,this.type=_}init(h){return this._buffer=h,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(h){let _=this._buffer.lines.get(h);if(_)return new u.BufferLineApiView(_)}getNullCell(){return new y.CellData}}},793:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLineApiView=void 0;let u=l(3055);n.BufferLineApiView=class{constructor(y){this._line=y}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(y,h){if(!(y<0||y>=this._line.length))return h?(this._line.loadCell(y,h),h):this._line.loadCell(y,new u.CellData)}translateToString(y,h,_){return this._line.translateToString(y,h,_)}}},5101:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferNamespaceApi=void 0;let u=l(3235),y=l(7150),h=l(802);class _ extends y.Disposable{constructor(p){super(),this._core=p,this._onBufferChange=this._register(new h.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new u.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new u.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}n.BufferNamespaceApi=_},6097:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ParserApi=void 0,n.ParserApi=class{constructor(l){this._core=l}registerCsiHandler(l,u){return this._core.registerCsiHandler(l,(y=>u(y.toArray())))}addCsiHandler(l,u){return this.registerCsiHandler(l,u)}registerDcsHandler(l,u){return this._core.registerDcsHandler(l,((y,h)=>u(y,h.toArray())))}addDcsHandler(l,u){return this.registerDcsHandler(l,u)}registerEscHandler(l,u){return this._core.registerEscHandler(l,u)}addEscHandler(l,u){return this.registerEscHandler(l,u)}registerOscHandler(l,u){return this._core.registerOscHandler(l,u)}addOscHandler(l,u){return this.registerOscHandler(l,u)}}},4335:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeApi=void 0,n.UnicodeApi=class{constructor(l){this._core=l}register(l){this._core.unicodeService.register(l)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(l){this._core.unicodeService.activeVersion=l}}},9640:function(a,n,l){var u=this&&this.__decorate||function(c,v,g,f){var m,w=arguments.length,C=w<3?v:f===null?f=Object.getOwnPropertyDescriptor(v,g):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,v,g,f);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(C=(w<3?m(C):w>3?m(v,g,C):m(v,g))||C);return w>3&&C&&Object.defineProperty(v,g,C),C},y=this&&this.__param||function(c,v){return function(g,f){v(g,f,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferService=n.MINIMUM_ROWS=n.MINIMUM_COLS=void 0;let h=l(7150),_=l(4097),d=l(6501),p=l(802);n.MINIMUM_COLS=2,n.MINIMUM_ROWS=1;let b=class extends h.Disposable{get buffer(){return this.buffers.active}constructor(c){super(),this.isUserScrolling=!1,this._onResize=this._register(new p.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new p.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(c.rawOptions.cols||0,n.MINIMUM_COLS),this.rows=Math.max(c.rawOptions.rows||0,n.MINIMUM_ROWS),this.buffers=this._register(new _.BufferSet(c,this)),this._register(this.buffers.onBufferActivate((v=>{this._onScroll.fire(v.activeBuffer.ydisp)})))}resize(c,v){let g=this.cols!==c,f=this.rows!==v;this.cols=c,this.rows=v,this.buffers.resize(c,v),this._onResize.fire({cols:c,rows:v,colsChanged:g,rowsChanged:f})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(c,v=!1){let g=this.buffer,f;f=this._cachedBlankLine,f&&f.length===this.cols&&f.getFg(0)===c.fg&&f.getBg(0)===c.bg||(f=g.getBlankLine(c,v),this._cachedBlankLine=f),f.isWrapped=v;let m=g.ybase+g.scrollTop,w=g.ybase+g.scrollBottom;if(g.scrollTop===0){let C=g.lines.isFull;w===g.lines.length-1?C?g.lines.recycle().copyFrom(f):g.lines.push(f.clone()):g.lines.splice(w+1,0,f.clone()),C?this.isUserScrolling&&(g.ydisp=Math.max(g.ydisp-1,0)):(g.ybase++,this.isUserScrolling||g.ydisp++)}else{let C=w-m+1;g.lines.shiftElements(m+1,C-1,-1),g.lines.set(w,f.clone())}this.isUserScrolling||(g.ydisp=g.ybase),this._onScroll.fire(g.ydisp)}scrollLines(c,v){let g=this.buffer;if(c<0){if(g.ydisp===0)return;this.isUserScrolling=!0}else c+g.ydisp>=g.ybase&&(this.isUserScrolling=!1);let f=g.ydisp;g.ydisp=Math.max(Math.min(g.ydisp+c,g.ybase),0),f!==g.ydisp&&(v||this._onScroll.fire(g.ydisp))}};n.BufferService=b,n.BufferService=b=u([y(0,d.IOptionsService)],b)},5746:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CharsetService=void 0,n.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(l){this.glevel=l,this.charset=this._charsets[l]}setgCharset(l,u){this._charsets[l]=u,this.glevel===l&&(this.charset=u)}}},7792:function(a,n,l){var u=this&&this.__decorate||function(f,m,w,C){var k,A=arguments.length,D=A<3?m:C===null?C=Object.getOwnPropertyDescriptor(m,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(f,m,w,C);else for(var O=f.length-1;O>=0;O--)(k=f[O])&&(D=(A<3?k(D):A>3?k(m,w,D):k(m,w))||D);return A>3&&D&&Object.defineProperty(m,w,D),D},y=this&&this.__param||function(f,m){return function(w,C){m(w,C,f)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreMouseService=void 0;let h=l(6501),_=l(7150),d=l(802),p={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:f=>f.button!==4&&f.action===1&&(f.ctrl=!1,f.alt=!1,f.shift=!1,!0)},VT200:{events:19,restrict:f=>f.action!==32},DRAG:{events:23,restrict:f=>f.action!==32||f.button!==3},ANY:{events:31,restrict:f=>!0}};function b(f,m){let w=(f.ctrl?16:0)|(f.shift?4:0)|(f.alt?8:0);return f.button===4?(w|=64,w|=f.action):(w|=3&f.button,4&f.button&&(w|=64),8&f.button&&(w|=128),f.action===32?w|=32:f.action!==0||m||(w|=3)),w}let c=String.fromCharCode,v={DEFAULT:f=>{let m=[b(f,!1)+32,f.col+32,f.row+32];return m[0]>255||m[1]>255||m[2]>255?"":`\x1B[M${c(m[0])}${c(m[1])}${c(m[2])}`},SGR:f=>{let m=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${b(f,!0)};${f.col};${f.row}${m}`},SGR_PIXELS:f=>{let m=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${b(f,!0)};${f.x};${f.y}${m}`}},g=class extends _.Disposable{constructor(f,m,w){super(),this._bufferService=f,this._coreService=m,this._optionsService=w,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new d.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(let C of Object.keys(p))this.addProtocol(C,p[C]);for(let C of Object.keys(v))this.addEncoding(C,v[C]);this.reset()}addProtocol(f,m){this._protocols[f]=m}addEncoding(f,m){this._encodings[f]=m}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(f){if(!this._protocols[f])throw new Error(`unknown protocol "${f}"`);this._activeProtocol=f,this._onProtocolChange.fire(this._protocols[f].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(f){if(!this._encodings[f])throw new Error(`unknown encoding "${f}"`);this._activeEncoding=f}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(f,m,w){if(f.deltaY===0||f.shiftKey||m===void 0||w===void 0)return 0;let C=m/w,k=this._applyScrollModifier(f.deltaY,f);return f.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(k/=C+0,Math.abs(f.deltaY)<50&&(k*=.3),this._wheelPartialScroll+=k,k=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):f.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(k*=this._bufferService.rows),k}_applyScrollModifier(f,m){return m.altKey||m.ctrlKey||m.shiftKey?f*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:f*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(f){if(f.col<0||f.col>=this._bufferService.cols||f.row<0||f.row>=this._bufferService.rows||f.button===4&&f.action===32||f.button===3&&f.action!==32||f.button!==4&&(f.action===2||f.action===3)||(f.col++,f.row++,f.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,f,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(f))return!1;let m=this._encodings[this._activeEncoding](f);return m&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(m):this._coreService.triggerDataEvent(m,!0)),this._lastEvent=f,!0}explainEvents(f){return{down:!!(1&f),up:!!(2&f),drag:!!(4&f),move:!!(8&f),wheel:!!(16&f)}}_equalEvents(f,m,w){if(w){if(f.x!==m.x||f.y!==m.y)return!1}else if(f.col!==m.col||f.row!==m.row)return!1;return f.button===m.button&&f.action===m.action&&f.ctrl===m.ctrl&&f.alt===m.alt&&f.shift===m.shift}};n.CoreMouseService=g,n.CoreMouseService=g=u([y(0,h.IBufferService),y(1,h.ICoreService),y(2,h.IOptionsService)],g)},4071:function(a,n,l){var u=this&&this.__decorate||function(g,f,m,w){var C,k=arguments.length,A=k<3?f:w===null?w=Object.getOwnPropertyDescriptor(f,m):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(g,f,m,w);else for(var D=g.length-1;D>=0;D--)(C=g[D])&&(A=(k<3?C(A):k>3?C(f,m,A):C(f,m))||A);return k>3&&A&&Object.defineProperty(f,m,A),A},y=this&&this.__param||function(g,f){return function(m,w){f(m,w,g)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreService=void 0;let h=l(7453),_=l(7150),d=l(6501),p=l(802),b=Object.freeze({insertMode:!1}),c=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),v=class extends _.Disposable{constructor(g,f,m){super(),this._bufferService=g,this._logService=f,this._optionsService=m,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new p.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new p.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new p.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new p.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,h.clone)(b),this.decPrivateModes=(0,h.clone)(c)}reset(){this.modes=(0,h.clone)(b),this.decPrivateModes=(0,h.clone)(c)}triggerDataEvent(g,f=!1){if(this._optionsService.rawOptions.disableStdin)return;let m=this._bufferService.buffer;f&&this._optionsService.rawOptions.scrollOnUserInput&&m.ybase!==m.ydisp&&this._onRequestScrollToBottom.fire(),f&&this._onUserInput.fire(),this._logService.debug(`sending data "${g}"`),this._logService.trace("sending data (codes)",(()=>g.split("").map((w=>w.charCodeAt(0))))),this._onData.fire(g)}triggerBinaryEvent(g){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${g}"`),this._logService.trace("sending binary (codes)",(()=>g.split("").map((f=>f.charCodeAt(0))))),this._onBinary.fire(g))}};n.CoreService=v,n.CoreService=v=u([y(0,d.IBufferService),y(1,d.ILogService),y(2,d.IOptionsService)],v)},6025:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.InstantiationService=n.ServiceCollection=void 0;let u=l(6501),y=l(6201);class h{constructor(...d){this._entries=new Map;for(let[p,b]of d)this.set(p,b)}set(d,p){let b=this._entries.get(d);return this._entries.set(d,p),b}forEach(d){for(let[p,b]of this._entries.entries())d(p,b)}has(d){return this._entries.has(d)}get(d){return this._entries.get(d)}}n.ServiceCollection=h,n.InstantiationService=class{constructor(){this._services=new h,this._services.set(u.IInstantiationService,this)}setService(_,d){this._services.set(_,d)}getService(_){return this._services.get(_)}createInstance(_,...d){let p=(0,y.getServiceDependencies)(_).sort(((v,g)=>v.index-g.index)),b=[];for(let v of p){let g=this._services.get(v.id);if(!g)throw new Error(`[createInstance] ${_.name} depends on UNKNOWN service ${v.id._id}.`);b.push(g)}let c=p.length>0?p[0].index:d.length;if(d.length!==c)throw new Error(`[createInstance] First service dependency of ${_.name} at position ${c+1} conflicts with ${d.length} static arguments`);return new _(...d,...b)}}},7276:function(a,n,l){var u=this&&this.__decorate||function(c,v,g,f){var m,w=arguments.length,C=w<3?v:f===null?f=Object.getOwnPropertyDescriptor(v,g):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,v,g,f);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(C=(w<3?m(C):w>3?m(v,g,C):m(v,g))||C);return w>3&&C&&Object.defineProperty(v,g,C),C},y=this&&this.__param||function(c,v){return function(g,f){v(g,f,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.LogService=void 0,n.setTraceLogger=function(c){p=c},n.traceCall=function(c,v,g){if(typeof g.value!="function")throw new Error("not supported");let f=g.value;g.value=function(...m){if(p.logLevel!==_.LogLevelEnum.TRACE)return f.apply(this,m);p.trace(`GlyphRenderer#${f.name}(${m.map((C=>JSON.stringify(C))).join(", ")})`);let w=f.apply(this,m);return p.trace(`GlyphRenderer#${f.name} return`,w),w}};let h=l(7150),_=l(6501),d={trace:_.LogLevelEnum.TRACE,debug:_.LogLevelEnum.DEBUG,info:_.LogLevelEnum.INFO,warn:_.LogLevelEnum.WARN,error:_.LogLevelEnum.ERROR,off:_.LogLevelEnum.OFF},p,b=class extends h.Disposable{get logLevel(){return this._logLevel}constructor(c){super(),this._optionsService=c,this._logLevel=_.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),p=this}_updateLogLevel(){this._logLevel=d[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(c){for(let v=0;v<c.length;v++)typeof c[v]=="function"&&(c[v]=c[v]())}_log(c,v,g){this._evalLazyOptionalParams(g),c.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+v,...g)}trace(c,...v){this._logLevel<=_.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,c,v)}debug(c,...v){this._logLevel<=_.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,c,v)}info(c,...v){this._logLevel<=_.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,c,v)}warn(c,...v){this._logLevel<=_.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,c,v)}error(c,...v){this._logLevel<=_.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,c,v)}};n.LogService=b,n.LogService=b=u([y(0,_.IOptionsService)],b)},56:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OptionsService=n.DEFAULT_OPTIONS=void 0;let u=l(7150),y=l(701),h=l(802);n.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:y.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}};let _=["normal","bold","100","200","300","400","500","600","700","800","900"];class d extends u.Disposable{constructor(b){super(),this._onOptionChange=this._register(new h.Emitter),this.onOptionChange=this._onOptionChange.event;let c={...n.DEFAULT_OPTIONS};for(let v in b)if(v in c)try{let g=b[v];c[v]=this._sanitizeAndValidateOption(v,g)}catch(g){console.error(g)}this.rawOptions=c,this.options={...c},this._setupOptions(),this._register((0,u.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(b,c){return this.onOptionChange((v=>{v===b&&c(this.rawOptions[b])}))}onMultipleOptionChange(b,c){return this.onOptionChange((v=>{b.indexOf(v)!==-1&&c()}))}_setupOptions(){let b=v=>{if(!(v in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${v}"`);return this.rawOptions[v]},c=(v,g)=>{if(!(v in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${v}"`);g=this._sanitizeAndValidateOption(v,g),this.rawOptions[v]!==g&&(this.rawOptions[v]=g,this._onOptionChange.fire(v))};for(let v in this.rawOptions){let g={get:b.bind(this,v),set:c.bind(this,v)};Object.defineProperty(this.options,v,g)}}_sanitizeAndValidateOption(b,c){switch(b){case"cursorStyle":if(c||(c=n.DEFAULT_OPTIONS[b]),!(function(v){return v==="block"||v==="underline"||v==="bar"})(c))throw new Error(`"${c}" is not a valid value for ${b}`);break;case"wordSeparator":c||(c=n.DEFAULT_OPTIONS[b]);break;case"fontWeight":case"fontWeightBold":if(typeof c=="number"&&1<=c&&c<=1e3)break;c=_.includes(c)?c:n.DEFAULT_OPTIONS[b];break;case"cursorWidth":c=Math.floor(c);case"lineHeight":case"tabStopWidth":if(c<1)throw new Error(`${b} cannot be less than 1, value: ${c}`);break;case"minimumContrastRatio":c=Math.max(1,Math.min(21,Math.round(10*c)/10));break;case"scrollback":if((c=Math.min(c,4294967295))<0)throw new Error(`${b} cannot be less than 0, value: ${c}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(c<=0)throw new Error(`${b} cannot be less than or equal to 0, value: ${c}`);break;case"rows":case"cols":if(!c&&c!==0)throw new Error(`${b} must be numeric, value: ${c}`);break;case"windowsPty":c=c??{}}return c}}n.OptionsService=d},8811:function(a,n,l){var u=this&&this.__decorate||function(d,p,b,c){var v,g=arguments.length,f=g<3?p:c===null?c=Object.getOwnPropertyDescriptor(p,b):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(d,p,b,c);else for(var m=d.length-1;m>=0;m--)(v=d[m])&&(f=(g<3?v(f):g>3?v(p,b,f):v(p,b))||f);return g>3&&f&&Object.defineProperty(p,b,f),f},y=this&&this.__param||function(d,p){return function(b,c){p(b,c,d)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkService=void 0;let h=l(6501),_=class{constructor(d){this._bufferService=d,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(d){let p=this._bufferService.buffer;if(d.id===void 0){let m=p.addMarker(p.ybase+p.y),w={data:d,id:this._nextId++,lines:[m]};return m.onDispose((()=>this._removeMarkerFromLink(w,m))),this._dataByLinkId.set(w.id,w),w.id}let b=d,c=this._getEntryIdKey(b),v=this._entriesWithId.get(c);if(v)return this.addLineToLink(v.id,p.ybase+p.y),v.id;let g=p.addMarker(p.ybase+p.y),f={id:this._nextId++,key:this._getEntryIdKey(b),data:b,lines:[g]};return g.onDispose((()=>this._removeMarkerFromLink(f,g))),this._entriesWithId.set(f.key,f),this._dataByLinkId.set(f.id,f),f.id}addLineToLink(d,p){let b=this._dataByLinkId.get(d);if(b&&b.lines.every((c=>c.line!==p))){let c=this._bufferService.buffer.addMarker(p);b.lines.push(c),c.onDispose((()=>this._removeMarkerFromLink(b,c)))}}getLinkData(d){return this._dataByLinkId.get(d)?.data}_getEntryIdKey(d){return`${d.id};;${d.uri}`}_removeMarkerFromLink(d,p){let b=d.lines.indexOf(p);b!==-1&&(d.lines.splice(b,1),d.lines.length===0&&(d.data.id!==void 0&&this._entriesWithId.delete(d.key),this._dataByLinkId.delete(d.id)))}};n.OscLinkService=_,n.OscLinkService=_=u([y(0,h.IBufferService)],_)},6201:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.serviceRegistry=void 0,n.getServiceDependencies=function(y){return y[u]||[]},n.createDecorator=function(y){if(n.serviceRegistry.has(y))return n.serviceRegistry.get(y);let h=function(_,d,p){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(b,c,v){c[l]===c?c[u].push({id:b,index:v}):(c[u]=[{id:b,index:v}],c[l]=c)})(h,_,p)};return h._id=y,n.serviceRegistry.set(y,h),h};let l="di$target",u="di$dependencies";n.serviceRegistry=new Map},6501:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IDecorationService=n.IUnicodeService=n.IOscLinkService=n.IOptionsService=n.ILogService=n.LogLevelEnum=n.IInstantiationService=n.ICharsetService=n.ICoreService=n.ICoreMouseService=n.IBufferService=void 0;let u=l(6201);var y;n.IBufferService=(0,u.createDecorator)("BufferService"),n.ICoreMouseService=(0,u.createDecorator)("CoreMouseService"),n.ICoreService=(0,u.createDecorator)("CoreService"),n.ICharsetService=(0,u.createDecorator)("CharsetService"),n.IInstantiationService=(0,u.createDecorator)("InstantiationService"),(function(h){h[h.TRACE=0]="TRACE",h[h.DEBUG=1]="DEBUG",h[h.INFO=2]="INFO",h[h.WARN=3]="WARN",h[h.ERROR=4]="ERROR",h[h.OFF=5]="OFF"})(y||(n.LogLevelEnum=y={})),n.ILogService=(0,u.createDecorator)("LogService"),n.IOptionsService=(0,u.createDecorator)("OptionsService"),n.IOscLinkService=(0,u.createDecorator)("OscLinkService"),n.IUnicodeService=(0,u.createDecorator)("UnicodeService"),n.IDecorationService=(0,u.createDecorator)("DecorationService")},6415:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeService=void 0;let u=l(7428),y=l(802);class h{static extractShouldJoin(d){return!!(1&d)}static extractWidth(d){return d>>1&3}static extractCharKind(d){return d>>3}static createPropertyValue(d,p,b=!1){return(16777215&d)<<3|(3&p)<<1|(b?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new y.Emitter,this.onChange=this._onChange.event;let d=new u.UnicodeV6;this.register(d),this._active=d.version,this._activeProvider=d}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(d){if(!this._providers[d])throw new Error(`unknown Unicode version "${d}"`);this._active=d,this._activeProvider=this._providers[d],this._onChange.fire(d)}register(d){this._providers[d.version]=d}wcwidth(d){return this._activeProvider.wcwidth(d)}getStringCellWidth(d){let p=0,b=0,c=d.length;for(let v=0;v<c;++v){let g=d.charCodeAt(v);if(55296<=g&&g<=56319){if(++v>=c)return p+this.wcwidth(g);let w=d.charCodeAt(v);56320<=w&&w<=57343?g=1024*(g-55296)+w-56320+65536:p+=this.wcwidth(w)}let f=this.charProperties(g,b),m=h.extractWidth(f);h.extractShouldJoin(f)&&(m-=h.extractWidth(b)),p+=m,b=f}return p}charProperties(d,p){return this._activeProvider.charProperties(d,p)}}n.UnicodeService=h},5856:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;let u=l(6107),y=l(5777),h=l(802);class _ extends y.CoreTerminal{constructor(p={}){super(p),this._onBell=this._register(new h.Emitter),this.onBell=this._onBell.event,this._onCursorMove=this._register(new h.Emitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this._register(new h.Emitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this._register(new h.Emitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this._register(new h.Emitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this._register(this._inputHandler.onRequestBell((()=>this.bell()))),this._register(this._inputHandler.onRequestReset((()=>this.reset()))),this._register(h.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(h.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(h.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(h.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(p){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+p)}bell(){this._onBell.fire()}input(p,b=!0){this.coreService.triggerDataEvent(p,b)}resize(p,b){p===this.cols&&b===this.rows||super.resize(p,b)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let p=1;p<this.rows;p++)this.buffer.lines.push(this.buffer.getBlankLine(u.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}n.Terminal=_},3058:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Permutation=n.CallbackIterable=n.ArrayQueue=n.booleanComparator=n.numberComparator=n.CompareResult=void 0,n.tail=function(m,w=0){return m[m.length-(1+w)]},n.tail2=function(m){if(m.length===0)throw new Error("Invalid tail call");return[m.slice(0,m.length-1),m[m.length-1]]},n.equals=function(m,w,C=(k,A)=>k===A){if(m===w)return!0;if(!m||!w||m.length!==w.length)return!1;for(let k=0,A=m.length;k<A;k++)if(!C(m[k],w[k]))return!1;return!0},n.removeFastWithoutKeepingOrder=function(m,w){let C=m.length-1;w<C&&(m[w]=m[C]),m.pop()},n.binarySearch=function(m,w,C){return h(m.length,(k=>C(m[k],w)))},n.binarySearch2=h,n.quickSelect=function m(w,C,k){if((w|=0)>=C.length)throw new TypeError("invalid index");let A=C[Math.floor(C.length*Math.random())],D=[],O=[],L=[];for(let R of C){let P=k(R,A);P<0?D.push(R):P>0?O.push(R):L.push(R)}return w<D.length?m(w,D,k):w<D.length+L.length?L[0]:m(w-(D.length+L.length),O,k)},n.groupBy=function(m,w){let C=[],k;for(let A of m.slice(0).sort(w))k&&w(k[0],A)===0?k.push(A):(k=[A],C.push(k));return C},n.groupAdjacentBy=function*(m,w){let C,k;for(let A of m)k!==void 0&&w(k,A)?C.push(A):(C&&(yield C),C=[A]),k=A;C&&(yield C)},n.forEachAdjacent=function(m,w){for(let C=0;C<=m.length;C++)w(C===0?void 0:m[C-1],C===m.length?void 0:m[C])},n.forEachWithNeighbors=function(m,w){for(let C=0;C<m.length;C++)w(C===0?void 0:m[C-1],m[C],C+1===m.length?void 0:m[C+1])},n.sortedDiff=_,n.delta=function(m,w,C){let k=_(m,w,C),A=[],D=[];for(let O of k)A.push(...m.slice(O.start,O.start+O.deleteCount)),D.push(...O.toInsert);return{removed:A,added:D}},n.top=function(m,w,C){if(C===0)return[];let k=m.slice(0,C).sort(w);return d(m,w,k,C,m.length),k},n.topAsync=function(m,w,C,k,A){return C===0?Promise.resolve([]):new Promise(((D,O)=>{(async()=>{let L=m.length,R=m.slice(0,C).sort(w);for(let P=C,F=Math.min(C+k,L);P<L;P=F,F=Math.min(F+k,L)){if(P>C&&await new Promise((V=>setTimeout(V))),A&&A.isCancellationRequested)throw new u.CancellationError;d(m,w,R,P,F)}return R})().then(D,O)}))},n.coalesce=function(m){return m.filter((w=>!!w))},n.coalesceInPlace=function(m){let w=0;for(let C=0;C<m.length;C++)m[C]&&(m[w]=m[C],w+=1);m.length=w},n.move=function(m,w,C){m.splice(C,0,m.splice(w,1)[0])},n.isFalsyOrEmpty=function(m){return!Array.isArray(m)||m.length===0},n.isNonEmptyArray=function(m){return Array.isArray(m)&&m.length>0},n.distinct=function(m,w=C=>C){let C=new Set;return m.filter((k=>{let A=w(k);return!C.has(A)&&(C.add(A),!0)}))},n.uniqueFilter=function(m){let w=new Set;return C=>{let k=m(C);return!w.has(k)&&(w.add(k),!0)}},n.firstOrDefault=function(m,w){return m.length>0?m[0]:w},n.lastOrDefault=function(m,w){return m.length>0?m[m.length-1]:w},n.commonPrefixLength=function(m,w,C=(k,A)=>k===A){let k=0;for(let A=0,D=Math.min(m.length,w.length);A<D&&C(m[A],w[A]);A++)k++;return k},n.range=function(m,w){let C=typeof w=="number"?m:0;typeof w=="number"?C=m:(C=0,w=m);let k=[];if(C<=w)for(let A=C;A<w;A++)k.push(A);else for(let A=C;A>w;A--)k.push(A);return k},n.index=function(m,w,C){return m.reduce(((k,A)=>(k[w(A)]=C?C(A):A,k)),Object.create(null))},n.insert=function(m,w){return m.push(w),()=>p(m,w)},n.remove=p,n.arrayInsert=function(m,w,C){let k=m.slice(0,w),A=m.slice(w);return k.concat(C,A)},n.shuffle=function(m,w){let C;if(typeof w=="number"){let k=w;C=()=>{let A=179426549*Math.sin(k++);return A-Math.floor(A)}}else C=Math.random;for(let k=m.length-1;k>0;k-=1){let A=Math.floor(C()*(k+1)),D=m[k];m[k]=m[A],m[A]=D}},n.pushToStart=function(m,w){let C=m.indexOf(w);C>-1&&(m.splice(C,1),m.unshift(w))},n.pushToEnd=function(m,w){let C=m.indexOf(w);C>-1&&(m.splice(C,1),m.push(w))},n.pushMany=function(m,w){for(let C of w)m.push(C)},n.mapArrayOrNot=function(m,w){return Array.isArray(m)?m.map(w):w(m)},n.asArray=function(m){return Array.isArray(m)?m:[m]},n.getRandomElement=function(m){return m[Math.floor(Math.random()*m.length)]},n.insertInto=b,n.splice=function(m,w,C,k){let A=c(m,w),D=m.splice(A,C);return D===void 0&&(D=[]),b(m,A,k),D},n.compareBy=function(m,w){return(C,k)=>w(m(C),m(k))},n.tieBreakComparators=function(...m){return(w,C)=>{for(let k of m){let A=k(w,C);if(!v.isNeitherLessOrGreaterThan(A))return A}return v.neitherLessOrGreaterThan}},n.reverseOrder=function(m){return(w,C)=>-m(w,C)};let u=l(9807),y=l(8297);function h(m,w){let C=0,k=m-1;for(;C<=k;){let A=(C+k)/2|0,D=w(A);if(D<0)C=A+1;else{if(!(D>0))return A;k=A-1}}return-(C+1)}function _(m,w,C){let k=[];function A(L,R,P){if(R===0&&P.length===0)return;let F=k[k.length-1];F&&F.start+F.deleteCount===L?(F.deleteCount+=R,F.toInsert.push(...P)):k.push({start:L,deleteCount:R,toInsert:P})}let D=0,O=0;for(;;){if(D===m.length){A(D,0,w.slice(O));break}if(O===w.length){A(D,m.length-D,[]);break}let L=m[D],R=w[O],P=C(L,R);P===0?(D+=1,O+=1):P<0?(A(D,1,[]),D+=1):P>0&&(A(D,0,[R]),O+=1)}return k}function d(m,w,C,k,A){for(let D=C.length;k<A;k++){let O=m[k];if(w(O,C[D-1])<0){C.pop();let L=(0,y.findFirstIdxMonotonousOrArrLen)(C,(R=>w(O,R)<0));C.splice(L,0,O)}}}function p(m,w){let C=m.indexOf(w);if(C>-1)return m.splice(C,1),w}function b(m,w,C){let k=c(m,w),A=m.length,D=C.length;m.length=A+D;for(let O=A-1;O>=k;O--)m[O+D]=m[O];for(let O=0;O<D;O++)m[O+k]=C[O]}function c(m,w){return w<0?Math.max(w+m.length,0):Math.min(w,m.length)}var v;(function(m){m.isLessThan=function(w){return w<0},m.isLessThanOrEqual=function(w){return w<=0},m.isGreaterThan=function(w){return w>0},m.isNeitherLessOrGreaterThan=function(w){return w===0},m.greaterThan=1,m.lessThan=-1,m.neitherLessOrGreaterThan=0})(v||(n.CompareResult=v={})),n.numberComparator=(m,w)=>m-w,n.booleanComparator=(m,w)=>(0,n.numberComparator)(m?1:0,w?1:0),n.ArrayQueue=class{constructor(m){this.items=m,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(m){let w=this.firstIdx;for(;w<this.items.length&&m(this.items[w]);)w++;let C=w===this.firstIdx?null:this.items.slice(this.firstIdx,w);return this.firstIdx=w,C}takeFromEndWhile(m){let w=this.lastIdx;for(;w>=0&&m(this.items[w]);)w--;let C=w===this.lastIdx?null:this.items.slice(w+1,this.lastIdx+1);return this.lastIdx=w,C}peek(){if(this.length!==0)return this.items[this.firstIdx]}peekLast(){if(this.length!==0)return this.items[this.lastIdx]}dequeue(){let m=this.items[this.firstIdx];return this.firstIdx++,m}removeLast(){let m=this.items[this.lastIdx];return this.lastIdx--,m}takeCount(m){let w=this.items.slice(this.firstIdx,this.firstIdx+m);return this.firstIdx+=m,w}};class g{static{this.empty=new g((w=>{}))}constructor(w){this.iterate=w}forEach(w){this.iterate((C=>(w(C),!0)))}toArray(){let w=[];return this.iterate((C=>(w.push(C),!0))),w}filter(w){return new g((C=>this.iterate((k=>!w(k)||C(k)))))}map(w){return new g((C=>this.iterate((k=>C(w(k))))))}some(w){let C=!1;return this.iterate((k=>(C=w(k),!C))),C}findFirst(w){let C;return this.iterate((k=>!w(k)||(C=k,!1))),C}findLast(w){let C;return this.iterate((k=>(w(k)&&(C=k),!0))),C}findLastMaxBy(w){let C,k=!0;return this.iterate((A=>((k||v.isGreaterThan(w(A,C)))&&(k=!1,C=A),!0))),C}}n.CallbackIterable=g;class f{constructor(w){this._indexMap=w}static createSortPermutation(w,C){let k=Array.from(w.keys()).sort(((A,D)=>C(w[A],w[D])));return new f(k)}apply(w){return w.map(((C,k)=>w[this._indexMap[k]]))}inverse(){let w=this._indexMap.slice();for(let C=0;C<this._indexMap.length;C++)w[this._indexMap[C]]=C;return new f(w)}}n.Permutation=f},8297:(a,n)=>{function l(d,p,b=d.length-1){for(let c=b;c>=0;c--)if(p(d[c]))return c;return-1}function u(d,p,b=0,c=d.length){let v=b,g=c;for(;v<g;){let f=Math.floor((v+g)/2);p(d[f])?v=f+1:g=f}return v-1}function y(d,p,b=0,c=d.length){let v=b,g=c;for(;v<g;){let f=Math.floor((v+g)/2);p(d[f])?g=f:v=f+1}return v}Object.defineProperty(n,"__esModule",{value:!0}),n.MonotonousArray=void 0,n.findLast=function(d,p){let b=l(d,p);if(b!==-1)return d[b]},n.findLastIdx=l,n.findLastMonotonous=function(d,p){let b=u(d,p);return b===-1?void 0:d[b]},n.findLastIdxMonotonous=u,n.findFirstMonotonous=function(d,p){let b=y(d,p);return b===d.length?void 0:d[b]},n.findFirstIdxMonotonousOrArrLen=y,n.findFirstIdxMonotonous=function(d,p,b=0,c=d.length){let v=y(d,p,b,c);return v===d.length?-1:v},n.findFirstMax=_,n.findLastMax=function(d,p){if(d.length===0)return;let b=d[0];for(let c=1;c<d.length;c++){let v=d[c];p(v,b)>=0&&(b=v)}return b},n.findFirstMin=function(d,p){return _(d,((b,c)=>-p(b,c)))},n.findMaxIdx=function(d,p){if(d.length===0)return-1;let b=0;for(let c=1;c<d.length;c++)p(d[c],d[b])>0&&(b=c);return b},n.mapFindFirst=function(d,p){for(let b of d){let c=p(b);if(c!==void 0)return c}};class h{static{this.assertInvariants=!1}constructor(p){this._array=p,this._findLastMonotonousLastIdx=0}findLastMonotonous(p){if(h.assertInvariants){if(this._prevFindLastPredicate){for(let c of this._array)if(this._prevFindLastPredicate(c)&&!p(c))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=p}let b=u(this._array,p,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=b+1,b===-1?void 0:this._array[b]}}function _(d,p){if(d.length===0)return;let b=d[0];for(let c=1;c<d.length;c++){let v=d[c];p(v,b)>0&&(b=v)}return b}n.MonotonousArray=h},9087:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.SetWithKey=void 0,n.groupBy=function(y,h){let _=Object.create(null);for(let d of y){let p=h(d),b=_[p];b||(b=_[p]=[]),b.push(d)}return _},n.diffSets=function(y,h){let _=[],d=[];for(let p of y)h.has(p)||_.push(p);for(let p of h)y.has(p)||d.push(p);return{removed:_,added:d}},n.diffMaps=function(y,h){let _=[],d=[];for(let[p,b]of y)h.has(p)||_.push(b);for(let[p,b]of h)y.has(p)||d.push(b);return{removed:_,added:d}},n.intersection=function(y,h){let _=new Set;for(let d of h)y.has(d)&&_.add(d);return _};class u{static{l=Symbol.toStringTag}constructor(h,_){this.toKey=_,this._map=new Map,this[l]="SetWithKey";for(let d of h)this.add(d)}get size(){return this._map.size}add(h){let _=this.toKey(h);return this._map.set(_,h),this}delete(h){return this._map.delete(this.toKey(h))}has(h){return this._map.has(this.toKey(h))}*entries(){for(let h of this._map.values())yield[h,h]}keys(){return this.values()}*values(){for(let h of this._map.values())yield h}clear(){this._map.clear()}forEach(h,_){this._map.forEach((d=>h.call(_,d,d,this)))}[Symbol.iterator](){return this.values()}}n.SetWithKey=u},9807:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BugIndicatingError=n.ErrorNoTelemetry=n.ExpectedError=n.NotSupportedError=n.NotImplementedError=n.ReadonlyError=n.CancellationError=n.errorHandler=n.ErrorHandler=void 0,n.setUnexpectedErrorHandler=function(g){n.errorHandler.setUnexpectedErrorHandler(g)},n.isSigPipeError=function(g){if(!g||typeof g!="object")return!1;let f=g;return f.code==="EPIPE"&&f.syscall?.toUpperCase()==="WRITE"},n.onUnexpectedError=function(g){y(g)||n.errorHandler.onUnexpectedError(g)},n.onUnexpectedExternalError=function(g){y(g)||n.errorHandler.onUnexpectedExternalError(g)},n.transformErrorForSerialization=function(g){if(g instanceof Error){let{name:f,message:m}=g;return{$isError:!0,name:f,message:m,stack:g.stacktrace||g.stack,noTelemetry:c.isErrorNoTelemetry(g)}}return g},n.transformErrorFromSerialization=function(g){let f;return g.noTelemetry?f=new c:(f=new Error,f.name=g.name),f.message=g.message,f.stack=g.stack,f},n.isCancellationError=y,n.canceled=function(){let g=new Error(u);return g.name=g.message,g},n.illegalArgument=function(g){return g?new Error(`Illegal argument: ${g}`):new Error("Illegal argument")},n.illegalState=function(g){return g?new Error(`Illegal state: ${g}`):new Error("Illegal state")},n.getErrorMessage=function(g){return g?g.message?g.message:g.stack?g.stack.split(`
63
+ `}function kh(){return is(Jn(),"Library","LaunchAgents",`${Kt}.plist`)}function Th(){return is(Jn(),".config","systemd","user",Ar)}function Zn(t,e=Jn()){return t==="darwin"?Yn(is(e,"Library","LaunchAgents",`${Kt}.plist`)):t==="linux"?Yn(is(e,".config","systemd","user",Ar)):!1}async function Kn(t){if(t.platform!=="darwin"&&t.platform!=="linux")throw new Error(`unsupported platform for daemon install: ${t.platform}`);if(!t.loadIdentity())throw new Error("no identity found; run `djinn new --invite <CODE> --server <wss>` first");if(await t.pingDaemon()&&(await t.stopDaemon().catch(()=>{}),!await t.waitForSocketGone()))throw new Error("daemon socket did not disappear after stop; aborting install (please stop the daemon manually)");let e=process.env.PATH??"";if(t.platform==="darwin"){let r=kh();await t.writeConfig(r,Eh({execPath:t.execPath,entry:t.entry,logPath:is(t.dir,"daemon.log"),path:e}));let s=process.getuid?.()??0;await t.runCommand("launchctl",["bootout",`gui/${s}/${Kt}`]).catch(()=>{}),await t.runCommand("launchctl",["bootstrap",`gui/${s}`,r])}else{let r=Th();await t.writeConfig(r,xh({execPath:t.execPath,entry:t.entry,path:e})),await t.runCommand("systemctl",["--user","daemon-reload"]),await t.runCommand("systemctl",["--user","enable","--now",Ar]),await t.runCommand("loginctl",["enable-linger",Fg().username]).catch(()=>{})}if(!await t.verifySupervisorActive())throw new Error("daemon did not come up under the OS supervisor (a competing daemon may have grabbed the socket); please re-run `djinn daemon install`")}async function Xn(t){if(t.platform==="darwin"){let e=process.getuid?.()??0;await t.runCommand("launchctl",["bootout",`gui/${e}/${Kt}`]).catch(()=>{}),await t.removeConfig(kh())}else if(t.platform==="linux")await t.runCommand("systemctl",["--user","disable","--now",Ar]).catch(()=>{}),await t.removeConfig(Th()),await t.runCommand("systemctl",["--user","daemon-reload"]).catch(()=>{});else throw new Error(`unsupported platform for daemon uninstall: ${t.platform}`)}function Tr(t){return new Promise(e=>{let r=jg($e(t)),s,i=o=>{clearTimeout(s),r.destroy(),e(o)};s=setTimeout(()=>i(!1),300),r.on("connect",()=>r.write(JSON.stringify({cmd:"ping"})+`
64
+ `)),r.on("data",()=>i(!0)),r.on("error",()=>i(!1))})}async function ns(t,e=3e3){let r=Date.now()+e;for(;Date.now()<r;){if(!Yn($e(t))&&!await Tr(t))return!0;await new Promise(s=>setTimeout(s,150))}return!await Tr(t)}async function li(t,e){let r=e.timeoutMs??3e3,s=e.sleep??(a=>new Promise(n=>setTimeout(n,a))),i=Date.now()+r,o=async()=>{if(t==="linux")return(await e.exec("systemctl",["--user","is-active","--quiet",Ar])).ok;if(t==="darwin"){let a=await e.exec("launchctl",["print",`gui/${e.uid}/${Kt}`]);return a.ok&&/\bpid = \d+/.test(a.stdout)}return!1};for(;Date.now()<i;){if(await o())return!0;await s(150)}return o()}var Kt,Ar,Qn=bt(()=>{"use strict";Ts();me();Kt="top.unit00.djinn.daemon",Ar="djinn-daemon.service"});var Ph=$(Ih=>{"use strict";(()=>{"use strict";var t={5639:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CircularList=void 0;let u=l(7150),y=l(802);class h extends u.Disposable{constructor(d){super(),this._maxLength=d,this.onDeleteEmitter=this._register(new y.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new y.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new y.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(d){if(this._maxLength===d)return;let p=new Array(d);for(let b=0;b<Math.min(d,this.length);b++)p[b]=this._array[this._getCyclicIndex(b)];this._array=p,this._maxLength=d,this._startIndex=0}get length(){return this._length}set length(d){if(d>this._length)for(let p=this._length;p<d;p++)this._array[p]=void 0;this._length=d}get(d){return this._array[this._getCyclicIndex(d)]}set(d,p){this._array[this._getCyclicIndex(d)]=p}push(d){this._array[this._getCyclicIndex(this._length)]=d,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(d,p,...b){if(p){for(let c=d;c<this._length-p;c++)this._array[this._getCyclicIndex(c)]=this._array[this._getCyclicIndex(c+p)];this._length-=p,this.onDeleteEmitter.fire({index:d,amount:p})}for(let c=this._length-1;c>=d;c--)this._array[this._getCyclicIndex(c+b.length)]=this._array[this._getCyclicIndex(c)];for(let c=0;c<b.length;c++)this._array[this._getCyclicIndex(d+c)]=b[c];if(b.length&&this.onInsertEmitter.fire({index:d,amount:b.length}),this._length+b.length>this._maxLength){let c=this._length+b.length-this._maxLength;this._startIndex+=c,this._length=this._maxLength,this.onTrimEmitter.fire(c)}else this._length+=b.length}trimStart(d){d>this._length&&(d=this._length),this._startIndex+=d,this._length-=d,this.onTrimEmitter.fire(d)}shiftElements(d,p,b){if(!(p<=0)){if(d<0||d>=this._length)throw new Error("start argument out of range");if(d+b<0)throw new Error("Cannot shift elements in list beyond index 0");if(b>0){for(let v=p-1;v>=0;v--)this.set(d+v+b,this.get(d+v));let c=d+p+b-this._length;if(c>0)for(this._length+=c;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let c=0;c<p;c++)this.set(d+c+b,this.get(d+c))}}_getCyclicIndex(d){return(this._startIndex+d)%this._maxLength}}n.CircularList=h},7453:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.clone=function l(u,y=5){if(typeof u!="object")return u;let h=Array.isArray(u)?[]:{};for(let _ in u)h[_]=y<=1?u[_]:u[_]&&l(u[_],y-1);return h}},5777:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreTerminal=void 0;let u=l(6501),y=l(6025),h=l(7276),_=l(9640),d=l(56),p=l(4071),b=l(7792),c=l(6415),v=l(5746),g=l(5882),f=l(2486),m=l(3562),w=l(8811),C=l(802),k=l(7150),A=!1;class O extends k.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new C.Emitter),this._onScroll.event((L=>{this._onScrollApi?.fire(L.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(L){for(let R in L)this.optionsService.options[R]=L[R]}constructor(L){super(),this._windowsWrappingHeuristics=this._register(new k.MutableDisposable),this._onBinary=this._register(new C.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new C.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new C.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new C.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new C.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new C.Emitter),this._instantiationService=new y.InstantiationService,this.optionsService=this._register(new d.OptionsService(L)),this._instantiationService.setService(u.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(_.BufferService)),this._instantiationService.setService(u.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(h.LogService)),this._instantiationService.setService(u.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(p.CoreService)),this._instantiationService.setService(u.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(b.CoreMouseService)),this._instantiationService.setService(u.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(c.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(v.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(w.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new f.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(C.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(C.Event.forward(this._bufferService.onResize,this._onResize)),this._register(C.Event.forward(this.coreService.onData,this._onData)),this._register(C.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom(!0)))),this._register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this._register(this._bufferService.onScroll((()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this._register(new m.WriteBuffer(((R,P)=>this._inputHandler.parse(R,P)))),this._register(C.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(L,R){this._writeBuffer.write(L,R)}writeSync(L,R){this._logService.logLevel<=u.LogLevelEnum.WARN&&!A&&(this._logService.warn("writeSync is unreliable and will be removed soon."),A=!0),this._writeBuffer.writeSync(L,R)}input(L,R=!0){this.coreService.triggerDataEvent(L,R)}resize(L,R){isNaN(L)||isNaN(R)||(L=Math.max(L,_.MINIMUM_COLS),R=Math.max(R,_.MINIMUM_ROWS),this._bufferService.resize(L,R))}scroll(L,R=!1){this._bufferService.scroll(L,R)}scrollLines(L,R){this._bufferService.scrollLines(L,R)}scrollPages(L){this.scrollLines(L*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(L){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(L){let R=L-this._bufferService.buffer.ydisp;R!==0&&this.scrollLines(R)}registerEscHandler(L,R){return this._inputHandler.registerEscHandler(L,R)}registerDcsHandler(L,R){return this._inputHandler.registerDcsHandler(L,R)}registerCsiHandler(L,R){return this._inputHandler.registerCsiHandler(L,R)}registerOscHandler(L,R){return this._inputHandler.registerOscHandler(L,R)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let L=!1,R=this.optionsService.rawOptions.windowsPty;R&&R.buildNumber!==void 0&&R.buildNumber!==void 0?L=R.backend==="conpty"&&R.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(L=!0),L?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let L=[];L.push(this.onLineFeed(g.updateWindowsModeWrappedState.bind(null,this._bufferService))),L.push(this.registerCsiHandler({final:"H"},(()=>((0,g.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,k.toDisposable)((()=>{for(let R of L)R.dispose()}))}}}n.CoreTerminal=O},2486:function(a,n,l){var u=this&&this.__decorate||function(j,S,T,E){var x,M=arguments.length,N=M<3?S:E===null?E=Object.getOwnPropertyDescriptor(S,T):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(j,S,T,E);else for(var H=j.length-1;H>=0;H--)(x=j[H])&&(N=(M<3?x(N):M>3?x(S,T,N):x(S,T))||N);return M>3&&N&&Object.defineProperty(S,T,N),N},y=this&&this.__param||function(j,S){return function(T,E){S(T,E,j)}};Object.defineProperty(n,"__esModule",{value:!0}),n.InputHandler=n.WindowsOptionsReportType=void 0,n.isValidColorIndex=Y;let h=l(3534),_=l(6760),d=l(6717),p=l(7150),b=l(726),c=l(6107),v=l(8938),g=l(3055),f=l(5451),m=l(6501),w=l(6415),C=l(1346),k=l(9823),A=l(8693),O=l(802),D={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function R(j,S){if(j>24)return S.setWinLines||!1;switch(j){case 1:return!!S.restoreWin;case 2:return!!S.minimizeWin;case 3:return!!S.setWinPosition;case 4:return!!S.setWinSizePixels;case 5:return!!S.raiseWin;case 6:return!!S.lowerWin;case 7:return!!S.refreshWin;case 8:return!!S.setWinSizeChars;case 9:return!!S.maximizeWin;case 10:return!!S.fullscreenWin;case 11:return!!S.getWinState;case 13:return!!S.getWinPosition;case 14:return!!S.getWinSizePixels;case 15:return!!S.getScreenSizePixels;case 16:return!!S.getCellSizePixels;case 18:return!!S.getWinSizeChars;case 19:return!!S.getScreenSizeChars;case 20:return!!S.getIconTitle;case 21:return!!S.getWinTitle;case 22:return!!S.pushTitle;case 23:return!!S.popTitle;case 24:return!!S.setWinLines}return!1}var P;(function(j){j[j.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",j[j.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(P||(n.WindowsOptionsReportType=P={}));let F=0;class V extends p.Disposable{getAttrData(){return this._curAttrData}constructor(S,T,E,x,M,N,H,z,ne=new d.EscapeSequenceParser){super(),this._bufferService=S,this._charsetService=T,this._coreService=E,this._logService=x,this._optionsService=M,this._oscLinkService=N,this._coreMouseService=H,this._unicodeService=z,this._parser=ne,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new b.StringToUtf32,this._utf8Decoder=new b.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new O.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new O.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new O.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new O.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new O.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new O.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new O.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new O.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new O.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new O.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new O.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new O.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new O.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((I=>this._activeBuffer=I.activeBuffer))),this._parser.setCsiHandlerFallback(((I,Q)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(I),params:Q.toArray()})})),this._parser.setEscHandlerFallback((I=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(I)})})),this._parser.setExecuteHandlerFallback((I=>{this._logService.debug("Unknown EXECUTE code: ",{code:I})})),this._parser.setOscHandlerFallback(((I,Q,J)=>{this._logService.debug("Unknown OSC code: ",{identifier:I,action:Q,data:J})})),this._parser.setDcsHandlerFallback(((I,Q,J)=>{Q==="HOOK"&&(J=J.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(I),action:Q,payload:J})})),this._parser.setPrintHandler(((I,Q,J)=>this.print(I,Q,J))),this._parser.registerCsiHandler({final:"@"},(I=>this.insertChars(I))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(I=>this.scrollLeft(I))),this._parser.registerCsiHandler({final:"A"},(I=>this.cursorUp(I))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(I=>this.scrollRight(I))),this._parser.registerCsiHandler({final:"B"},(I=>this.cursorDown(I))),this._parser.registerCsiHandler({final:"C"},(I=>this.cursorForward(I))),this._parser.registerCsiHandler({final:"D"},(I=>this.cursorBackward(I))),this._parser.registerCsiHandler({final:"E"},(I=>this.cursorNextLine(I))),this._parser.registerCsiHandler({final:"F"},(I=>this.cursorPrecedingLine(I))),this._parser.registerCsiHandler({final:"G"},(I=>this.cursorCharAbsolute(I))),this._parser.registerCsiHandler({final:"H"},(I=>this.cursorPosition(I))),this._parser.registerCsiHandler({final:"I"},(I=>this.cursorForwardTab(I))),this._parser.registerCsiHandler({final:"J"},(I=>this.eraseInDisplay(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(I=>this.eraseInDisplay(I,!0))),this._parser.registerCsiHandler({final:"K"},(I=>this.eraseInLine(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(I=>this.eraseInLine(I,!0))),this._parser.registerCsiHandler({final:"L"},(I=>this.insertLines(I))),this._parser.registerCsiHandler({final:"M"},(I=>this.deleteLines(I))),this._parser.registerCsiHandler({final:"P"},(I=>this.deleteChars(I))),this._parser.registerCsiHandler({final:"S"},(I=>this.scrollUp(I))),this._parser.registerCsiHandler({final:"T"},(I=>this.scrollDown(I))),this._parser.registerCsiHandler({final:"X"},(I=>this.eraseChars(I))),this._parser.registerCsiHandler({final:"Z"},(I=>this.cursorBackwardTab(I))),this._parser.registerCsiHandler({final:"`"},(I=>this.charPosAbsolute(I))),this._parser.registerCsiHandler({final:"a"},(I=>this.hPositionRelative(I))),this._parser.registerCsiHandler({final:"b"},(I=>this.repeatPrecedingCharacter(I))),this._parser.registerCsiHandler({final:"c"},(I=>this.sendDeviceAttributesPrimary(I))),this._parser.registerCsiHandler({prefix:">",final:"c"},(I=>this.sendDeviceAttributesSecondary(I))),this._parser.registerCsiHandler({final:"d"},(I=>this.linePosAbsolute(I))),this._parser.registerCsiHandler({final:"e"},(I=>this.vPositionRelative(I))),this._parser.registerCsiHandler({final:"f"},(I=>this.hVPosition(I))),this._parser.registerCsiHandler({final:"g"},(I=>this.tabClear(I))),this._parser.registerCsiHandler({final:"h"},(I=>this.setMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(I=>this.setModePrivate(I))),this._parser.registerCsiHandler({final:"l"},(I=>this.resetMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(I=>this.resetModePrivate(I))),this._parser.registerCsiHandler({final:"m"},(I=>this.charAttributes(I))),this._parser.registerCsiHandler({final:"n"},(I=>this.deviceStatus(I))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(I=>this.deviceStatusPrivate(I))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(I=>this.softReset(I))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(I=>this.setCursorStyle(I))),this._parser.registerCsiHandler({final:"r"},(I=>this.setScrollRegion(I))),this._parser.registerCsiHandler({final:"s"},(I=>this.saveCursor(I))),this._parser.registerCsiHandler({final:"t"},(I=>this.windowOptions(I))),this._parser.registerCsiHandler({final:"u"},(I=>this.restoreCursor(I))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(I=>this.insertColumns(I))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(I=>this.deleteColumns(I))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(I=>this.selectProtected(I))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(I=>this.requestMode(I,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(I=>this.requestMode(I,!1))),this._parser.setExecuteHandler(h.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(h.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(h.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(h.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(h.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(h.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(h.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(h.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(h.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new C.OscHandler((I=>(this.setTitle(I),this.setIconName(I),!0)))),this._parser.registerOscHandler(1,new C.OscHandler((I=>this.setIconName(I)))),this._parser.registerOscHandler(2,new C.OscHandler((I=>this.setTitle(I)))),this._parser.registerOscHandler(4,new C.OscHandler((I=>this.setOrReportIndexedColor(I)))),this._parser.registerOscHandler(8,new C.OscHandler((I=>this.setHyperlink(I)))),this._parser.registerOscHandler(10,new C.OscHandler((I=>this.setOrReportFgColor(I)))),this._parser.registerOscHandler(11,new C.OscHandler((I=>this.setOrReportBgColor(I)))),this._parser.registerOscHandler(12,new C.OscHandler((I=>this.setOrReportCursorColor(I)))),this._parser.registerOscHandler(104,new C.OscHandler((I=>this.restoreIndexedColor(I)))),this._parser.registerOscHandler(110,new C.OscHandler((I=>this.restoreFgColor(I)))),this._parser.registerOscHandler(111,new C.OscHandler((I=>this.restoreBgColor(I)))),this._parser.registerOscHandler(112,new C.OscHandler((I=>this.restoreCursorColor(I)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(let I in _.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:I},(()=>this.selectCharset("("+I))),this._parser.registerEscHandler({intermediates:")",final:I},(()=>this.selectCharset(")"+I))),this._parser.registerEscHandler({intermediates:"*",final:I},(()=>this.selectCharset("*"+I))),this._parser.registerEscHandler({intermediates:"+",final:I},(()=>this.selectCharset("+"+I))),this._parser.registerEscHandler({intermediates:"-",final:I},(()=>this.selectCharset("-"+I))),this._parser.registerEscHandler({intermediates:".",final:I},(()=>this.selectCharset("."+I))),this._parser.registerEscHandler({intermediates:"/",final:I},(()=>this.selectCharset("/"+I)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((I=>(this._logService.error("Parsing error: ",I),I))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new k.DcsHandler(((I,Q)=>this.requestStatusString(I,Q))))}_preserveStack(S,T,E,x){this._parseStack.paused=!0,this._parseStack.cursorStartX=S,this._parseStack.cursorStartY=T,this._parseStack.decodedLength=E,this._parseStack.position=x}_logSlowResolvingAsync(S){this._logService.logLevel<=m.LogLevelEnum.WARN&&Promise.race([S,new Promise(((T,E)=>setTimeout((()=>E("#SLOW_TIMEOUT")),5e3)))]).catch((T=>{if(T!=="#SLOW_TIMEOUT")throw T;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(S,T){let E,x=this._activeBuffer.x,M=this._activeBuffer.y,N=0,H=this._parseStack.paused;if(H){if(E=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,T))return this._logSlowResolvingAsync(E),E;x=this._parseStack.cursorStartX,M=this._parseStack.cursorStartY,this._parseStack.paused=!1,S.length>L&&(N=this._parseStack.position+L)}if(this._logService.logLevel<=m.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+(typeof S=="string"?` "${S}"`:` "${Array.prototype.map.call(S,(I=>String.fromCharCode(I))).join("")}"`)),this._logService.logLevel===m.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)",typeof S=="string"?S.split("").map((I=>I.charCodeAt(0))):S),this._parseBuffer.length<S.length&&this._parseBuffer.length<L&&(this._parseBuffer=new Uint32Array(Math.min(S.length,L))),H||this._dirtyRowTracker.clearRange(),S.length>L)for(let I=N;I<S.length;I+=L){let Q=I+L<S.length?I+L:S.length,J=typeof S=="string"?this._stringDecoder.decode(S.substring(I,Q),this._parseBuffer):this._utf8Decoder.decode(S.subarray(I,Q),this._parseBuffer);if(E=this._parser.parse(this._parseBuffer,J))return this._preserveStack(x,M,J,I),this._logSlowResolvingAsync(E),E}else if(!H){let I=typeof S=="string"?this._stringDecoder.decode(S,this._parseBuffer):this._utf8Decoder.decode(S,this._parseBuffer);if(E=this._parser.parse(this._parseBuffer,I))return this._preserveStack(x,M,I,0),this._logSlowResolvingAsync(E),E}this._activeBuffer.x===x&&this._activeBuffer.y===M||this._onCursorMove.fire();let z=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),ne=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);ne<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(ne,this._bufferService.rows-1),end:Math.min(z,this._bufferService.rows-1)})}print(S,T,E){let x,M,N=this._charsetService.charset,H=this._optionsService.rawOptions.screenReaderMode,z=this._bufferService.cols,ne=this._coreService.decPrivateModes.wraparound,I=this._coreService.modes.insertMode,Q=this._curAttrData,J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&E-T>0&&J.getWidth(this._activeBuffer.x-1)===2&&J.setCellFromCodepoint(this._activeBuffer.x-1,0,1,Q);let te=this._parser.precedingJoinState;for(let Ae=T;Ae<E;++Ae){if(x=S[Ae],x<127&&N){let yt=N[String.fromCharCode(x)];yt&&(x=yt.charCodeAt(0))}let Ie=this._unicodeService.charProperties(x,te);M=w.UnicodeService.extractWidth(Ie);let Xt=w.UnicodeService.extractShouldJoin(Ie),We=Xt?w.UnicodeService.extractWidth(te):0;if(te=Ie,H&&this._onA11yChar.fire((0,b.stringFromCodePoint)(x)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+M-We>z){if(ne){let yt=J,Ir=this._activeBuffer.x-We;for(this._activeBuffer.x=We,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),We>0&&J instanceof c.BufferLine&&J.copyCellsFrom(yt,Ir,0,We,!1);Ir<z;)yt.setCellFromCodepoint(Ir++,0,1,Q)}else if(this._activeBuffer.x=z-1,M===2)continue}if(Xt&&this._activeBuffer.x){let yt=J.getWidth(this._activeBuffer.x-1)?1:2;J.addCodepointToCell(this._activeBuffer.x-yt,x,M);for(let Ir=M-We;--Ir>=0;)J.setCellFromCodepoint(this._activeBuffer.x++,0,0,Q)}else if(I&&(J.insertCells(this._activeBuffer.x,M-We,this._activeBuffer.getNullCell(Q)),J.getWidth(z-1)===2&&J.setCellFromCodepoint(z-1,v.NULL_CELL_CODE,v.NULL_CELL_WIDTH,Q)),J.setCellFromCodepoint(this._activeBuffer.x++,x,M,Q),M>0)for(;--M;)J.setCellFromCodepoint(this._activeBuffer.x++,0,0,Q)}this._parser.precedingJoinState=te,this._activeBuffer.x<z&&E-T>0&&J.getWidth(this._activeBuffer.x)===0&&!J.hasContent(this._activeBuffer.x)&&J.setCellFromCodepoint(this._activeBuffer.x,0,1,Q),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(S,T){return S.final!=="t"||S.prefix||S.intermediates?this._parser.registerCsiHandler(S,T):this._parser.registerCsiHandler(S,(E=>!R(E.params[0],this._optionsService.rawOptions.windowOptions)||T(E)))}registerDcsHandler(S,T){return this._parser.registerDcsHandler(S,new k.DcsHandler(T))}registerEscHandler(S,T){return this._parser.registerEscHandler(S,T)}registerOscHandler(S,T){return this._parser.registerOscHandler(S,new C.OscHandler(T))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let S=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);S.hasWidth(this._activeBuffer.x)&&!S.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let S=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-S),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(S=this._bufferService.cols-1){this._activeBuffer.x=Math.min(S,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(S,T){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=S,this._activeBuffer.y=this._activeBuffer.scrollTop+T):(this._activeBuffer.x=S,this._activeBuffer.y=T),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(S,T){this._restrictCursor(),this._setCursor(this._activeBuffer.x+S,this._activeBuffer.y+T)}cursorUp(S){let T=this._activeBuffer.y-this._activeBuffer.scrollTop;return T>=0?this._moveCursor(0,-Math.min(T,S.params[0]||1)):this._moveCursor(0,-(S.params[0]||1)),!0}cursorDown(S){let T=this._activeBuffer.scrollBottom-this._activeBuffer.y;return T>=0?this._moveCursor(0,Math.min(T,S.params[0]||1)):this._moveCursor(0,S.params[0]||1),!0}cursorForward(S){return this._moveCursor(S.params[0]||1,0),!0}cursorBackward(S){return this._moveCursor(-(S.params[0]||1),0),!0}cursorNextLine(S){return this.cursorDown(S),this._activeBuffer.x=0,!0}cursorPrecedingLine(S){return this.cursorUp(S),this._activeBuffer.x=0,!0}cursorCharAbsolute(S){return this._setCursor((S.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(S){return this._setCursor(S.length>=2?(S.params[1]||1)-1:0,(S.params[0]||1)-1),!0}charPosAbsolute(S){return this._setCursor((S.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(S){return this._moveCursor(S.params[0]||1,0),!0}linePosAbsolute(S){return this._setCursor(this._activeBuffer.x,(S.params[0]||1)-1),!0}vPositionRelative(S){return this._moveCursor(0,S.params[0]||1),!0}hVPosition(S){return this.cursorPosition(S),!0}tabClear(S){let T=S.params[0];return T===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:T===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(S){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=S.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(S){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=S.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(S){let T=S.params[0];return T===1&&(this._curAttrData.bg|=536870912),T!==2&&T!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(S,T,E,x=!1,M=!1){let N=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);N.replaceCells(T,E,this._activeBuffer.getNullCell(this._eraseAttrData()),M),x&&(N.isWrapped=!1)}_resetBufferLine(S,T=!1){let E=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);E&&(E.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),T),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+S),E.isWrapped=!1)}eraseInDisplay(S,T=!1){let E;switch(this._restrictCursor(this._bufferService.cols),S.params[0]){case 0:for(E=this._activeBuffer.y,this._dirtyRowTracker.markDirty(E),this._eraseInBufferLine(E++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);E<this._bufferService.rows;E++)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(E);break;case 1:for(E=this._activeBuffer.y,this._dirtyRowTracker.markDirty(E),this._eraseInBufferLine(E,0,this._activeBuffer.x+1,!0,T),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(E+1).isWrapped=!1);E--;)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(E=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,E-1);E--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+E)?.getTrimmedLength(););for(;E>=0;E--)this._bufferService.scroll(this._eraseAttrData())}else{for(E=this._bufferService.rows,this._dirtyRowTracker.markDirty(E-1);E--;)this._resetBufferLine(E,T);this._dirtyRowTracker.markDirty(0)}break;case 3:let x=this._activeBuffer.lines.length-this._bufferService.rows;x>0&&(this._activeBuffer.lines.trimStart(x),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-x,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-x,0),this._onScroll.fire(0))}return!0}eraseInLine(S,T=!1){switch(this._restrictCursor(this._bufferService.cols),S.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,T);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,T)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(S){this._restrictCursor();let T=S.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let E=this._activeBuffer.ybase+this._activeBuffer.y,x=this._bufferService.rows-1-this._activeBuffer.scrollBottom,M=this._bufferService.rows-1+this._activeBuffer.ybase-x+1;for(;T--;)this._activeBuffer.lines.splice(M-1,1),this._activeBuffer.lines.splice(E,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(S){this._restrictCursor();let T=S.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let E=this._activeBuffer.ybase+this._activeBuffer.y,x;for(x=this._bufferService.rows-1-this._activeBuffer.scrollBottom,x=this._bufferService.rows-1+this._activeBuffer.ybase-x;T--;)this._activeBuffer.lines.splice(E,1),this._activeBuffer.lines.splice(x,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.insertCells(this._activeBuffer.x,S.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.deleteCells(this._activeBuffer.x,S.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(S){let T=S.params[0]||1;for(;T--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(S){let T=S.params[0]||1;for(;T--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(c.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.deleteCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.insertCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.insertCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(S){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let T=S.params[0]||1;for(let E=this._activeBuffer.scrollTop;E<=this._activeBuffer.scrollBottom;++E){let x=this._activeBuffer.lines.get(this._activeBuffer.ybase+E);x.deleteCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),x.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(S){this._restrictCursor();let T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(S.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(S){let T=this._parser.precedingJoinState;if(!T)return!0;let E=S.params[0]||1,x=w.UnicodeService.extractWidth(T),M=this._activeBuffer.x-x,N=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(M),H=new Uint32Array(N.length*E),z=0;for(let I=0;I<N.length;){let Q=N.codePointAt(I)||0;H[z++]=Q,I+=Q>65535?2:1}let ne=z;for(let I=1;I<E;++I)H.copyWithin(ne,0,z),ne+=z;return this.print(H,0,ne),!0}sendDeviceAttributesPrimary(S){return S.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(h.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(h.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(S){return S.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(h.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(h.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(S.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(h.C0.ESC+"[>83;40003;0c")),!0}_is(S){return(this._optionsService.rawOptions.termName+"").indexOf(S)===0}setMode(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),this._charsetService.setgCharset(1,_.DEFAULT_CHARSET),this._charsetService.setgCharset(2,_.DEFAULT_CHARSET),this._charsetService.setgCharset(3,_.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(S){for(let T=0;T<S.length;T++)switch(S.params[T]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),S.params[T]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(S,T){let E=this._coreService.decPrivateModes,{activeProtocol:x,activeEncoding:M}=this._coreMouseService,N=this._coreService,{buffers:H,cols:z}=this._bufferService,{active:ne,alt:I}=H,Q=this._optionsService.rawOptions,J=Xt=>Xt?1:2,te=S.params[0];return Ae=te,Ie=T?te===2?4:te===4?J(N.modes.insertMode):te===12?3:te===20?J(Q.convertEol):0:te===1?J(E.applicationCursorKeys):te===3?Q.windowOptions.setWinLines?z===80?2:z===132?1:0:0:te===6?J(E.origin):te===7?J(E.wraparound):te===8?3:te===9?J(x==="X10"):te===12?J(Q.cursorBlink):te===25?J(!N.isCursorHidden):te===45?J(E.reverseWraparound):te===66?J(E.applicationKeypad):te===67?4:te===1e3?J(x==="VT200"):te===1002?J(x==="DRAG"):te===1003?J(x==="ANY"):te===1004?J(E.sendFocus):te===1005?4:te===1006?J(M==="SGR"):te===1015?4:te===1016?J(M==="SGR_PIXELS"):te===1048?1:te===47||te===1047||te===1049?J(ne===I):te===2004?J(E.bracketedPasteMode):te===2026?J(E.synchronizedOutput):0,N.triggerDataEvent(`${h.C0.ESC}[${T?"":"?"}${Ae};${Ie}$y`),!0;var Ae,Ie}_updateAttrColor(S,T,E,x,M){return T===2?(S|=50331648,S&=-16777216,S|=f.AttributeData.fromColorRGB([E,x,M])):T===5&&(S&=-50331904,S|=33554432|255&E),S}_extractColor(S,T,E){let x=[0,0,-1,0,0,0],M=0,N=0;do{if(x[N+M]=S.params[T+N],S.hasSubParams(T+N)){let H=S.getSubParams(T+N),z=0;do x[1]===5&&(M=1),x[N+z+1+M]=H[z];while(++z<H.length&&z+N+1+M<x.length);break}if(x[1]===5&&N+M>=2||x[1]===2&&N+M>=5)break;x[1]&&(M=1)}while(++N+T<S.length&&N+M<x.length);for(let H=2;H<x.length;++H)x[H]===-1&&(x[H]=0);switch(x[0]){case 38:E.fg=this._updateAttrColor(E.fg,x[1],x[3],x[4],x[5]);break;case 48:E.bg=this._updateAttrColor(E.bg,x[1],x[3],x[4],x[5]);break;case 58:E.extended=E.extended.clone(),E.extended.underlineColor=this._updateAttrColor(E.extended.underlineColor,x[1],x[3],x[4],x[5])}return N}_processUnderline(S,T){T.extended=T.extended.clone(),(!~S||S>5)&&(S=1),T.extended.underlineStyle=S,T.fg|=268435456,S===0&&(T.fg&=-268435457),T.updateExtended()}_processSGR0(S){S.fg=c.DEFAULT_ATTR_DATA.fg,S.bg=c.DEFAULT_ATTR_DATA.bg,S.extended=S.extended.clone(),S.extended.underlineStyle=0,S.extended.underlineColor&=-67108864,S.updateExtended()}charAttributes(S){if(S.length===1&&S.params[0]===0)return this._processSGR0(this._curAttrData),!0;let T=S.length,E,x=this._curAttrData;for(let M=0;M<T;M++)E=S.params[M],E>=30&&E<=37?(x.fg&=-50331904,x.fg|=16777216|E-30):E>=40&&E<=47?(x.bg&=-50331904,x.bg|=16777216|E-40):E>=90&&E<=97?(x.fg&=-50331904,x.fg|=16777224|E-90):E>=100&&E<=107?(x.bg&=-50331904,x.bg|=16777224|E-100):E===0?this._processSGR0(x):E===1?x.fg|=134217728:E===3?x.bg|=67108864:E===4?(x.fg|=268435456,this._processUnderline(S.hasSubParams(M)?S.getSubParams(M)[0]:1,x)):E===5?x.fg|=536870912:E===7?x.fg|=67108864:E===8?x.fg|=1073741824:E===9?x.fg|=2147483648:E===2?x.bg|=134217728:E===21?this._processUnderline(2,x):E===22?(x.fg&=-134217729,x.bg&=-134217729):E===23?x.bg&=-67108865:E===24?(x.fg&=-268435457,this._processUnderline(0,x)):E===25?x.fg&=-536870913:E===27?x.fg&=-67108865:E===28?x.fg&=-1073741825:E===29?x.fg&=2147483647:E===39?(x.fg&=-67108864,x.fg|=16777215&c.DEFAULT_ATTR_DATA.fg):E===49?(x.bg&=-67108864,x.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):E===38||E===48||E===58?M+=this._extractColor(S,M,x):E===53?x.bg|=1073741824:E===55?x.bg&=-1073741825:E===59?(x.extended=x.extended.clone(),x.extended.underlineColor=-1,x.updateExtended()):E===100?(x.fg&=-67108864,x.fg|=16777215&c.DEFAULT_ATTR_DATA.fg,x.bg&=-67108864,x.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",E);return!0}deviceStatus(S){switch(S.params[0]){case 5:this._coreService.triggerDataEvent(`${h.C0.ESC}[0n`);break;case 6:let T=this._activeBuffer.y+1,E=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[${T};${E}R`)}return!0}deviceStatusPrivate(S){if(S.params[0]===6){let T=this._activeBuffer.y+1,E=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[?${T};${E}R`)}return!0}softReset(S){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(S){let T=S.length===0?1:S.params[0];if(T===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(T){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}let E=T%2==1;this._coreService.decPrivateModes.cursorBlink=E}return!0}setScrollRegion(S){let T=S.params[0]||1,E;return(S.length<2||(E=S.params[1])>this._bufferService.rows||E===0)&&(E=this._bufferService.rows),E>T&&(this._activeBuffer.scrollTop=T-1,this._activeBuffer.scrollBottom=E-1,this._setCursor(0,0)),!0}windowOptions(S){if(!R(S.params[0],this._optionsService.rawOptions.windowOptions))return!0;let T=S.length>1?S.params[1]:0;switch(S.params[0]){case 14:T!==2&&this._onRequestWindowsOptionsReport.fire(P.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(P.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${h.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:T!==0&&T!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),T!==0&&T!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:T!==0&&T!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),T!==0&&T!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(S){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(S){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(S){return this._windowTitle=S,this._onTitleChange.fire(S),!0}setIconName(S){return this._iconName=S,!0}setOrReportIndexedColor(S){let T=[],E=S.split(";");for(;E.length>1;){let x=E.shift(),M=E.shift();if(/^\d+$/.exec(x)){let N=parseInt(x);if(Y(N))if(M==="?")T.push({type:0,index:N});else{let H=(0,A.parseColor)(M);H&&T.push({type:1,index:N,color:H})}}}return T.length&&this._onColor.fire(T),!0}setHyperlink(S){let T=S.indexOf(";");if(T===-1)return!0;let E=S.slice(0,T).trim(),x=S.slice(T+1);return x?this._createHyperlink(E,x):!E.trim()&&this._finishHyperlink()}_createHyperlink(S,T){this._getCurrentLinkId()&&this._finishHyperlink();let E=S.split(":"),x,M=E.findIndex((N=>N.startsWith("id=")));return M!==-1&&(x=E[M].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:x,uri:T}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(S,T){let E=S.split(";");for(let x=0;x<E.length&&!(T>=this._specialColors.length);++x,++T)if(E[x]==="?")this._onColor.fire([{type:0,index:this._specialColors[T]}]);else{let M=(0,A.parseColor)(E[x]);M&&this._onColor.fire([{type:1,index:this._specialColors[T],color:M}])}return!0}setOrReportFgColor(S){return this._setOrReportSpecialColor(S,0)}setOrReportBgColor(S){return this._setOrReportSpecialColor(S,1)}setOrReportCursorColor(S){return this._setOrReportSpecialColor(S,2)}restoreIndexedColor(S){if(!S)return this._onColor.fire([{type:2}]),!0;let T=[],E=S.split(";");for(let x=0;x<E.length;++x)if(/^\d+$/.exec(E[x])){let M=parseInt(E[x]);Y(M)&&T.push({type:2,index:M})}return T.length&&this._onColor.fire(T),!0}restoreFgColor(S){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(S){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(S){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),!0}selectCharset(S){return S.length!==2?(this.selectDefaultCharset(),!0):(S[0]==="/"||this._charsetService.setgCharset(D[S[0]],_.CHARSETS[S[1]]||_.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let S=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,S,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(S){return this._charsetService.setgLevel(S),!0}screenAlignmentPattern(){let S=new g.CellData;S.content=4194373,S.fg=this._curAttrData.fg,S.bg=this._curAttrData.bg,this._setCursor(0,0);for(let T=0;T<this._bufferService.rows;++T){let E=this._activeBuffer.ybase+this._activeBuffer.y+T,x=this._activeBuffer.lines.get(E);x&&(x.fill(S),x.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(S,T){let E=this._bufferService.buffer,x=this._optionsService.rawOptions;return(M=>(this._coreService.triggerDataEvent(`${h.C0.ESC}${M}${h.C0.ESC}\\`),!0))(S==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:S==='"p'?'P1$r61;1"p':S==="r"?`P1$r${E.scrollTop+1};${E.scrollBottom+1}r`:S==="m"?"P1$r0m":S===" q"?`P1$r${{block:2,underline:4,bar:6}[x.cursorStyle]-(x.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(S,T){this._dirtyRowTracker.markRangeDirty(S,T)}}n.InputHandler=V;let Z=class{constructor(j){this._bufferService=j,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(j){j<this.start?this.start=j:j>this.end&&(this.end=j)}markRangeDirty(j,S){j>S&&(F=j,j=S,S=F),j<this.start&&(this.start=j),S>this.end&&(this.end=S)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function Y(j){return 0<=j&&j<256}Z=u([y(0,m.IBufferService)],Z)},701:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isChromeOS=n.isLinux=n.isWindows=n.isIphone=n.isIpad=n.isMac=n.isSafari=n.isLegacyEdge=n.isFirefox=n.isNode=void 0,n.getSafariVersion=function(){if(!n.isSafari)return 0;let y=l.match(/Version\/(\d+)/);return y===null||y.length<2?0:parseInt(y[1])},n.isNode=typeof process<"u"&&"title"in process;let l=n.isNode?"node":navigator.userAgent,u=n.isNode?"node":navigator.platform;n.isFirefox=l.includes("Firefox"),n.isLegacyEdge=l.includes("Edge"),n.isSafari=/^((?!chrome|android).)*safari/i.test(l),n.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(u),n.isIpad=u==="iPad",n.isIphone=u==="iPhone",n.isWindows=["Windows","Win16","Win32","WinCE"].includes(u),n.isLinux=u.indexOf("Linux")>=0,n.isChromeOS=/\bCrOS\b/.test(l)},6168:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DebouncedIdleTask=n.IdleTaskQueue=n.PriorityTaskQueue=void 0;let u=l(701);class y{constructor(){this._tasks=[],this._i=0}enqueue(d){this._tasks.push(d),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(d){this._idleCallback=void 0;let p=0,b=0,c=d.timeRemaining(),v=0;for(;this._i<this._tasks.length;){if(p=performance.now(),this._tasks[this._i]()||this._i++,p=Math.max(1,performance.now()-p),b=Math.max(p,b),v=d.timeRemaining(),1.5*b>v)return c-p<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(c-p))}ms`),void this._start();c=v}this.clear()}}class h extends y{_requestCallback(d){return setTimeout((()=>d(this._createDeadline(16))))}_cancelCallback(d){clearTimeout(d)}_createDeadline(d){let p=performance.now()+d;return{timeRemaining:()=>Math.max(0,p-performance.now())}}}n.PriorityTaskQueue=h,n.IdleTaskQueue=!u.isNode&&"requestIdleCallback"in window?class extends y{_requestCallback(_){return requestIdleCallback(_)}_cancelCallback(_){cancelIdleCallback(_)}}:h,n.DebouncedIdleTask=class{constructor(){this._queue=new n.IdleTaskQueue}set(_){this._queue.clear(),this._queue.enqueue(_)}flush(){this._queue.flush()}}},5882:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateWindowsModeWrappedState=function(y){let h=y.buffer.lines.get(y.buffer.ybase+y.buffer.y-1),_=h?.get(y.cols-1),d=y.buffer.lines.get(y.buffer.ybase+y.buffer.y);d&&_&&(d.isWrapped=_[u.CHAR_DATA_CODE_INDEX]!==u.NULL_CELL_CODE&&_[u.CHAR_DATA_CODE_INDEX]!==u.WHITESPACE_CELL_CODE)};let u=l(8938)},5451:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExtendedAttrs=n.AttributeData=void 0;class l{constructor(){this.fg=0,this.bg=0,this.extended=new u}static toColorRGB(h){return[h>>>16&255,h>>>8&255,255&h]}static fromColorRGB(h){return(255&h[0])<<16|(255&h[1])<<8|255&h[2]}clone(){let h=new l;return h.fg=this.fg,h.bg=this.bg,h.extended=this.extended.clone(),h}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}n.AttributeData=l;class u{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(h){this._ext=h}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(h){this._ext&=-469762049,this._ext|=h<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(h){this._ext&=-67108864,this._ext|=67108863&h}get urlId(){return this._urlId}set urlId(h){this._urlId=h}get underlineVariantOffset(){let h=(3758096384&this._ext)>>29;return h<0?4294967288^h:h}set underlineVariantOffset(h){this._ext&=536870911,this._ext|=h<<29&3758096384}constructor(h=0,_=0){this._ext=0,this._urlId=0,this._ext=h,this._urlId=_}clone(){return new u(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}n.ExtendedAttrs=u},1073:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Buffer=n.MAX_BUFFER_SIZE=void 0;let u=l(5639),y=l(6168),h=l(5451),_=l(6107),d=l(732),p=l(3055),b=l(8938),c=l(8158),v=l(6760);n.MAX_BUFFER_SIZE=4294967295,n.Buffer=class{constructor(g,f,m){this._hasScrollback=g,this._optionsService=f,this._bufferService=m,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=_.DEFAULT_ATTR_DATA.clone(),this.savedCharset=v.DEFAULT_CHARSET,this.markers=[],this._nullCell=p.CellData.fromCharData([0,b.NULL_CELL_CHAR,b.NULL_CELL_WIDTH,b.NULL_CELL_CODE]),this._whitespaceCell=p.CellData.fromCharData([0,b.WHITESPACE_CELL_CHAR,b.WHITESPACE_CELL_WIDTH,b.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new y.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new u.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(g){return g?(this._nullCell.fg=g.fg,this._nullCell.bg=g.bg,this._nullCell.extended=g.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new h.ExtendedAttrs),this._nullCell}getWhitespaceCell(g){return g?(this._whitespaceCell.fg=g.fg,this._whitespaceCell.bg=g.bg,this._whitespaceCell.extended=g.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new h.ExtendedAttrs),this._whitespaceCell}getBlankLine(g,f){return new _.BufferLine(this._bufferService.cols,this.getNullCell(g),f)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let g=this.ybase+this.y-this.ydisp;return g>=0&&g<this._rows}_getCorrectBufferLength(g){if(!this._hasScrollback)return g;let f=g+this._optionsService.rawOptions.scrollback;return f>n.MAX_BUFFER_SIZE?n.MAX_BUFFER_SIZE:f}fillViewportRows(g){if(this.lines.length===0){g===void 0&&(g=_.DEFAULT_ATTR_DATA);let f=this._rows;for(;f--;)this.lines.push(this.getBlankLine(g))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new u.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(g,f){let m=this.getNullCell(_.DEFAULT_ATTR_DATA),w=0,C=this._getCorrectBufferLength(f);if(C>this.lines.maxLength&&(this.lines.maxLength=C),this.lines.length>0){if(this._cols<g)for(let A=0;A<this.lines.length;A++)w+=+this.lines.get(A).resize(g,m);let k=0;if(this._rows<f)for(let A=this._rows;A<f;A++)this.lines.length<f+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new _.BufferLine(g,m)):this.ybase>0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new _.BufferLine(g,m)));else for(let A=this._rows;A>f;A--)this.lines.length>f+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(C<this.lines.maxLength){let A=this.lines.length-C;A>0&&(this.lines.trimStart(A),this.ybase=Math.max(this.ybase-A,0),this.ydisp=Math.max(this.ydisp-A,0),this.savedY=Math.max(this.savedY-A,0)),this.lines.maxLength=C}this.x=Math.min(this.x,g-1),this.y=Math.min(this.y,f-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,g-1),this.scrollTop=0}if(this.scrollBottom=f-1,this._isReflowEnabled&&(this._reflow(g,f),this._cols>g))for(let k=0;k<this.lines.length;k++)w+=+this.lines.get(k).resize(g,m);this._cols=g,this._rows=f,this._memoryCleanupQueue.clear(),w>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let g=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,g=!1);let f=0;for(;this._memoryCleanupPosition<this.lines.length;)if(f+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),f>100)return!0;return g}get _isReflowEnabled(){let g=this._optionsService.rawOptions.windowsPty;return g&&g.buildNumber?this._hasScrollback&&g.backend==="conpty"&&g.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(g,f){this._cols!==g&&(g>this._cols?this._reflowLarger(g,f):this._reflowSmaller(g,f))}_reflowLarger(g,f){let m=this._optionsService.rawOptions.reflowCursorLine,w=(0,d.reflowLargerGetLinesToRemove)(this.lines,this._cols,g,this.ybase+this.y,this.getNullCell(_.DEFAULT_ATTR_DATA),m);if(w.length>0){let C=(0,d.reflowLargerCreateNewLayout)(this.lines,w);(0,d.reflowLargerApplyNewLayout)(this.lines,C.layout),this._reflowLargerAdjustViewport(g,f,C.countRemoved)}}_reflowLargerAdjustViewport(g,f,m){let w=this.getNullCell(_.DEFAULT_ATTR_DATA),C=m;for(;C-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<f&&this.lines.push(new _.BufferLine(g,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-m,0)}_reflowSmaller(g,f){let m=this._optionsService.rawOptions.reflowCursorLine,w=this.getNullCell(_.DEFAULT_ATTR_DATA),C=[],k=0;for(let A=this.lines.length-1;A>=0;A--){let O=this.lines.get(A);if(!O||!O.isWrapped&&O.getTrimmedLength()<=g)continue;let D=[O];for(;O.isWrapped&&A>0;)O=this.lines.get(--A),D.unshift(O);if(!m){let E=this.ybase+this.y;if(E>=A&&E<A+D.length)continue}let L=D[D.length-1].getTrimmedLength(),R=(0,d.reflowSmallerGetNewLineLengths)(D,this._cols,g),P=R.length-D.length,F;F=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+P):Math.max(0,this.lines.length-this.lines.maxLength+P);let V=[];for(let E=0;E<P;E++){let x=this.getBlankLine(_.DEFAULT_ATTR_DATA,!0);V.push(x)}V.length>0&&(C.push({start:A+D.length+k,newLines:V}),k+=V.length),D.push(...V);let Z=R.length-1,Y=R[Z];Y===0&&(Z--,Y=R[Z]);let j=D.length-P-1,S=L;for(;j>=0;){let E=Math.min(S,Y);if(D[Z]===void 0)break;if(D[Z].copyCellsFrom(D[j],S-E,Y-E,E,!0),Y-=E,Y===0&&(Z--,Y=R[Z]),S-=E,S===0){j--;let x=Math.max(j,0);S=(0,d.getWrappedLineTrimmedLength)(D,x,this._cols)}}for(let E=0;E<D.length;E++)R[E]<g&&D[E].setCell(R[E],w);let T=P-F;for(;T-- >0;)this.ybase===0?this.y<f-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+k)-f&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+P,this.ybase+f-1)}if(C.length>0){let A=[],O=[];for(let Y=0;Y<this.lines.length;Y++)O.push(this.lines.get(Y));let D=this.lines.length,L=D-1,R=0,P=C[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+k);let F=0;for(let Y=Math.min(this.lines.maxLength-1,D+k-1);Y>=0;Y--)if(P&&P.start>L+F){for(let j=P.newLines.length-1;j>=0;j--)this.lines.set(Y--,P.newLines[j]);Y++,A.push({index:L+1,amount:P.newLines.length}),F+=P.newLines.length,P=C[++R]}else this.lines.set(Y,O[L--]);let V=0;for(let Y=A.length-1;Y>=0;Y--)A[Y].index+=V,this.lines.onInsertEmitter.fire(A[Y]),V+=A[Y].amount;let Z=Math.max(0,D+k-this.lines.maxLength);Z>0&&this.lines.onTrimEmitter.fire(Z)}}translateBufferLineToString(g,f,m=0,w){let C=this.lines.get(g);return C?C.translateToString(f,m,w):""}getWrappedRangeForLine(g){let f=g,m=g;for(;f>0&&this.lines.get(f).isWrapped;)f--;for(;m+1<this.lines.length&&this.lines.get(m+1).isWrapped;)m++;return{first:f,last:m}}setupTabStops(g){for(g!=null?this.tabs[g]||(g=this.prevStop(g)):(this.tabs={},g=0);g<this._cols;g+=this._optionsService.rawOptions.tabStopWidth)this.tabs[g]=!0}prevStop(g){for(g==null&&(g=this.x);!this.tabs[--g]&&g>0;);return g>=this._cols?this._cols-1:g<0?0:g}nextStop(g){for(g==null&&(g=this.x);!this.tabs[++g]&&g<this._cols;);return g>=this._cols?this._cols-1:g<0?0:g}clearMarkers(g){this._isClearing=!0;for(let f=0;f<this.markers.length;f++)this.markers[f].line===g&&(this.markers[f].dispose(),this.markers.splice(f--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let g=0;g<this.markers.length;g++)this.markers[g].dispose();this.markers.length=0,this._isClearing=!1}addMarker(g){let f=new c.Marker(g);return this.markers.push(f),f.register(this.lines.onTrim((m=>{f.line-=m,f.line<0&&f.dispose()}))),f.register(this.lines.onInsert((m=>{f.line>=m.index&&(f.line+=m.amount)}))),f.register(this.lines.onDelete((m=>{f.line>=m.index&&f.line<m.index+m.amount&&f.dispose(),f.line>m.index&&(f.line-=m.amount)}))),f.register(f.onDispose((()=>this._removeMarker(f)))),f}_removeMarker(g){this._isClearing||this.markers.splice(this.markers.indexOf(g),1)}}},6107:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLine=n.DEFAULT_ATTR_DATA=void 0;let u=l(5451),y=l(3055),h=l(8938),_=l(726);n.DEFAULT_ATTR_DATA=Object.freeze(new u.AttributeData);let d=0;class p{constructor(c,v,g=!1){this.isWrapped=g,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*c);let f=v||y.CellData.fromCharData([0,h.NULL_CELL_CHAR,h.NULL_CELL_WIDTH,h.NULL_CELL_CODE]);for(let m=0;m<c;++m)this.setCell(m,f);this.length=c}get(c){let v=this._data[3*c+0],g=2097151&v;return[this._data[3*c+1],2097152&v?this._combined[c]:g?(0,_.stringFromCodePoint)(g):"",v>>22,2097152&v?this._combined[c].charCodeAt(this._combined[c].length-1):g]}set(c,v){this._data[3*c+1]=v[h.CHAR_DATA_ATTR_INDEX],v[h.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[c]=v[1],this._data[3*c+0]=2097152|c|v[h.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*c+0]=v[h.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|v[h.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(c){return this._data[3*c+0]>>22}hasWidth(c){return 12582912&this._data[3*c+0]}getFg(c){return this._data[3*c+1]}getBg(c){return this._data[3*c+2]}hasContent(c){return 4194303&this._data[3*c+0]}getCodePoint(c){let v=this._data[3*c+0];return 2097152&v?this._combined[c].charCodeAt(this._combined[c].length-1):2097151&v}isCombined(c){return 2097152&this._data[3*c+0]}getString(c){let v=this._data[3*c+0];return 2097152&v?this._combined[c]:2097151&v?(0,_.stringFromCodePoint)(2097151&v):""}isProtected(c){return 536870912&this._data[3*c+2]}loadCell(c,v){return d=3*c,v.content=this._data[d+0],v.fg=this._data[d+1],v.bg=this._data[d+2],2097152&v.content&&(v.combinedData=this._combined[c]),268435456&v.bg&&(v.extended=this._extendedAttrs[c]),v}setCell(c,v){2097152&v.content&&(this._combined[c]=v.combinedData),268435456&v.bg&&(this._extendedAttrs[c]=v.extended),this._data[3*c+0]=v.content,this._data[3*c+1]=v.fg,this._data[3*c+2]=v.bg}setCellFromCodepoint(c,v,g,f){268435456&f.bg&&(this._extendedAttrs[c]=f.extended),this._data[3*c+0]=v|g<<22,this._data[3*c+1]=f.fg,this._data[3*c+2]=f.bg}addCodepointToCell(c,v,g){let f=this._data[3*c+0];2097152&f?this._combined[c]+=(0,_.stringFromCodePoint)(v):2097151&f?(this._combined[c]=(0,_.stringFromCodePoint)(2097151&f)+(0,_.stringFromCodePoint)(v),f&=-2097152,f|=2097152):f=v|4194304,g&&(f&=-12582913,f|=g<<22),this._data[3*c+0]=f}insertCells(c,v,g){if((c%=this.length)&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length-c){let f=new y.CellData;for(let m=this.length-c-v-1;m>=0;--m)this.setCell(c+v+m,this.loadCell(c+m,f));for(let m=0;m<v;++m)this.setCell(c+m,g)}else for(let f=c;f<this.length;++f)this.setCell(f,g);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,g)}deleteCells(c,v,g){if(c%=this.length,v<this.length-c){let f=new y.CellData;for(let m=0;m<this.length-c-v;++m)this.setCell(c+m,this.loadCell(c+v+m,f));for(let m=this.length-v;m<this.length;++m)this.setCell(m,g)}else for(let f=c;f<this.length;++f)this.setCell(f,g);c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),this.getWidth(c)!==0||this.hasContent(c)||this.setCellFromCodepoint(c,0,1,g)}replaceCells(c,v,g,f=!1){if(f)for(c&&this.getWidth(c-1)===2&&!this.isProtected(c-1)&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length&&this.getWidth(v-1)===2&&!this.isProtected(v)&&this.setCellFromCodepoint(v,0,1,g);c<v&&c<this.length;)this.isProtected(c)||this.setCell(c,g),c++;else for(c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,g),v<this.length&&this.getWidth(v-1)===2&&this.setCellFromCodepoint(v,0,1,g);c<v&&c<this.length;)this.setCell(c++,g)}resize(c,v){if(c===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let g=3*c;if(c>this.length){if(this._data.buffer.byteLength>=4*g)this._data=new Uint32Array(this._data.buffer,0,g);else{let f=new Uint32Array(g);f.set(this._data),this._data=f}for(let f=this.length;f<c;++f)this.setCell(f,v)}else{this._data=this._data.subarray(0,g);let f=Object.keys(this._combined);for(let w=0;w<f.length;w++){let C=parseInt(f[w],10);C>=c&&delete this._combined[C]}let m=Object.keys(this._extendedAttrs);for(let w=0;w<m.length;w++){let C=parseInt(m[w],10);C>=c&&delete this._extendedAttrs[C]}}return this.length=c,4*g*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let c=new Uint32Array(this._data.length);return c.set(this._data),this._data=c,1}return 0}fill(c,v=!1){if(v)for(let g=0;g<this.length;++g)this.isProtected(g)||this.setCell(g,c);else{this._combined={},this._extendedAttrs={};for(let g=0;g<this.length;++g)this.setCell(g,c)}}copyFrom(c){this.length!==c.length?this._data=new Uint32Array(c._data):this._data.set(c._data),this.length=c.length,this._combined={};for(let v in c._combined)this._combined[v]=c._combined[v];this._extendedAttrs={};for(let v in c._extendedAttrs)this._extendedAttrs[v]=c._extendedAttrs[v];this.isWrapped=c.isWrapped}clone(){let c=new p(0);c._data=new Uint32Array(this._data),c.length=this.length;for(let v in this._combined)c._combined[v]=this._combined[v];for(let v in this._extendedAttrs)c._extendedAttrs[v]=this._extendedAttrs[v];return c.isWrapped=this.isWrapped,c}getTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0])return c+(this._data[3*c+0]>>22);return 0}getNoBgTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0]||50331648&this._data[3*c+2])return c+(this._data[3*c+0]>>22);return 0}copyCellsFrom(c,v,g,f,m){let w=c._data;if(m)for(let k=f-1;k>=0;k--){for(let A=0;A<3;A++)this._data[3*(g+k)+A]=w[3*(v+k)+A];268435456&w[3*(v+k)+2]&&(this._extendedAttrs[g+k]=c._extendedAttrs[v+k])}else for(let k=0;k<f;k++){for(let A=0;A<3;A++)this._data[3*(g+k)+A]=w[3*(v+k)+A];268435456&w[3*(v+k)+2]&&(this._extendedAttrs[g+k]=c._extendedAttrs[v+k])}let C=Object.keys(c._combined);for(let k=0;k<C.length;k++){let A=parseInt(C[k],10);A>=v&&(this._combined[A-v+g]=c._combined[A])}}translateToString(c,v,g,f){v=v??0,g=g??this.length,c&&(g=Math.min(g,this.getTrimmedLength())),f&&(f.length=0);let m="";for(;v<g;){let w=this._data[3*v+0],C=2097151&w,k=2097152&w?this._combined[v]:C?(0,_.stringFromCodePoint)(C):h.WHITESPACE_CELL_CHAR;if(m+=k,f)for(let A=0;A<k.length;++A)f.push(v);v+=w>>22||1}return f&&f.push(v),m}}n.BufferLine=p},732:(a,n)=>{function l(u,y,h){if(y===u.length-1)return u[y].getTrimmedLength();let _=!u[y].hasContent(h-1)&&u[y].getWidth(h-1)===1,d=u[y+1].getWidth(0)===2;return _&&d?h-1:h}Object.defineProperty(n,"__esModule",{value:!0}),n.reflowLargerGetLinesToRemove=function(u,y,h,_,d,p){let b=[];for(let c=0;c<u.length-1;c++){let v=c,g=u.get(++v);if(!g.isWrapped)continue;let f=[u.get(c)];for(;v<u.length&&g.isWrapped;)f.push(g),g=u.get(++v);if(!p&&_>=c&&_<v){c+=f.length-1;continue}let m=0,w=l(f,m,y),C=1,k=0;for(;C<f.length;){let O=l(f,C,y),D=O-k,L=h-w,R=Math.min(D,L);f[m].copyCellsFrom(f[C],k,w,R,!1),w+=R,w===h&&(m++,w=0),k+=R,k===O&&(C++,k=0),w===0&&m!==0&&f[m-1].getWidth(h-1)===2&&(f[m].copyCellsFrom(f[m-1],h-1,w++,1,!1),f[m-1].setCell(h-1,d))}f[m].replaceCells(w,h,d);let A=0;for(let O=f.length-1;O>0&&(O>m||f[O].getTrimmedLength()===0);O--)A++;A>0&&(b.push(c+f.length-A),b.push(A)),c+=f.length-1}return b},n.reflowLargerCreateNewLayout=function(u,y){let h=[],_=0,d=y[_],p=0;for(let b=0;b<u.length;b++)if(d===b){let c=y[++_];u.onDeleteEmitter.fire({index:b-p,amount:c}),b+=c-1,p+=c,d=y[++_]}else h.push(b);return{layout:h,countRemoved:p}},n.reflowLargerApplyNewLayout=function(u,y){let h=[];for(let _=0;_<y.length;_++)h.push(u.get(y[_]));for(let _=0;_<h.length;_++)u.set(_,h[_]);u.length=y.length},n.reflowSmallerGetNewLineLengths=function(u,y,h){let _=[],d=u.map(((v,g)=>l(u,g,y))).reduce(((v,g)=>v+g)),p=0,b=0,c=0;for(;c<d;){if(d-c<h){_.push(d-c);break}p+=h;let v=l(u,b,y);p>v&&(p-=v,b++);let g=u[b].getWidth(p-1)===2;g&&p--;let f=g?h-1:h;_.push(f),c+=f}return _},n.getWrappedLineTrimmedLength=l},4097:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferSet=void 0;let u=l(7150),y=l(1073),h=l(802);class _ extends u.Disposable{constructor(p,b){super(),this._optionsService=p,this._bufferService=b,this._onBufferActivate=this._register(new h.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new y.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new y.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(p){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(p),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(p,b){this._normal.resize(p,b),this._alt.resize(p,b),this.setupTabStops(p)}setupTabStops(p){this._normal.setupTabStops(p),this._alt.setupTabStops(p)}}n.BufferSet=_},3055:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CellData=void 0;let u=l(726),y=l(8938),h=l(5451);class _ extends h.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new h.ExtendedAttrs,this.combinedData=""}static fromCharData(p){let b=new _;return b.setFromCharData(p),b}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,u.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(p){this.fg=p[y.CHAR_DATA_ATTR_INDEX],this.bg=0;let b=!1;if(p[y.CHAR_DATA_CHAR_INDEX].length>2)b=!0;else if(p[y.CHAR_DATA_CHAR_INDEX].length===2){let c=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=c&&c<=56319){let v=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=v&&v<=57343?this.content=1024*(c-55296)+v-56320+65536|p[y.CHAR_DATA_WIDTH_INDEX]<<22:b=!0}else b=!0}else this.content=p[y.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|p[y.CHAR_DATA_WIDTH_INDEX]<<22;b&&(this.combinedData=p[y.CHAR_DATA_CHAR_INDEX],this.content=2097152|p[y.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.CellData=_},8938:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WHITESPACE_CELL_CODE=n.WHITESPACE_CELL_WIDTH=n.WHITESPACE_CELL_CHAR=n.NULL_CELL_CODE=n.NULL_CELL_WIDTH=n.NULL_CELL_CHAR=n.CHAR_DATA_CODE_INDEX=n.CHAR_DATA_WIDTH_INDEX=n.CHAR_DATA_CHAR_INDEX=n.CHAR_DATA_ATTR_INDEX=n.DEFAULT_EXT=n.DEFAULT_ATTR=n.DEFAULT_COLOR=void 0,n.DEFAULT_COLOR=0,n.DEFAULT_ATTR=n.DEFAULT_COLOR<<9|256,n.DEFAULT_EXT=0,n.CHAR_DATA_ATTR_INDEX=0,n.CHAR_DATA_CHAR_INDEX=1,n.CHAR_DATA_WIDTH_INDEX=2,n.CHAR_DATA_CODE_INDEX=3,n.NULL_CELL_CHAR="",n.NULL_CELL_WIDTH=1,n.NULL_CELL_CODE=0,n.WHITESPACE_CELL_CHAR=" ",n.WHITESPACE_CELL_WIDTH=1,n.WHITESPACE_CELL_CODE=32},8158:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Marker=void 0;let u=l(802),y=l(7150);class h{get id(){return this._id}constructor(d){this.line=d,this.isDisposed=!1,this._disposables=[],this._id=h._nextId++,this._onDispose=this.register(new u.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,y.dispose)(this._disposables),this._disposables.length=0)}register(d){return this._disposables.push(d),d}}n.Marker=h,h._nextId=1},6760:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DEFAULT_CHARSET=n.CHARSETS=void 0,n.CHARSETS={},n.DEFAULT_CHARSET=n.CHARSETS.B,n.CHARSETS[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"},n.CHARSETS.A={"#":"\xA3"},n.CHARSETS.B=void 0,n.CHARSETS[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"},n.CHARSETS.C=n.CHARSETS[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},n.CHARSETS.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"},n.CHARSETS.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"},n.CHARSETS.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"},n.CHARSETS.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"},n.CHARSETS.E=n.CHARSETS[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"},n.CHARSETS.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"},n.CHARSETS.H=n.CHARSETS[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},n.CHARSETS["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"}},3534:(a,n)=>{var l,u,y;Object.defineProperty(n,"__esModule",{value:!0}),n.C1_ESCAPED=n.C1=n.C0=void 0,(function(h){h.NUL="\0",h.SOH="",h.STX="",h.ETX="",h.EOT="",h.ENQ="",h.ACK="",h.BEL="\x07",h.BS="\b",h.HT=" ",h.LF=`
65
+ `,h.VT="\v",h.FF="\f",h.CR="\r",h.SO="",h.SI="",h.DLE="",h.DC1="",h.DC2="",h.DC3="",h.DC4="",h.NAK="",h.SYN="",h.ETB="",h.CAN="",h.EM="",h.SUB="",h.ESC="\x1B",h.FS="",h.GS="",h.RS="",h.US="",h.SP=" ",h.DEL="\x7F"})(l||(n.C0=l={})),(function(h){h.PAD="\x80",h.HOP="\x81",h.BPH="\x82",h.NBH="\x83",h.IND="\x84",h.NEL="\x85",h.SSA="\x86",h.ESA="\x87",h.HTS="\x88",h.HTJ="\x89",h.VTS="\x8A",h.PLD="\x8B",h.PLU="\x8C",h.RI="\x8D",h.SS2="\x8E",h.SS3="\x8F",h.DCS="\x90",h.PU1="\x91",h.PU2="\x92",h.STS="\x93",h.CCH="\x94",h.MW="\x95",h.SPA="\x96",h.EPA="\x97",h.SOS="\x98",h.SGCI="\x99",h.SCI="\x9A",h.CSI="\x9B",h.ST="\x9C",h.OSC="\x9D",h.PM="\x9E",h.APC="\x9F"})(u||(n.C1=u={})),(function(h){h.ST=`${l.ESC}\\`})(y||(n.C1_ESCAPED=y={}))},726:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=void 0,n.stringFromCodePoint=function(l){return l>65535?(l-=65536,String.fromCharCode(55296+(l>>10))+String.fromCharCode(l%1024+56320)):String.fromCharCode(l)},n.utf32ToString=function(l,u=0,y=l.length){let h="";for(let _=u;_<y;++_){let d=l[_];d>65535?(d-=65536,h+=String.fromCharCode(55296+(d>>10))+String.fromCharCode(d%1024+56320)):h+=String.fromCharCode(d)}return h},n.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(l,u){let y=l.length;if(!y)return 0;let h=0,_=0;if(this._interim){let d=l.charCodeAt(_++);56320<=d&&d<=57343?u[h++]=1024*(this._interim-55296)+d-56320+65536:(u[h++]=this._interim,u[h++]=d),this._interim=0}for(let d=_;d<y;++d){let p=l.charCodeAt(d);if(55296<=p&&p<=56319){if(++d>=y)return this._interim=p,h;let b=l.charCodeAt(d);56320<=b&&b<=57343?u[h++]=1024*(p-55296)+b-56320+65536:(u[h++]=p,u[h++]=b)}else p!==65279&&(u[h++]=p)}return h}},n.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(l,u){let y=l.length;if(!y)return 0;let h,_,d,p,b=0,c=0,v=0;if(this.interim[0]){let m=!1,w=this.interim[0];w&=(224&w)==192?31:(240&w)==224?15:7;let C,k=0;for(;(C=63&this.interim[++k])&&k<4;)w<<=6,w|=C;let A=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,O=A-k;for(;v<O;){if(v>=y)return 0;if(C=l[v++],(192&C)!=128){v--,m=!0;break}this.interim[k++]=C,w<<=6,w|=63&C}m||(A===2?w<128?v--:u[b++]=w:A===3?w<2048||w>=55296&&w<=57343||w===65279||(u[b++]=w):w<65536||w>1114111||(u[b++]=w)),this.interim.fill(0)}let g=y-4,f=v;for(;f<y;){for(;!(!(f<g)||128&(h=l[f])||128&(_=l[f+1])||128&(d=l[f+2])||128&(p=l[f+3]));)u[b++]=h,u[b++]=_,u[b++]=d,u[b++]=p,f+=4;if(h=l[f++],h<128)u[b++]=h;else if((224&h)==192){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(c=(31&h)<<6|63&_,c<128){f--;continue}u[b++]=c}else if((240&h)==224){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,b;if(d=l[f++],(192&d)!=128){f--;continue}if(c=(15&h)<<12|(63&_)<<6|63&d,c<2048||c>=55296&&c<=57343||c===65279)continue;u[b++]=c}else if((248&h)==240){if(f>=y)return this.interim[0]=h,b;if(_=l[f++],(192&_)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,b;if(d=l[f++],(192&d)!=128){f--;continue}if(f>=y)return this.interim[0]=h,this.interim[1]=_,this.interim[2]=d,b;if(p=l[f++],(192&p)!=128){f--;continue}if(c=(7&h)<<18|(63&_)<<12|(63&d)<<6|63&p,c<65536||c>1114111)continue;u[b++]=c}}return b}}},7428:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeV6=void 0;let u=l(6415),y=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],h=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],_;n.UnicodeV6=class{constructor(){if(this.version="6",!_){_=new Uint8Array(65536),_.fill(1),_[0]=0,_.fill(0,1,32),_.fill(0,127,160),_.fill(2,4352,4448),_[9001]=2,_[9002]=2,_.fill(2,11904,42192),_[12351]=1,_.fill(2,44032,55204),_.fill(2,63744,64256),_.fill(2,65040,65050),_.fill(2,65072,65136),_.fill(2,65280,65377),_.fill(2,65504,65511);for(let d=0;d<y.length;++d)_.fill(0,y[d][0],y[d][1]+1)}}wcwidth(d){return d<32?0:d<127?1:d<65536?_[d]:(function(p,b){let c,v=0,g=b.length-1;if(p<b[0][0]||p>b[g][1])return!1;for(;g>=v;)if(c=v+g>>1,p>b[c][1])v=c+1;else{if(!(p<b[c][0]))return!0;g=c-1}return!1})(d,h)?0:d>=131072&&d<=196605||d>=196608&&d<=262141?2:1}charProperties(d,p){let b=this.wcwidth(d),c=b===0&&p!==0;if(c){let v=u.UnicodeService.extractWidth(p);v===0?c=!1:v>b&&(b=v)}return u.UnicodeService.createPropertyValue(0,b,c)}}},3562:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WriteBuffer=void 0;let u=l(7150),y=l(802);class h extends u.Disposable{constructor(d){super(),this._action=d,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new y.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(d,p){if(p!==void 0&&this._syncCalls>p)return void(this._syncCalls=0);if(this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let b;for(this._isSyncWriting=!0;b=this._writeBuffer.shift();){this._action(b);let c=this._callbacks.shift();c&&c()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(d,p){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(p),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=d.length,this._writeBuffer.push(d),this._callbacks.push(p)}_innerWrite(d=0,p=!0){let b=d||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let c=this._writeBuffer[this._bufferOffset],v=this._action(c,p);if(v){let f=m=>performance.now()-b>=12?setTimeout((()=>this._innerWrite(0,m))):this._innerWrite(b,m);return void v.catch((m=>(queueMicrotask((()=>{throw m})),Promise.resolve(!1)))).then(f)}let g=this._callbacks[this._bufferOffset];if(g&&g(),this._bufferOffset++,this._pendingData-=c.length,performance.now()-b>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}n.WriteBuffer=h},8693:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseColor=function(h){if(!h)return;let _=h.toLowerCase();if(_.indexOf("rgb:")===0){_=_.slice(4);let d=l.exec(_);if(d){let p=d[1]?15:d[4]?255:d[7]?4095:65535;return[Math.round(parseInt(d[1]||d[4]||d[7]||d[10],16)/p*255),Math.round(parseInt(d[2]||d[5]||d[8]||d[11],16)/p*255),Math.round(parseInt(d[3]||d[6]||d[9]||d[12],16)/p*255)]}}else if(_.indexOf("#")===0&&(_=_.slice(1),u.exec(_)&&[3,6,9,12].includes(_.length))){let d=_.length/3,p=[0,0,0];for(let b=0;b<3;++b){let c=parseInt(_.slice(d*b,d*b+d),16);p[b]=d===1?c<<4:d===2?c:d===3?c>>4:c>>8}return p}},n.toRgbString=function(h,_=16){let[d,p,b]=h;return`rgb:${y(d,_)}/${y(p,_)}/${y(b,_)}`};let l=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,u=/^[\da-f]+$/;function y(h,_){let d=h.toString(16),p=d.length<2?"0"+d:d;switch(_){case 4:return d[0];case 8:return p;case 12:return(p+p).slice(0,3);default:return p+p}}},1263:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PAYLOAD_LIMIT=void 0,n.PAYLOAD_LIMIT=1e7},9823:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DcsHandler=n.DcsParser=void 0;let u=l(726),y=l(7262),h=l(1263),_=[];n.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=_,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_}registerHandler(p,b){this._handlers[p]===void 0&&(this._handlers[p]=[]);let c=this._handlers[p];return c.push(b),{dispose:()=>{let v=c.indexOf(b);v!==-1&&c.splice(v,1)}}}clearHandler(p){this._handlers[p]&&delete this._handlers[p]}setHandlerFallback(p){this._handlerFb=p}reset(){if(this._active.length)for(let p=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;p>=0;--p)this._active[p].unhook(!1);this._stack.paused=!1,this._active=_,this._ident=0}hook(p,b){if(this.reset(),this._ident=p,this._active=this._handlers[p]||_,this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].hook(b);else this._handlerFb(this._ident,"HOOK",b)}put(p,b,c){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(p,b,c);else this._handlerFb(this._ident,"PUT",(0,u.utf32ToString)(p,b,c))}unhook(p,b=!0){if(this._active.length){let c=!1,v=this._active.length-1,g=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,c=b,g=this._stack.fallThrough,this._stack.paused=!1),!g&&c===!1){for(;v>=0&&(c=this._active[v].unhook(p),c!==!0);v--)if(c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,c;v--}for(;v>=0;v--)if(c=this._active[v].unhook(!1),c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,c}else this._handlerFb(this._ident,"UNHOOK",p);this._active=_,this._ident=0}};let d=new y.Params;d.addParam(0),n.DcsHandler=class{constructor(p){this._handler=p,this._data="",this._params=d,this._hitLimit=!1}hook(p){this._params=p.length>1||p.params[0]?p.clone():d,this._data="",this._hitLimit=!1}put(p,b,c){this._hitLimit||(this._data+=(0,u.utf32ToString)(p,b,c),this._data.length>h.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(p){let b=!1;if(this._hitLimit)b=!1;else if(p&&(b=this._handler(this._data,this._params),b instanceof Promise))return b.then((c=>(this._params=d,this._data="",this._hitLimit=!1,c)));return this._params=d,this._data="",this._hitLimit=!1,b}}},6717:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.EscapeSequenceParser=n.VT500_TRANSITION_TABLE=n.TransitionTable=void 0;let u=l(7150),y=l(7262),h=l(1346),_=l(9823);class d{constructor(v){this.table=new Uint8Array(v)}setDefault(v,g){this.table.fill(v<<4|g)}add(v,g,f,m){this.table[g<<8|v]=f<<4|m}addMany(v,g,f,m){for(let w=0;w<v.length;w++)this.table[g<<8|v[w]]=f<<4|m}}n.TransitionTable=d;let p=160;n.VT500_TRANSITION_TABLE=(function(){let c=new d(4095),v=Array.apply(null,Array(256)).map(((k,A)=>A)),g=(k,A)=>v.slice(k,A),f=g(32,127),m=g(0,24);m.push(25),m.push.apply(m,g(28,32));let w=g(0,14),C;for(C in c.setDefault(1,0),c.addMany(f,0,2,0),w)c.addMany([24,26,153,154],C,3,0),c.addMany(g(128,144),C,3,0),c.addMany(g(144,152),C,3,0),c.add(156,C,0,0),c.add(27,C,11,1),c.add(157,C,4,8),c.addMany([152,158,159],C,0,7),c.add(155,C,11,3),c.add(144,C,11,9);return c.addMany(m,0,3,0),c.addMany(m,1,3,1),c.add(127,1,0,1),c.addMany(m,8,0,8),c.addMany(m,3,3,3),c.add(127,3,0,3),c.addMany(m,4,3,4),c.add(127,4,0,4),c.addMany(m,6,3,6),c.addMany(m,5,3,5),c.add(127,5,0,5),c.addMany(m,2,3,2),c.add(127,2,0,2),c.add(93,1,4,8),c.addMany(f,8,5,8),c.add(127,8,5,8),c.addMany([156,27,24,26,7],8,6,0),c.addMany(g(28,32),8,0,8),c.addMany([88,94,95],1,0,7),c.addMany(f,7,0,7),c.addMany(m,7,0,7),c.add(156,7,0,0),c.add(127,7,0,7),c.add(91,1,11,3),c.addMany(g(64,127),3,7,0),c.addMany(g(48,60),3,8,4),c.addMany([60,61,62,63],3,9,4),c.addMany(g(48,60),4,8,4),c.addMany(g(64,127),4,7,0),c.addMany([60,61,62,63],4,0,6),c.addMany(g(32,64),6,0,6),c.add(127,6,0,6),c.addMany(g(64,127),6,0,0),c.addMany(g(32,48),3,9,5),c.addMany(g(32,48),5,9,5),c.addMany(g(48,64),5,0,6),c.addMany(g(64,127),5,7,0),c.addMany(g(32,48),4,9,5),c.addMany(g(32,48),1,9,2),c.addMany(g(32,48),2,9,2),c.addMany(g(48,127),2,10,0),c.addMany(g(48,80),1,10,0),c.addMany(g(81,88),1,10,0),c.addMany([89,90,92],1,10,0),c.addMany(g(96,127),1,10,0),c.add(80,1,11,9),c.addMany(m,9,0,9),c.add(127,9,0,9),c.addMany(g(28,32),9,0,9),c.addMany(g(32,48),9,9,12),c.addMany(g(48,60),9,8,10),c.addMany([60,61,62,63],9,9,10),c.addMany(m,11,0,11),c.addMany(g(32,128),11,0,11),c.addMany(g(28,32),11,0,11),c.addMany(m,10,0,10),c.add(127,10,0,10),c.addMany(g(28,32),10,0,10),c.addMany(g(48,60),10,8,10),c.addMany([60,61,62,63],10,0,11),c.addMany(g(32,48),10,9,12),c.addMany(m,12,0,12),c.add(127,12,0,12),c.addMany(g(28,32),12,0,12),c.addMany(g(32,48),12,9,12),c.addMany(g(48,64),12,0,11),c.addMany(g(64,127),12,12,13),c.addMany(g(64,127),10,12,13),c.addMany(g(64,127),9,12,13),c.addMany(m,13,13,13),c.addMany(f,13,13,13),c.add(127,13,0,13),c.addMany([27,156,24,26],13,14,0),c.add(p,0,2,0),c.add(p,8,5,8),c.add(p,6,0,6),c.add(p,11,0,11),c.add(p,13,13,13),c})();class b extends u.Disposable{constructor(v=n.VT500_TRANSITION_TABLE){super(),this._transitions=v,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new y.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(g,f,m)=>{},this._executeHandlerFb=g=>{},this._csiHandlerFb=(g,f)=>{},this._escHandlerFb=g=>{},this._errorHandlerFb=g=>g,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,u.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this._register(new h.OscParser),this._dcsParser=this._register(new _.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(v,g=[64,126]){let f=0;if(v.prefix){if(v.prefix.length>1)throw new Error("only one byte as prefix supported");if(f=v.prefix.charCodeAt(0),f&&60>f||f>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(v.intermediates){if(v.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let w=0;w<v.intermediates.length;++w){let C=v.intermediates.charCodeAt(w);if(32>C||C>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");f<<=8,f|=C}}if(v.final.length!==1)throw new Error("final must be a single byte");let m=v.final.charCodeAt(0);if(g[0]>m||m>g[1])throw new Error(`final must be in range ${g[0]} .. ${g[1]}`);return f<<=8,f|=m,f}identToString(v){let g=[];for(;v;)g.push(String.fromCharCode(255&v)),v>>=8;return g.reverse().join("")}setPrintHandler(v){this._printHandler=v}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(v,g){let f=this._identifier(v,[48,126]);this._escHandlers[f]===void 0&&(this._escHandlers[f]=[]);let m=this._escHandlers[f];return m.push(g),{dispose:()=>{let w=m.indexOf(g);w!==-1&&m.splice(w,1)}}}clearEscHandler(v){this._escHandlers[this._identifier(v,[48,126])]&&delete this._escHandlers[this._identifier(v,[48,126])]}setEscHandlerFallback(v){this._escHandlerFb=v}setExecuteHandler(v,g){this._executeHandlers[v.charCodeAt(0)]=g}clearExecuteHandler(v){this._executeHandlers[v.charCodeAt(0)]&&delete this._executeHandlers[v.charCodeAt(0)]}setExecuteHandlerFallback(v){this._executeHandlerFb=v}registerCsiHandler(v,g){let f=this._identifier(v);this._csiHandlers[f]===void 0&&(this._csiHandlers[f]=[]);let m=this._csiHandlers[f];return m.push(g),{dispose:()=>{let w=m.indexOf(g);w!==-1&&m.splice(w,1)}}}clearCsiHandler(v){this._csiHandlers[this._identifier(v)]&&delete this._csiHandlers[this._identifier(v)]}setCsiHandlerFallback(v){this._csiHandlerFb=v}registerDcsHandler(v,g){return this._dcsParser.registerHandler(this._identifier(v),g)}clearDcsHandler(v){this._dcsParser.clearHandler(this._identifier(v))}setDcsHandlerFallback(v){this._dcsParser.setHandlerFallback(v)}registerOscHandler(v,g){return this._oscParser.registerHandler(v,g)}clearOscHandler(v){this._oscParser.clearHandler(v)}setOscHandlerFallback(v){this._oscParser.setHandlerFallback(v)}setErrorHandler(v){this._errorHandler=v}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(v,g,f,m,w){this._parseStack.state=v,this._parseStack.handlers=g,this._parseStack.handlerPos=f,this._parseStack.transition=m,this._parseStack.chunkPos=w}parse(v,g,f){let m,w=0,C=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(f===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let A=this._parseStack.handlers,O=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(f===!1&&O>-1){for(;O>=0&&(m=A[O](this._params),m!==!0);O--)if(m instanceof Promise)return this._parseStack.handlerPos=O,m}this._parseStack.handlers=[];break;case 4:if(f===!1&&O>-1){for(;O>=0&&(m=A[O](),m!==!0);O--)if(m instanceof Promise)return this._parseStack.handlerPos=O,m}this._parseStack.handlers=[];break;case 6:if(w=v[this._parseStack.chunkPos],m=this._dcsParser.unhook(w!==24&&w!==26,f),m)return m;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(w=v[this._parseStack.chunkPos],m=this._oscParser.end(w!==24&&w!==26,f),m)return m;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let A=k;A<g;++A){switch(w=v[A],C=this._transitions.table[this.currentState<<8|(w<160?w:p)],C>>4){case 2:for(let P=A+1;;++P){if(P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}if(++P>=g||(w=v[P])<32||w>126&&w<p){this._printHandler(v,A,P),A=P-1;break}}break;case 3:this._executeHandlers[w]?this._executeHandlers[w]():this._executeHandlerFb(w),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:A,code:w,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let O=this._csiHandlers[this._collect<<8|w],D=O?O.length-1:-1;for(;D>=0&&(m=O[D](this._params),m!==!0);D--)if(m instanceof Promise)return this._preserveStack(3,O,D,C,A),m;D<0&&this._csiHandlerFb(this._collect<<8|w,this._params),this.precedingJoinState=0;break;case 8:do switch(w){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(w-48)}while(++A<g&&(w=v[A])>47&&w<60);A--;break;case 9:this._collect<<=8,this._collect|=w;break;case 10:let L=this._escHandlers[this._collect<<8|w],R=L?L.length-1:-1;for(;R>=0&&(m=L[R](),m!==!0);R--)if(m instanceof Promise)return this._preserveStack(4,L,R,C,A),m;R<0&&this._escHandlerFb(this._collect<<8|w),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|w,this._params);break;case 13:for(let P=A+1;;++P)if(P>=g||(w=v[P])===24||w===26||w===27||w>127&&w<p){this._dcsParser.put(v,A,P),A=P-1;break}break;case 14:if(m=this._dcsParser.unhook(w!==24&&w!==26),m)return this._preserveStack(6,[],0,C,A),m;w===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let P=A+1;;P++)if(P>=g||(w=v[P])<32||w>127&&w<p){this._oscParser.put(v,A,P),A=P-1;break}break;case 6:if(m=this._oscParser.end(w!==24&&w!==26),m)return this._preserveStack(5,[],0,C,A),m;w===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&C}}}n.EscapeSequenceParser=b},1346:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OscHandler=n.OscParser=void 0;let u=l(1263),y=l(726),h=[];n.OscParser=class{constructor(){this._state=0,this._active=h,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(_,d){this._handlers[_]===void 0&&(this._handlers[_]=[]);let p=this._handlers[_];return p.push(d),{dispose:()=>{let b=p.indexOf(d);b!==-1&&p.splice(b,1)}}}clearHandler(_){this._handlers[_]&&delete this._handlers[_]}setHandlerFallback(_){this._handlerFb=_}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}reset(){if(this._state===2)for(let _=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;_>=0;--_)this._active[_].end(!1);this._stack.paused=!1,this._active=h,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||h,this._active.length)for(let _=this._active.length-1;_>=0;_--)this._active[_].start();else this._handlerFb(this._id,"START")}_put(_,d,p){if(this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].put(_,d,p);else this._handlerFb(this._id,"PUT",(0,y.utf32ToString)(_,d,p))}start(){this.reset(),this._state=1}put(_,d,p){if(this._state!==3){if(this._state===1)for(;d<p;){let b=_[d++];if(b===59){this._state=2,this._start();break}if(b<48||57<b)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+b-48}this._state===2&&p-d>0&&this._put(_,d,p)}}end(_,d=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let p=!1,b=this._active.length-1,c=!1;if(this._stack.paused&&(b=this._stack.loopPosition-1,p=d,c=this._stack.fallThrough,this._stack.paused=!1),!c&&p===!1){for(;b>=0&&(p=this._active[b].end(_),p!==!0);b--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!1,p;b--}for(;b>=0;b--)if(p=this._active[b].end(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!0,p}else this._handlerFb(this._id,"END",_);this._active=h,this._id=-1,this._state=0}}},n.OscHandler=class{constructor(_){this._handler=_,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(_,d,p){this._hitLimit||(this._data+=(0,y.utf32ToString)(_,d,p),this._data.length>u.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(_){let d=!1;if(this._hitLimit)d=!1;else if(_&&(d=this._handler(this._data),d instanceof Promise))return d.then((p=>(this._data="",this._hitLimit=!1,p)));return this._data="",this._hitLimit=!1,d}}},7262:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Params=void 0;let l=2147483647;class u{static fromArray(h){let _=new u;if(!h.length)return _;for(let d=Array.isArray(h[0])?1:0;d<h.length;++d){let p=h[d];if(Array.isArray(p))for(let b=0;b<p.length;++b)_.addSubParam(p[b]);else _.addParam(p)}return _}constructor(h=32,_=32){if(this.maxLength=h,this.maxSubParamsLength=_,_>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(h),this.length=0,this._subParams=new Int32Array(_),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(h),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let h=new u(this.maxLength,this.maxSubParamsLength);return h.params.set(this.params),h.length=this.length,h._subParams.set(this._subParams),h._subParamsLength=this._subParamsLength,h._subParamsIdx.set(this._subParamsIdx),h._rejectDigits=this._rejectDigits,h._rejectSubDigits=this._rejectSubDigits,h._digitIsSub=this._digitIsSub,h}toArray(){let h=[];for(let _=0;_<this.length;++_){h.push(this.params[_]);let d=this._subParamsIdx[_]>>8,p=255&this._subParamsIdx[_];p-d>0&&h.push(Array.prototype.slice.call(this._subParams,d,p))}return h}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(h){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=h>l?l:h}}addSubParam(h){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=h>l?l:h,this._subParamsIdx[this.length-1]++}}hasSubParams(h){return(255&this._subParamsIdx[h])-(this._subParamsIdx[h]>>8)>0}getSubParams(h){let _=this._subParamsIdx[h]>>8,d=255&this._subParamsIdx[h];return d-_>0?this._subParams.subarray(_,d):null}getSubParamsAll(){let h={};for(let _=0;_<this.length;++_){let d=this._subParamsIdx[_]>>8,p=255&this._subParamsIdx[_];p-d>0&&(h[_]=this._subParams.slice(d,p))}return h}addDigit(h){let _;if(this._rejectDigits||!(_=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let d=this._digitIsSub?this._subParams:this.params,p=d[_-1];d[_-1]=~p?Math.min(10*p+h,l):h}}n.Params=u},3027:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.AddonManager=void 0,n.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let l=this._addons.length-1;l>=0;l--)this._addons[l].instance.dispose()}loadAddon(l,u){let y={instance:u,dispose:u.dispose,isDisposed:!1};this._addons.push(y),u.dispose=()=>this._wrappedAddonDispose(y),u.activate(l)}_wrappedAddonDispose(l){if(l.isDisposed)return;let u=-1;for(let y=0;y<this._addons.length;y++)if(this._addons[y]===l){u=y;break}if(u===-1)throw new Error("Could not dispose an addon that has not been loaded");l.isDisposed=!0,l.dispose.apply(l.instance),this._addons.splice(u,1)}}},3235:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferApiView=void 0;let u=l(793),y=l(3055);n.BufferApiView=class{constructor(h,_){this._buffer=h,this.type=_}init(h){return this._buffer=h,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(h){let _=this._buffer.lines.get(h);if(_)return new u.BufferLineApiView(_)}getNullCell(){return new y.CellData}}},793:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLineApiView=void 0;let u=l(3055);n.BufferLineApiView=class{constructor(y){this._line=y}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(y,h){if(!(y<0||y>=this._line.length))return h?(this._line.loadCell(y,h),h):this._line.loadCell(y,new u.CellData)}translateToString(y,h,_){return this._line.translateToString(y,h,_)}}},5101:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferNamespaceApi=void 0;let u=l(3235),y=l(7150),h=l(802);class _ extends y.Disposable{constructor(p){super(),this._core=p,this._onBufferChange=this._register(new h.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new u.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new u.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}n.BufferNamespaceApi=_},6097:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ParserApi=void 0,n.ParserApi=class{constructor(l){this._core=l}registerCsiHandler(l,u){return this._core.registerCsiHandler(l,(y=>u(y.toArray())))}addCsiHandler(l,u){return this.registerCsiHandler(l,u)}registerDcsHandler(l,u){return this._core.registerDcsHandler(l,((y,h)=>u(y,h.toArray())))}addDcsHandler(l,u){return this.registerDcsHandler(l,u)}registerEscHandler(l,u){return this._core.registerEscHandler(l,u)}addEscHandler(l,u){return this.registerEscHandler(l,u)}registerOscHandler(l,u){return this._core.registerOscHandler(l,u)}addOscHandler(l,u){return this.registerOscHandler(l,u)}}},4335:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeApi=void 0,n.UnicodeApi=class{constructor(l){this._core=l}register(l){this._core.unicodeService.register(l)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(l){this._core.unicodeService.activeVersion=l}}},9640:function(a,n,l){var u=this&&this.__decorate||function(c,v,g,f){var m,w=arguments.length,C=w<3?v:f===null?f=Object.getOwnPropertyDescriptor(v,g):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,v,g,f);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(C=(w<3?m(C):w>3?m(v,g,C):m(v,g))||C);return w>3&&C&&Object.defineProperty(v,g,C),C},y=this&&this.__param||function(c,v){return function(g,f){v(g,f,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferService=n.MINIMUM_ROWS=n.MINIMUM_COLS=void 0;let h=l(7150),_=l(4097),d=l(6501),p=l(802);n.MINIMUM_COLS=2,n.MINIMUM_ROWS=1;let b=class extends h.Disposable{get buffer(){return this.buffers.active}constructor(c){super(),this.isUserScrolling=!1,this._onResize=this._register(new p.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new p.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(c.rawOptions.cols||0,n.MINIMUM_COLS),this.rows=Math.max(c.rawOptions.rows||0,n.MINIMUM_ROWS),this.buffers=this._register(new _.BufferSet(c,this)),this._register(this.buffers.onBufferActivate((v=>{this._onScroll.fire(v.activeBuffer.ydisp)})))}resize(c,v){let g=this.cols!==c,f=this.rows!==v;this.cols=c,this.rows=v,this.buffers.resize(c,v),this._onResize.fire({cols:c,rows:v,colsChanged:g,rowsChanged:f})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(c,v=!1){let g=this.buffer,f;f=this._cachedBlankLine,f&&f.length===this.cols&&f.getFg(0)===c.fg&&f.getBg(0)===c.bg||(f=g.getBlankLine(c,v),this._cachedBlankLine=f),f.isWrapped=v;let m=g.ybase+g.scrollTop,w=g.ybase+g.scrollBottom;if(g.scrollTop===0){let C=g.lines.isFull;w===g.lines.length-1?C?g.lines.recycle().copyFrom(f):g.lines.push(f.clone()):g.lines.splice(w+1,0,f.clone()),C?this.isUserScrolling&&(g.ydisp=Math.max(g.ydisp-1,0)):(g.ybase++,this.isUserScrolling||g.ydisp++)}else{let C=w-m+1;g.lines.shiftElements(m+1,C-1,-1),g.lines.set(w,f.clone())}this.isUserScrolling||(g.ydisp=g.ybase),this._onScroll.fire(g.ydisp)}scrollLines(c,v){let g=this.buffer;if(c<0){if(g.ydisp===0)return;this.isUserScrolling=!0}else c+g.ydisp>=g.ybase&&(this.isUserScrolling=!1);let f=g.ydisp;g.ydisp=Math.max(Math.min(g.ydisp+c,g.ybase),0),f!==g.ydisp&&(v||this._onScroll.fire(g.ydisp))}};n.BufferService=b,n.BufferService=b=u([y(0,d.IOptionsService)],b)},5746:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CharsetService=void 0,n.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(l){this.glevel=l,this.charset=this._charsets[l]}setgCharset(l,u){this._charsets[l]=u,this.glevel===l&&(this.charset=u)}}},7792:function(a,n,l){var u=this&&this.__decorate||function(f,m,w,C){var k,A=arguments.length,O=A<3?m:C===null?C=Object.getOwnPropertyDescriptor(m,w):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(f,m,w,C);else for(var D=f.length-1;D>=0;D--)(k=f[D])&&(O=(A<3?k(O):A>3?k(m,w,O):k(m,w))||O);return A>3&&O&&Object.defineProperty(m,w,O),O},y=this&&this.__param||function(f,m){return function(w,C){m(w,C,f)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreMouseService=void 0;let h=l(6501),_=l(7150),d=l(802),p={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:f=>f.button!==4&&f.action===1&&(f.ctrl=!1,f.alt=!1,f.shift=!1,!0)},VT200:{events:19,restrict:f=>f.action!==32},DRAG:{events:23,restrict:f=>f.action!==32||f.button!==3},ANY:{events:31,restrict:f=>!0}};function b(f,m){let w=(f.ctrl?16:0)|(f.shift?4:0)|(f.alt?8:0);return f.button===4?(w|=64,w|=f.action):(w|=3&f.button,4&f.button&&(w|=64),8&f.button&&(w|=128),f.action===32?w|=32:f.action!==0||m||(w|=3)),w}let c=String.fromCharCode,v={DEFAULT:f=>{let m=[b(f,!1)+32,f.col+32,f.row+32];return m[0]>255||m[1]>255||m[2]>255?"":`\x1B[M${c(m[0])}${c(m[1])}${c(m[2])}`},SGR:f=>{let m=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${b(f,!0)};${f.col};${f.row}${m}`},SGR_PIXELS:f=>{let m=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${b(f,!0)};${f.x};${f.y}${m}`}},g=class extends _.Disposable{constructor(f,m,w){super(),this._bufferService=f,this._coreService=m,this._optionsService=w,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new d.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(let C of Object.keys(p))this.addProtocol(C,p[C]);for(let C of Object.keys(v))this.addEncoding(C,v[C]);this.reset()}addProtocol(f,m){this._protocols[f]=m}addEncoding(f,m){this._encodings[f]=m}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(f){if(!this._protocols[f])throw new Error(`unknown protocol "${f}"`);this._activeProtocol=f,this._onProtocolChange.fire(this._protocols[f].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(f){if(!this._encodings[f])throw new Error(`unknown encoding "${f}"`);this._activeEncoding=f}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(f,m,w){if(f.deltaY===0||f.shiftKey||m===void 0||w===void 0)return 0;let C=m/w,k=this._applyScrollModifier(f.deltaY,f);return f.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(k/=C+0,Math.abs(f.deltaY)<50&&(k*=.3),this._wheelPartialScroll+=k,k=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):f.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(k*=this._bufferService.rows),k}_applyScrollModifier(f,m){return m.altKey||m.ctrlKey||m.shiftKey?f*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:f*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(f){if(f.col<0||f.col>=this._bufferService.cols||f.row<0||f.row>=this._bufferService.rows||f.button===4&&f.action===32||f.button===3&&f.action!==32||f.button!==4&&(f.action===2||f.action===3)||(f.col++,f.row++,f.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,f,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(f))return!1;let m=this._encodings[this._activeEncoding](f);return m&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(m):this._coreService.triggerDataEvent(m,!0)),this._lastEvent=f,!0}explainEvents(f){return{down:!!(1&f),up:!!(2&f),drag:!!(4&f),move:!!(8&f),wheel:!!(16&f)}}_equalEvents(f,m,w){if(w){if(f.x!==m.x||f.y!==m.y)return!1}else if(f.col!==m.col||f.row!==m.row)return!1;return f.button===m.button&&f.action===m.action&&f.ctrl===m.ctrl&&f.alt===m.alt&&f.shift===m.shift}};n.CoreMouseService=g,n.CoreMouseService=g=u([y(0,h.IBufferService),y(1,h.ICoreService),y(2,h.IOptionsService)],g)},4071:function(a,n,l){var u=this&&this.__decorate||function(g,f,m,w){var C,k=arguments.length,A=k<3?f:w===null?w=Object.getOwnPropertyDescriptor(f,m):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(g,f,m,w);else for(var O=g.length-1;O>=0;O--)(C=g[O])&&(A=(k<3?C(A):k>3?C(f,m,A):C(f,m))||A);return k>3&&A&&Object.defineProperty(f,m,A),A},y=this&&this.__param||function(g,f){return function(m,w){f(m,w,g)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreService=void 0;let h=l(7453),_=l(7150),d=l(6501),p=l(802),b=Object.freeze({insertMode:!1}),c=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),v=class extends _.Disposable{constructor(g,f,m){super(),this._bufferService=g,this._logService=f,this._optionsService=m,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new p.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new p.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new p.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new p.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,h.clone)(b),this.decPrivateModes=(0,h.clone)(c)}reset(){this.modes=(0,h.clone)(b),this.decPrivateModes=(0,h.clone)(c)}triggerDataEvent(g,f=!1){if(this._optionsService.rawOptions.disableStdin)return;let m=this._bufferService.buffer;f&&this._optionsService.rawOptions.scrollOnUserInput&&m.ybase!==m.ydisp&&this._onRequestScrollToBottom.fire(),f&&this._onUserInput.fire(),this._logService.debug(`sending data "${g}"`),this._logService.trace("sending data (codes)",(()=>g.split("").map((w=>w.charCodeAt(0))))),this._onData.fire(g)}triggerBinaryEvent(g){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${g}"`),this._logService.trace("sending binary (codes)",(()=>g.split("").map((f=>f.charCodeAt(0))))),this._onBinary.fire(g))}};n.CoreService=v,n.CoreService=v=u([y(0,d.IBufferService),y(1,d.ILogService),y(2,d.IOptionsService)],v)},6025:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.InstantiationService=n.ServiceCollection=void 0;let u=l(6501),y=l(6201);class h{constructor(...d){this._entries=new Map;for(let[p,b]of d)this.set(p,b)}set(d,p){let b=this._entries.get(d);return this._entries.set(d,p),b}forEach(d){for(let[p,b]of this._entries.entries())d(p,b)}has(d){return this._entries.has(d)}get(d){return this._entries.get(d)}}n.ServiceCollection=h,n.InstantiationService=class{constructor(){this._services=new h,this._services.set(u.IInstantiationService,this)}setService(_,d){this._services.set(_,d)}getService(_){return this._services.get(_)}createInstance(_,...d){let p=(0,y.getServiceDependencies)(_).sort(((v,g)=>v.index-g.index)),b=[];for(let v of p){let g=this._services.get(v.id);if(!g)throw new Error(`[createInstance] ${_.name} depends on UNKNOWN service ${v.id._id}.`);b.push(g)}let c=p.length>0?p[0].index:d.length;if(d.length!==c)throw new Error(`[createInstance] First service dependency of ${_.name} at position ${c+1} conflicts with ${d.length} static arguments`);return new _(...d,...b)}}},7276:function(a,n,l){var u=this&&this.__decorate||function(c,v,g,f){var m,w=arguments.length,C=w<3?v:f===null?f=Object.getOwnPropertyDescriptor(v,g):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,v,g,f);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(C=(w<3?m(C):w>3?m(v,g,C):m(v,g))||C);return w>3&&C&&Object.defineProperty(v,g,C),C},y=this&&this.__param||function(c,v){return function(g,f){v(g,f,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.LogService=void 0,n.setTraceLogger=function(c){p=c},n.traceCall=function(c,v,g){if(typeof g.value!="function")throw new Error("not supported");let f=g.value;g.value=function(...m){if(p.logLevel!==_.LogLevelEnum.TRACE)return f.apply(this,m);p.trace(`GlyphRenderer#${f.name}(${m.map((C=>JSON.stringify(C))).join(", ")})`);let w=f.apply(this,m);return p.trace(`GlyphRenderer#${f.name} return`,w),w}};let h=l(7150),_=l(6501),d={trace:_.LogLevelEnum.TRACE,debug:_.LogLevelEnum.DEBUG,info:_.LogLevelEnum.INFO,warn:_.LogLevelEnum.WARN,error:_.LogLevelEnum.ERROR,off:_.LogLevelEnum.OFF},p,b=class extends h.Disposable{get logLevel(){return this._logLevel}constructor(c){super(),this._optionsService=c,this._logLevel=_.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),p=this}_updateLogLevel(){this._logLevel=d[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(c){for(let v=0;v<c.length;v++)typeof c[v]=="function"&&(c[v]=c[v]())}_log(c,v,g){this._evalLazyOptionalParams(g),c.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+v,...g)}trace(c,...v){this._logLevel<=_.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,c,v)}debug(c,...v){this._logLevel<=_.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,c,v)}info(c,...v){this._logLevel<=_.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,c,v)}warn(c,...v){this._logLevel<=_.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,c,v)}error(c,...v){this._logLevel<=_.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,c,v)}};n.LogService=b,n.LogService=b=u([y(0,_.IOptionsService)],b)},56:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OptionsService=n.DEFAULT_OPTIONS=void 0;let u=l(7150),y=l(701),h=l(802);n.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:y.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}};let _=["normal","bold","100","200","300","400","500","600","700","800","900"];class d extends u.Disposable{constructor(b){super(),this._onOptionChange=this._register(new h.Emitter),this.onOptionChange=this._onOptionChange.event;let c={...n.DEFAULT_OPTIONS};for(let v in b)if(v in c)try{let g=b[v];c[v]=this._sanitizeAndValidateOption(v,g)}catch(g){console.error(g)}this.rawOptions=c,this.options={...c},this._setupOptions(),this._register((0,u.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(b,c){return this.onOptionChange((v=>{v===b&&c(this.rawOptions[b])}))}onMultipleOptionChange(b,c){return this.onOptionChange((v=>{b.indexOf(v)!==-1&&c()}))}_setupOptions(){let b=v=>{if(!(v in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${v}"`);return this.rawOptions[v]},c=(v,g)=>{if(!(v in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${v}"`);g=this._sanitizeAndValidateOption(v,g),this.rawOptions[v]!==g&&(this.rawOptions[v]=g,this._onOptionChange.fire(v))};for(let v in this.rawOptions){let g={get:b.bind(this,v),set:c.bind(this,v)};Object.defineProperty(this.options,v,g)}}_sanitizeAndValidateOption(b,c){switch(b){case"cursorStyle":if(c||(c=n.DEFAULT_OPTIONS[b]),!(function(v){return v==="block"||v==="underline"||v==="bar"})(c))throw new Error(`"${c}" is not a valid value for ${b}`);break;case"wordSeparator":c||(c=n.DEFAULT_OPTIONS[b]);break;case"fontWeight":case"fontWeightBold":if(typeof c=="number"&&1<=c&&c<=1e3)break;c=_.includes(c)?c:n.DEFAULT_OPTIONS[b];break;case"cursorWidth":c=Math.floor(c);case"lineHeight":case"tabStopWidth":if(c<1)throw new Error(`${b} cannot be less than 1, value: ${c}`);break;case"minimumContrastRatio":c=Math.max(1,Math.min(21,Math.round(10*c)/10));break;case"scrollback":if((c=Math.min(c,4294967295))<0)throw new Error(`${b} cannot be less than 0, value: ${c}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(c<=0)throw new Error(`${b} cannot be less than or equal to 0, value: ${c}`);break;case"rows":case"cols":if(!c&&c!==0)throw new Error(`${b} must be numeric, value: ${c}`);break;case"windowsPty":c=c??{}}return c}}n.OptionsService=d},8811:function(a,n,l){var u=this&&this.__decorate||function(d,p,b,c){var v,g=arguments.length,f=g<3?p:c===null?c=Object.getOwnPropertyDescriptor(p,b):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(d,p,b,c);else for(var m=d.length-1;m>=0;m--)(v=d[m])&&(f=(g<3?v(f):g>3?v(p,b,f):v(p,b))||f);return g>3&&f&&Object.defineProperty(p,b,f),f},y=this&&this.__param||function(d,p){return function(b,c){p(b,c,d)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkService=void 0;let h=l(6501),_=class{constructor(d){this._bufferService=d,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(d){let p=this._bufferService.buffer;if(d.id===void 0){let m=p.addMarker(p.ybase+p.y),w={data:d,id:this._nextId++,lines:[m]};return m.onDispose((()=>this._removeMarkerFromLink(w,m))),this._dataByLinkId.set(w.id,w),w.id}let b=d,c=this._getEntryIdKey(b),v=this._entriesWithId.get(c);if(v)return this.addLineToLink(v.id,p.ybase+p.y),v.id;let g=p.addMarker(p.ybase+p.y),f={id:this._nextId++,key:this._getEntryIdKey(b),data:b,lines:[g]};return g.onDispose((()=>this._removeMarkerFromLink(f,g))),this._entriesWithId.set(f.key,f),this._dataByLinkId.set(f.id,f),f.id}addLineToLink(d,p){let b=this._dataByLinkId.get(d);if(b&&b.lines.every((c=>c.line!==p))){let c=this._bufferService.buffer.addMarker(p);b.lines.push(c),c.onDispose((()=>this._removeMarkerFromLink(b,c)))}}getLinkData(d){return this._dataByLinkId.get(d)?.data}_getEntryIdKey(d){return`${d.id};;${d.uri}`}_removeMarkerFromLink(d,p){let b=d.lines.indexOf(p);b!==-1&&(d.lines.splice(b,1),d.lines.length===0&&(d.data.id!==void 0&&this._entriesWithId.delete(d.key),this._dataByLinkId.delete(d.id)))}};n.OscLinkService=_,n.OscLinkService=_=u([y(0,h.IBufferService)],_)},6201:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.serviceRegistry=void 0,n.getServiceDependencies=function(y){return y[u]||[]},n.createDecorator=function(y){if(n.serviceRegistry.has(y))return n.serviceRegistry.get(y);let h=function(_,d,p){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(b,c,v){c[l]===c?c[u].push({id:b,index:v}):(c[u]=[{id:b,index:v}],c[l]=c)})(h,_,p)};return h._id=y,n.serviceRegistry.set(y,h),h};let l="di$target",u="di$dependencies";n.serviceRegistry=new Map},6501:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IDecorationService=n.IUnicodeService=n.IOscLinkService=n.IOptionsService=n.ILogService=n.LogLevelEnum=n.IInstantiationService=n.ICharsetService=n.ICoreService=n.ICoreMouseService=n.IBufferService=void 0;let u=l(6201);var y;n.IBufferService=(0,u.createDecorator)("BufferService"),n.ICoreMouseService=(0,u.createDecorator)("CoreMouseService"),n.ICoreService=(0,u.createDecorator)("CoreService"),n.ICharsetService=(0,u.createDecorator)("CharsetService"),n.IInstantiationService=(0,u.createDecorator)("InstantiationService"),(function(h){h[h.TRACE=0]="TRACE",h[h.DEBUG=1]="DEBUG",h[h.INFO=2]="INFO",h[h.WARN=3]="WARN",h[h.ERROR=4]="ERROR",h[h.OFF=5]="OFF"})(y||(n.LogLevelEnum=y={})),n.ILogService=(0,u.createDecorator)("LogService"),n.IOptionsService=(0,u.createDecorator)("OptionsService"),n.IOscLinkService=(0,u.createDecorator)("OscLinkService"),n.IUnicodeService=(0,u.createDecorator)("UnicodeService"),n.IDecorationService=(0,u.createDecorator)("DecorationService")},6415:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeService=void 0;let u=l(7428),y=l(802);class h{static extractShouldJoin(d){return!!(1&d)}static extractWidth(d){return d>>1&3}static extractCharKind(d){return d>>3}static createPropertyValue(d,p,b=!1){return(16777215&d)<<3|(3&p)<<1|(b?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new y.Emitter,this.onChange=this._onChange.event;let d=new u.UnicodeV6;this.register(d),this._active=d.version,this._activeProvider=d}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(d){if(!this._providers[d])throw new Error(`unknown Unicode version "${d}"`);this._active=d,this._activeProvider=this._providers[d],this._onChange.fire(d)}register(d){this._providers[d.version]=d}wcwidth(d){return this._activeProvider.wcwidth(d)}getStringCellWidth(d){let p=0,b=0,c=d.length;for(let v=0;v<c;++v){let g=d.charCodeAt(v);if(55296<=g&&g<=56319){if(++v>=c)return p+this.wcwidth(g);let w=d.charCodeAt(v);56320<=w&&w<=57343?g=1024*(g-55296)+w-56320+65536:p+=this.wcwidth(w)}let f=this.charProperties(g,b),m=h.extractWidth(f);h.extractShouldJoin(f)&&(m-=h.extractWidth(b)),p+=m,b=f}return p}charProperties(d,p){return this._activeProvider.charProperties(d,p)}}n.UnicodeService=h},5856:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;let u=l(6107),y=l(5777),h=l(802);class _ extends y.CoreTerminal{constructor(p={}){super(p),this._onBell=this._register(new h.Emitter),this.onBell=this._onBell.event,this._onCursorMove=this._register(new h.Emitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this._register(new h.Emitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this._register(new h.Emitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this._register(new h.Emitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this._register(this._inputHandler.onRequestBell((()=>this.bell()))),this._register(this._inputHandler.onRequestReset((()=>this.reset()))),this._register(h.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(h.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(h.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(h.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(p){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+p)}bell(){this._onBell.fire()}input(p,b=!0){this.coreService.triggerDataEvent(p,b)}resize(p,b){p===this.cols&&b===this.rows||super.resize(p,b)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let p=1;p<this.rows;p++)this.buffer.lines.push(this.buffer.getBlankLine(u.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}n.Terminal=_},3058:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Permutation=n.CallbackIterable=n.ArrayQueue=n.booleanComparator=n.numberComparator=n.CompareResult=void 0,n.tail=function(m,w=0){return m[m.length-(1+w)]},n.tail2=function(m){if(m.length===0)throw new Error("Invalid tail call");return[m.slice(0,m.length-1),m[m.length-1]]},n.equals=function(m,w,C=(k,A)=>k===A){if(m===w)return!0;if(!m||!w||m.length!==w.length)return!1;for(let k=0,A=m.length;k<A;k++)if(!C(m[k],w[k]))return!1;return!0},n.removeFastWithoutKeepingOrder=function(m,w){let C=m.length-1;w<C&&(m[w]=m[C]),m.pop()},n.binarySearch=function(m,w,C){return h(m.length,(k=>C(m[k],w)))},n.binarySearch2=h,n.quickSelect=function m(w,C,k){if((w|=0)>=C.length)throw new TypeError("invalid index");let A=C[Math.floor(C.length*Math.random())],O=[],D=[],L=[];for(let R of C){let P=k(R,A);P<0?O.push(R):P>0?D.push(R):L.push(R)}return w<O.length?m(w,O,k):w<O.length+L.length?L[0]:m(w-(O.length+L.length),D,k)},n.groupBy=function(m,w){let C=[],k;for(let A of m.slice(0).sort(w))k&&w(k[0],A)===0?k.push(A):(k=[A],C.push(k));return C},n.groupAdjacentBy=function*(m,w){let C,k;for(let A of m)k!==void 0&&w(k,A)?C.push(A):(C&&(yield C),C=[A]),k=A;C&&(yield C)},n.forEachAdjacent=function(m,w){for(let C=0;C<=m.length;C++)w(C===0?void 0:m[C-1],C===m.length?void 0:m[C])},n.forEachWithNeighbors=function(m,w){for(let C=0;C<m.length;C++)w(C===0?void 0:m[C-1],m[C],C+1===m.length?void 0:m[C+1])},n.sortedDiff=_,n.delta=function(m,w,C){let k=_(m,w,C),A=[],O=[];for(let D of k)A.push(...m.slice(D.start,D.start+D.deleteCount)),O.push(...D.toInsert);return{removed:A,added:O}},n.top=function(m,w,C){if(C===0)return[];let k=m.slice(0,C).sort(w);return d(m,w,k,C,m.length),k},n.topAsync=function(m,w,C,k,A){return C===0?Promise.resolve([]):new Promise(((O,D)=>{(async()=>{let L=m.length,R=m.slice(0,C).sort(w);for(let P=C,F=Math.min(C+k,L);P<L;P=F,F=Math.min(F+k,L)){if(P>C&&await new Promise((V=>setTimeout(V))),A&&A.isCancellationRequested)throw new u.CancellationError;d(m,w,R,P,F)}return R})().then(O,D)}))},n.coalesce=function(m){return m.filter((w=>!!w))},n.coalesceInPlace=function(m){let w=0;for(let C=0;C<m.length;C++)m[C]&&(m[w]=m[C],w+=1);m.length=w},n.move=function(m,w,C){m.splice(C,0,m.splice(w,1)[0])},n.isFalsyOrEmpty=function(m){return!Array.isArray(m)||m.length===0},n.isNonEmptyArray=function(m){return Array.isArray(m)&&m.length>0},n.distinct=function(m,w=C=>C){let C=new Set;return m.filter((k=>{let A=w(k);return!C.has(A)&&(C.add(A),!0)}))},n.uniqueFilter=function(m){let w=new Set;return C=>{let k=m(C);return!w.has(k)&&(w.add(k),!0)}},n.firstOrDefault=function(m,w){return m.length>0?m[0]:w},n.lastOrDefault=function(m,w){return m.length>0?m[m.length-1]:w},n.commonPrefixLength=function(m,w,C=(k,A)=>k===A){let k=0;for(let A=0,O=Math.min(m.length,w.length);A<O&&C(m[A],w[A]);A++)k++;return k},n.range=function(m,w){let C=typeof w=="number"?m:0;typeof w=="number"?C=m:(C=0,w=m);let k=[];if(C<=w)for(let A=C;A<w;A++)k.push(A);else for(let A=C;A>w;A--)k.push(A);return k},n.index=function(m,w,C){return m.reduce(((k,A)=>(k[w(A)]=C?C(A):A,k)),Object.create(null))},n.insert=function(m,w){return m.push(w),()=>p(m,w)},n.remove=p,n.arrayInsert=function(m,w,C){let k=m.slice(0,w),A=m.slice(w);return k.concat(C,A)},n.shuffle=function(m,w){let C;if(typeof w=="number"){let k=w;C=()=>{let A=179426549*Math.sin(k++);return A-Math.floor(A)}}else C=Math.random;for(let k=m.length-1;k>0;k-=1){let A=Math.floor(C()*(k+1)),O=m[k];m[k]=m[A],m[A]=O}},n.pushToStart=function(m,w){let C=m.indexOf(w);C>-1&&(m.splice(C,1),m.unshift(w))},n.pushToEnd=function(m,w){let C=m.indexOf(w);C>-1&&(m.splice(C,1),m.push(w))},n.pushMany=function(m,w){for(let C of w)m.push(C)},n.mapArrayOrNot=function(m,w){return Array.isArray(m)?m.map(w):w(m)},n.asArray=function(m){return Array.isArray(m)?m:[m]},n.getRandomElement=function(m){return m[Math.floor(Math.random()*m.length)]},n.insertInto=b,n.splice=function(m,w,C,k){let A=c(m,w),O=m.splice(A,C);return O===void 0&&(O=[]),b(m,A,k),O},n.compareBy=function(m,w){return(C,k)=>w(m(C),m(k))},n.tieBreakComparators=function(...m){return(w,C)=>{for(let k of m){let A=k(w,C);if(!v.isNeitherLessOrGreaterThan(A))return A}return v.neitherLessOrGreaterThan}},n.reverseOrder=function(m){return(w,C)=>-m(w,C)};let u=l(9807),y=l(8297);function h(m,w){let C=0,k=m-1;for(;C<=k;){let A=(C+k)/2|0,O=w(A);if(O<0)C=A+1;else{if(!(O>0))return A;k=A-1}}return-(C+1)}function _(m,w,C){let k=[];function A(L,R,P){if(R===0&&P.length===0)return;let F=k[k.length-1];F&&F.start+F.deleteCount===L?(F.deleteCount+=R,F.toInsert.push(...P)):k.push({start:L,deleteCount:R,toInsert:P})}let O=0,D=0;for(;;){if(O===m.length){A(O,0,w.slice(D));break}if(D===w.length){A(O,m.length-O,[]);break}let L=m[O],R=w[D],P=C(L,R);P===0?(O+=1,D+=1):P<0?(A(O,1,[]),O+=1):P>0&&(A(O,0,[R]),D+=1)}return k}function d(m,w,C,k,A){for(let O=C.length;k<A;k++){let D=m[k];if(w(D,C[O-1])<0){C.pop();let L=(0,y.findFirstIdxMonotonousOrArrLen)(C,(R=>w(D,R)<0));C.splice(L,0,D)}}}function p(m,w){let C=m.indexOf(w);if(C>-1)return m.splice(C,1),w}function b(m,w,C){let k=c(m,w),A=m.length,O=C.length;m.length=A+O;for(let D=A-1;D>=k;D--)m[D+O]=m[D];for(let D=0;D<O;D++)m[D+k]=C[D]}function c(m,w){return w<0?Math.max(w+m.length,0):Math.min(w,m.length)}var v;(function(m){m.isLessThan=function(w){return w<0},m.isLessThanOrEqual=function(w){return w<=0},m.isGreaterThan=function(w){return w>0},m.isNeitherLessOrGreaterThan=function(w){return w===0},m.greaterThan=1,m.lessThan=-1,m.neitherLessOrGreaterThan=0})(v||(n.CompareResult=v={})),n.numberComparator=(m,w)=>m-w,n.booleanComparator=(m,w)=>(0,n.numberComparator)(m?1:0,w?1:0),n.ArrayQueue=class{constructor(m){this.items=m,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(m){let w=this.firstIdx;for(;w<this.items.length&&m(this.items[w]);)w++;let C=w===this.firstIdx?null:this.items.slice(this.firstIdx,w);return this.firstIdx=w,C}takeFromEndWhile(m){let w=this.lastIdx;for(;w>=0&&m(this.items[w]);)w--;let C=w===this.lastIdx?null:this.items.slice(w+1,this.lastIdx+1);return this.lastIdx=w,C}peek(){if(this.length!==0)return this.items[this.firstIdx]}peekLast(){if(this.length!==0)return this.items[this.lastIdx]}dequeue(){let m=this.items[this.firstIdx];return this.firstIdx++,m}removeLast(){let m=this.items[this.lastIdx];return this.lastIdx--,m}takeCount(m){let w=this.items.slice(this.firstIdx,this.firstIdx+m);return this.firstIdx+=m,w}};class g{static{this.empty=new g((w=>{}))}constructor(w){this.iterate=w}forEach(w){this.iterate((C=>(w(C),!0)))}toArray(){let w=[];return this.iterate((C=>(w.push(C),!0))),w}filter(w){return new g((C=>this.iterate((k=>!w(k)||C(k)))))}map(w){return new g((C=>this.iterate((k=>C(w(k))))))}some(w){let C=!1;return this.iterate((k=>(C=w(k),!C))),C}findFirst(w){let C;return this.iterate((k=>!w(k)||(C=k,!1))),C}findLast(w){let C;return this.iterate((k=>(w(k)&&(C=k),!0))),C}findLastMaxBy(w){let C,k=!0;return this.iterate((A=>((k||v.isGreaterThan(w(A,C)))&&(k=!1,C=A),!0))),C}}n.CallbackIterable=g;class f{constructor(w){this._indexMap=w}static createSortPermutation(w,C){let k=Array.from(w.keys()).sort(((A,O)=>C(w[A],w[O])));return new f(k)}apply(w){return w.map(((C,k)=>w[this._indexMap[k]]))}inverse(){let w=this._indexMap.slice();for(let C=0;C<this._indexMap.length;C++)w[this._indexMap[C]]=C;return new f(w)}}n.Permutation=f},8297:(a,n)=>{function l(d,p,b=d.length-1){for(let c=b;c>=0;c--)if(p(d[c]))return c;return-1}function u(d,p,b=0,c=d.length){let v=b,g=c;for(;v<g;){let f=Math.floor((v+g)/2);p(d[f])?v=f+1:g=f}return v-1}function y(d,p,b=0,c=d.length){let v=b,g=c;for(;v<g;){let f=Math.floor((v+g)/2);p(d[f])?g=f:v=f+1}return v}Object.defineProperty(n,"__esModule",{value:!0}),n.MonotonousArray=void 0,n.findLast=function(d,p){let b=l(d,p);if(b!==-1)return d[b]},n.findLastIdx=l,n.findLastMonotonous=function(d,p){let b=u(d,p);return b===-1?void 0:d[b]},n.findLastIdxMonotonous=u,n.findFirstMonotonous=function(d,p){let b=y(d,p);return b===d.length?void 0:d[b]},n.findFirstIdxMonotonousOrArrLen=y,n.findFirstIdxMonotonous=function(d,p,b=0,c=d.length){let v=y(d,p,b,c);return v===d.length?-1:v},n.findFirstMax=_,n.findLastMax=function(d,p){if(d.length===0)return;let b=d[0];for(let c=1;c<d.length;c++){let v=d[c];p(v,b)>=0&&(b=v)}return b},n.findFirstMin=function(d,p){return _(d,((b,c)=>-p(b,c)))},n.findMaxIdx=function(d,p){if(d.length===0)return-1;let b=0;for(let c=1;c<d.length;c++)p(d[c],d[b])>0&&(b=c);return b},n.mapFindFirst=function(d,p){for(let b of d){let c=p(b);if(c!==void 0)return c}};class h{static{this.assertInvariants=!1}constructor(p){this._array=p,this._findLastMonotonousLastIdx=0}findLastMonotonous(p){if(h.assertInvariants){if(this._prevFindLastPredicate){for(let c of this._array)if(this._prevFindLastPredicate(c)&&!p(c))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=p}let b=u(this._array,p,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=b+1,b===-1?void 0:this._array[b]}}function _(d,p){if(d.length===0)return;let b=d[0];for(let c=1;c<d.length;c++){let v=d[c];p(v,b)>0&&(b=v)}return b}n.MonotonousArray=h},9087:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.SetWithKey=void 0,n.groupBy=function(y,h){let _=Object.create(null);for(let d of y){let p=h(d),b=_[p];b||(b=_[p]=[]),b.push(d)}return _},n.diffSets=function(y,h){let _=[],d=[];for(let p of y)h.has(p)||_.push(p);for(let p of h)y.has(p)||d.push(p);return{removed:_,added:d}},n.diffMaps=function(y,h){let _=[],d=[];for(let[p,b]of y)h.has(p)||_.push(b);for(let[p,b]of h)y.has(p)||d.push(b);return{removed:_,added:d}},n.intersection=function(y,h){let _=new Set;for(let d of h)y.has(d)&&_.add(d);return _};class u{static{l=Symbol.toStringTag}constructor(h,_){this.toKey=_,this._map=new Map,this[l]="SetWithKey";for(let d of h)this.add(d)}get size(){return this._map.size}add(h){let _=this.toKey(h);return this._map.set(_,h),this}delete(h){return this._map.delete(this.toKey(h))}has(h){return this._map.has(this.toKey(h))}*entries(){for(let h of this._map.values())yield[h,h]}keys(){return this.values()}*values(){for(let h of this._map.values())yield h}clear(){this._map.clear()}forEach(h,_){this._map.forEach((d=>h.call(_,d,d,this)))}[Symbol.iterator](){return this.values()}}n.SetWithKey=u},9807:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BugIndicatingError=n.ErrorNoTelemetry=n.ExpectedError=n.NotSupportedError=n.NotImplementedError=n.ReadonlyError=n.CancellationError=n.errorHandler=n.ErrorHandler=void 0,n.setUnexpectedErrorHandler=function(g){n.errorHandler.setUnexpectedErrorHandler(g)},n.isSigPipeError=function(g){if(!g||typeof g!="object")return!1;let f=g;return f.code==="EPIPE"&&f.syscall?.toUpperCase()==="WRITE"},n.onUnexpectedError=function(g){y(g)||n.errorHandler.onUnexpectedError(g)},n.onUnexpectedExternalError=function(g){y(g)||n.errorHandler.onUnexpectedExternalError(g)},n.transformErrorForSerialization=function(g){if(g instanceof Error){let{name:f,message:m}=g;return{$isError:!0,name:f,message:m,stack:g.stacktrace||g.stack,noTelemetry:c.isErrorNoTelemetry(g)}}return g},n.transformErrorFromSerialization=function(g){let f;return g.noTelemetry?f=new c:(f=new Error,f.name=g.name),f.message=g.message,f.stack=g.stack,f},n.isCancellationError=y,n.canceled=function(){let g=new Error(u);return g.name=g.message,g},n.illegalArgument=function(g){return g?new Error(`Illegal argument: ${g}`):new Error("Illegal argument")},n.illegalState=function(g){return g?new Error(`Illegal state: ${g}`):new Error("Illegal state")},n.getErrorMessage=function(g){return g?g.message?g.message:g.stack?g.stack.split(`
66
66
  `)[0]:String(g):"Error"};class l{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(f){setTimeout((()=>{throw f.stack?c.isErrorNoTelemetry(f)?new c(f.message+`
67
67
 
68
68
  `+f.stack):new Error(f.message+`
69
69
 
70
- `+f.stack):f}),0)}}addListener(f){return this.listeners.push(f),()=>{this._removeListener(f)}}emit(f){this.listeners.forEach((m=>{m(f)}))}_removeListener(f){this.listeners.splice(this.listeners.indexOf(f),1)}setUnexpectedErrorHandler(f){this.unexpectedErrorHandler=f}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(f){this.unexpectedErrorHandler(f),this.emit(f)}onUnexpectedExternalError(f){this.unexpectedErrorHandler(f)}}n.ErrorHandler=l,n.errorHandler=new l;let u="Canceled";function y(g){return g instanceof h||g instanceof Error&&g.name===u&&g.message===u}class h extends Error{constructor(){super(u),this.name=this.message}}n.CancellationError=h;class _ extends TypeError{constructor(f){super(f?`${f} is read-only and cannot be changed`:"Cannot change read-only property")}}n.ReadonlyError=_;class d extends Error{constructor(f){super("NotImplemented"),f&&(this.message=f)}}n.NotImplementedError=d;class p extends Error{constructor(f){super("NotSupported"),f&&(this.message=f)}}n.NotSupportedError=p;class b extends Error{constructor(){super(...arguments),this.isExpected=!0}}n.ExpectedError=b;class c extends Error{constructor(f){super(f),this.name="CodeExpectedError"}static fromError(f){if(f instanceof c)return f;let m=new c;return m.message=f.message,m.stack=f.stack,m}static isErrorNoTelemetry(f){return f.name==="CodeExpectedError"}}n.ErrorNoTelemetry=c;class v extends Error{constructor(f){super(f||"An unexpected bug occurred."),Object.setPrototypeOf(this,v.prototype)}}n.BugIndicatingError=v},802:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ValueWithChangeEvent=n.Relay=n.EventBufferer=n.DynamicListEventMultiplexer=n.EventMultiplexer=n.MicrotaskEmitter=n.DebounceEmitter=n.PauseableEmitter=n.AsyncEmitter=n.createEventDeliveryQueue=n.Emitter=n.ListenerRefusalError=n.ListenerLeakError=n.EventProfiling=n.Event=void 0,n.setGlobalLeakWarningThreshold=function(R){let P=c;return c=R,{dispose(){c=P}}};let u=l(9807),y=l(8841),h=l(7150),_=l(6317),d=l(9725);var p;(function(R){function P(E){return(x,M=null,N)=>{let U,z=!1;return U=E((ne=>{if(!z)return U?U.dispose():z=!0,x.call(M,ne)}),null,N),z&&U.dispose(),U}}function F(E,x,M){return Z(((N,U=null,z)=>E((ne=>N.call(U,x(ne))),null,z)),M)}function V(E,x,M){return Z(((N,U=null,z)=>E((ne=>x(ne)&&N.call(U,ne)),null,z)),M)}function Z(E,x){let M,N=new k({onWillAddFirstListener(){M=E(N.fire,N)},onDidRemoveLastListener(){M?.dispose()}});return x?.add(N),N.event}function Y(E,x,M=100,N=!1,U=!1,z,ne){let I,Q,J,te,Ae=0,Ie=new k({leakWarningThreshold:z,onWillAddFirstListener(){I=E((Jt=>{Ae++,Q=x(Q,Jt),N&&!J&&(Ie.fire(Q),Q=void 0),te=()=>{let We=Q;Q=void 0,J=void 0,(!N||Ae>1)&&Ie.fire(We),Ae=0},typeof M=="number"?(clearTimeout(J),J=setTimeout(te,M)):J===void 0&&(J=0,queueMicrotask(te))}))},onWillRemoveListener(){U&&Ae>0&&te?.()},onDidRemoveLastListener(){te=void 0,I.dispose()}});return ne?.add(Ie),Ie.event}R.None=()=>h.Disposable.None,R.defer=function(E,x){return Y(E,(()=>{}),0,void 0,!0,void 0,x)},R.once=P,R.map=F,R.forEach=function(E,x,M){return Z(((N,U=null,z)=>E((ne=>{x(ne),N.call(U,ne)}),null,z)),M)},R.filter=V,R.signal=function(E){return E},R.any=function(...E){return(x,M=null,N)=>{return U=(0,h.combinedDisposable)(...E.map((ne=>ne((I=>x.call(M,I)))))),(z=N)instanceof Array?z.push(U):z&&z.add(U),U;var U,z}},R.reduce=function(E,x,M,N){let U=M;return F(E,(z=>(U=x(U,z),U)),N)},R.debounce=Y,R.accumulate=function(E,x=0,M){return R.debounce(E,((N,U)=>N?(N.push(U),N):[U]),x,void 0,!0,void 0,M)},R.latch=function(E,x=(N,U)=>N===U,M){let N,U=!0;return V(E,(z=>{let ne=U||!x(z,N);return U=!1,N=z,ne}),M)},R.split=function(E,x,M){return[R.filter(E,x,M),R.filter(E,(N=>!x(N)),M)]},R.buffer=function(E,x=!1,M=[],N){let U=M.slice(),z=E((Q=>{U?U.push(Q):I.fire(Q)}));N&&N.add(z);let ne=()=>{U?.forEach((Q=>I.fire(Q))),U=null},I=new k({onWillAddFirstListener(){z||(z=E((Q=>I.fire(Q))),N&&N.add(z))},onDidAddFirstListener(){U&&(x?setTimeout(ne):ne())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return N&&N.add(I),I.event},R.chain=function(E,x){return(M,N,U)=>{let z=x(new S);return E((function(ne){let I=z.evaluate(ne);I!==j&&M.call(N,I)}),void 0,U)}};let j=Symbol("HaltChainable");class S{constructor(){this.steps=[]}map(x){return this.steps.push(x),this}forEach(x){return this.steps.push((M=>(x(M),M))),this}filter(x){return this.steps.push((M=>x(M)?M:j)),this}reduce(x,M){let N=M;return this.steps.push((U=>(N=x(N,U),N))),this}latch(x=(M,N)=>M===N){let M,N=!0;return this.steps.push((U=>{let z=N||!x(U,M);return N=!1,M=U,z?U:j})),this}evaluate(x){for(let M of this.steps)if((x=M(x))===j)break;return x}}R.fromNodeEventEmitter=function(E,x,M=N=>N){let N=(...z)=>U.fire(M(...z)),U=new k({onWillAddFirstListener:()=>E.on(x,N),onDidRemoveLastListener:()=>E.removeListener(x,N)});return U.event},R.fromDOMEventEmitter=function(E,x,M=N=>N){let N=(...z)=>U.fire(M(...z)),U=new k({onWillAddFirstListener:()=>E.addEventListener(x,N),onDidRemoveLastListener:()=>E.removeEventListener(x,N)});return U.event},R.toPromise=function(E){return new Promise((x=>P(E)(x)))},R.fromPromise=function(E){let x=new k;return E.then((M=>{x.fire(M)}),(()=>{x.fire(void 0)})).finally((()=>{x.dispose()})),x.event},R.forward=function(E,x){return E((M=>x.fire(M)))},R.runAndSubscribe=function(E,x,M){return x(M),E((N=>x(N)))};class T{constructor(x,M){this._observable=x,this._counter=0,this._hasChanged=!1;let N={onWillAddFirstListener:()=>{x.addObserver(this)},onDidRemoveLastListener:()=>{x.removeObserver(this)}};this.emitter=new k(N),M&&M.add(this.emitter)}beginUpdate(x){this._counter++}handlePossibleChange(x){}handleChange(x,M){this._hasChanged=!0}endUpdate(x){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}R.fromObservable=function(E,x){return new T(E,x).emitter.event},R.fromObservableLight=function(E){return(x,M,N)=>{let U=0,z=!1,ne={beginUpdate(){U++},endUpdate(){U--,U===0&&(E.reportChanges(),z&&(z=!1,x.call(M)))},handlePossibleChange(){},handleChange(){z=!0}};E.addObserver(ne),E.reportChanges();let I={dispose(){E.removeObserver(ne)}};return N instanceof h.DisposableStore?N.add(I):Array.isArray(N)&&N.push(I),I}}})(p||(n.Event=p={}));class b{static{this.all=new Set}static{this._idPool=0}constructor(P){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${P}_${b._idPool++}`,b.all.add(this)}start(P){this._stopWatch=new d.StopWatch,this.listenerCount=P}stop(){if(this._stopWatch){let P=this._stopWatch.elapsed();this.durations.push(P),this.elapsedOverall+=P,this.invocationCount+=1,this._stopWatch=void 0}}}n.EventProfiling=b;let c=-1;class v{static{this._idPool=1}constructor(P,F,V=(v._idPool++).toString(16).padStart(3,"0")){this._errorHandler=P,this.threshold=F,this.name=V,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(P,F){let V=this.threshold;if(V<=0||F<V)return;this._stacks||(this._stacks=new Map);let Z=this._stacks.get(P.value)||0;if(this._stacks.set(P.value,Z+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*V;let[Y,j]=this.getMostFrequentStack(),S=`[${this.name}] potential listener LEAK detected, having ${F} listeners already. MOST frequent listener (${j}):`;console.warn(S),console.warn(Y);let T=new f(S,Y);this._errorHandler(T)}return()=>{let Y=this._stacks.get(P.value)||0;this._stacks.set(P.value,Y-1)}}getMostFrequentStack(){if(!this._stacks)return;let P,F=0;for(let[V,Z]of this._stacks)(!P||F<Z)&&(P=[V,Z],F=Z);return P}}class g{static create(){let P=new Error;return new g(P.stack??"")}constructor(P){this.value=P}print(){console.warn(this.value.split(`
70
+ `+f.stack):f}),0)}}addListener(f){return this.listeners.push(f),()=>{this._removeListener(f)}}emit(f){this.listeners.forEach((m=>{m(f)}))}_removeListener(f){this.listeners.splice(this.listeners.indexOf(f),1)}setUnexpectedErrorHandler(f){this.unexpectedErrorHandler=f}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(f){this.unexpectedErrorHandler(f),this.emit(f)}onUnexpectedExternalError(f){this.unexpectedErrorHandler(f)}}n.ErrorHandler=l,n.errorHandler=new l;let u="Canceled";function y(g){return g instanceof h||g instanceof Error&&g.name===u&&g.message===u}class h extends Error{constructor(){super(u),this.name=this.message}}n.CancellationError=h;class _ extends TypeError{constructor(f){super(f?`${f} is read-only and cannot be changed`:"Cannot change read-only property")}}n.ReadonlyError=_;class d extends Error{constructor(f){super("NotImplemented"),f&&(this.message=f)}}n.NotImplementedError=d;class p extends Error{constructor(f){super("NotSupported"),f&&(this.message=f)}}n.NotSupportedError=p;class b extends Error{constructor(){super(...arguments),this.isExpected=!0}}n.ExpectedError=b;class c extends Error{constructor(f){super(f),this.name="CodeExpectedError"}static fromError(f){if(f instanceof c)return f;let m=new c;return m.message=f.message,m.stack=f.stack,m}static isErrorNoTelemetry(f){return f.name==="CodeExpectedError"}}n.ErrorNoTelemetry=c;class v extends Error{constructor(f){super(f||"An unexpected bug occurred."),Object.setPrototypeOf(this,v.prototype)}}n.BugIndicatingError=v},802:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ValueWithChangeEvent=n.Relay=n.EventBufferer=n.DynamicListEventMultiplexer=n.EventMultiplexer=n.MicrotaskEmitter=n.DebounceEmitter=n.PauseableEmitter=n.AsyncEmitter=n.createEventDeliveryQueue=n.Emitter=n.ListenerRefusalError=n.ListenerLeakError=n.EventProfiling=n.Event=void 0,n.setGlobalLeakWarningThreshold=function(R){let P=c;return c=R,{dispose(){c=P}}};let u=l(9807),y=l(8841),h=l(7150),_=l(6317),d=l(9725);var p;(function(R){function P(E){return(x,M=null,N)=>{let H,z=!1;return H=E((ne=>{if(!z)return H?H.dispose():z=!0,x.call(M,ne)}),null,N),z&&H.dispose(),H}}function F(E,x,M){return Z(((N,H=null,z)=>E((ne=>N.call(H,x(ne))),null,z)),M)}function V(E,x,M){return Z(((N,H=null,z)=>E((ne=>x(ne)&&N.call(H,ne)),null,z)),M)}function Z(E,x){let M,N=new k({onWillAddFirstListener(){M=E(N.fire,N)},onDidRemoveLastListener(){M?.dispose()}});return x?.add(N),N.event}function Y(E,x,M=100,N=!1,H=!1,z,ne){let I,Q,J,te,Ae=0,Ie=new k({leakWarningThreshold:z,onWillAddFirstListener(){I=E((Xt=>{Ae++,Q=x(Q,Xt),N&&!J&&(Ie.fire(Q),Q=void 0),te=()=>{let We=Q;Q=void 0,J=void 0,(!N||Ae>1)&&Ie.fire(We),Ae=0},typeof M=="number"?(clearTimeout(J),J=setTimeout(te,M)):J===void 0&&(J=0,queueMicrotask(te))}))},onWillRemoveListener(){H&&Ae>0&&te?.()},onDidRemoveLastListener(){te=void 0,I.dispose()}});return ne?.add(Ie),Ie.event}R.None=()=>h.Disposable.None,R.defer=function(E,x){return Y(E,(()=>{}),0,void 0,!0,void 0,x)},R.once=P,R.map=F,R.forEach=function(E,x,M){return Z(((N,H=null,z)=>E((ne=>{x(ne),N.call(H,ne)}),null,z)),M)},R.filter=V,R.signal=function(E){return E},R.any=function(...E){return(x,M=null,N)=>{return H=(0,h.combinedDisposable)(...E.map((ne=>ne((I=>x.call(M,I)))))),(z=N)instanceof Array?z.push(H):z&&z.add(H),H;var H,z}},R.reduce=function(E,x,M,N){let H=M;return F(E,(z=>(H=x(H,z),H)),N)},R.debounce=Y,R.accumulate=function(E,x=0,M){return R.debounce(E,((N,H)=>N?(N.push(H),N):[H]),x,void 0,!0,void 0,M)},R.latch=function(E,x=(N,H)=>N===H,M){let N,H=!0;return V(E,(z=>{let ne=H||!x(z,N);return H=!1,N=z,ne}),M)},R.split=function(E,x,M){return[R.filter(E,x,M),R.filter(E,(N=>!x(N)),M)]},R.buffer=function(E,x=!1,M=[],N){let H=M.slice(),z=E((Q=>{H?H.push(Q):I.fire(Q)}));N&&N.add(z);let ne=()=>{H?.forEach((Q=>I.fire(Q))),H=null},I=new k({onWillAddFirstListener(){z||(z=E((Q=>I.fire(Q))),N&&N.add(z))},onDidAddFirstListener(){H&&(x?setTimeout(ne):ne())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return N&&N.add(I),I.event},R.chain=function(E,x){return(M,N,H)=>{let z=x(new S);return E((function(ne){let I=z.evaluate(ne);I!==j&&M.call(N,I)}),void 0,H)}};let j=Symbol("HaltChainable");class S{constructor(){this.steps=[]}map(x){return this.steps.push(x),this}forEach(x){return this.steps.push((M=>(x(M),M))),this}filter(x){return this.steps.push((M=>x(M)?M:j)),this}reduce(x,M){let N=M;return this.steps.push((H=>(N=x(N,H),N))),this}latch(x=(M,N)=>M===N){let M,N=!0;return this.steps.push((H=>{let z=N||!x(H,M);return N=!1,M=H,z?H:j})),this}evaluate(x){for(let M of this.steps)if((x=M(x))===j)break;return x}}R.fromNodeEventEmitter=function(E,x,M=N=>N){let N=(...z)=>H.fire(M(...z)),H=new k({onWillAddFirstListener:()=>E.on(x,N),onDidRemoveLastListener:()=>E.removeListener(x,N)});return H.event},R.fromDOMEventEmitter=function(E,x,M=N=>N){let N=(...z)=>H.fire(M(...z)),H=new k({onWillAddFirstListener:()=>E.addEventListener(x,N),onDidRemoveLastListener:()=>E.removeEventListener(x,N)});return H.event},R.toPromise=function(E){return new Promise((x=>P(E)(x)))},R.fromPromise=function(E){let x=new k;return E.then((M=>{x.fire(M)}),(()=>{x.fire(void 0)})).finally((()=>{x.dispose()})),x.event},R.forward=function(E,x){return E((M=>x.fire(M)))},R.runAndSubscribe=function(E,x,M){return x(M),E((N=>x(N)))};class T{constructor(x,M){this._observable=x,this._counter=0,this._hasChanged=!1;let N={onWillAddFirstListener:()=>{x.addObserver(this)},onDidRemoveLastListener:()=>{x.removeObserver(this)}};this.emitter=new k(N),M&&M.add(this.emitter)}beginUpdate(x){this._counter++}handlePossibleChange(x){}handleChange(x,M){this._hasChanged=!0}endUpdate(x){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}R.fromObservable=function(E,x){return new T(E,x).emitter.event},R.fromObservableLight=function(E){return(x,M,N)=>{let H=0,z=!1,ne={beginUpdate(){H++},endUpdate(){H--,H===0&&(E.reportChanges(),z&&(z=!1,x.call(M)))},handlePossibleChange(){},handleChange(){z=!0}};E.addObserver(ne),E.reportChanges();let I={dispose(){E.removeObserver(ne)}};return N instanceof h.DisposableStore?N.add(I):Array.isArray(N)&&N.push(I),I}}})(p||(n.Event=p={}));class b{static{this.all=new Set}static{this._idPool=0}constructor(P){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${P}_${b._idPool++}`,b.all.add(this)}start(P){this._stopWatch=new d.StopWatch,this.listenerCount=P}stop(){if(this._stopWatch){let P=this._stopWatch.elapsed();this.durations.push(P),this.elapsedOverall+=P,this.invocationCount+=1,this._stopWatch=void 0}}}n.EventProfiling=b;let c=-1;class v{static{this._idPool=1}constructor(P,F,V=(v._idPool++).toString(16).padStart(3,"0")){this._errorHandler=P,this.threshold=F,this.name=V,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(P,F){let V=this.threshold;if(V<=0||F<V)return;this._stacks||(this._stacks=new Map);let Z=this._stacks.get(P.value)||0;if(this._stacks.set(P.value,Z+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*V;let[Y,j]=this.getMostFrequentStack(),S=`[${this.name}] potential listener LEAK detected, having ${F} listeners already. MOST frequent listener (${j}):`;console.warn(S),console.warn(Y);let T=new f(S,Y);this._errorHandler(T)}return()=>{let Y=this._stacks.get(P.value)||0;this._stacks.set(P.value,Y-1)}}getMostFrequentStack(){if(!this._stacks)return;let P,F=0;for(let[V,Z]of this._stacks)(!P||F<Z)&&(P=[V,Z],F=Z);return P}}class g{static create(){let P=new Error;return new g(P.stack??"")}constructor(P){this.value=P}print(){console.warn(this.value.split(`
71
71
  `).slice(2).join(`
72
- `))}}class f extends Error{constructor(P,F){super(P),this.name="ListenerLeakError",this.stack=F}}n.ListenerLeakError=f;class m extends Error{constructor(P,F){super(P),this.name="ListenerRefusalError",this.stack=F}}n.ListenerRefusalError=m;let w=0;class C{constructor(P){this.value=P,this.id=w++}}class k{constructor(P){this._size=0,this._options=P,this._leakageMon=c>0||this._options?.leakWarningThreshold?new v(P?.onListenerError??u.onUnexpectedError,this._options?.leakWarningThreshold??c):void 0,this._perfMon=this._options?._profName?new b(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(P,F,V)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let S=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(S);let T=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],E=new m(`${S}. HINT: Stack shows most frequent listener (${T[1]}-times)`,T[0]);return(this._options?.onListenerError||u.onUnexpectedError)(E),h.Disposable.None}if(this._disposed)return h.Disposable.None;F&&(P=P.bind(F));let Z=new C(P),Y;this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(Z.stack=g.create(),Y=this._leakageMon.check(Z.stack,this._size+1)),this._listeners?this._listeners instanceof C?(this._deliveryQueue??=new A,this._listeners=[this._listeners,Z]):this._listeners.push(Z):(this._options?.onWillAddFirstListener?.(this),this._listeners=Z,this._options?.onDidAddFirstListener?.(this)),this._size++;let j=(0,h.toDisposable)((()=>{Y?.(),this._removeListener(Z)}));return V instanceof h.DisposableStore?V.add(j):Array.isArray(V)&&V.push(j),j},this._event}_removeListener(P){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1)return this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),void(this._size=0);let F=this._listeners,V=F.indexOf(P);if(V===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,F[V]=void 0;let Z=this._deliveryQueue.current===this;if(2*this._size<=F.length){let Y=0;for(let j=0;j<F.length;j++)F[j]?F[Y++]=F[j]:Z&&(this._deliveryQueue.end--,Y<this._deliveryQueue.i&&this._deliveryQueue.i--);F.length=Y}}_deliver(P,F){if(!P)return;let V=this._options?.onListenerError||u.onUnexpectedError;if(V)try{P.value(F)}catch(Z){V(Z)}else P.value(F)}_deliverQueue(P){let F=P.current._listeners;for(;P.i<P.end;)this._deliver(F[P.i++],P.value);P.reset()}fire(P){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof C)this._deliver(this._listeners,P);else{let F=this._deliveryQueue;F.enqueue(this,P,this._listeners.length),this._deliverQueue(F)}this._perfMon?.stop()}hasListeners(){return this._size>0}}n.Emitter=k,n.createEventDeliveryQueue=()=>new A;class A{constructor(){this.i=-1,this.end=0}enqueue(P,F,V){this.i=0,this.end=V,this.current=P,this.value=F}reset(){this.i=this.end,this.current=void 0,this.value=void 0}}n.AsyncEmitter=class extends k{async fireAsync(R,P,F){if(this._listeners)for(this._asyncDeliveryQueue||(this._asyncDeliveryQueue=new _.LinkedList),((V,Z)=>{if(V instanceof C)Z(V);else for(let Y=0;Y<V.length;Y++){let j=V[Y];j&&Z(j)}})(this._listeners,(V=>this._asyncDeliveryQueue.push([V.value,R])));this._asyncDeliveryQueue.size>0&&!P.isCancellationRequested;){let[V,Z]=this._asyncDeliveryQueue.shift(),Y=[],j={...Z,token:P,waitUntil:S=>{if(Object.isFrozen(Y))throw new Error("waitUntil can NOT be called asynchronous");F&&(S=F(S,V)),Y.push(S)}};try{V(j)}catch(S){(0,u.onUnexpectedError)(S);continue}Object.freeze(Y),await Promise.allSettled(Y).then((S=>{for(let T of S)T.status==="rejected"&&(0,u.onUnexpectedError)(T.reason)}))}}};class D extends k{get isPaused(){return this._isPaused!==0}constructor(P){super(P),this._isPaused=0,this._eventQueue=new _.LinkedList,this._mergeFn=P?.merge}pause(){this._isPaused++}resume(){if(this._isPaused!==0&&--this._isPaused==0)if(this._mergeFn){if(this._eventQueue.size>0){let P=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(P))}}else for(;!this._isPaused&&this._eventQueue.size!==0;)super.fire(this._eventQueue.shift())}fire(P){this._size&&(this._isPaused!==0?this._eventQueue.push(P):super.fire(P))}}n.PauseableEmitter=D,n.DebounceEmitter=class extends D{constructor(R){super(R),this._delay=R.delay??100}fire(R){this._handle||(this.pause(),this._handle=setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(R)}},n.MicrotaskEmitter=class extends k{constructor(R){super(R),this._queuedEvents=[],this._mergeFn=R?.merge}fire(R){this.hasListeners()&&(this._queuedEvents.push(R),this._queuedEvents.length===1&&queueMicrotask((()=>{this._mergeFn?super.fire(this._mergeFn(this._queuedEvents)):this._queuedEvents.forEach((P=>super.fire(P))),this._queuedEvents=[]})))}};class O{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new k({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(P){let F={event:P,listener:null};return this.events.push(F),this.hasListeners&&this.hook(F),(0,h.toDisposable)((0,y.createSingleCallFunction)((()=>{this.hasListeners&&this.unhook(F);let V=this.events.indexOf(F);this.events.splice(V,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((P=>this.hook(P)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((P=>this.unhook(P)))}hook(P){P.listener=P.event((F=>this.emitter.fire(F)))}unhook(P){P.listener?.dispose(),P.listener=null}dispose(){this.emitter.dispose();for(let P of this.events)P.listener?.dispose();this.events=[]}}n.EventMultiplexer=O,n.DynamicListEventMultiplexer=class{constructor(R,P,F,V){this._store=new h.DisposableStore;let Z=this._store.add(new O),Y=this._store.add(new h.DisposableMap);function j(S){Y.set(S,Z.add(V(S)))}for(let S of R)j(S);this._store.add(P((S=>{j(S)}))),this._store.add(F((S=>{Y.deleteAndDispose(S)}))),this.event=Z.event}dispose(){this._store.dispose()}},n.EventBufferer=class{constructor(){this.data=[]}wrapEvent(R,P,F){return(V,Z,Y)=>R((j=>{let S=this.data[this.data.length-1];if(!P)return void(S?S.buffers.push((()=>V.call(Z,j))):V.call(Z,j));let T=S;T?(T.items??=[],T.items.push(j),T.buffers.length===0&&S.buffers.push((()=>{T.reducedResult??=F?T.items.reduce(P,F):T.items.reduce(P),V.call(Z,T.reducedResult)}))):V.call(Z,P(F,j))}),void 0,Y)}bufferEvents(R){let P={buffers:new Array};this.data.push(P);let F=R();return this.data.pop(),P.buffers.forEach((V=>V())),F}},n.Relay=class{constructor(){this.listening=!1,this.inputEvent=p.None,this.inputEventListener=h.Disposable.None,this.emitter=new k({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(R){this.inputEvent=R,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=R(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}},n.ValueWithChangeEvent=class{static const(R){return new L(R)}constructor(R){this._value=R,this._onDidChange=new k,this.onDidChange=this._onDidChange.event}get value(){return this._value}set value(R){R!==this._value&&(this._value=R,this._onDidChange.fire(void 0))}};class L{constructor(P){this.value=P,this.onDidChange=p.None}}},8841:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createSingleCallFunction=function(l,u){let y=this,h,_=!1;return function(){if(_)return h;if(_=!0,u)try{h=l.apply(y,arguments)}finally{u()}else h=l.apply(y,arguments);return h}}},4218:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.Iterable=void 0,(function(u){function y(d){return d&&typeof d=="object"&&typeof d[Symbol.iterator]=="function"}u.is=y;let h=Object.freeze([]);function*_(d){yield d}u.empty=function(){return h},u.single=_,u.wrap=function(d){return y(d)?d:_(d)},u.from=function(d){return d||h},u.reverse=function*(d){for(let p=d.length-1;p>=0;p--)yield d[p]},u.isEmpty=function(d){return!d||d[Symbol.iterator]().next().done===!0},u.first=function(d){return d[Symbol.iterator]().next().value},u.some=function(d,p){let b=0;for(let c of d)if(p(c,b++))return!0;return!1},u.find=function(d,p){for(let b of d)if(p(b))return b},u.filter=function*(d,p){for(let b of d)p(b)&&(yield b)},u.map=function*(d,p){let b=0;for(let c of d)yield p(c,b++)},u.flatMap=function*(d,p){let b=0;for(let c of d)yield*p(c,b++)},u.concat=function*(...d){for(let p of d)yield*p},u.reduce=function(d,p,b){let c=b;for(let v of d)c=p(c,v);return c},u.slice=function*(d,p,b=d.length){for(p<0&&(p+=d.length),b<0?b+=d.length:b>d.length&&(b=d.length);p<b;p++)yield d[p]},u.consume=function(d,p=Number.POSITIVE_INFINITY){let b=[];if(p===0)return[b,d];let c=d[Symbol.iterator]();for(let v=0;v<p;v++){let g=c.next();if(g.done)return[b,u.empty()];b.push(g.value)}return[b,{[Symbol.iterator]:()=>c}]},u.asyncToArray=async function(d){let p=[];for await(let b of d)p.push(b);return Promise.resolve(p)}})(l||(n.Iterable=l={}))},7150:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DisposableMap=n.ImmortalReference=n.AsyncReferenceCollection=n.ReferenceCollection=n.SafeDisposable=n.RefCountedDisposable=n.MandatoryMutableDisposable=n.MutableDisposable=n.Disposable=n.DisposableStore=n.DisposableTracker=void 0,n.setDisposableTracker=function(O){p=O},n.trackDisposable=c,n.markAsDisposed=v,n.markAsSingleton=function(O){return p?.markAsSingleton(O),O},n.isDisposable=f,n.dispose=m,n.disposeIfDisposable=function(O){for(let L of O)f(L)&&L.dispose();return[]},n.combinedDisposable=function(...O){let L=w((()=>m(O)));return(function(R,P){if(p)for(let F of R)p.setParent(F,P)})(O,L),L},n.toDisposable=w,n.disposeOnReturn=function(O){let L=new C;try{O(L)}finally{L.dispose()}};let u=l(3058),y=l(9087),h=l(2608),_=l(8841),d=l(4218),p=null;class b{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(L){let R=this.livingDisposables.get(L);return R||(R={parent:null,source:null,isSingleton:!1,value:L,idx:b.idx++},this.livingDisposables.set(L,R)),R}trackDisposable(L){let R=this.getDisposableData(L);R.source||(R.source=new Error().stack)}setParent(L,R){this.getDisposableData(L).parent=R}markAsDisposed(L){this.livingDisposables.delete(L)}markAsSingleton(L){this.getDisposableData(L).isSingleton=!0}getRootParent(L,R){let P=R.get(L);if(P)return P;let F=L.parent?this.getRootParent(this.getDisposableData(L.parent),R):L;return R.set(L,F),F}getTrackedDisposables(){let L=new Map;return[...this.livingDisposables.entries()].filter((([,R])=>R.source!==null&&!this.getRootParent(R,L).isSingleton)).flatMap((([R])=>R))}computeLeakingDisposables(L=10,R){let P;if(R)P=R;else{let j=new Map,S=[...this.livingDisposables.values()].filter((E=>E.source!==null&&!this.getRootParent(E,j).isSingleton));if(S.length===0)return;let T=new Set(S.map((E=>E.value)));if(P=S.filter((E=>!(E.parent&&T.has(E.parent)))),P.length===0)throw new Error("There are cyclic diposable chains!")}if(!P)return;function F(j){let S=j.source.split(`
72
+ `))}}class f extends Error{constructor(P,F){super(P),this.name="ListenerLeakError",this.stack=F}}n.ListenerLeakError=f;class m extends Error{constructor(P,F){super(P),this.name="ListenerRefusalError",this.stack=F}}n.ListenerRefusalError=m;let w=0;class C{constructor(P){this.value=P,this.id=w++}}class k{constructor(P){this._size=0,this._options=P,this._leakageMon=c>0||this._options?.leakWarningThreshold?new v(P?.onListenerError??u.onUnexpectedError,this._options?.leakWarningThreshold??c):void 0,this._perfMon=this._options?._profName?new b(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(P,F,V)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let S=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(S);let T=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],E=new m(`${S}. HINT: Stack shows most frequent listener (${T[1]}-times)`,T[0]);return(this._options?.onListenerError||u.onUnexpectedError)(E),h.Disposable.None}if(this._disposed)return h.Disposable.None;F&&(P=P.bind(F));let Z=new C(P),Y;this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(Z.stack=g.create(),Y=this._leakageMon.check(Z.stack,this._size+1)),this._listeners?this._listeners instanceof C?(this._deliveryQueue??=new A,this._listeners=[this._listeners,Z]):this._listeners.push(Z):(this._options?.onWillAddFirstListener?.(this),this._listeners=Z,this._options?.onDidAddFirstListener?.(this)),this._size++;let j=(0,h.toDisposable)((()=>{Y?.(),this._removeListener(Z)}));return V instanceof h.DisposableStore?V.add(j):Array.isArray(V)&&V.push(j),j},this._event}_removeListener(P){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1)return this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),void(this._size=0);let F=this._listeners,V=F.indexOf(P);if(V===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,F[V]=void 0;let Z=this._deliveryQueue.current===this;if(2*this._size<=F.length){let Y=0;for(let j=0;j<F.length;j++)F[j]?F[Y++]=F[j]:Z&&(this._deliveryQueue.end--,Y<this._deliveryQueue.i&&this._deliveryQueue.i--);F.length=Y}}_deliver(P,F){if(!P)return;let V=this._options?.onListenerError||u.onUnexpectedError;if(V)try{P.value(F)}catch(Z){V(Z)}else P.value(F)}_deliverQueue(P){let F=P.current._listeners;for(;P.i<P.end;)this._deliver(F[P.i++],P.value);P.reset()}fire(P){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof C)this._deliver(this._listeners,P);else{let F=this._deliveryQueue;F.enqueue(this,P,this._listeners.length),this._deliverQueue(F)}this._perfMon?.stop()}hasListeners(){return this._size>0}}n.Emitter=k,n.createEventDeliveryQueue=()=>new A;class A{constructor(){this.i=-1,this.end=0}enqueue(P,F,V){this.i=0,this.end=V,this.current=P,this.value=F}reset(){this.i=this.end,this.current=void 0,this.value=void 0}}n.AsyncEmitter=class extends k{async fireAsync(R,P,F){if(this._listeners)for(this._asyncDeliveryQueue||(this._asyncDeliveryQueue=new _.LinkedList),((V,Z)=>{if(V instanceof C)Z(V);else for(let Y=0;Y<V.length;Y++){let j=V[Y];j&&Z(j)}})(this._listeners,(V=>this._asyncDeliveryQueue.push([V.value,R])));this._asyncDeliveryQueue.size>0&&!P.isCancellationRequested;){let[V,Z]=this._asyncDeliveryQueue.shift(),Y=[],j={...Z,token:P,waitUntil:S=>{if(Object.isFrozen(Y))throw new Error("waitUntil can NOT be called asynchronous");F&&(S=F(S,V)),Y.push(S)}};try{V(j)}catch(S){(0,u.onUnexpectedError)(S);continue}Object.freeze(Y),await Promise.allSettled(Y).then((S=>{for(let T of S)T.status==="rejected"&&(0,u.onUnexpectedError)(T.reason)}))}}};class O extends k{get isPaused(){return this._isPaused!==0}constructor(P){super(P),this._isPaused=0,this._eventQueue=new _.LinkedList,this._mergeFn=P?.merge}pause(){this._isPaused++}resume(){if(this._isPaused!==0&&--this._isPaused==0)if(this._mergeFn){if(this._eventQueue.size>0){let P=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(P))}}else for(;!this._isPaused&&this._eventQueue.size!==0;)super.fire(this._eventQueue.shift())}fire(P){this._size&&(this._isPaused!==0?this._eventQueue.push(P):super.fire(P))}}n.PauseableEmitter=O,n.DebounceEmitter=class extends O{constructor(R){super(R),this._delay=R.delay??100}fire(R){this._handle||(this.pause(),this._handle=setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(R)}},n.MicrotaskEmitter=class extends k{constructor(R){super(R),this._queuedEvents=[],this._mergeFn=R?.merge}fire(R){this.hasListeners()&&(this._queuedEvents.push(R),this._queuedEvents.length===1&&queueMicrotask((()=>{this._mergeFn?super.fire(this._mergeFn(this._queuedEvents)):this._queuedEvents.forEach((P=>super.fire(P))),this._queuedEvents=[]})))}};class D{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new k({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(P){let F={event:P,listener:null};return this.events.push(F),this.hasListeners&&this.hook(F),(0,h.toDisposable)((0,y.createSingleCallFunction)((()=>{this.hasListeners&&this.unhook(F);let V=this.events.indexOf(F);this.events.splice(V,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((P=>this.hook(P)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((P=>this.unhook(P)))}hook(P){P.listener=P.event((F=>this.emitter.fire(F)))}unhook(P){P.listener?.dispose(),P.listener=null}dispose(){this.emitter.dispose();for(let P of this.events)P.listener?.dispose();this.events=[]}}n.EventMultiplexer=D,n.DynamicListEventMultiplexer=class{constructor(R,P,F,V){this._store=new h.DisposableStore;let Z=this._store.add(new D),Y=this._store.add(new h.DisposableMap);function j(S){Y.set(S,Z.add(V(S)))}for(let S of R)j(S);this._store.add(P((S=>{j(S)}))),this._store.add(F((S=>{Y.deleteAndDispose(S)}))),this.event=Z.event}dispose(){this._store.dispose()}},n.EventBufferer=class{constructor(){this.data=[]}wrapEvent(R,P,F){return(V,Z,Y)=>R((j=>{let S=this.data[this.data.length-1];if(!P)return void(S?S.buffers.push((()=>V.call(Z,j))):V.call(Z,j));let T=S;T?(T.items??=[],T.items.push(j),T.buffers.length===0&&S.buffers.push((()=>{T.reducedResult??=F?T.items.reduce(P,F):T.items.reduce(P),V.call(Z,T.reducedResult)}))):V.call(Z,P(F,j))}),void 0,Y)}bufferEvents(R){let P={buffers:new Array};this.data.push(P);let F=R();return this.data.pop(),P.buffers.forEach((V=>V())),F}},n.Relay=class{constructor(){this.listening=!1,this.inputEvent=p.None,this.inputEventListener=h.Disposable.None,this.emitter=new k({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(R){this.inputEvent=R,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=R(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}},n.ValueWithChangeEvent=class{static const(R){return new L(R)}constructor(R){this._value=R,this._onDidChange=new k,this.onDidChange=this._onDidChange.event}get value(){return this._value}set value(R){R!==this._value&&(this._value=R,this._onDidChange.fire(void 0))}};class L{constructor(P){this.value=P,this.onDidChange=p.None}}},8841:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createSingleCallFunction=function(l,u){let y=this,h,_=!1;return function(){if(_)return h;if(_=!0,u)try{h=l.apply(y,arguments)}finally{u()}else h=l.apply(y,arguments);return h}}},4218:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.Iterable=void 0,(function(u){function y(d){return d&&typeof d=="object"&&typeof d[Symbol.iterator]=="function"}u.is=y;let h=Object.freeze([]);function*_(d){yield d}u.empty=function(){return h},u.single=_,u.wrap=function(d){return y(d)?d:_(d)},u.from=function(d){return d||h},u.reverse=function*(d){for(let p=d.length-1;p>=0;p--)yield d[p]},u.isEmpty=function(d){return!d||d[Symbol.iterator]().next().done===!0},u.first=function(d){return d[Symbol.iterator]().next().value},u.some=function(d,p){let b=0;for(let c of d)if(p(c,b++))return!0;return!1},u.find=function(d,p){for(let b of d)if(p(b))return b},u.filter=function*(d,p){for(let b of d)p(b)&&(yield b)},u.map=function*(d,p){let b=0;for(let c of d)yield p(c,b++)},u.flatMap=function*(d,p){let b=0;for(let c of d)yield*p(c,b++)},u.concat=function*(...d){for(let p of d)yield*p},u.reduce=function(d,p,b){let c=b;for(let v of d)c=p(c,v);return c},u.slice=function*(d,p,b=d.length){for(p<0&&(p+=d.length),b<0?b+=d.length:b>d.length&&(b=d.length);p<b;p++)yield d[p]},u.consume=function(d,p=Number.POSITIVE_INFINITY){let b=[];if(p===0)return[b,d];let c=d[Symbol.iterator]();for(let v=0;v<p;v++){let g=c.next();if(g.done)return[b,u.empty()];b.push(g.value)}return[b,{[Symbol.iterator]:()=>c}]},u.asyncToArray=async function(d){let p=[];for await(let b of d)p.push(b);return Promise.resolve(p)}})(l||(n.Iterable=l={}))},7150:(a,n,l)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DisposableMap=n.ImmortalReference=n.AsyncReferenceCollection=n.ReferenceCollection=n.SafeDisposable=n.RefCountedDisposable=n.MandatoryMutableDisposable=n.MutableDisposable=n.Disposable=n.DisposableStore=n.DisposableTracker=void 0,n.setDisposableTracker=function(D){p=D},n.trackDisposable=c,n.markAsDisposed=v,n.markAsSingleton=function(D){return p?.markAsSingleton(D),D},n.isDisposable=f,n.dispose=m,n.disposeIfDisposable=function(D){for(let L of D)f(L)&&L.dispose();return[]},n.combinedDisposable=function(...D){let L=w((()=>m(D)));return(function(R,P){if(p)for(let F of R)p.setParent(F,P)})(D,L),L},n.toDisposable=w,n.disposeOnReturn=function(D){let L=new C;try{D(L)}finally{L.dispose()}};let u=l(3058),y=l(9087),h=l(2608),_=l(8841),d=l(4218),p=null;class b{constructor(){this.livingDisposables=new Map}static{this.idx=0}getDisposableData(L){let R=this.livingDisposables.get(L);return R||(R={parent:null,source:null,isSingleton:!1,value:L,idx:b.idx++},this.livingDisposables.set(L,R)),R}trackDisposable(L){let R=this.getDisposableData(L);R.source||(R.source=new Error().stack)}setParent(L,R){this.getDisposableData(L).parent=R}markAsDisposed(L){this.livingDisposables.delete(L)}markAsSingleton(L){this.getDisposableData(L).isSingleton=!0}getRootParent(L,R){let P=R.get(L);if(P)return P;let F=L.parent?this.getRootParent(this.getDisposableData(L.parent),R):L;return R.set(L,F),F}getTrackedDisposables(){let L=new Map;return[...this.livingDisposables.entries()].filter((([,R])=>R.source!==null&&!this.getRootParent(R,L).isSingleton)).flatMap((([R])=>R))}computeLeakingDisposables(L=10,R){let P;if(R)P=R;else{let j=new Map,S=[...this.livingDisposables.values()].filter((E=>E.source!==null&&!this.getRootParent(E,j).isSingleton));if(S.length===0)return;let T=new Set(S.map((E=>E.value)));if(P=S.filter((E=>!(E.parent&&T.has(E.parent)))),P.length===0)throw new Error("There are cyclic diposable chains!")}if(!P)return;function F(j){let S=j.source.split(`
73
73
  `).map((T=>T.trim().replace("at ",""))).filter((T=>T!==""));return(function(T,E){for(;T.length>0&&E.some((x=>typeof x=="string"?x===T[0]:T[0].match(x)));)T.shift()})(S,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),S.reverse()}let V=new h.SetMap;for(let j of P){let S=F(j);for(let T=0;T<=S.length;T++)V.add(S.slice(0,T).join(`
74
74
  `),j)}P.sort((0,u.compareBy)((j=>j.idx),u.numberComparator));let Z="",Y=0;for(let j of P.slice(0,L)){Y++;let S=F(j),T=[];for(let E=0;E<S.length;E++){let x=S[E];x=`(shared with ${V.get(S.slice(0,E+1).join(`
75
75
  `)).size}/${P.length} leaks) at ${x}`;let M=V.get(S.slice(0,E).join(`
76
- `)),N=(0,y.groupBy)([...M].map((U=>F(U)[E])),(U=>U));delete N[S[E]];for(let[U,z]of Object.entries(N))T.unshift(` - stacktraces of ${z.length} other leaks continue with ${U}`);T.unshift(x)}Z+=`
76
+ `)),N=(0,y.groupBy)([...M].map((H=>F(H)[E])),(H=>H));delete N[S[E]];for(let[H,z]of Object.entries(N))T.unshift(` - stacktraces of ${z.length} other leaks continue with ${H}`);T.unshift(x)}Z+=`
77
77
 
78
78
 
79
79
  ==================== Leaking disposable ${Y}/${P.length}: ${j.value.constructor.name} ====================
@@ -86,52 +86,54 @@ ${T.join(`
86
86
 
87
87
  ... and ${P.length-L} more leaking disposables
88
88
 
89
- `),{leaks:P,details:Z}}}function c(O){return p?.trackDisposable(O),O}function v(O){p?.markAsDisposed(O)}function g(O,L){p?.setParent(O,L)}function f(O){return typeof O=="object"&&O!==null&&typeof O.dispose=="function"&&O.dispose.length===0}function m(O){if(d.Iterable.is(O)){let L=[];for(let R of O)if(R)try{R.dispose()}catch(P){L.push(P)}if(L.length===1)throw L[0];if(L.length>1)throw new AggregateError(L,"Encountered errors while disposing of store");return Array.isArray(O)?[]:O}if(O)return O.dispose(),O}function w(O){let L=c({dispose:(0,_.createSingleCallFunction)((()=>{v(L),O()}))});return L}n.DisposableTracker=b;class C{static{this.DISABLE_DISPOSED_WARNING=!1}constructor(){this._toDispose=new Set,this._isDisposed=!1,c(this)}dispose(){this._isDisposed||(v(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{m(this._toDispose)}finally{this._toDispose.clear()}}add(L){if(!L)return L;if(L===this)throw new Error("Cannot register a disposable on itself!");return g(L,this),this._isDisposed?C.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(L),L}delete(L){if(L){if(L===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(L),L.dispose()}}deleteAndLeak(L){L&&this._toDispose.has(L)&&(this._toDispose.delete(L),g(L,null))}}n.DisposableStore=C;class k{static{this.None=Object.freeze({dispose(){}})}constructor(){this._store=new C,c(this),g(this._store,this)}dispose(){v(this),this._store.dispose()}_register(L){if(L===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(L)}}n.Disposable=k;class A{constructor(){this._isDisposed=!1,c(this)}get value(){return this._isDisposed?void 0:this._value}set value(L){this._isDisposed||L===this._value||(this._value?.dispose(),L&&g(L,this),this._value=L)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,v(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let L=this._value;return this._value=void 0,L&&g(L,null),L}}n.MutableDisposable=A,n.MandatoryMutableDisposable=class{constructor(O){this._disposable=new A,this._isDisposed=!1,this._disposable.value=O}get value(){return this._disposable.value}set value(O){this._isDisposed||O===this._disposable.value||(this._disposable.value=O)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},n.RefCountedDisposable=class{constructor(O){this._disposable=O,this._counter=1}acquire(){return this._counter++,this}release(){return--this._counter==0&&this._disposable.dispose(),this}},n.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,c(this)}set(O){let L=O;return this.unset=()=>L=void 0,this.isset=()=>L!==void 0,this.dispose=()=>{L&&(L(),L=void 0,v(this))},this}},n.ReferenceCollection=class{constructor(){this.references=new Map}acquire(O,...L){let R=this.references.get(O);R||(R={counter:0,object:this.createReferencedObject(O,...L)},this.references.set(O,R));let{object:P}=R,F=(0,_.createSingleCallFunction)((()=>{--R.counter==0&&(this.destroyReferencedObject(O,R.object),this.references.delete(O))}));return R.counter++,{object:P,dispose:F}}},n.AsyncReferenceCollection=class{constructor(O){this.referenceCollection=O}async acquire(O,...L){let R=this.referenceCollection.acquire(O,...L);try{return{object:await R.object,dispose:()=>R.dispose()}}catch(P){throw R.dispose(),P}}},n.ImmortalReference=class{constructor(O){this.object=O}dispose(){}};class D{constructor(){this._store=new Map,this._isDisposed=!1,c(this)}dispose(){v(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{m(this._store.values())}finally{this._store.clear()}}has(L){return this._store.has(L)}get size(){return this._store.size}get(L){return this._store.get(L)}set(L,R,P=!1){this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),P||this._store.get(L)?.dispose(),this._store.set(L,R)}deleteAndDispose(L){this._store.get(L)?.dispose(),this._store.delete(L)}deleteAndLeak(L){let R=this._store.get(L);return this._store.delete(L),R}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}n.DisposableMap=D},6317:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.LinkedList=void 0;class l{static{this.Undefined=new l(void 0)}constructor(h){this.element=h,this.next=l.Undefined,this.prev=l.Undefined}}class u{constructor(){this._first=l.Undefined,this._last=l.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===l.Undefined}clear(){let h=this._first;for(;h!==l.Undefined;){let _=h.next;h.prev=l.Undefined,h.next=l.Undefined,h=_}this._first=l.Undefined,this._last=l.Undefined,this._size=0}unshift(h){return this._insert(h,!1)}push(h){return this._insert(h,!0)}_insert(h,_){let d=new l(h);if(this._first===l.Undefined)this._first=d,this._last=d;else if(_){let b=this._last;this._last=d,d.prev=b,b.next=d}else{let b=this._first;this._first=d,d.next=b,b.prev=d}this._size+=1;let p=!1;return()=>{p||(p=!0,this._remove(d))}}shift(){if(this._first!==l.Undefined){let h=this._first.element;return this._remove(this._first),h}}pop(){if(this._last!==l.Undefined){let h=this._last.element;return this._remove(this._last),h}}_remove(h){if(h.prev!==l.Undefined&&h.next!==l.Undefined){let _=h.prev;_.next=h.next,h.next.prev=_}else h.prev===l.Undefined&&h.next===l.Undefined?(this._first=l.Undefined,this._last=l.Undefined):h.next===l.Undefined?(this._last=this._last.prev,this._last.next=l.Undefined):h.prev===l.Undefined&&(this._first=this._first.next,this._first.prev=l.Undefined);this._size-=1}*[Symbol.iterator](){let h=this._first;for(;h!==l.Undefined;)yield h.element,h=h.next}}n.LinkedList=u},2608:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.SetMap=n.BidirectionalMap=n.CounterSet=n.Touch=void 0,n.getOrSet=function(u,y,h){let _=u.get(y);return _===void 0&&(_=h,u.set(y,_)),_},n.mapToString=function(u){let y=[];return u.forEach(((h,_)=>{y.push(`${_} => ${h}`)})),`Map(${u.size}) {${y.join(", ")}}`},n.setToString=function(u){let y=[];return u.forEach((h=>{y.push(h)})),`Set(${u.size}) {${y.join(", ")}}`},n.mapsStrictEqualIgnoreOrder=function(u,y){if(u===y)return!0;if(u.size!==y.size)return!1;for(let[h,_]of u)if(!y.has(h)||y.get(h)!==_)return!1;for(let[h]of y)if(!u.has(h))return!1;return!0},(function(u){u[u.None=0]="None",u[u.AsOld=1]="AsOld",u[u.AsNew=2]="AsNew"})(l||(n.Touch=l={})),n.CounterSet=class{constructor(){this.map=new Map}add(u){return this.map.set(u,(this.map.get(u)||0)+1),this}delete(u){let y=this.map.get(u)||0;return y!==0&&(y--,y===0?this.map.delete(u):this.map.set(u,y),!0)}has(u){return this.map.has(u)}},n.BidirectionalMap=class{constructor(u){if(this._m1=new Map,this._m2=new Map,u)for(let[y,h]of u)this.set(y,h)}clear(){this._m1.clear(),this._m2.clear()}set(u,y){this._m1.set(u,y),this._m2.set(y,u)}get(u){return this._m1.get(u)}getKey(u){return this._m2.get(u)}delete(u){let y=this._m1.get(u);return y!==void 0&&(this._m1.delete(u),this._m2.delete(y),!0)}forEach(u,y){this._m1.forEach(((h,_)=>{u.call(y,h,_,this)}))}keys(){return this._m1.keys()}values(){return this._m1.values()}},n.SetMap=class{constructor(){this.map=new Map}add(u,y){let h=this.map.get(u);h||(h=new Set,this.map.set(u,h)),h.add(y)}delete(u,y){let h=this.map.get(u);h&&(h.delete(y),h.size===0&&this.map.delete(u))}forEach(u,y){let h=this.map.get(u);h&&h.forEach(y)}get(u){return this.map.get(u)||new Set}}},9725:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.StopWatch=void 0;let l=globalThis.performance&&typeof globalThis.performance.now=="function";class u{static create(h){return new u(h)}constructor(h){this._now=l&&h===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}}n.StopWatch=u}},e={};function r(a){var n=e[a];if(n!==void 0)return n.exports;var l=e[a]={exports:{}};return t[a].call(l.exports,l,l.exports,r),l.exports}var s={};(()=>{var a=s;Object.defineProperty(a,"__esModule",{value:!0}),a.Terminal=void 0;let n=r(5101),l=r(6097),u=r(4335),y=r(5856),h=r(3027),_=r(7150),d=["cols","rows"];class p extends _.Disposable{constructor(c){super(),this._core=this._register(new y.Terminal(c)),this._addonManager=this._register(new h.AddonManager),this._publicOptions={...this._core.options};let v=f=>this._core.options[f],g=(f,m)=>{this._checkReadonlyOptions(f),this._core.options[f]=m};for(let f in this._core.options){Object.defineProperty(this._publicOptions,f,{get:()=>this._core.options[f],set:w=>{this._checkReadonlyOptions(f),this._core.options[f]=w}});let m={get:v.bind(this,f),set:g.bind(this,f)};Object.defineProperty(this._publicOptions,f,m)}}_checkReadonlyOptions(c){if(d.includes(c))throw new Error(`Option "${c}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get parser(){return this._checkProposedApi(),this._parser||(this._parser=new l.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new u.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||(this._buffer=this._register(new n.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let c=this._core.coreService.decPrivateModes,v="none";switch(this._core.coreMouseService.activeProtocol){case"X10":v="x10";break;case"VT200":v="vt200";break;case"DRAG":v="drag";break;case"ANY":v="any"}return{applicationCursorKeysMode:c.applicationCursorKeys,applicationKeypadMode:c.applicationKeypad,bracketedPasteMode:c.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:v,originMode:c.origin,reverseWraparoundMode:c.reverseWraparound,sendFocusMode:c.sendFocus,synchronizedOutputMode:c.synchronizedOutput,wraparoundMode:c.wraparound}}get options(){return this._publicOptions}set options(c){for(let v in c)this._publicOptions[v]=c[v]}input(c,v=!0){this._core.input(c,v)}resize(c,v){this._verifyIntegers(c,v),this._core.resize(c,v)}registerMarker(c=0){return this._checkProposedApi(),this._verifyIntegers(c),this._core.addMarker(c)}addMarker(c){return this.registerMarker(c)}dispose(){super.dispose()}scrollLines(c){this._verifyIntegers(c),this._core.scrollLines(c)}scrollPages(c){this._verifyIntegers(c),this._core.scrollPages(c)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(c){this._verifyIntegers(c),this._core.scrollToLine(c)}clear(){this._core.clear()}write(c,v){this._core.write(c,v)}writeln(c,v){this._core.write(c),this._core.write(`\r
90
- `,v)}reset(){this._core.reset()}loadAddon(c){this._addonManager.loadAddon(this,c)}_verifyIntegers(...c){for(let v of c)if(v===1/0||isNaN(v)||v%1!=0)throw new Error("This API only accepts integers")}}a.Terminal=p})();var i=kh;for(var o in s)i[o]=s[o];s.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})()});function Nh(t){let r=t.trim().replace(/^v/,"").split(/[-+]/)[0].split(".").map(s=>Number.parseInt(s,10));return[r[0]||0,r[1]||0,r[2]||0]}function Hh(t,e){let r=Nh(t),s=Nh(e);for(let i=0;i<3;i++){if(r[i]>s[i])return!0;if(r[i]<s[i])return!1}return!1}var Uh=mt(()=>{"use strict"});var jh={};ns(jh,{isGlobalNpmInstall:()=>io,resolveGlobalRoot:()=>r0});import{execFile as Zg}from"child_process";import{promisify as Kg}from"util";import{realpathSync as Xg}from"fs";import{sep as Fh,relative as Qg,isAbsolute as e0}from"path";async function r0(){try{let{stdout:t}=await t0("npm",["root","-g"]);return Xg(t.trim())}catch{return}}function io(t,e,r){if(t==="0.0.0-dev"||!r)return!1;let s=`${r}${Fh}@hown${Fh}djinn`,i=Qg(s,e);return i===""||!i.startsWith("..")&&!e0(i)}var t0,no=mt(()=>{"use strict";t0=Kg(Zg)});var Wh={};ns(Wh,{runUpdate:()=>s0});async function s0(t){let e=await t.resolveGlobalRoot();if(!io(t.currentVersion,t.entryPath,e))return t.log("update \u4EC5\u9002\u7528\u4E8E npm \u5168\u5C40\u5B89\u88C5(npm i -g @hown/djinn)\u3002\u68C0\u6D4B\u5230\u4ECE\u6E90\u7801 / \u672C\u5730\u6784\u5EFA\u8FD0\u884C\u3002"),1;let r;try{r=await t.fetchLatest()}catch(s){return t.log(`\u67E5\u8BE2\u6700\u65B0\u7248\u5931\u8D25:${s instanceof Error?s.message:String(s)}`),1}if(!Hh(r,t.currentVersion))return t.log(`\u5DF2\u662F\u6700\u65B0 v${t.currentVersion}`),0;t.log(`\u53D1\u73B0\u65B0\u7248 v${r}(\u5F53\u524D v${t.currentVersion}),\u6B63\u5728\u66F4\u65B0\u2026`);try{await t.npmInstallLatest()}catch(s){return t.log(`\u66F4\u65B0\u5931\u8D25:${s instanceof Error?s.message:String(s)}`),1}t.log("\u66F4\u65B0\u5B8C\u6210,\u6B63\u5728\u91CD\u542F daemon \u4EE5\u542F\u7528\u65B0\u4EE3\u7801\u2026");try{t.supervisorInstalled()?await t.restartSupervised():await t.restartUnmanaged()}catch(s){return t.log(`daemon \u91CD\u542F\u5931\u8D25(\u53EF\u624B\u52A8 \`djinn daemon stop\` \u540E\u91CD\u8BD5):${s instanceof Error?s.message:String(s)}`),1}return t.log(`\u5DF2\u66F4\u65B0\u5230 v${r}`),0}var qh=mt(()=>{"use strict";Uh();no()});import{realpathSync as i0}from"fs";import{hostname as n0}from"os";import{resolve as $h}from"path";import{pathToFileURL as zh}from"url";var Qh="wss://unit00.top/djinn/relay";function oo(t=process.argv,e=process.env){let r=t[2],s=t.slice(3);switch(r){case"start":throw new Error("`djinn start` has been removed. Use `djinn new` instead.");case"pair":return{command:"pair",config:nu(s)};case"new":return{command:"new",config:tu(s,e)};case"attach":return{command:"attach",config:{sessionId:eu(s[0],"attach <sessionId>")}};case"ls":return{command:"ls",config:{}};case"project":return{command:"project",config:ru(s)};case"daemon":return{command:"daemon",config:{action:su(s[0])}};case"update":return{command:"update",config:{}};case"__worker":return{command:"__worker",config:iu(s)};default:throw new Error(`Unknown command: ${r??"(none)"}. Try: djinn new | attach | ls | pair | project | daemon | update`)}}function eu(t,e){if(!t)throw new Error(`missing argument: djinn ${e}`);return t}function tu(t,e){let r=t.indexOf("--"),s=r>=0?t.slice(0,r):t,i=r>=0?t.slice(r+1):[],o=u=>{let y=s.indexOf(u);return y>=0?s[y+1]:void 0},a=o("--adapter")??"claude-code",n=s.includes("--detach")||s.includes("-d"),l=o("--label");return{adapterId:a,detach:n,aiCliArgs:i,cwd:process.cwd(),server:o("--server")??e.DJINN_SERVER_URL??Qh,invite:o("--invite")??e.DJINN_INVITE,...l?{label:l}:{}}}function ru(t){let e=t[0];if(e!=="add"&&e!=="ls"&&e!=="rm")throw new Error("djinn project <add|ls|rm> [path]");if((e==="add"||e==="rm")&&!t[1])throw new Error(`djinn project ${e} <path>`);return e==="ls"?{action:e}:{action:e,path:t[1]}}function su(t){if(t==="run"||t==="run-detached"||t==="status"||t==="stop"||t==="install"||t==="uninstall")return t;throw new Error("djinn daemon <run|status|stop|install|uninstall>")}function iu(t){let e=t.indexOf("--"),r=e>=0?t.slice(0,e):t,s=e>=0?t.slice(e+1):[],i=_=>{let d=r.indexOf(_);return d>=0?r[d+1]:void 0},o=i("--session-id"),a=i("--cwd"),n=i("--adapter"),l=i("--mode");if(!o||!a||!n||l!=="new"&&l!=="resume")throw new Error("djinn __worker requires --session-id --cwd --adapter --mode <new|resume>");let u=i("--origin");if(u!==void 0&&u!=="local"&&u!=="remote")throw new Error("djinn __worker --origin must be <local|remote>");let y=u??"local",h=i("--label");return{sessionId:o,cwd:a,adapterId:n,mode:l,origin:y,aiCliArgs:s,...h?{label:h}:{}}}function nu(t){if(t.includes("--terminal")||t.includes("--no-png"))return{png:!1};let e=t.indexOf("--png");if(e!==-1){let r=t[e+1];if(r!==void 0&&!r.startsWith("--"))return{png:!0,pngPath:r}}return{png:!0}}import{existsSync as yu,mkdirSync as bu,readFileSync as wu,writeFileSync as Su}from"fs";import{homedir as uo}from"os";import{join as fo}from"path";ye();import{readFileSync as uu,writeFileSync as du,renameSync as fu,existsSync as pu,realpathSync as _u}from"fs";import{resolve as mu,relative as gu,isAbsolute as vu}from"path";function mi(t){let e=mu(t);try{return _u(e)}catch{return e}}function cs(t){let e=_i(t);return pu(e)?JSON.parse(uu(e,"utf8")).projects??[]:[]}function lo(t,e){Qe(t);let r=_i(t),s=`${r}.${process.pid}.tmp`;du(s,JSON.stringify({projects:e},null,2),{mode:384}),fu(s,r)}function Xt(t){return cs(t)}function ls(t,e,r){let s=mi(e),i=cs(t);i.some(o=>o.path===s)||lo(t,[...i,{path:s,label:r}])}function ho(t,e){let r=mi(e);lo(t,cs(t).filter(s=>s.path!==r))}function gi(t,e){let r=mi(e);return cs(t).some(s=>{if(r===s.path)return!0;let i=gu(s.path,r);return i!==""&&!i.startsWith("..")&&!vu(i)})}function po(){return fo(uo(),".djinn")}function _o(t){return fo(t,"identity.json")}function et(t){let e=_o(t);if(!yu(e))return;let r=wu(e,"utf8");return JSON.parse(r)}function Cu(t,e){bu(t,{recursive:!0,mode:448}),Su(_o(t),JSON.stringify(e,null,2),{mode:384})}async function mo(t){let e=et(t.dir);if(e)return e;if(!t.invite)throw new Error("No identity found. Pass --invite <CODE> (or DJINN_INVITE) to register this machine.");if(!t.serverUrl)throw new Error("First-run registration needs --server <url> (or DJINN_SERVER_URL).");let r=t.fetchImpl??fetch,s=vi(t.serverUrl),i=await r(`${s}/v1/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({invite_code:t.invite,label:t.label})});if(!i.ok)throw i.status===409?new Error("Registration failed: invite code is invalid or already used."):new Error(`Registration failed with status ${i.status}.`);let o=await i.json(),a={ownerId:o.owner_id,deviceId:o.device_id,token:o.token,serverUrl:o.server_url||t.serverUrl};return Cu(t.dir,a),Xt(t.dir).length===0&&ls(t.dir,uo()),a}function vi(t){return t.replace(/^ws/,"http").replace(/\/$/,"")}var un=Be(xc(),1);import{join as Wf}from"path";import{createHash as Ff,randomBytes as Lv,timingSafeEqual as Rv}from"crypto";var jf="sha256:";function hn(t){return`${jf}${Ff("sha256").update(t).digest("hex")}`}function qf(t,e){return Buffer.from(JSON.stringify({v:1,url:t,code:e}),"utf8").toString("base64url")}var kc=t=>new Promise(e=>setTimeout(e,t));async function $f(t){return un.default.toString(t,{type:"terminal",small:!1})}function zf(t,e){return un.default.toFile(e,t,{type:"png",width:600,margin:4,errorCorrectionLevel:"M"})}async function Vf(t){let{platform:e}=process,[r,s]=e==="darwin"?["open",[t]]:e==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let{spawn:i}=await import("child_process");await new Promise(o=>{let a=i(r,s,{stdio:"ignore",detached:!0});a.on("error",()=>o()),a.on("spawn",()=>{a.unref(),o()})})}catch{}}async function Tc(t){let e=t.out??(p=>process.stderr.write(`${p}
91
- `)),r=t.fetchImpl??fetch,s=t.printQr??$f,i=t.writeQrPng??zf,o=t.openFile??Vf,a=t.pollIntervalMs??1500,n=et(t.dir);if(!n)return e("\u672A\u627E\u5230\u8EAB\u4EFD\u3002\u8BF7\u5148\u8FD0\u884C djinn start --invite <CODE> \u6CE8\u518C\u672C\u673A\u3002"),1;let l=vi(n.serverUrl),u;try{u=await r(`${l}/v1/pairing`,{method:"POST",headers:{authorization:`Bearer ${n.token}`}})}catch(p){return e(`\u53D1\u8D77\u914D\u5BF9\u5931\u8D25\uFF1A\u65E0\u6CD5\u8FDE\u63A5 ${l}\uFF08${p instanceof Error?p.message:String(p)}\uFF09`),1}if(!u.ok)return e(`\u53D1\u8D77\u914D\u5BF9\u5931\u8D25\uFF1AHTTP ${u.status}`),1;let{code:y,expires_at_ms:h}=await u.json(),_=qf(l,y);if(t.png){let p=t.pngPath??Wf(process.cwd(),"djinn-pair-qr.png");await i(_,p);try{await o(p)}catch{}e(`\u4E8C\u7EF4\u7801\u5DF2\u4FDD\u5B58\u5230 ${p} \u5E76\u5C1D\u8BD5\u6253\u5F00\uFF0C\u8BF7\u7528\u624B\u673A djinn PWA \u626B\u7801\uFF0860 \u79D2\u5185\u6709\u6548\uFF09\u3002`),e("\uFF08\u82E5\u56FE\u7247\u6CA1\u81EA\u52A8\u6253\u5F00\uFF0C\u53EF\u626B\u63CF\u4E0B\u65B9\u7EC8\u7AEF\u4E8C\u7EF4\u7801\uFF0C\u6216\u7528 djinn pair --terminal \u53EA\u663E\u793A\u7EC8\u7AEF\u7801\u3002\uFF09"),e(await s(_))}else e(await s(_)),e("\u7528\u624B\u673A djinn PWA \u626B\u7801\uFF0860 \u79D2\u5185\u6709\u6548\uFF09\u3002");let d=encodeURIComponent(hn(y));for(;;){if(Date.now()>=h)return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;let p;try{p=await r(`${l}/v1/pairing/${d}/status`,{headers:{authorization:`Bearer ${n.token}`}})}catch{await kc(a);continue}if(p.status===404)return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;if(!p.ok)return e(`\u8F6E\u8BE2\u914D\u5BF9\u72B6\u6001\u5931\u8D25\uFF1AHTTP ${p.status}`),1;let{status:b}=await p.json();if(b==="consumed")return e("\u2713 \u624B\u673A\u5DF2\u914D\u5BF9\u3002"),0;if(b==="expired")return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;await kc(a)}}ye();xs();import{spawn as np}from"child_process";import{connect as op}from"net";function Lc(t){return new Promise(e=>{let r=op(qe(t)),s=i=>{r.destroy(),e(i)};r.on("connect",()=>r.write(JSON.stringify({cmd:"ping"})+`
92
- `)),r.on("data",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),300)})}async function Wr(t,e){if(await Lc(t))return;np(process.execPath,ar(e,["daemon","run-detached"]),{detached:!0,stdio:"ignore",env:process.env}).unref();let s=Date.now()+5e3;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,150)),await Lc(t))return;throw new Error("daemon did not become ready in time")}ye();import{createServer as $_,connect as z_}from"net";import{rmSync as Ns,writeFileSync as V_}from"fs";import{connect as g_}from"net";var B={};ns(B,{BRAND:()=>Rp,DIRTY:()=>xt,EMPTY_PATH:()=>hp,INVALID:()=>K,NEVER:()=>m_,OK:()=>_e,ParseStatus:()=>fe,Schema:()=>re,ZodAny:()=>ht,ZodArray:()=>Ye,ZodBigInt:()=>Tt,ZodBoolean:()=>At,ZodBranded:()=>$r,ZodCatch:()=>Ut,ZodDate:()=>It,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>As,ZodEffects:()=>xe,ZodEnum:()=>Mt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>Ps,ZodIntersection:()=>Bt,ZodIssueCode:()=>H,ZodLazy:()=>Ot,ZodLiteral:()=>Dt,ZodMap:()=>fr,ZodNaN:()=>_r,ZodNativeEnum:()=>Nt,ZodNever:()=>Le,ZodNull:()=>Lt,ZodNullable:()=>Ue,ZodNumber:()=>kt,ZodObject:()=>ve,ZodOptional:()=>Ce,ZodParsedType:()=>$,ZodPipeline:()=>zr,ZodPromise:()=>ut,ZodReadonly:()=>Ft,ZodRecord:()=>Is,ZodSchema:()=>re,ZodSet:()=>pr,ZodString:()=>lt,ZodSymbol:()=>ur,ZodTransformer:()=>xe,ZodTuple:()=>He,ZodType:()=>re,ZodUndefined:()=>Pt,ZodUnion:()=>Rt,ZodUnknown:()=>Ge,ZodVoid:()=>dr,addIssueToContext:()=>W,any:()=>jp,array:()=>zp,bigint:()=>Mp,boolean:()=>Wc,coerce:()=>__,custom:()=>Uc,date:()=>Np,datetimeRegex:()=>Nc,defaultErrorMap:()=>ze,discriminatedUnion:()=>Jp,effect:()=>a_,enum:()=>i_,function:()=>t_,getErrorMap:()=>cr,getParsedType:()=>Ne,instanceof:()=>Op,intersection:()=>Zp,isAborted:()=>ks,isAsync:()=>lr,isDirty:()=>Ts,isValid:()=>ct,late:()=>Bp,lazy:()=>r_,literal:()=>s_,makeIssue:()=>qr,map:()=>Qp,nan:()=>Dp,nativeEnum:()=>n_,never:()=>qp,null:()=>Fp,nullable:()=>l_,number:()=>jc,object:()=>Vp,objectUtil:()=>pn,oboolean:()=>p_,onumber:()=>f_,optional:()=>c_,ostring:()=>d_,pipeline:()=>u_,preprocess:()=>h_,promise:()=>o_,quotelessJson:()=>ap,record:()=>Xp,set:()=>e_,setErrorMap:()=>lp,strictObject:()=>Gp,string:()=>Fc,symbol:()=>Hp,transformer:()=>a_,tuple:()=>Kp,undefined:()=>Up,union:()=>Yp,unknown:()=>Wp,util:()=>ie,void:()=>$p});var ie;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(n=>typeof i[i[n]]!="number"),a={};for(let n of o)a[n]=i[n];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},t.find=(i,o)=>{for(let a of i)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=s,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));var pn;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(pn||(pn={}));var $=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ne=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var H=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ap=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},s={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)s._errors.push(r(a));else{let n=s,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(n[u]=n[u]||{_errors:[]},n[u]._errors.push(r(a))):n[u]=n[u]||{_errors:[]},n=n[u],l++}}};return i(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else s.push(e(i));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};ge.create=t=>new ge(t);var cp=(t,e)=>{let r;switch(t.code){case H.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case H.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case H.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case H.invalid_union:r="Invalid input";break;case H.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case H.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case H.invalid_arguments:r="Invalid function arguments";break;case H.invalid_return_type:r="Invalid function return type";break;case H.invalid_date:r="Invalid date";break;case H.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case H.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case H.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case H.custom:r="Invalid input";break;case H.invalid_intersection_types:r="Intersection results could not be merged";break;case H.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case H.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},ze=cp;var Rc=ze;function lp(t){Rc=t}function cr(){return Rc}var qr=t=>{let{data:e,path:r,errorMaps:s,issueData:i}=t,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let n="",l=s.filter(u=>!!u).slice().reverse();for(let u of l)n=u(a,{data:e,defaultError:n}).message;return{...i,path:o,message:n}},hp=[];function W(t,e){let r=cr(),s=qr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ze?void 0:ze].filter(i=>!!i)});t.common.issues.push(s)}var fe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let i of r){if(i.status==="aborted")return K;i.status==="dirty"&&e.dirty(),s.push(i.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let i of r){let o=await i.key,a=await i.value;s.push({key:o,value:a})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return K;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(s[o.value]=a.value)}return{status:e.value,value:s}}},K=Object.freeze({status:"aborted"}),xt=t=>({status:"dirty",value:t}),_e=t=>({status:"valid",value:t}),ks=t=>t.status==="aborted",Ts=t=>t.status==="dirty",ct=t=>t.status==="valid",lr=t=>typeof Promise<"u"&&t instanceof Promise;var G;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}));var Ee=class{constructor(e,r,s,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Bc=(t,e)=>{if(ct(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ge(t.common.issues);return this._error=r,this._error}}};function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:i}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,n)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??n.defaultError}:typeof n.data>"u"?{message:l??s??n.defaultError}:a.code!=="invalid_type"?{message:n.defaultError}:{message:l??r??n.defaultError}},description:i}}var re=class{get description(){return this._def.description}_getType(e){return Ne(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new fe,ctx:{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(lr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},i=this._parseSync({data:e,path:s.path,parent:s});return Bc(s,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return ct(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>ct(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},i=this._parse({data:e,path:s.path,parent:s}),o=await(lr(i)?i:Promise.resolve(i));return Bc(s,o)}refine(e,r){let s=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=e(i),n=()=>o.addIssue({code:H.custom,...s(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(n(),!1)):a?!0:(n(),!1)})}refinement(e,r){return this._refinement((s,i)=>e(s)?!0:(i.addIssue(typeof r=="function"?r(s,i):r),!1))}_refinement(e){return new xe({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ce.create(this,this._def)}nullable(){return Ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ye.create(this)}promise(){return ut.create(this,this._def)}or(e){return Rt.create([this,e],this._def)}and(e){return Bt.create(this,e,this._def)}transform(e){return new xe({...ee(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ht({...ee(this._def),innerType:this,defaultValue:r,typeName:X.ZodDefault})}brand(){return new $r({typeName:X.ZodBranded,type:this,...ee(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ut({...ee(this._def),innerType:this,catchValue:r,typeName:X.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return zr.create(this,e)}readonly(){return Ft.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},up=/^c[^\s-]{8,}$/i,dp=/^[0-9a-z]+$/,fp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_p=/^[a-z0-9_-]{21}$/i,mp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,gp=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,vp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,yp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",_n,bp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,wp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Sp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Cp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ep=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Dc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",kp=new RegExp(`^${Dc}$`);function Mc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Tp(t){return new RegExp(`^${Mc(t)}$`)}function Nc(t){let e=`${Dc}T${Mc(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ap(t,e){return!!((e==="v4"||!e)&&bp.test(t)||(e==="v6"||!e)&&Sp.test(t))}function Ip(t,e){if(!mp.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Pp(t,e){return!!((e==="v4"||!e)&&wp.test(t)||(e==="v6"||!e)&&Cp.test(t))}var lt=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_type,expected:$.string,received:o.parsedType}),K}let s=new fe,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,n=e.data.length<o.value;(a||n)&&(i=this._getOrReturnCtx(e,i),a?W(i,{code:H.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):n&&W(i,{code:H.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),s.dirty())}else if(o.kind==="email")vp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"email",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="emoji")_n||(_n=new RegExp(yp,"u")),_n.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"emoji",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="uuid")pp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"uuid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="nanoid")_p.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"nanoid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid")up.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cuid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid2")dp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cuid2",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="ulid")fp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"ulid",code:H.invalid_string,message:o.message}),s.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),W(i,{validation:"url",code:H.invalid_string,message:o.message}),s.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"regex",code:H.invalid_string,message:o.message}),s.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),s.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:{startsWith:o.value},message:o.message}),s.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:{endsWith:o.value},message:o.message}),s.dirty()):o.kind==="datetime"?Nc(o).test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:"datetime",message:o.message}),s.dirty()):o.kind==="date"?kp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:"date",message:o.message}),s.dirty()):o.kind==="time"?Tp(o).test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:H.invalid_string,validation:"time",message:o.message}),s.dirty()):o.kind==="duration"?gp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"duration",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="ip"?Ap(e.data,o.version)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"ip",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="jwt"?Ip(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"jwt",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="cidr"?Pp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cidr",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="base64"?Ep.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"base64",code:H.invalid_string,message:o.message}),s.dirty()):o.kind==="base64url"?xp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"base64url",code:H.invalid_string,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(i=>e.test(i),{validation:r,code:H.invalid_string,...G.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};lt.create=t=>new lt({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...ee(t)});function Lp(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,i=r>s?r:s,o=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var kt=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_type,expected:$.number,received:o.parsedType}),K}let s,i=new fe;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:H.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Lp(e.data,o.value)!==0&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:H.not_finite,message:o.message}),i.dirty()):ie.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,s,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};kt.create=t=>new kt({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var Tt=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let s,i=new fe;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),W(s,{code:H.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ie.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return W(r,{code:H.invalid_type,expected:$.bigint,received:r.parsedType}),K}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,s,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Tt.create=t=>new Tt({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var At=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.boolean,received:s.parsedType}),K}return _e(e.data)}};At.create=t=>new At({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var It=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_type,expected:$.date,received:o.parsedType}),K}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return W(o,{code:H.invalid_date}),K}let s=new fe,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),s.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:H.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),s.dirty()):ie.assertNever(o);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};It.create=t=>new It({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...ee(t)});var ur=class extends re{_parse(e){if(this._getType(e)!==$.symbol){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.symbol,received:s.parsedType}),K}return _e(e.data)}};ur.create=t=>new ur({typeName:X.ZodSymbol,...ee(t)});var Pt=class extends re{_parse(e){if(this._getType(e)!==$.undefined){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.undefined,received:s.parsedType}),K}return _e(e.data)}};Pt.create=t=>new Pt({typeName:X.ZodUndefined,...ee(t)});var Lt=class extends re{_parse(e){if(this._getType(e)!==$.null){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.null,received:s.parsedType}),K}return _e(e.data)}};Lt.create=t=>new Lt({typeName:X.ZodNull,...ee(t)});var ht=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};ht.create=t=>new ht({typeName:X.ZodAny,...ee(t)});var Ge=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};Ge.create=t=>new Ge({typeName:X.ZodUnknown,...ee(t)});var Le=class extends re{_parse(e){let r=this._getOrReturnCtx(e);return W(r,{code:H.invalid_type,expected:$.never,received:r.parsedType}),K}};Le.create=t=>new Le({typeName:X.ZodNever,...ee(t)});var dr=class extends re{_parse(e){if(this._getType(e)!==$.undefined){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.void,received:s.parsedType}),K}return _e(e.data)}};dr.create=t=>new dr({typeName:X.ZodVoid,...ee(t)});var Ye=class t extends re{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),i=this._def;if(r.parsedType!==$.array)return W(r,{code:H.invalid_type,expected:$.array,received:r.parsedType}),K;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,n=r.data.length<i.exactLength.value;(a||n)&&(W(r,{code:a?H.too_big:H.too_small,minimum:n?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(W(r,{code:H.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(W(r,{code:H.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((a,n)=>i.type._parseAsync(new Ee(r,a,r.path,n)))).then(a=>fe.mergeArray(s,a));let o=[...r.data].map((a,n)=>i.type._parseSync(new Ee(r,a,r.path,n)));return fe.mergeArray(s,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Ye.create=(t,e)=>new Ye({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ee(e)});function hr(t){if(t instanceof ve){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Ce.create(hr(s))}return new ve({...t._def,shape:()=>e})}else return t instanceof Ye?new Ye({...t._def,type:hr(t.element)}):t instanceof Ce?Ce.create(hr(t.unwrap())):t instanceof Ue?Ue.create(hr(t.unwrap())):t instanceof He?He.create(t.items.map(e=>hr(e))):t}var ve=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let u=this._getOrReturnCtx(e);return W(u,{code:H.invalid_type,expected:$.object,received:u.parsedType}),K}let{status:s,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||n.push(u);let l=[];for(let u of a){let y=o[u],h=i.data[u];l.push({key:{status:"valid",value:u},value:y._parse(new Ee(i,h,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Le){let u=this._def.unknownKeys;if(u==="passthrough")for(let y of n)l.push({key:{status:"valid",value:y},value:{status:"valid",value:i.data[y]}});else if(u==="strict")n.length>0&&(W(i,{code:H.unrecognized_keys,keys:n}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let y of n){let h=i.data[y];l.push({key:{status:"valid",value:y},value:u._parse(new Ee(i,h,i.path,y)),alwaysSet:y in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let y of l){let h=await y.key,_=await y.value;u.push({key:h,value:_,alwaysSet:y.alwaysSet})}return u}).then(u=>fe.mergeObjectSync(s,u)):fe.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let i=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:G.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:X.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of ie.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of ie.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return hr(this)}partial(e){let r={};for(let s of ie.objectKeys(this.shape)){let i=this.shape[s];e&&!e[s]?r[s]=i:r[s]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of ie.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let o=this.shape[s];for(;o instanceof Ce;)o=o._def.innerType;r[s]=o}return new t({...this._def,shape:()=>r})}keyof(){return Hc(ie.objectKeys(this.shape))}};ve.create=(t,e)=>new ve({shape:()=>t,unknownKeys:"strip",catchall:Le.create(),typeName:X.ZodObject,...ee(e)});ve.strictCreate=(t,e)=>new ve({shape:()=>t,unknownKeys:"strict",catchall:Le.create(),typeName:X.ZodObject,...ee(e)});ve.lazycreate=(t,e)=>new ve({shape:t,unknownKeys:"strip",catchall:Le.create(),typeName:X.ZodObject,...ee(e)});var Rt=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function i(o){for(let n of o)if(n.result.status==="valid")return n.result;for(let n of o)if(n.result.status==="dirty")return r.common.issues.push(...n.ctx.common.issues),n.result;let a=o.map(n=>new ge(n.ctx.common.issues));return W(r,{code:H.invalid_union,unionErrors:a}),K}if(r.common.async)return Promise.all(s.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of s){let u={...r,common:{...r.common,issues:[]},parent:null},y=l._parseSync({data:r.data,path:r.path,parent:u});if(y.status==="valid")return y;y.status==="dirty"&&!o&&(o={result:y,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let n=a.map(l=>new ge(l));return W(r,{code:H.invalid_union,unionErrors:n}),K}}get options(){return this._def.options}};Rt.create=(t,e)=>new Rt({options:t,typeName:X.ZodUnion,...ee(e)});var Ve=t=>t instanceof Ot?Ve(t.schema):t instanceof xe?Ve(t.innerType()):t instanceof Dt?[t.value]:t instanceof Mt?t.options:t instanceof Nt?ie.objectValues(t.enum):t instanceof Ht?Ve(t._def.innerType):t instanceof Pt?[void 0]:t instanceof Lt?[null]:t instanceof Ce?[void 0,...Ve(t.unwrap())]:t instanceof Ue?[null,...Ve(t.unwrap())]:t instanceof $r||t instanceof Ft?Ve(t.unwrap()):t instanceof Ut?Ve(t._def.innerType):[],As=class t extends re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return W(r,{code:H.invalid_type,expected:$.object,received:r.parsedType}),K;let s=this.discriminator,i=r.data[s],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(W(r,{code:H.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let i=new Map;for(let o of r){let a=Ve(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of a){if(i.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);i.set(n,o)}}return new t({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...ee(s)})}};function mn(t,e){let r=Ne(t),s=Ne(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&s===$.object){let i=ie.objectKeys(e),o=ie.objectKeys(t).filter(n=>i.indexOf(n)!==-1),a={...t,...e};for(let n of o){let l=mn(t[n],e[n]);if(!l.valid)return{valid:!1};a[n]=l.data}return{valid:!0,data:a}}else if(r===$.array&&s===$.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let a=t[o],n=e[o],l=mn(a,n);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===$.date&&s===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Bt=class extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),i=(o,a)=>{if(ks(o)||ks(a))return K;let n=mn(o.value,a.value);return n.valid?((Ts(o)||Ts(a))&&r.dirty(),{status:r.value,value:n.data}):(W(s,{code:H.invalid_intersection_types}),K)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Bt.create=(t,e,r)=>new Bt({left:t,right:e,typeName:X.ZodIntersection,...ee(r)});var He=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.array)return W(s,{code:H.invalid_type,expected:$.array,received:s.parsedType}),K;if(s.data.length<this._def.items.length)return W(s,{code:H.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&s.data.length>this._def.items.length&&(W(s,{code:H.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...s.data].map((a,n)=>{let l=this._def.items[n]||this._def.rest;return l?l._parse(new Ee(s,a,s.path,n)):null}).filter(a=>!!a);return s.common.async?Promise.all(o).then(a=>fe.mergeArray(r,a)):fe.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};He.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:t,typeName:X.ZodTuple,rest:null,...ee(e)})};var Is=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.object)return W(s,{code:H.invalid_type,expected:$.object,received:s.parsedType}),K;let i=[],o=this._def.keyType,a=this._def.valueType;for(let n in s.data)i.push({key:o._parse(new Ee(s,n,s.path,n)),value:a._parse(new Ee(s,s.data[n],s.path,n)),alwaysSet:n in s.data});return s.common.async?fe.mergeObjectAsync(r,i):fe.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof re?new t({keyType:e,valueType:r,typeName:X.ZodRecord,...ee(s)}):new t({keyType:lt.create(),valueType:e,typeName:X.ZodRecord,...ee(r)})}},fr=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.map)return W(s,{code:H.invalid_type,expected:$.map,received:s.parsedType}),K;let i=this._def.keyType,o=this._def.valueType,a=[...s.data.entries()].map(([n,l],u)=>({key:i._parse(new Ee(s,n,s.path,[u,"key"])),value:o._parse(new Ee(s,l,s.path,[u,"value"]))}));if(s.common.async){let n=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,y=await l.value;if(u.status==="aborted"||y.status==="aborted")return K;(u.status==="dirty"||y.status==="dirty")&&r.dirty(),n.set(u.value,y.value)}return{status:r.value,value:n}})}else{let n=new Map;for(let l of a){let u=l.key,y=l.value;if(u.status==="aborted"||y.status==="aborted")return K;(u.status==="dirty"||y.status==="dirty")&&r.dirty(),n.set(u.value,y.value)}return{status:r.value,value:n}}}};fr.create=(t,e,r)=>new fr({valueType:e,keyType:t,typeName:X.ZodMap,...ee(r)});var pr=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==$.set)return W(s,{code:H.invalid_type,expected:$.set,received:s.parsedType}),K;let i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(W(s,{code:H.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(W(s,{code:H.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(l){let u=new Set;for(let y of l){if(y.status==="aborted")return K;y.status==="dirty"&&r.dirty(),u.add(y.value)}return{status:r.value,value:u}}let n=[...s.data.values()].map((l,u)=>o._parse(new Ee(s,l,s.path,u)));return s.common.async?Promise.all(n).then(l=>a(l)):a(n)}min(e,r){return new t({...this._def,minSize:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};pr.create=(t,e)=>new pr({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...ee(e)});var Ps=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return W(r,{code:H.invalid_type,expected:$.function,received:r.parsedType}),K;function s(n,l){return qr({data:n,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cr(),ze].filter(u=>!!u),issueData:{code:H.invalid_arguments,argumentsError:l}})}function i(n,l){return qr({data:n,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cr(),ze].filter(u=>!!u),issueData:{code:H.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof ut){let n=this;return _e(async function(...l){let u=new ge([]),y=await n._def.args.parseAsync(l,o).catch(d=>{throw u.addIssue(s(l,d)),u}),h=await Reflect.apply(a,this,y);return await n._def.returns._def.type.parseAsync(h,o).catch(d=>{throw u.addIssue(i(h,d)),u})})}else{let n=this;return _e(function(...l){let u=n._def.args.safeParse(l,o);if(!u.success)throw new ge([s(l,u.error)]);let y=Reflect.apply(a,this,u.data),h=n._def.returns.safeParse(y,o);if(!h.success)throw new ge([i(y,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:He.create(e).rest(Ge.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||He.create([]).rest(Ge.create()),returns:r||Ge.create(),typeName:X.ZodFunction,...ee(s)})}},Ot=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ot.create=(t,e)=>new Ot({getter:t,typeName:X.ZodLazy,...ee(e)});var Dt=class extends re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return W(r,{received:r.data,code:H.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Dt.create=(t,e)=>new Dt({value:t,typeName:X.ZodLiteral,...ee(e)});function Hc(t,e){return new Mt({values:t,typeName:X.ZodEnum,...ee(e)})}var Mt=class t extends re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return W(r,{expected:ie.joinValues(s),received:r.parsedType,code:H.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return W(r,{received:r.data,code:H.invalid_enum_value,options:s}),K}return _e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};Mt.create=Hc;var Nt=class extends re{_parse(e){let r=ie.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==$.string&&s.parsedType!==$.number){let i=ie.objectValues(r);return W(s,{expected:ie.joinValues(i),received:s.parsedType,code:H.invalid_type}),K}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ie.objectValues(r);return W(s,{received:s.data,code:H.invalid_enum_value,options:i}),K}return _e(e.data)}get enum(){return this._def.values}};Nt.create=(t,e)=>new Nt({values:t,typeName:X.ZodNativeEnum,...ee(e)});var ut=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return W(r,{code:H.invalid_type,expected:$.promise,received:r.parsedType}),K;let s=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return _e(s.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ut.create=(t,e)=>new ut({type:t,typeName:X.ZodPromise,...ee(e)});var xe=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{W(s,a),a.fatal?r.abort():r.dirty()},get path(){return s.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(s.data,o);if(s.common.async)return Promise.resolve(a).then(async n=>{if(r.value==="aborted")return K;let l=await this._def.schema._parseAsync({data:n,path:s.path,parent:s});return l.status==="aborted"?K:l.status==="dirty"?xt(l.value):r.value==="dirty"?xt(l.value):l});{if(r.value==="aborted")return K;let n=this._def.schema._parseSync({data:a,path:s.path,parent:s});return n.status==="aborted"?K:n.status==="dirty"?xt(n.value):r.value==="dirty"?xt(n.value):n}}if(i.type==="refinement"){let a=n=>{let l=i.refinement(n,o);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return n};if(s.common.async===!1){let n=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?K:(n.status==="dirty"&&r.dirty(),a(n.value),{status:r.value,value:n.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(n=>n.status==="aborted"?K:(n.status==="dirty"&&r.dirty(),a(n.value).then(()=>({status:r.value,value:n.value}))))}if(i.type==="transform")if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ct(a))return K;let n=i.transform(a.value,o);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:n}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>ct(a)?Promise.resolve(i.transform(a.value,o)).then(n=>({status:r.value,value:n})):K);ie.assertNever(i)}};xe.create=(t,e,r)=>new xe({schema:t,typeName:X.ZodEffects,effect:e,...ee(r)});xe.createWithPreprocess=(t,e,r)=>new xe({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...ee(r)});var Ce=class extends re{_parse(e){return this._getType(e)===$.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ce.create=(t,e)=>new Ce({innerType:t,typeName:X.ZodOptional,...ee(e)});var Ue=class extends re{_parse(e){return this._getType(e)===$.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ue.create=(t,e)=>new Ue({innerType:t,typeName:X.ZodNullable,...ee(e)});var Ht=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===$.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ht.create=(t,e)=>new Ht({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var Ut=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return lr(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ge(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Ut.create=(t,e)=>new Ut({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var _r=class extends re{_parse(e){if(this._getType(e)!==$.nan){let s=this._getOrReturnCtx(e);return W(s,{code:H.invalid_type,expected:$.nan,received:s.parsedType}),K}return{status:"valid",value:e.data}}};_r.create=t=>new _r({typeName:X.ZodNaN,...ee(t)});var Rp=Symbol("zod_brand"),$r=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},zr=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?K:o.status==="dirty"?(r.dirty(),xt(o.value)):this._def.out._parseAsync({data:o.value,path:s.path,parent:s})})();{let i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?K:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:X.ZodPipeline})}},Ft=class extends re{_parse(e){let r=this._def.innerType._parse(e),s=i=>(ct(i)&&(i.value=Object.freeze(i.value)),i);return lr(r)?r.then(i=>s(i)):s(r)}unwrap(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:X.ZodReadonly,...ee(e)});function Oc(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Uc(t,e={},r){return t?ht.create().superRefine((s,i)=>{let o=t(s);if(o instanceof Promise)return o.then(a=>{if(!a){let n=Oc(e,s),l=n.fatal??r??!0;i.addIssue({code:"custom",...n,fatal:l})}});if(!o){let a=Oc(e,s),n=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:n})}}):ht.create()}var Bp={object:ve.lazycreate},X;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(X||(X={}));var Op=(t,e={message:`Input not instance of ${t.name}`})=>Uc(r=>r instanceof t,e),Fc=lt.create,jc=kt.create,Dp=_r.create,Mp=Tt.create,Wc=At.create,Np=It.create,Hp=ur.create,Up=Pt.create,Fp=Lt.create,jp=ht.create,Wp=Ge.create,qp=Le.create,$p=dr.create,zp=Ye.create,Vp=ve.create,Gp=ve.strictCreate,Yp=Rt.create,Jp=As.create,Zp=Bt.create,Kp=He.create,Xp=Is.create,Qp=fr.create,e_=pr.create,t_=Ps.create,r_=Ot.create,s_=Dt.create,i_=Mt.create,n_=Nt.create,o_=ut.create,a_=xe.create,c_=Ce.create,l_=Ue.create,h_=xe.createWithPreprocess,u_=zr.create,d_=()=>Fc().optional(),f_=()=>jc().optional(),p_=()=>Wc().optional(),__={string:(t=>lt.create({...t,coerce:!0})),number:(t=>kt.create({...t,coerce:!0})),boolean:(t=>At.create({...t,coerce:!0})),bigint:(t=>Tt.create({...t,coerce:!0})),date:(t=>It.create({...t,coerce:!0}))};var m_=K;ye();var qc=B.discriminatedUnion("cmd",[B.object({cmd:B.literal("ping")}).strict(),B.object({cmd:B.literal("new"),adapterId:B.string(),cwd:B.string(),aiCliArgs:B.array(B.string()),label:B.string().max(64).optional()}).strict(),B.object({cmd:B.literal("ls")}).strict(),B.object({cmd:B.literal("attach-info"),sessionId:B.string()}).strict(),B.object({cmd:B.literal("status")}).strict(),B.object({cmd:B.literal("stop")}).strict(),B.object({cmd:B.literal("project"),action:B.enum(["add","ls","rm"]),path:B.string().optional()}).strict()]),v_=B.union([B.object({ok:B.literal(!0),data:B.unknown().optional()}).strict(),B.object({ok:B.literal(!1),code:B.string(),message:B.string()}).strict()]);function Fe(t,e,r=5e3){return new Promise((s,i)=>{let o=g_(qe(t)),a="",n=setTimeout(()=>{o.destroy(),i(new Error("daemon command timeout"))},r);o.on("connect",()=>o.write(JSON.stringify(e)+`
89
+ `),{leaks:P,details:Z}}}function c(D){return p?.trackDisposable(D),D}function v(D){p?.markAsDisposed(D)}function g(D,L){p?.setParent(D,L)}function f(D){return typeof D=="object"&&D!==null&&typeof D.dispose=="function"&&D.dispose.length===0}function m(D){if(d.Iterable.is(D)){let L=[];for(let R of D)if(R)try{R.dispose()}catch(P){L.push(P)}if(L.length===1)throw L[0];if(L.length>1)throw new AggregateError(L,"Encountered errors while disposing of store");return Array.isArray(D)?[]:D}if(D)return D.dispose(),D}function w(D){let L=c({dispose:(0,_.createSingleCallFunction)((()=>{v(L),D()}))});return L}n.DisposableTracker=b;class C{static{this.DISABLE_DISPOSED_WARNING=!1}constructor(){this._toDispose=new Set,this._isDisposed=!1,c(this)}dispose(){this._isDisposed||(v(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{m(this._toDispose)}finally{this._toDispose.clear()}}add(L){if(!L)return L;if(L===this)throw new Error("Cannot register a disposable on itself!");return g(L,this),this._isDisposed?C.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(L),L}delete(L){if(L){if(L===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(L),L.dispose()}}deleteAndLeak(L){L&&this._toDispose.has(L)&&(this._toDispose.delete(L),g(L,null))}}n.DisposableStore=C;class k{static{this.None=Object.freeze({dispose(){}})}constructor(){this._store=new C,c(this),g(this._store,this)}dispose(){v(this),this._store.dispose()}_register(L){if(L===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(L)}}n.Disposable=k;class A{constructor(){this._isDisposed=!1,c(this)}get value(){return this._isDisposed?void 0:this._value}set value(L){this._isDisposed||L===this._value||(this._value?.dispose(),L&&g(L,this),this._value=L)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,v(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let L=this._value;return this._value=void 0,L&&g(L,null),L}}n.MutableDisposable=A,n.MandatoryMutableDisposable=class{constructor(D){this._disposable=new A,this._isDisposed=!1,this._disposable.value=D}get value(){return this._disposable.value}set value(D){this._isDisposed||D===this._disposable.value||(this._disposable.value=D)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},n.RefCountedDisposable=class{constructor(D){this._disposable=D,this._counter=1}acquire(){return this._counter++,this}release(){return--this._counter==0&&this._disposable.dispose(),this}},n.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,c(this)}set(D){let L=D;return this.unset=()=>L=void 0,this.isset=()=>L!==void 0,this.dispose=()=>{L&&(L(),L=void 0,v(this))},this}},n.ReferenceCollection=class{constructor(){this.references=new Map}acquire(D,...L){let R=this.references.get(D);R||(R={counter:0,object:this.createReferencedObject(D,...L)},this.references.set(D,R));let{object:P}=R,F=(0,_.createSingleCallFunction)((()=>{--R.counter==0&&(this.destroyReferencedObject(D,R.object),this.references.delete(D))}));return R.counter++,{object:P,dispose:F}}},n.AsyncReferenceCollection=class{constructor(D){this.referenceCollection=D}async acquire(D,...L){let R=this.referenceCollection.acquire(D,...L);try{return{object:await R.object,dispose:()=>R.dispose()}}catch(P){throw R.dispose(),P}}},n.ImmortalReference=class{constructor(D){this.object=D}dispose(){}};class O{constructor(){this._store=new Map,this._isDisposed=!1,c(this)}dispose(){v(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{m(this._store.values())}finally{this._store.clear()}}has(L){return this._store.has(L)}get size(){return this._store.size}get(L){return this._store.get(L)}set(L,R,P=!1){this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),P||this._store.get(L)?.dispose(),this._store.set(L,R)}deleteAndDispose(L){this._store.get(L)?.dispose(),this._store.delete(L)}deleteAndLeak(L){let R=this._store.get(L);return this._store.delete(L),R}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}n.DisposableMap=O},6317:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.LinkedList=void 0;class l{static{this.Undefined=new l(void 0)}constructor(h){this.element=h,this.next=l.Undefined,this.prev=l.Undefined}}class u{constructor(){this._first=l.Undefined,this._last=l.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===l.Undefined}clear(){let h=this._first;for(;h!==l.Undefined;){let _=h.next;h.prev=l.Undefined,h.next=l.Undefined,h=_}this._first=l.Undefined,this._last=l.Undefined,this._size=0}unshift(h){return this._insert(h,!1)}push(h){return this._insert(h,!0)}_insert(h,_){let d=new l(h);if(this._first===l.Undefined)this._first=d,this._last=d;else if(_){let b=this._last;this._last=d,d.prev=b,b.next=d}else{let b=this._first;this._first=d,d.next=b,b.prev=d}this._size+=1;let p=!1;return()=>{p||(p=!0,this._remove(d))}}shift(){if(this._first!==l.Undefined){let h=this._first.element;return this._remove(this._first),h}}pop(){if(this._last!==l.Undefined){let h=this._last.element;return this._remove(this._last),h}}_remove(h){if(h.prev!==l.Undefined&&h.next!==l.Undefined){let _=h.prev;_.next=h.next,h.next.prev=_}else h.prev===l.Undefined&&h.next===l.Undefined?(this._first=l.Undefined,this._last=l.Undefined):h.next===l.Undefined?(this._last=this._last.prev,this._last.next=l.Undefined):h.prev===l.Undefined&&(this._first=this._first.next,this._first.prev=l.Undefined);this._size-=1}*[Symbol.iterator](){let h=this._first;for(;h!==l.Undefined;)yield h.element,h=h.next}}n.LinkedList=u},2608:(a,n)=>{var l;Object.defineProperty(n,"__esModule",{value:!0}),n.SetMap=n.BidirectionalMap=n.CounterSet=n.Touch=void 0,n.getOrSet=function(u,y,h){let _=u.get(y);return _===void 0&&(_=h,u.set(y,_)),_},n.mapToString=function(u){let y=[];return u.forEach(((h,_)=>{y.push(`${_} => ${h}`)})),`Map(${u.size}) {${y.join(", ")}}`},n.setToString=function(u){let y=[];return u.forEach((h=>{y.push(h)})),`Set(${u.size}) {${y.join(", ")}}`},n.mapsStrictEqualIgnoreOrder=function(u,y){if(u===y)return!0;if(u.size!==y.size)return!1;for(let[h,_]of u)if(!y.has(h)||y.get(h)!==_)return!1;for(let[h]of y)if(!u.has(h))return!1;return!0},(function(u){u[u.None=0]="None",u[u.AsOld=1]="AsOld",u[u.AsNew=2]="AsNew"})(l||(n.Touch=l={})),n.CounterSet=class{constructor(){this.map=new Map}add(u){return this.map.set(u,(this.map.get(u)||0)+1),this}delete(u){let y=this.map.get(u)||0;return y!==0&&(y--,y===0?this.map.delete(u):this.map.set(u,y),!0)}has(u){return this.map.has(u)}},n.BidirectionalMap=class{constructor(u){if(this._m1=new Map,this._m2=new Map,u)for(let[y,h]of u)this.set(y,h)}clear(){this._m1.clear(),this._m2.clear()}set(u,y){this._m1.set(u,y),this._m2.set(y,u)}get(u){return this._m1.get(u)}getKey(u){return this._m2.get(u)}delete(u){let y=this._m1.get(u);return y!==void 0&&(this._m1.delete(u),this._m2.delete(y),!0)}forEach(u,y){this._m1.forEach(((h,_)=>{u.call(y,h,_,this)}))}keys(){return this._m1.keys()}values(){return this._m1.values()}},n.SetMap=class{constructor(){this.map=new Map}add(u,y){let h=this.map.get(u);h||(h=new Set,this.map.set(u,h)),h.add(y)}delete(u,y){let h=this.map.get(u);h&&(h.delete(y),h.size===0&&this.map.delete(u))}forEach(u,y){let h=this.map.get(u);h&&h.forEach(y)}get(u){return this.map.get(u)||new Set}}},9725:(a,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.StopWatch=void 0;let l=globalThis.performance&&typeof globalThis.performance.now=="function";class u{static create(h){return new u(h)}constructor(h){this._now=l&&h===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}}n.StopWatch=u}},e={};function r(a){var n=e[a];if(n!==void 0)return n.exports;var l=e[a]={exports:{}};return t[a].call(l.exports,l,l.exports,r),l.exports}var s={};(()=>{var a=s;Object.defineProperty(a,"__esModule",{value:!0}),a.Terminal=void 0;let n=r(5101),l=r(6097),u=r(4335),y=r(5856),h=r(3027),_=r(7150),d=["cols","rows"];class p extends _.Disposable{constructor(c){super(),this._core=this._register(new y.Terminal(c)),this._addonManager=this._register(new h.AddonManager),this._publicOptions={...this._core.options};let v=f=>this._core.options[f],g=(f,m)=>{this._checkReadonlyOptions(f),this._core.options[f]=m};for(let f in this._core.options){Object.defineProperty(this._publicOptions,f,{get:()=>this._core.options[f],set:w=>{this._checkReadonlyOptions(f),this._core.options[f]=w}});let m={get:v.bind(this,f),set:g.bind(this,f)};Object.defineProperty(this._publicOptions,f,m)}}_checkReadonlyOptions(c){if(d.includes(c))throw new Error(`Option "${c}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get parser(){return this._checkProposedApi(),this._parser||(this._parser=new l.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new u.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||(this._buffer=this._register(new n.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let c=this._core.coreService.decPrivateModes,v="none";switch(this._core.coreMouseService.activeProtocol){case"X10":v="x10";break;case"VT200":v="vt200";break;case"DRAG":v="drag";break;case"ANY":v="any"}return{applicationCursorKeysMode:c.applicationCursorKeys,applicationKeypadMode:c.applicationKeypad,bracketedPasteMode:c.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:v,originMode:c.origin,reverseWraparoundMode:c.reverseWraparound,sendFocusMode:c.sendFocus,synchronizedOutputMode:c.synchronizedOutput,wraparoundMode:c.wraparound}}get options(){return this._publicOptions}set options(c){for(let v in c)this._publicOptions[v]=c[v]}input(c,v=!0){this._core.input(c,v)}resize(c,v){this._verifyIntegers(c,v),this._core.resize(c,v)}registerMarker(c=0){return this._checkProposedApi(),this._verifyIntegers(c),this._core.addMarker(c)}addMarker(c){return this.registerMarker(c)}dispose(){super.dispose()}scrollLines(c){this._verifyIntegers(c),this._core.scrollLines(c)}scrollPages(c){this._verifyIntegers(c),this._core.scrollPages(c)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(c){this._verifyIntegers(c),this._core.scrollToLine(c)}clear(){this._core.clear()}write(c,v){this._core.write(c,v)}writeln(c,v){this._core.write(c),this._core.write(`\r
90
+ `,v)}reset(){this._core.reset()}loadAddon(c){this._addonManager.loadAddon(this,c)}_verifyIntegers(...c){for(let v of c)if(v===1/0||isNaN(v)||v%1!=0)throw new Error("This API only accepts integers")}}a.Terminal=p})();var i=Ih;for(var o in s)i[o]=s[o];s.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})()});function jh(t){let r=t.trim().replace(/^v/,"").split(/[-+]/)[0].split(".").map(s=>Number.parseInt(s,10));return[r[0]||0,r[1]||0,r[2]||0]}function Wh(t,e){let r=jh(t),s=jh(e);for(let i=0;i<3;i++){if(r[i]>s[i])return!0;if(r[i]<s[i])return!1}return!1}var $h=bt(()=>{"use strict"});var Yh={};os(Yh,{matchedGlobalRoot:()=>ao,resolveGlobalRoots:()=>u0});import{execFile as n0}from"child_process";import{promisify as o0}from"util";import{realpathSync as Gh}from"fs";import{sep as qh,relative as a0,isAbsolute as c0,dirname as l0,join as zh}from"path";async function u0(){let t=[],e=["npm","pnpm"];for(let r of e)try{let{stdout:s}=await h0(r,["root","-g"]),i=s.trim();i&&t.push({manager:r,root:Gh(i)})}catch{}return t}function Vh(t){try{return Gh(t)}catch{return t}}function _i(t,e){let r=a0(t,e);return r===""||!r.startsWith("..")&&!c0(r)}function d0(t,e){return!!(_i(t,e)||_i(zh(t,".pnpm"),e)||_i(zh(l0(t),".pnpm"),e))}function ao(t,e,r){if(t==="0.0.0-dev")return;let s=Vh(e);return r.find(({root:i})=>{let o=Vh(`${i}${qh}@hown${qh}djinn`);return d0(i,o)?_i(o,s):!1})}var h0,co=bt(()=>{"use strict";h0=o0(n0)});var Jh={};os(Jh,{runUpdate:()=>f0});async function f0(t){let e=await t.resolveGlobalRoots(),r=ao(t.currentVersion,t.entryPath,e);if(!r)return t.log("update \u4EC5\u9002\u7528\u4E8E npm / pnpm \u5168\u5C40\u5B89\u88C5(npm i -g \u6216 pnpm add -g @hown/djinn)\u3002\u68C0\u6D4B\u5230\u4ECE\u6E90\u7801 / \u672C\u5730\u6784\u5EFA / \u672C\u5730\u94FE\u63A5\u8FD0\u884C\u3002"),1;let s;try{s=await t.fetchLatest(r.manager)}catch(i){return t.log(`\u67E5\u8BE2\u6700\u65B0\u7248\u5931\u8D25:${i instanceof Error?i.message:String(i)}`),1}if(!Wh(s,t.currentVersion))return t.log(`\u5DF2\u662F\u6700\u65B0 v${t.currentVersion}`),0;t.log(`\u53D1\u73B0\u65B0\u7248 v${s}(\u5F53\u524D v${t.currentVersion}),\u6B63\u5728\u66F4\u65B0\u2026`);try{await t.installLatest(r.manager)}catch(i){return t.log(`\u66F4\u65B0\u5931\u8D25:${i instanceof Error?i.message:String(i)}`),1}t.log("\u66F4\u65B0\u5B8C\u6210,\u6B63\u5728\u91CD\u542F daemon \u4EE5\u542F\u7528\u65B0\u4EE3\u7801\u2026");try{t.supervisorInstalled()?await t.restartSupervised():await t.restartUnmanaged()}catch(i){return t.log(`daemon \u91CD\u542F\u5931\u8D25(\u53EF\u624B\u52A8 \`djinn daemon stop\` \u540E\u91CD\u8BD5):${i instanceof Error?i.message:String(i)}`),1}return t.log(`\u5DF2\u66F4\u65B0\u5230 v${s}`),0}var Zh=bt(()=>{"use strict";$h();co()});import{realpathSync as p0}from"fs";import{hostname as _0}from"os";import{resolve as Kh}from"path";import{pathToFileURL as Xh}from"url";var ou="wss://unit00.top/djinn/relay";function ho(t=process.argv,e=process.env){let r=t[2],s=t.slice(3);switch(r){case"start":throw new Error("`djinn start` has been removed. Use `djinn new` instead.");case"pair":return{command:"pair",config:du(s)};case"new":return{command:"new",config:cu(s,e)};case"attach":return{command:"attach",config:{sessionId:au(s[0],"attach <sessionId>")}};case"status":return{command:"status",config:{}};case"project":return{command:"project",config:lu(s)};case"daemon":return{command:"daemon",config:{action:hu(s[0])}};case"update":return{command:"update",config:{}};case"__worker":return{command:"__worker",config:uu(s)};default:throw new Error(`Unknown command: ${r??"(none)"}. Try: djinn new | attach | status | pair | project | daemon | update`)}}function au(t,e){if(!t)throw new Error(`missing argument: djinn ${e}`);return t}function cu(t,e){let r=t.indexOf("--"),s=r>=0?t.slice(0,r):t,i=r>=0?t.slice(r+1):[],o=u=>{let y=s.indexOf(u);return y>=0?s[y+1]:void 0},a=o("--adapter")??"claude-code",n=s.includes("--detach")||s.includes("-d"),l=o("--label");return{adapterId:a,detach:n,aiCliArgs:i,cwd:process.cwd(),server:o("--server")??e.DJINN_SERVER_URL??ou,invite:o("--invite")??e.DJINN_INVITE,...l?{label:l}:{}}}function lu(t){let e=t[0];if(e!=="add"&&e!=="ls"&&e!=="rm")throw new Error("djinn project <add|ls|rm> [path]");if((e==="add"||e==="rm")&&!t[1])throw new Error(`djinn project ${e} <path>`);return e==="ls"?{action:e}:{action:e,path:t[1]}}function hu(t){if(t==="run"||t==="run-detached"||t==="stop"||t==="install"||t==="uninstall")return t;throw new Error("djinn daemon <run|run-detached|stop|install|uninstall>")}function uu(t){let e=t.indexOf("--"),r=e>=0?t.slice(0,e):t,s=e>=0?t.slice(e+1):[],i=_=>{let d=r.indexOf(_);return d>=0?r[d+1]:void 0},o=i("--session-id"),a=i("--cwd"),n=i("--adapter"),l=i("--mode");if(!o||!a||!n||l!=="new"&&l!=="resume")throw new Error("djinn __worker requires --session-id --cwd --adapter --mode <new|resume>");let u=i("--origin");if(u!==void 0&&u!=="local"&&u!=="remote")throw new Error("djinn __worker --origin must be <local|remote>");let y=u??"local",h=i("--label");return{sessionId:o,cwd:a,adapterId:n,mode:l,origin:y,aiCliArgs:s,...h?{label:h}:{}}}function du(t){if(t.includes("--terminal")||t.includes("--no-png"))return{png:!1};let e=t.indexOf("--png");if(e!==-1){let r=t[e+1];if(r!==void 0&&!r.startsWith("--"))return{png:!0,pngPath:r}}return{png:!0}}import{existsSync as ku,mkdirSync as Tu,readFileSync as Au,writeFileSync as Iu}from"fs";import{homedir as mo}from"os";import{join as go}from"path";me();import{readFileSync as vu,writeFileSync as yu,renameSync as bu,existsSync as wu,realpathSync as Su}from"fs";import{resolve as Cu,relative as Eu,isAbsolute as xu}from"path";function yi(t){let e=Cu(t);try{return Su(e)}catch{return e}}function ls(t){let e=vi(t);return wu(e)?JSON.parse(vu(e,"utf8")).projects??[]:[]}function po(t,e){rt(t);let r=vi(t),s=`${r}.${process.pid}.tmp`;yu(s,JSON.stringify({projects:e},null,2),{mode:384}),bu(s,r)}function Qt(t){return ls(t)}function hs(t,e,r){let s=yi(e),i=ls(t);i.some(o=>o.path===s)||po(t,[...i,{path:s,label:r}])}function _o(t,e){let r=yi(e);po(t,ls(t).filter(s=>s.path!==r))}function bi(t,e){let r=yi(e);return ls(t).some(s=>{if(r===s.path)return!0;let i=Eu(s.path,r);return i!==""&&!i.startsWith("..")&&!xu(i)})}function vo(){return go(mo(),".djinn")}function yo(t){return go(t,"identity.json")}function st(t){let e=yo(t);if(!ku(e))return;let r=Au(e,"utf8");return JSON.parse(r)}function Pu(t,e){Tu(t,{recursive:!0,mode:448}),Iu(yo(t),JSON.stringify(e,null,2),{mode:384})}async function bo(t){let e=st(t.dir);if(e)return e;if(!t.invite)throw new Error("No identity found. Pass --invite <CODE> (or DJINN_INVITE) to register this machine.");if(!t.serverUrl)throw new Error("First-run registration needs --server <url> (or DJINN_SERVER_URL).");let r=t.fetchImpl??fetch,s=wi(t.serverUrl),i=await r(`${s}/v1/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({invite_code:t.invite,label:t.label})});if(!i.ok)throw i.status===409?new Error("Registration failed: invite code is invalid or already used."):new Error(`Registration failed with status ${i.status}.`);let o=await i.json(),a={ownerId:o.owner_id,deviceId:o.device_id,token:o.token,serverUrl:o.server_url||t.serverUrl};return Pu(t.dir,a),Qt(t.dir).length===0&&hs(t.dir,mo()),a}function wi(t){return t.replace(/^ws/,"http").replace(/\/$/,"")}var pn=Be(Ic(),1);import{join as Jf}from"path";import{createHash as Gf,randomBytes as Wv,timingSafeEqual as $v}from"crypto";var Yf="sha256:";function fn(t){return`${Yf}${Gf("sha256").update(t).digest("hex")}`}function Zf(t,e){return Buffer.from(JSON.stringify({v:1,url:t,code:e}),"utf8").toString("base64url")}var Pc=t=>new Promise(e=>setTimeout(e,t));async function Kf(t){return pn.default.toString(t,{type:"terminal",small:!1})}function Xf(t,e){return pn.default.toFile(e,t,{type:"png",width:600,margin:4,errorCorrectionLevel:"M"})}async function Qf(t){let{platform:e}=process,[r,s]=e==="darwin"?["open",[t]]:e==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let{spawn:i}=await import("child_process");await new Promise(o=>{let a=i(r,s,{stdio:"ignore",detached:!0});a.on("error",()=>o()),a.on("spawn",()=>{a.unref(),o()})})}catch{}}async function Lc(t){let e=t.out??(p=>process.stderr.write(`${p}
91
+ `)),r=t.fetchImpl??fetch,s=t.printQr??Kf,i=t.writeQrPng??Xf,o=t.openFile??Qf,a=t.pollIntervalMs??1500,n=st(t.dir);if(!n)return e("\u672A\u627E\u5230\u8EAB\u4EFD\u3002\u8BF7\u5148\u8FD0\u884C djinn start --invite <CODE> \u6CE8\u518C\u672C\u673A\u3002"),1;let l=wi(n.serverUrl),u;try{u=await r(`${l}/v1/pairing`,{method:"POST",headers:{authorization:`Bearer ${n.token}`}})}catch(p){return e(`\u53D1\u8D77\u914D\u5BF9\u5931\u8D25\uFF1A\u65E0\u6CD5\u8FDE\u63A5 ${l}\uFF08${p instanceof Error?p.message:String(p)}\uFF09`),1}if(!u.ok)return e(`\u53D1\u8D77\u914D\u5BF9\u5931\u8D25\uFF1AHTTP ${u.status}`),1;let{code:y,expires_at_ms:h}=await u.json(),_=Zf(l,y);if(t.png){let p=t.pngPath??Jf(process.cwd(),"djinn-pair-qr.png");await i(_,p);try{await o(p)}catch{}e(`\u4E8C\u7EF4\u7801\u5DF2\u4FDD\u5B58\u5230 ${p} \u5E76\u5C1D\u8BD5\u6253\u5F00\uFF0C\u8BF7\u7528\u624B\u673A djinn PWA \u626B\u7801\uFF0860 \u79D2\u5185\u6709\u6548\uFF09\u3002`),e("\uFF08\u82E5\u56FE\u7247\u6CA1\u81EA\u52A8\u6253\u5F00\uFF0C\u53EF\u626B\u63CF\u4E0B\u65B9\u7EC8\u7AEF\u4E8C\u7EF4\u7801\uFF0C\u6216\u7528 djinn pair --terminal \u53EA\u663E\u793A\u7EC8\u7AEF\u7801\u3002\uFF09"),e(await s(_))}else e(await s(_)),e("\u7528\u624B\u673A djinn PWA \u626B\u7801\uFF0860 \u79D2\u5185\u6709\u6548\uFF09\u3002");let d=encodeURIComponent(fn(y));for(;;){if(Date.now()>=h)return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;let p;try{p=await r(`${l}/v1/pairing/${d}/status`,{headers:{authorization:`Bearer ${n.token}`}})}catch{await Pc(a);continue}if(p.status===404)return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;if(!p.ok)return e(`\u8F6E\u8BE2\u914D\u5BF9\u72B6\u6001\u5931\u8D25\uFF1AHTTP ${p.status}`),1;let{status:b}=await p.json();if(b==="consumed")return e("\u2713 \u624B\u673A\u5DF2\u914D\u5BF9\u3002"),0;if(b==="expired")return e("\u914D\u5BF9\u7801\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C djinn pair\u3002"),1;await Pc(a)}}me();Ts();import{spawn as dp}from"child_process";import{connect as fp}from"net";function Oc(t){return new Promise(e=>{let r=fp($e(t)),s=i=>{r.destroy(),e(i)};r.on("connect",()=>r.write(JSON.stringify({cmd:"ping"})+`
92
+ `)),r.on("data",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),300)})}async function As(t,e){if(await Oc(t))return;dp(process.execPath,lr(e,["daemon","run-detached"]),{detached:!0,stdio:"ignore",env:process.env}).unref();let s=Date.now()+5e3;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,150)),await Oc(t))return;throw new Error("daemon did not become ready in time")}me();import{createServer as K_,connect as X_}from"net";import{rmSync as Fs,writeFileSync as Q_}from"fs";import{connect as E_}from"net";var B={};os(B,{BRAND:()=>Hp,DIRTY:()=>At,EMPTY_PATH:()=>gp,INVALID:()=>K,NEVER:()=>C_,OK:()=>_e,ParseStatus:()=>fe,Schema:()=>re,ZodAny:()=>pt,ZodArray:()=>Je,ZodBigInt:()=>Pt,ZodBoolean:()=>Lt,ZodBranded:()=>zr,ZodCatch:()=>Wt,ZodDate:()=>Rt,ZodDefault:()=>jt,ZodDiscriminatedUnion:()=>Ls,ZodEffects:()=>xe,ZodEnum:()=>Ht,ZodError:()=>ve,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>Bs,ZodIntersection:()=>Mt,ZodIssueCode:()=>U,ZodLazy:()=>Nt,ZodLiteral:()=>Ut,ZodMap:()=>_r,ZodNaN:()=>gr,ZodNativeEnum:()=>Ft,ZodNever:()=>Le,ZodNull:()=>Dt,ZodNullable:()=>He,ZodNumber:()=>It,ZodObject:()=>ye,ZodOptional:()=>Ce,ZodParsedType:()=>q,ZodPipeline:()=>Vr,ZodPromise:()=>_t,ZodReadonly:()=>$t,ZodRecord:()=>Rs,ZodSchema:()=>re,ZodSet:()=>mr,ZodString:()=>ft,ZodSymbol:()=>fr,ZodTransformer:()=>xe,ZodTuple:()=>Ue,ZodType:()=>re,ZodUndefined:()=>Bt,ZodUnion:()=>Ot,ZodUnknown:()=>Ye,ZodVoid:()=>pr,addIssueToContext:()=>W,any:()=>Yp,array:()=>Xp,bigint:()=>$p,boolean:()=>Vc,coerce:()=>S_,custom:()=>$c,date:()=>qp,datetimeRegex:()=>jc,defaultErrorMap:()=>Ve,discriminatedUnion:()=>r_,effect:()=>p_,enum:()=>u_,function:()=>c_,getErrorMap:()=>hr,getParsedType:()=>Ne,instanceof:()=>jp,intersection:()=>s_,isAborted:()=>Is,isAsync:()=>ur,isDirty:()=>Ps,isValid:()=>dt,late:()=>Fp,lazy:()=>l_,literal:()=>h_,makeIssue:()=>qr,map:()=>o_,nan:()=>Wp,nativeEnum:()=>d_,never:()=>Zp,null:()=>Gp,nullable:()=>m_,number:()=>zc,object:()=>Qp,objectUtil:()=>mn,oboolean:()=>w_,onumber:()=>b_,optional:()=>__,ostring:()=>y_,pipeline:()=>v_,preprocess:()=>g_,promise:()=>f_,quotelessJson:()=>pp,record:()=>n_,set:()=>a_,setErrorMap:()=>mp,strictObject:()=>e_,string:()=>qc,symbol:()=>zp,transformer:()=>p_,tuple:()=>i_,undefined:()=>Vp,union:()=>t_,unknown:()=>Jp,util:()=>ie,void:()=>Kp});var ie;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(n=>typeof i[i[n]]!="number"),a={};for(let n of o)a[n]=i[n];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},t.find=(i,o)=>{for(let a of i)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=s,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ie||(ie={}));var mn;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(mn||(mn={}));var q=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ne=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}};var U=ie.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),pp=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ve=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},s={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)s._errors.push(r(a));else{let n=s,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(n[u]=n[u]||{_errors:[]},n[u]._errors.push(r(a))):n[u]=n[u]||{_errors:[]},n=n[u],l++}}};return i(this),s}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ie.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},s=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else s.push(e(i));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}};ve.create=t=>new ve(t);var _p=(t,e)=>{let r;switch(t.code){case U.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case U.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case U.invalid_union:r="Invalid input";break;case U.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case U.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case U.invalid_arguments:r="Invalid function arguments";break;case U.invalid_return_type:r="Invalid function return type";break;case U.invalid_date:r="Invalid date";break;case U.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ie.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case U.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case U.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case U.custom:r="Invalid input";break;case U.invalid_intersection_types:r="Intersection results could not be merged";break;case U.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case U.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},Ve=_p;var Mc=Ve;function mp(t){Mc=t}function hr(){return Mc}var qr=t=>{let{data:e,path:r,errorMaps:s,issueData:i}=t,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let n="",l=s.filter(u=>!!u).slice().reverse();for(let u of l)n=u(a,{data:e,defaultError:n}).message;return{...i,path:o,message:n}},gp=[];function W(t,e){let r=hr(),s=qr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ve?void 0:Ve].filter(i=>!!i)});t.common.issues.push(s)}var fe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let s=[];for(let i of r){if(i.status==="aborted")return K;i.status==="dirty"&&e.dirty(),s.push(i.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,r){let s=[];for(let i of r){let o=await i.key,a=await i.value;s.push({key:o,value:a})}return t.mergeObjectSync(e,s)}static mergeObjectSync(e,r){let s={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return K;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(s[o.value]=a.value)}return{status:e.value,value:s}}},K=Object.freeze({status:"aborted"}),At=t=>({status:"dirty",value:t}),_e=t=>({status:"valid",value:t}),Is=t=>t.status==="aborted",Ps=t=>t.status==="dirty",dt=t=>t.status==="valid",ur=t=>typeof Promise<"u"&&t instanceof Promise;var G;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}));var Ee=class{constructor(e,r,s,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=s,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Nc=(t,e)=>{if(dt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ve(t.common.issues);return this._error=r,this._error}}};function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:s,description:i}=t;if(e&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,n)=>{let{message:l}=t;return a.code==="invalid_enum_value"?{message:l??n.defaultError}:typeof n.data>"u"?{message:l??s??n.defaultError}:a.code!=="invalid_type"?{message:n.defaultError}:{message:l??r??n.defaultError}},description:i}}var re=class{get description(){return this._def.description}_getType(e){return Ne(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new fe,ctx:{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ur(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let s=this.safeParse(e,r);if(s.success)return s.data;throw s.error}safeParse(e,r){let s={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},i=this._parseSync({data:e,path:s.path,parent:s});return Nc(s,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:r});return dt(s)?{value:s.value}:{issues:r.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>dt(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){let s=await this.safeParseAsync(e,r);if(s.success)return s.data;throw s.error}async safeParseAsync(e,r){let s={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},i=this._parse({data:e,path:s.path,parent:s}),o=await(ur(i)?i:Promise.resolve(i));return Nc(s,o)}refine(e,r){let s=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=e(i),n=()=>o.addIssue({code:U.custom,...s(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(n(),!1)):a?!0:(n(),!1)})}refinement(e,r){return this._refinement((s,i)=>e(s)?!0:(i.addIssue(typeof r=="function"?r(s,i):r),!1))}_refinement(e){return new xe({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ce.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Je.create(this)}promise(){return _t.create(this,this._def)}or(e){return Ot.create([this,e],this._def)}and(e){return Mt.create(this,e,this._def)}transform(e){return new xe({...ee(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new jt({...ee(this._def),innerType:this,defaultValue:r,typeName:X.ZodDefault})}brand(){return new zr({typeName:X.ZodBranded,type:this,...ee(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Wt({...ee(this._def),innerType:this,catchValue:r,typeName:X.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Vr.create(this,e)}readonly(){return $t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vp=/^c[^\s-]{8,}$/i,yp=/^[0-9a-z]+$/,bp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Sp=/^[a-z0-9_-]{21}$/i,Cp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ep=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gn,Tp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ap=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ip=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Pp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Lp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Hc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Bp=new RegExp(`^${Hc}$`);function Fc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Dp(t){return new RegExp(`^${Fc(t)}$`)}function jc(t){let e=`${Hc}T${Fc(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Op(t,e){return!!((e==="v4"||!e)&&Tp.test(t)||(e==="v6"||!e)&&Ip.test(t))}function Mp(t,e){if(!Cp.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Np(t,e){return!!((e==="v4"||!e)&&Ap.test(t)||(e==="v6"||!e)&&Pp.test(t))}var ft=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let o=this._getOrReturnCtx(e);return W(o,{code:U.invalid_type,expected:q.string,received:o.parsedType}),K}let s=new fe,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:U.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:U.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,n=e.data.length<o.value;(a||n)&&(i=this._getOrReturnCtx(e,i),a?W(i,{code:U.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):n&&W(i,{code:U.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),s.dirty())}else if(o.kind==="email")xp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"email",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="emoji")gn||(gn=new RegExp(kp,"u")),gn.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"emoji",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="uuid")wp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"uuid",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="nanoid")Sp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"nanoid",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid")vp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cuid",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid2")yp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cuid2",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="ulid")bp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"ulid",code:U.invalid_string,message:o.message}),s.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),W(i,{validation:"url",code:U.invalid_string,message:o.message}),s.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"regex",code:U.invalid_string,message:o.message}),s.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),W(i,{code:U.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),s.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),W(i,{code:U.invalid_string,validation:{startsWith:o.value},message:o.message}),s.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),W(i,{code:U.invalid_string,validation:{endsWith:o.value},message:o.message}),s.dirty()):o.kind==="datetime"?jc(o).test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:U.invalid_string,validation:"datetime",message:o.message}),s.dirty()):o.kind==="date"?Bp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:U.invalid_string,validation:"date",message:o.message}),s.dirty()):o.kind==="time"?Dp(o).test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{code:U.invalid_string,validation:"time",message:o.message}),s.dirty()):o.kind==="duration"?Ep.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"duration",code:U.invalid_string,message:o.message}),s.dirty()):o.kind==="ip"?Op(e.data,o.version)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"ip",code:U.invalid_string,message:o.message}),s.dirty()):o.kind==="jwt"?Mp(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"jwt",code:U.invalid_string,message:o.message}),s.dirty()):o.kind==="cidr"?Np(e.data,o.version)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"cidr",code:U.invalid_string,message:o.message}),s.dirty()):o.kind==="base64"?Lp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"base64",code:U.invalid_string,message:o.message}),s.dirty()):o.kind==="base64url"?Rp.test(e.data)||(i=this._getOrReturnCtx(e,i),W(i,{validation:"base64url",code:U.invalid_string,message:o.message}),s.dirty()):ie.assertNever(o);return{status:s.value,value:e.data}}_regex(e,r,s){return this.refinement(i=>e.test(i),{validation:r,code:U.invalid_string,...G.errToObj(s)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ft.create=t=>new ft({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...ee(t)});function Up(t,e){let r=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,i=r>s?r:s,o=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var It=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){let o=this._getOrReturnCtx(e);return W(o,{code:U.invalid_type,expected:q.number,received:o.parsedType}),K}let s,i=new fe;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:U.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:U.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:U.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Up(e.data,o.value)!==0&&(s=this._getOrReturnCtx(e,s),W(s,{code:U.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),W(s,{code:U.not_finite,message:o.message}),i.dirty()):ie.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,s,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ie.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(r)&&Number.isFinite(e)}};It.create=t=>new It({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var Pt=class t extends re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let s,i=new fe;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:U.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(s=this._getOrReturnCtx(e,s),W(s,{code:U.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),W(s,{code:U.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ie.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return W(r,{code:U.invalid_type,expected:q.bigint,received:r.parsedType}),K}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,s,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:s,message:G.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pt.create=t=>new Pt({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var Lt=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let s=this._getOrReturnCtx(e);return W(s,{code:U.invalid_type,expected:q.boolean,received:s.parsedType}),K}return _e(e.data)}};Lt.create=t=>new Lt({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var Rt=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let o=this._getOrReturnCtx(e);return W(o,{code:U.invalid_type,expected:q.date,received:o.parsedType}),K}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return W(o,{code:U.invalid_date}),K}let s=new fe,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:U.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),s.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),W(i,{code:U.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),s.dirty()):ie.assertNever(o);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Rt.create=t=>new Rt({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...ee(t)});var fr=class extends re{_parse(e){if(this._getType(e)!==q.symbol){let s=this._getOrReturnCtx(e);return W(s,{code:U.invalid_type,expected:q.symbol,received:s.parsedType}),K}return _e(e.data)}};fr.create=t=>new fr({typeName:X.ZodSymbol,...ee(t)});var Bt=class extends re{_parse(e){if(this._getType(e)!==q.undefined){let s=this._getOrReturnCtx(e);return W(s,{code:U.invalid_type,expected:q.undefined,received:s.parsedType}),K}return _e(e.data)}};Bt.create=t=>new Bt({typeName:X.ZodUndefined,...ee(t)});var Dt=class extends re{_parse(e){if(this._getType(e)!==q.null){let s=this._getOrReturnCtx(e);return W(s,{code:U.invalid_type,expected:q.null,received:s.parsedType}),K}return _e(e.data)}};Dt.create=t=>new Dt({typeName:X.ZodNull,...ee(t)});var pt=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};pt.create=t=>new pt({typeName:X.ZodAny,...ee(t)});var Ye=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};Ye.create=t=>new Ye({typeName:X.ZodUnknown,...ee(t)});var Le=class extends re{_parse(e){let r=this._getOrReturnCtx(e);return W(r,{code:U.invalid_type,expected:q.never,received:r.parsedType}),K}};Le.create=t=>new Le({typeName:X.ZodNever,...ee(t)});var pr=class extends re{_parse(e){if(this._getType(e)!==q.undefined){let s=this._getOrReturnCtx(e);return W(s,{code:U.invalid_type,expected:q.void,received:s.parsedType}),K}return _e(e.data)}};pr.create=t=>new pr({typeName:X.ZodVoid,...ee(t)});var Je=class t extends re{_parse(e){let{ctx:r,status:s}=this._processInputParams(e),i=this._def;if(r.parsedType!==q.array)return W(r,{code:U.invalid_type,expected:q.array,received:r.parsedType}),K;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,n=r.data.length<i.exactLength.value;(a||n)&&(W(r,{code:a?U.too_big:U.too_small,minimum:n?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(W(r,{code:U.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(W(r,{code:U.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((a,n)=>i.type._parseAsync(new Ee(r,a,r.path,n)))).then(a=>fe.mergeArray(s,a));let o=[...r.data].map((a,n)=>i.type._parseSync(new Ee(r,a,r.path,n)));return fe.mergeArray(s,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Je.create=(t,e)=>new Je({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ee(e)});function dr(t){if(t instanceof ye){let e={};for(let r in t.shape){let s=t.shape[r];e[r]=Ce.create(dr(s))}return new ye({...t._def,shape:()=>e})}else return t instanceof Je?new Je({...t._def,type:dr(t.element)}):t instanceof Ce?Ce.create(dr(t.unwrap())):t instanceof He?He.create(dr(t.unwrap())):t instanceof Ue?Ue.create(t.items.map(e=>dr(e))):t}var ye=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){let u=this._getOrReturnCtx(e);return W(u,{code:U.invalid_type,expected:q.object,received:u.parsedType}),K}let{status:s,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||n.push(u);let l=[];for(let u of a){let y=o[u],h=i.data[u];l.push({key:{status:"valid",value:u},value:y._parse(new Ee(i,h,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Le){let u=this._def.unknownKeys;if(u==="passthrough")for(let y of n)l.push({key:{status:"valid",value:y},value:{status:"valid",value:i.data[y]}});else if(u==="strict")n.length>0&&(W(i,{code:U.unrecognized_keys,keys:n}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let y of n){let h=i.data[y];l.push({key:{status:"valid",value:y},value:u._parse(new Ee(i,h,i.path,y)),alwaysSet:y in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let y of l){let h=await y.key,_=await y.value;u.push({key:h,value:_,alwaysSet:y.alwaysSet})}return u}).then(u=>fe.mergeObjectSync(s,u)):fe.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,s)=>{let i=this._def.errorMap?.(r,s).message??s.defaultError;return r.code==="unrecognized_keys"?{message:G.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:X.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let s of ie.objectKeys(e))e[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let s of ie.objectKeys(this.shape))e[s]||(r[s]=this.shape[s]);return new t({...this._def,shape:()=>r})}deepPartial(){return dr(this)}partial(e){let r={};for(let s of ie.objectKeys(this.shape)){let i=this.shape[s];e&&!e[s]?r[s]=i:r[s]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let s of ie.objectKeys(this.shape))if(e&&!e[s])r[s]=this.shape[s];else{let o=this.shape[s];for(;o instanceof Ce;)o=o._def.innerType;r[s]=o}return new t({...this._def,shape:()=>r})}keyof(){return Wc(ie.objectKeys(this.shape))}};ye.create=(t,e)=>new ye({shape:()=>t,unknownKeys:"strip",catchall:Le.create(),typeName:X.ZodObject,...ee(e)});ye.strictCreate=(t,e)=>new ye({shape:()=>t,unknownKeys:"strict",catchall:Le.create(),typeName:X.ZodObject,...ee(e)});ye.lazycreate=(t,e)=>new ye({shape:t,unknownKeys:"strip",catchall:Le.create(),typeName:X.ZodObject,...ee(e)});var Ot=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=this._def.options;function i(o){for(let n of o)if(n.result.status==="valid")return n.result;for(let n of o)if(n.result.status==="dirty")return r.common.issues.push(...n.ctx.common.issues),n.result;let a=o.map(n=>new ve(n.ctx.common.issues));return W(r,{code:U.invalid_union,unionErrors:a}),K}if(r.common.async)return Promise.all(s.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of s){let u={...r,common:{...r.common,issues:[]},parent:null},y=l._parseSync({data:r.data,path:r.path,parent:u});if(y.status==="valid")return y;y.status==="dirty"&&!o&&(o={result:y,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let n=a.map(l=>new ve(l));return W(r,{code:U.invalid_union,unionErrors:n}),K}}get options(){return this._def.options}};Ot.create=(t,e)=>new Ot({options:t,typeName:X.ZodUnion,...ee(e)});var Ge=t=>t instanceof Nt?Ge(t.schema):t instanceof xe?Ge(t.innerType()):t instanceof Ut?[t.value]:t instanceof Ht?t.options:t instanceof Ft?ie.objectValues(t.enum):t instanceof jt?Ge(t._def.innerType):t instanceof Bt?[void 0]:t instanceof Dt?[null]:t instanceof Ce?[void 0,...Ge(t.unwrap())]:t instanceof He?[null,...Ge(t.unwrap())]:t instanceof zr||t instanceof $t?Ge(t.unwrap()):t instanceof Wt?Ge(t._def.innerType):[],Ls=class t extends re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return W(r,{code:U.invalid_type,expected:q.object,received:r.parsedType}),K;let s=this.discriminator,i=r.data[s],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(W(r,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,s){let i=new Map;for(let o of r){let a=Ge(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of a){if(i.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);i.set(n,o)}}return new t({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...ee(s)})}};function vn(t,e){let r=Ne(t),s=Ne(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&s===q.object){let i=ie.objectKeys(e),o=ie.objectKeys(t).filter(n=>i.indexOf(n)!==-1),a={...t,...e};for(let n of o){let l=vn(t[n],e[n]);if(!l.valid)return{valid:!1};a[n]=l.data}return{valid:!0,data:a}}else if(r===q.array&&s===q.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let a=t[o],n=e[o],l=vn(a,n);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===q.date&&s===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Mt=class extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e),i=(o,a)=>{if(Is(o)||Is(a))return K;let n=vn(o.value,a.value);return n.valid?((Ps(o)||Ps(a))&&r.dirty(),{status:r.value,value:n.data}):(W(s,{code:U.invalid_intersection_types}),K)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Mt.create=(t,e,r)=>new Mt({left:t,right:e,typeName:X.ZodIntersection,...ee(r)});var Ue=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==q.array)return W(s,{code:U.invalid_type,expected:q.array,received:s.parsedType}),K;if(s.data.length<this._def.items.length)return W(s,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&s.data.length>this._def.items.length&&(W(s,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...s.data].map((a,n)=>{let l=this._def.items[n]||this._def.rest;return l?l._parse(new Ee(s,a,s.path,n)):null}).filter(a=>!!a);return s.common.async?Promise.all(o).then(a=>fe.mergeArray(r,a)):fe.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ue.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ue({items:t,typeName:X.ZodTuple,rest:null,...ee(e)})};var Rs=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==q.object)return W(s,{code:U.invalid_type,expected:q.object,received:s.parsedType}),K;let i=[],o=this._def.keyType,a=this._def.valueType;for(let n in s.data)i.push({key:o._parse(new Ee(s,n,s.path,n)),value:a._parse(new Ee(s,s.data[n],s.path,n)),alwaysSet:n in s.data});return s.common.async?fe.mergeObjectAsync(r,i):fe.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,s){return r instanceof re?new t({keyType:e,valueType:r,typeName:X.ZodRecord,...ee(s)}):new t({keyType:ft.create(),valueType:e,typeName:X.ZodRecord,...ee(r)})}},_r=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==q.map)return W(s,{code:U.invalid_type,expected:q.map,received:s.parsedType}),K;let i=this._def.keyType,o=this._def.valueType,a=[...s.data.entries()].map(([n,l],u)=>({key:i._parse(new Ee(s,n,s.path,[u,"key"])),value:o._parse(new Ee(s,l,s.path,[u,"value"]))}));if(s.common.async){let n=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,y=await l.value;if(u.status==="aborted"||y.status==="aborted")return K;(u.status==="dirty"||y.status==="dirty")&&r.dirty(),n.set(u.value,y.value)}return{status:r.value,value:n}})}else{let n=new Map;for(let l of a){let u=l.key,y=l.value;if(u.status==="aborted"||y.status==="aborted")return K;(u.status==="dirty"||y.status==="dirty")&&r.dirty(),n.set(u.value,y.value)}return{status:r.value,value:n}}}};_r.create=(t,e,r)=>new _r({valueType:e,keyType:t,typeName:X.ZodMap,...ee(r)});var mr=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.parsedType!==q.set)return W(s,{code:U.invalid_type,expected:q.set,received:s.parsedType}),K;let i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(W(s,{code:U.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(W(s,{code:U.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(l){let u=new Set;for(let y of l){if(y.status==="aborted")return K;y.status==="dirty"&&r.dirty(),u.add(y.value)}return{status:r.value,value:u}}let n=[...s.data.values()].map((l,u)=>o._parse(new Ee(s,l,s.path,u)));return s.common.async?Promise.all(n).then(l=>a(l)):a(n)}min(e,r){return new t({...this._def,minSize:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};mr.create=(t,e)=>new mr({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...ee(e)});var Bs=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.function)return W(r,{code:U.invalid_type,expected:q.function,received:r.parsedType}),K;function s(n,l){return qr({data:n,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hr(),Ve].filter(u=>!!u),issueData:{code:U.invalid_arguments,argumentsError:l}})}function i(n,l){return qr({data:n,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hr(),Ve].filter(u=>!!u),issueData:{code:U.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof _t){let n=this;return _e(async function(...l){let u=new ve([]),y=await n._def.args.parseAsync(l,o).catch(d=>{throw u.addIssue(s(l,d)),u}),h=await Reflect.apply(a,this,y);return await n._def.returns._def.type.parseAsync(h,o).catch(d=>{throw u.addIssue(i(h,d)),u})})}else{let n=this;return _e(function(...l){let u=n._def.args.safeParse(l,o);if(!u.success)throw new ve([s(l,u.error)]);let y=Reflect.apply(a,this,u.data),h=n._def.returns.safeParse(y,o);if(!h.success)throw new ve([i(y,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ue.create(e).rest(Ye.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,s){return new t({args:e||Ue.create([]).rest(Ye.create()),returns:r||Ye.create(),typeName:X.ZodFunction,...ee(s)})}},Nt=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Nt.create=(t,e)=>new Nt({getter:t,typeName:X.ZodLazy,...ee(e)});var Ut=class extends re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return W(r,{received:r.data,code:U.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ut.create=(t,e)=>new Ut({value:t,typeName:X.ZodLiteral,...ee(e)});function Wc(t,e){return new Ht({values:t,typeName:X.ZodEnum,...ee(e)})}var Ht=class t extends re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),s=this._def.values;return W(r,{expected:ie.joinValues(s),received:r.parsedType,code:U.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),s=this._def.values;return W(r,{received:r.data,code:U.invalid_enum_value,options:s}),K}return _e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...r})}};Ht.create=Wc;var Ft=class extends re{_parse(e){let r=ie.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==q.string&&s.parsedType!==q.number){let i=ie.objectValues(r);return W(s,{expected:ie.joinValues(i),received:s.parsedType,code:U.invalid_type}),K}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ie.objectValues(r);return W(s,{received:s.data,code:U.invalid_enum_value,options:i}),K}return _e(e.data)}get enum(){return this._def.values}};Ft.create=(t,e)=>new Ft({values:t,typeName:X.ZodNativeEnum,...ee(e)});var _t=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return W(r,{code:U.invalid_type,expected:q.promise,received:r.parsedType}),K;let s=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return _e(s.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};_t.create=(t,e)=>new _t({type:t,typeName:X.ZodPromise,...ee(e)});var xe=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:s}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{W(s,a),a.fatal?r.abort():r.dirty()},get path(){return s.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(s.data,o);if(s.common.async)return Promise.resolve(a).then(async n=>{if(r.value==="aborted")return K;let l=await this._def.schema._parseAsync({data:n,path:s.path,parent:s});return l.status==="aborted"?K:l.status==="dirty"?At(l.value):r.value==="dirty"?At(l.value):l});{if(r.value==="aborted")return K;let n=this._def.schema._parseSync({data:a,path:s.path,parent:s});return n.status==="aborted"?K:n.status==="dirty"?At(n.value):r.value==="dirty"?At(n.value):n}}if(i.type==="refinement"){let a=n=>{let l=i.refinement(n,o);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return n};if(s.common.async===!1){let n=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?K:(n.status==="dirty"&&r.dirty(),a(n.value),{status:r.value,value:n.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(n=>n.status==="aborted"?K:(n.status==="dirty"&&r.dirty(),a(n.value).then(()=>({status:r.value,value:n.value}))))}if(i.type==="transform")if(s.common.async===!1){let a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!dt(a))return K;let n=i.transform(a.value,o);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:n}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>dt(a)?Promise.resolve(i.transform(a.value,o)).then(n=>({status:r.value,value:n})):K);ie.assertNever(i)}};xe.create=(t,e,r)=>new xe({schema:t,typeName:X.ZodEffects,effect:e,...ee(r)});xe.createWithPreprocess=(t,e,r)=>new xe({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...ee(r)});var Ce=class extends re{_parse(e){return this._getType(e)===q.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ce.create=(t,e)=>new Ce({innerType:t,typeName:X.ZodOptional,...ee(e)});var He=class extends re{_parse(e){return this._getType(e)===q.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};He.create=(t,e)=>new He({innerType:t,typeName:X.ZodNullable,...ee(e)});var jt=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return r.parsedType===q.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};jt.create=(t,e)=>new jt({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var Wt=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ur(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ve(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ve(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};Wt.create=(t,e)=>new Wt({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var gr=class extends re{_parse(e){if(this._getType(e)!==q.nan){let s=this._getOrReturnCtx(e);return W(s,{code:U.invalid_type,expected:q.nan,received:s.parsedType}),K}return{status:"valid",value:e.data}}};gr.create=t=>new gr({typeName:X.ZodNaN,...ee(t)});var Hp=Symbol("zod_brand"),zr=class extends re{_parse(e){let{ctx:r}=this._processInputParams(e),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}},Vr=class t extends re{_parse(e){let{status:r,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?K:o.status==="dirty"?(r.dirty(),At(o.value)):this._def.out._parseAsync({data:o.value,path:s.path,parent:s})})();{let i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?K:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(e,r){return new t({in:e,out:r,typeName:X.ZodPipeline})}},$t=class extends re{_parse(e){let r=this._def.innerType._parse(e),s=i=>(dt(i)&&(i.value=Object.freeze(i.value)),i);return ur(r)?r.then(i=>s(i)):s(r)}unwrap(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:X.ZodReadonly,...ee(e)});function Uc(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function $c(t,e={},r){return t?pt.create().superRefine((s,i)=>{let o=t(s);if(o instanceof Promise)return o.then(a=>{if(!a){let n=Uc(e,s),l=n.fatal??r??!0;i.addIssue({code:"custom",...n,fatal:l})}});if(!o){let a=Uc(e,s),n=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:n})}}):pt.create()}var Fp={object:ye.lazycreate},X;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(X||(X={}));var jp=(t,e={message:`Input not instance of ${t.name}`})=>$c(r=>r instanceof t,e),qc=ft.create,zc=It.create,Wp=gr.create,$p=Pt.create,Vc=Lt.create,qp=Rt.create,zp=fr.create,Vp=Bt.create,Gp=Dt.create,Yp=pt.create,Jp=Ye.create,Zp=Le.create,Kp=pr.create,Xp=Je.create,Qp=ye.create,e_=ye.strictCreate,t_=Ot.create,r_=Ls.create,s_=Mt.create,i_=Ue.create,n_=Rs.create,o_=_r.create,a_=mr.create,c_=Bs.create,l_=Nt.create,h_=Ut.create,u_=Ht.create,d_=Ft.create,f_=_t.create,p_=xe.create,__=Ce.create,m_=He.create,g_=xe.createWithPreprocess,v_=Vr.create,y_=()=>qc().optional(),b_=()=>zc().optional(),w_=()=>Vc().optional(),S_={string:(t=>ft.create({...t,coerce:!0})),number:(t=>It.create({...t,coerce:!0})),boolean:(t=>Lt.create({...t,coerce:!0})),bigint:(t=>Pt.create({...t,coerce:!0})),date:(t=>Rt.create({...t,coerce:!0}))};var C_=K;me();var Gc=B.discriminatedUnion("cmd",[B.object({cmd:B.literal("ping")}).strict(),B.object({cmd:B.literal("new"),adapterId:B.string(),cwd:B.string(),aiCliArgs:B.array(B.string()),label:B.string().max(64).optional()}).strict(),B.object({cmd:B.literal("ls")}).strict(),B.object({cmd:B.literal("attach-info"),sessionId:B.string()}).strict(),B.object({cmd:B.literal("status")}).strict(),B.object({cmd:B.literal("stop")}).strict(),B.object({cmd:B.literal("project"),action:B.enum(["add","ls","rm"]),path:B.string().optional()}).strict()]),x_=B.union([B.object({ok:B.literal(!0),data:B.unknown().optional()}).strict(),B.object({ok:B.literal(!1),code:B.string(),message:B.string()}).strict()]);function Fe(t,e,r=5e3){return new Promise((s,i)=>{let o=E_($e(t)),a="",n=setTimeout(()=>{o.destroy(),i(new Error("daemon command timeout"))},r);o.on("connect",()=>o.write(JSON.stringify(e)+`
93
93
  `)),o.on("data",l=>{a+=l.toString();let u=a.indexOf(`
94
- `);if(u>=0){clearTimeout(n),o.destroy();try{s(v_.parse(JSON.parse(a.slice(0,u))))}catch(y){i(y)}}}),o.on("error",l=>{clearTimeout(n),i(l)})})}jr();ye();import{readFileSync as $c,writeFileSync as y_,renameSync as b_,readdirSync as w_,existsSync as zc}from"fs";function Ls(t,e){Qe(t);let r=fi(t,e.sessionId),s=`${r}.${process.pid}.tmp`;y_(s,JSON.stringify(e,null,2),{mode:384}),b_(s,r)}function dt(t,e){let r=fi(t,e);if(zc(r))return JSON.parse($c(r,"utf8"))}function Vc(t){let e=Kt(t);return zc(e)?w_(e).filter(r=>r.endsWith(".json")).map(r=>JSON.parse($c(`${e}/${r}`,"utf8"))):[]}import{spawn as S_}from"child_process";import{createHash as C_}from"crypto";import{constants as E_}from"fs";import{access as x_}from"fs/promises";import{delimiter as k_,join as T_}from"path";var Gc=1e3,A_=50;async function gn(t){await new Promise(e=>setTimeout(e,t))}async function Rs(t){for(let e of(process.env.PATH??"").split(k_)){if(!e)continue;let r=T_(e,t);try{return await x_(r,E_.X_OK),r}catch{}}}function Bs(t,e,r){let s=r.replace(/\u001b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\s+/g," ").trim(),i=C_("sha256").update(`${t}:${e}:${s}`).digest("hex");return`appr_${t}_${i.slice(0,16)}`}function mr(t){return{type:"terminal.output",stream:t.stream??"pty",text:t.text}}function vn(t){let e=t.replace(/(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),r=e.trimEnd();if(!r)return{kind:"none"};let s=r.split(`
95
- `),i=s[s.length-1].trim(),o=/^[>❯›\$]\s*$/.test(i),a=s.filter(u=>u.trim().length>0).length>3,n=s.slice(0,-1).some(u=>/^\s*>/.test(u)||/^(diff|npm|Installing|Compiling)/i.test(u.trim()));return o&&!a&&!n?{kind:"waiting_input",reason:"prompt",confidence:"high"}:/how can i help/i.test(e)&&o?{kind:"waiting_input",reason:"prompt",confidence:"high"}:{kind:"none"}}function Os(t){return/\b(no|not|without)\s+(approval|permission)\b/i.test(t)||/\bnot required\b/i.test(t)}function Ds(t){let e=t.replace(/\s+/g," ").trim(),r=/\b(permission|approval)\b/i.test(e),s=/\bneeds (?:your )?permission to\b.+\ballow\?/i.test(e),i=/\bdo you want to allow\b/i.test(e),o=/\brequesting approval before\b.+\bapprove\?/i.test(e);if(r&&(s||i||o))return!0;let a=I_(t).replace(/\s+/g,"").toLowerCase(),n=a.includes("doyouwanttoproceed?"),l=/\d+\.yes/.test(a),u=/\d+\.no/.test(a);return!!(n&&l&&u)}function I_(t){return t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-Z\\-_]/g,"")}function Ms(t,e={}){let r=S_(t,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),s=[],i=[],o=!1,a=l=>{s.push(l),s.length>Gc&&s.splice(0,s.length-Gc)},n=(l,u)=>{o||(o=!0,a({type:"session.status",status:"exited",exitCode:l,signal:u,message:`Process exited with code ${l??"null"}${u?` and signal ${u}`:""}`}))};return r.stdout?.on("data",l=>{a(mr({text:l.toString(),stream:"stdout"}))}),r.stderr?.on("data",l=>{a(mr({text:l.toString(),stream:"stderr"}))}),r.on("error",l=>{a({type:"error.reported",code:l.code??"PROCESS_ERROR",message:l.message,recoverable:!1})}),r.on("exit",n),r.on("close",n),{pid:r.pid,writes:i,async read(){return s.splice(0,s.length)},async write(l){if(!r.stdin||r.stdin.destroyed||r.stdin.writableEnded||!r.stdin.writable||o)throw new Error("Child process stdin is not writable because it is closed or destroyed");await new Promise((u,y)=>{r.stdin.write(l,h=>{if(h){y(h);return}i.push(l),u()})})},async stop(){r.killed||(r.kill("SIGTERM"),await gn(A_),o||r.kill("SIGKILL"))}}}var P_={approve:`y
94
+ `);if(u>=0){clearTimeout(n),o.destroy();try{s(x_.parse(JSON.parse(a.slice(0,u))))}catch(y){i(y)}}}),o.on("error",l=>{clearTimeout(n),i(l)})})}cr();me();import{readFileSync as Yc,writeFileSync as k_,renameSync as T_,readdirSync as A_,existsSync as Jc}from"fs";function Ds(t,e){rt(t);let r=gi(t,e.sessionId),s=`${r}.${process.pid}.tmp`;k_(s,JSON.stringify(e,null,2),{mode:384}),T_(s,r)}function mt(t,e){let r=gi(t,e);if(Jc(r))return JSON.parse(Yc(r,"utf8"))}function Zc(t){let e=tt(t);return Jc(e)?A_(e).filter(r=>r.endsWith(".json")).map(r=>JSON.parse(Yc(`${e}/${r}`,"utf8"))):[]}import{spawn as I_}from"child_process";import{createHash as P_}from"crypto";import{constants as L_}from"fs";import{access as R_}from"fs/promises";import{delimiter as B_,join as D_}from"path";var Kc=1e3,O_=50;async function yn(t){await new Promise(e=>setTimeout(e,t))}async function Os(t){for(let e of(process.env.PATH??"").split(B_)){if(!e)continue;let r=D_(e,t);try{return await R_(r,L_.X_OK),r}catch{}}}function Ms(t,e,r){let s=r.replace(/\u001b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\s+/g," ").trim(),i=P_("sha256").update(`${t}:${e}:${s}`).digest("hex");return`appr_${t}_${i.slice(0,16)}`}function vr(t){return{type:"terminal.output",stream:t.stream??"pty",text:t.text}}function bn(t){let e=t.replace(/(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),r=e.trimEnd();if(!r)return{kind:"none"};let s=r.split(`
95
+ `),i=s[s.length-1].trim(),o=/^[>❯›\$]\s*$/.test(i),a=s.filter(u=>u.trim().length>0).length>3,n=s.slice(0,-1).some(u=>/^\s*>/.test(u)||/^(diff|npm|Installing|Compiling)/i.test(u.trim()));return o&&!a&&!n?{kind:"waiting_input",reason:"prompt",confidence:"high"}:/how can i help/i.test(e)&&o?{kind:"waiting_input",reason:"prompt",confidence:"high"}:{kind:"none"}}function Ns(t){return/\b(no|not|without)\s+(approval|permission)\b/i.test(t)||/\bnot required\b/i.test(t)}function Us(t){let e=t.replace(/\s+/g," ").trim(),r=/\b(permission|approval)\b/i.test(e),s=/\bneeds (?:your )?permission to\b.+\ballow\?/i.test(e),i=/\bdo you want to allow\b/i.test(e),o=/\brequesting approval before\b.+\bapprove\?/i.test(e);if(r&&(s||i||o))return!0;let a=M_(t).replace(/\s+/g,"").toLowerCase(),n=a.includes("doyouwanttoproceed?"),l=/\d+\.yes/.test(a),u=/\d+\.no/.test(a);return!!(n&&l&&u)}function M_(t){return t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\x1b[@-Z\\-_]/g,"")}function Hs(t,e={}){let r=I_(t,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),s=[],i=[],o=!1,a=l=>{s.push(l),s.length>Kc&&s.splice(0,s.length-Kc)},n=(l,u)=>{o||(o=!0,a({type:"session.status",status:"exited",exitCode:l,signal:u,message:`Process exited with code ${l??"null"}${u?` and signal ${u}`:""}`}))};return r.stdout?.on("data",l=>{a(vr({text:l.toString(),stream:"stdout"}))}),r.stderr?.on("data",l=>{a(vr({text:l.toString(),stream:"stderr"}))}),r.on("error",l=>{a({type:"error.reported",code:l.code??"PROCESS_ERROR",message:l.message,recoverable:!1})}),r.on("exit",n),r.on("close",n),{pid:r.pid,writes:i,async read(){return s.splice(0,s.length)},async write(l){if(!r.stdin||r.stdin.destroyed||r.stdin.writableEnded||!r.stdin.writable||o)throw new Error("Child process stdin is not writable because it is closed or destroyed");await new Promise((u,y)=>{r.stdin.write(l,h=>{if(h){y(h);return}i.push(l),u()})})},async stop(){r.killed||(r.kill("SIGTERM"),await yn(O_),o||r.kill("SIGKILL"))}}}var N_={approve:`y
96
96
  `,deny:`n
97
- `},L_=500;function R_(t){if(t.textToWrite!==void 0)return[t.textToWrite];let e=t.text.split(`
97
+ `},U_=500;function H_(t){if(t.textToWrite!==void 0)return[t.textToWrite];let e=t.text.split(`
98
98
  `).flatMap((r,s,i)=>s===i.length-1&&r===""&&t.text.endsWith(`
99
- `)?[]:r?[r,"\r"]:["\r"]);return e.length>0?e:["\r"]}function Yc(t,e){return{type:"approval.requested",requestId:Bs("claude_code",t,e),title:t,rawText:e,choices:["approve","deny"],risk:"unknown"}}var B_=8e3;function Jc(){let t="",e=!1;return{id:"claude_code",displayName:"Claude Code",async detect(){let r=await Rs("claude");return r?{available:!0,command:"claude",path:r}:{available:!1,command:"claude",reason:"claude executable not found on PATH"}},async spawn(r={}){return Ms(r.command??"claude",r)},parseOutput(r){let s=[mr(r)],i=this.classifyPrompt(r.text);if(i.kind==="approval")return t="",e||(e=!0,s.push(Yc(i.title,r.text))),s;t=(t+r.text).slice(-B_);let o=this.classifyPrompt(t);return o.kind==="approval"?e||(e=!0,s.push(Yc(o.title,t))):e=!1,s},classifyPrompt(r){return Os(r)?{kind:"none",confidence:"low"}:Ds(r)?{kind:"approval",confidence:"high",title:"Claude Code approval required",risk:"unknown"}:{kind:"none",confidence:"low"}},resolveApprovalInput(r,s,i){return i!==void 0?{text:i,textToWrite:i}:{text:P_[s]}},async writeInput(r,s){let i=R_(s);for(let[o,a]of i.entries())a==="\r"&&o>0&&await gn(L_),await r.write(a)},async stop(r){await r.stop()}}}var jt=Jc();import{constants as O_}from"fs";import{access as D_}from"fs/promises";var M_={approve:`
100
- `,deny:"\x1B"};function N_(t,e){return{type:"approval.requested",requestId:Bs("cursor",t,e),title:t,rawText:e,choices:["approve","deny"],risk:"unknown"}}var Vr={id:"cursor",displayName:"Cursor",async detect(){let t=process.env.DJINN_CURSOR_EXECUTABLE;if(t)try{return await D_(t,O_.X_OK),{available:!0,command:t,path:t}}catch{return{available:!1,command:t,reason:"configured cursor executable is not executable"}}let e=await Rs("cursor");return e?{available:!0,command:"cursor",path:e}:{available:!1,command:"cursor",reason:"cursor executable not found on PATH"}},async spawn(t={}){return Ms(t.command??process.env.DJINN_CURSOR_EXECUTABLE??"cursor",t)},parseOutput(t){let e=[mr(t)],r=this.classifyPrompt(t.text);return r.kind==="approval"&&e.push(N_(r.title,t.text)),e},classifyPrompt(t){return Os(t)?{kind:"none",confidence:"low"}:Ds(t)?{kind:"approval",confidence:"high",title:"Cursor approval required",risk:"unknown"}:{kind:"none",confidence:"low"}},resolveApprovalInput(t,e,r){return r!==void 0?{text:r,textToWrite:r}:{text:M_[e]}},async writeInput(t,e){await t.write(e.text)},async stop(t){await t.stop()}};import{createHash as H_}from"crypto";var U_=[{type:"output",text:`fake adapter ready
101
- `},{type:"approval",title:"Allow fake action?",rawText:"Fake adapter requests approval for smoke testing",description:"Used by the local MVP smoke test.",risk:"low"}];function F_(t,e,r){let s=H_("sha256").update(`${t}:${e}:${r}`).digest("hex");return`appr_${t}_${s.slice(0,16)}`}function j_(t){let e=t.rawText??t.title;return{type:"approval.requested",requestId:F_("fake",t.title,e),title:t.title,description:t.description,rawText:e,choices:["approve","deny"],risk:t.risk??"unknown"}}function W_(t){return t==="approve"?`approve
99
+ `)?[]:r?[r,"\r"]:["\r"]);return e.length>0?e:["\r"]}function Xc(t,e){return{type:"approval.requested",requestId:Ms("claude_code",t,e),title:t,rawText:e,choices:["approve","deny"],risk:"unknown"}}var F_=8e3;function Qc(){let t="",e=!1;return{id:"claude_code",displayName:"Claude Code",async detect(){let r=await Os("claude");return r?{available:!0,command:"claude",path:r}:{available:!1,command:"claude",reason:"claude executable not found on PATH"}},async spawn(r={}){return Hs(r.command??"claude",r)},parseOutput(r){let s=[vr(r)],i=this.classifyPrompt(r.text);if(i.kind==="approval")return t="",e||(e=!0,s.push(Xc(i.title,r.text))),s;t=(t+r.text).slice(-F_);let o=this.classifyPrompt(t);return o.kind==="approval"?e||(e=!0,s.push(Xc(o.title,t))):e=!1,s},classifyPrompt(r){return Ns(r)?{kind:"none",confidence:"low"}:Us(r)?{kind:"approval",confidence:"high",title:"Claude Code approval required",risk:"unknown"}:{kind:"none",confidence:"low"}},resolveApprovalInput(r,s,i){return i!==void 0?{text:i,textToWrite:i}:{text:N_[s]}},async writeInput(r,s){let i=H_(s);for(let[o,a]of i.entries())a==="\r"&&o>0&&await yn(U_),await r.write(a)},async stop(r){await r.stop()}}}var qt=Qc();import{constants as j_}from"fs";import{access as W_}from"fs/promises";var $_={approve:`
100
+ `,deny:"\x1B"};function q_(t,e){return{type:"approval.requested",requestId:Ms("cursor",t,e),title:t,rawText:e,choices:["approve","deny"],risk:"unknown"}}var Gr={id:"cursor",displayName:"Cursor",async detect(){let t=process.env.DJINN_CURSOR_EXECUTABLE;if(t)try{return await W_(t,j_.X_OK),{available:!0,command:t,path:t}}catch{return{available:!1,command:t,reason:"configured cursor executable is not executable"}}let e=await Os("cursor");return e?{available:!0,command:"cursor",path:e}:{available:!1,command:"cursor",reason:"cursor executable not found on PATH"}},async spawn(t={}){return Hs(t.command??process.env.DJINN_CURSOR_EXECUTABLE??"cursor",t)},parseOutput(t){let e=[vr(t)],r=this.classifyPrompt(t.text);return r.kind==="approval"&&e.push(q_(r.title,t.text)),e},classifyPrompt(t){return Ns(t)?{kind:"none",confidence:"low"}:Us(t)?{kind:"approval",confidence:"high",title:"Cursor approval required",risk:"unknown"}:{kind:"none",confidence:"low"}},resolveApprovalInput(t,e,r){return r!==void 0?{text:r,textToWrite:r}:{text:$_[e]}},async writeInput(t,e){await t.write(e.text)},async stop(t){await t.stop()}};import{createHash as z_}from"crypto";var V_=[{type:"output",text:`fake adapter ready
101
+ `},{type:"approval",title:"Allow fake action?",rawText:"Fake adapter requests approval for smoke testing",description:"Used by the local MVP smoke test.",risk:"low"}];function G_(t,e,r){let s=z_("sha256").update(`${t}:${e}:${r}`).digest("hex");return`appr_${t}_${s.slice(0,16)}`}function Y_(t){let e=t.rawText??t.title;return{type:"approval.requested",requestId:G_("fake",t.title,e),title:t.title,description:t.description,rawText:e,choices:["approve","deny"],risk:t.risk??"unknown"}}function J_(t){return t==="approve"?`approve
102
102
  `:`deny
103
- `}function Zc(t={}){let e=t.script??U_,r=[...t.expectedInputs??[]],s;return{id:"fake",displayName:"Fake Adapter",get lastSpawnOptions(){return s},async detect(){return{available:!0,command:"fake"}},async spawn(i){s=i;let o=0,a=[];return{writes:a,async read(){let n=e[o++];return n?n.type==="output"?[{type:"terminal.output",stream:n.stream??"pty",text:n.text}]:[j_(n)]:[]},async write(n){let l=r.shift();if(l!==void 0&&l!==n)throw new Error(`Unexpected fake input: expected ${JSON.stringify(l)}, got ${JSON.stringify(n)}`);a.push(n)},async stop(){}}},parseOutput(i){return[{type:"terminal.output",stream:i.stream??"pty",text:i.text}]},classifyPrompt(i){return{kind:"none",confidence:"low"}},resolveApprovalInput(i,o,a){return a!==void 0?{text:a,textToWrite:a}:{text:W_(o)}},async writeInput(i,o){await i.write(o.text)},async stop(i){await i.stop()}}}var Gr=Zc();var q_={"claude-code":jt,claude_code:jt,cursor:Vr,fake:Gr};async function Yr(t,e){let r=q_[t];if(!r&&!e?.detect)return{ok:!1,reason:`unknown adapter: ${t}`};let i=await(e?.detect??(()=>r.detect()))();return i.available===!1?{ok:!1,reason:i.reason??`${t} executable not found on PATH. Install it and ensure it is on your PATH.`}:{ok:!0}}async function Qc(t){Qe(t.dir);let e=qe(t.dir),r,s=async()=>{r?.(),await new Promise(n=>o.close(()=>n())),Ns(e,{force:!0}),Ns(pi(t.dir),{force:!0})},i={...t,onStop:s},o=$_(n=>Z_(n,i));await G_(o,e),J_(t.dir),V_(pi(t.dir),String(process.pid),{mode:384});let a=t.onStarted?.({stop:s});return a&&typeof a.cleanup=="function"&&(r=a.cleanup),{stop:s}}async function G_(t,e){Ar(e);try{await Kc(t,e);return}catch(s){if(s.code!=="EADDRINUSE")throw s}if(await Y_(e))throw new Error("daemon already running");Ns(e,{force:!0}),await Kc(t,e)}function Kc(t,e){return new Promise((r,s)=>{let i=o=>s(o);t.once("error",i),t.listen(e,()=>{t.removeListener("error",i),r()})})}function Y_(t){return new Promise(e=>{let r=z_(t),s=i=>{r.destroy(),e(i)};r.on("connect",()=>{r.write(JSON.stringify({cmd:"ping"})+`
104
- `)}),r.on("data",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),500)})}function J_(t){for(let e of dn(t))if(!Et(e.pid)){let r=dt(t,e.sessionId);r&&r.status==="running"&&Ls(t,{...r,status:"exited",lastExitAtMs:Date.now()}),Es(t,e.sessionId),Ns(Tr(t,e.sessionId),{force:!0})}}function Z_(t,e){if(!as()){t.destroy();return}let r="";t.on("data",async s=>{r+=s.toString();let i=r.indexOf(`
105
- `);if(i<0)return;let o=r.slice(0,i),a;try{let n=qc.parse(JSON.parse(o));a=await K_(n,e)}catch(n){a={ok:!1,code:"bad_request",message:n instanceof Error?n.message:String(n)}}t.write(JSON.stringify(a)+`
106
- `),t.end()})}async function K_(t,e){switch(t.cmd){case"ping":return{ok:!0};case"ls":return{ok:!0,data:{sessions:Xc(e.dir)}};case"attach-info":{let r=Ct(e.dir,t.sessionId);return!r||!Et(r.pid)?{ok:!1,code:"not_found",message:"no live worker for session"}:{ok:!0,data:{socketPath:r.controlSocketPath}}}case"new":{let r=await Yr(t.adapterId);if(!r.ok)return{ok:!1,code:"spawn_failed",message:r.reason};let{sessionId:s}=await e.forkWorker({adapterId:t.adapterId,cwd:t.cwd,aiCliArgs:t.aiCliArgs,mode:"new",origin:"local",label:t.label});return{ok:!0,data:{sessionId:s}}}case"status":return{ok:!0,data:{pid:process.pid,sessions:Xc(e.dir).length}};case"stop":return setImmediate(()=>{e.onStop?.()}),{ok:!0};case"project":return t.action==="add"?(ls(e.dir,t.path),{ok:!0}):t.action==="rm"?(ho(e.dir,t.path),{ok:!0}):{ok:!0,data:{projects:Xt(e.dir)}};default:return{ok:!1,code:"bad_request",message:"unknown cmd"}}}function Xc(t){let e=new Map(dn(t).filter(s=>Et(s.pid)).map(s=>[s.sessionId,s])),r=[];for(let s of Vc(t)){let i=e.has(s.sessionId);r.push({sessionId:s.sessionId,label:s.label,adapterId:s.adapterId,cwd:s.cwd,status:i?"running":s.status,origin:s.origin})}return r}xs();import{readdirSync as Tg,readFileSync as Ag}from"fs";var gg=Be(Yl(),1),vg=Be(Vs(),1),yg=Be(yr(),1),bg=Be(In(),1),wg=Be(Rn(),1),Sg=Be(Hn(),1),sh=Be(Zs(),1),Cg=Be(rh(),1);var Gt=sh.default;var Fn=B.enum(["cli","pwa","server"]),ih=B.enum(["starting","running","waiting_approval","exited","error"]),nh=B.object({type:B.literal("session.started"),adapterId:B.string().optional(),command:B.array(B.string()).optional(),cwd:B.string().optional(),pid:B.number().int().positive().optional(),termSize:B.object({cols:B.number(),rows:B.number()}).optional()}).strict(),oh=B.object({type:B.literal("session.status"),status:ih,exitCode:B.number().int().nullable().optional(),signal:B.string().nullable().optional(),message:B.string().optional()}).strict(),ah=B.object({type:B.literal("terminal.output"),stream:B.enum(["pty","stdout","stderr"]),text:B.string()}).strict(),ch=B.object({type:B.literal("user.input"),text:B.string(),requestId:B.string().optional(),textToWrite:B.string().optional()}).strict(),lh=B.object({type:B.literal("approval.requested"),requestId:B.string(),title:B.string(),description:B.string().optional(),rawText:B.string().optional(),choices:B.array(B.enum(["approve","deny"])),risk:B.enum(["low","medium","high","unknown"]).optional()}).strict(),hh=B.object({type:B.literal("approval.resolved"),requestId:B.string(),decision:B.enum(["approve","deny"]),reason:B.string().optional(),textToWrite:B.string().optional()}).strict(),uh=B.object({type:B.literal("error.reported"),code:B.string(),message:B.string(),recoverable:B.boolean().optional()}).strict(),dh=B.object({type:B.literal("terminal.resize"),cols:B.number(),rows:B.number()}).strict(),fh=B.object({type:B.literal("terminal.reset"),generationId:B.string(),cols:B.number().int().positive(),rows:B.number().int().positive()}).strict(),ph=B.object({type:B.literal("heartbeat"),status:B.enum(["connected","reconnecting"]),message:B.string().optional()}).strict(),_h=B.object({type:B.literal("agent.waiting_for_input"),reason:B.enum(["prompt","quiet-window"]),confidence:B.enum(["high","medium"])}).strict(),jn=B.discriminatedUnion("type",[nh,oh,ah,ch,lh,hh,uh,dh,fh,ph,_h]);var mh=B.object({t:B.enum(["plain","encrypted"]),value:B.string()}).strict(),Wn=B.object({id:B.string(),seq:B.number().int().positive(),sessionId:B.string(),source:Fn,createdAt:B.number().int().nonnegative(),payload:jn,content:mh.optional()}).strict();var gh=B.object({path:B.string().min(1),label:B.string().optional()}).strict(),Xs=B.object({sessionId:B.string().min(1),cwd:B.string().min(1),adapterId:B.string().min(1),status:B.enum(["running","exited","crashed"]),lastMode:B.enum(["new","resume"]),alive:B.boolean(),createdAtMs:B.number(),lastExitAtMs:B.number().optional(),label:B.string().optional()}).strict(),qn=B.discriminatedUnion("type",[B.object({type:B.literal("new_session"),commandId:B.string().min(1),cwd:B.string().min(1),adapterId:B.string().min(1),label:B.string().max(64).optional()}).strict(),B.object({type:B.literal("wake_session"),commandId:B.string().min(1),sessionId:B.string().min(1)}).strict(),B.object({type:B.literal("list_projects"),commandId:B.string().min(1)}).strict(),B.object({type:B.literal("list_sessions"),commandId:B.string().min(1)}).strict()]),vh=B.enum(["project_not_allowed","daemon_offline","daemon_replaced","spawn_failed","unknown_session","already_running"]),Eg=B.discriminatedUnion("ok",[B.object({commandId:B.string().min(1),ok:B.literal(!0),sessionId:B.string().min(1).optional(),projects:B.array(gh).optional(),sessions:B.array(Xs).optional()}).strict(),B.object({commandId:B.string().min(1),ok:B.literal(!1),code:vh,message:B.string()}).strict()]);jr();ye();import xg from"tls";var kg=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_UNTRUSTED","SELF_SIGNED_CERT_IN_CHAIN"]);function Qs(t){let e=t?.code;return typeof e=="string"&&kg.has(e)}function ei(){return[...xg.rootCertificates]}function ti(t){return t.DJINN_TLS_BUNDLED_CA_FALLBACK!=="0"}function ri(t){let e,r=!1,s=()=>{e&&(clearInterval(e),e=void 0)};return{start(){r=!1,s(),e=setInterval(()=>{if(r){t.log(`[djinn] ${t.label}: pong timeout; terminating dead connection`),t.terminate();return}r=!0,t.ping()},t.intervalMs),e.unref?.()},stop(){s(),r=!1},onPong(){r=!1}}}function si(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?r:e}var ii=new Map;function Ig(t,e){let s=(ii.get(t)??Promise.resolve()).catch(()=>{}).then(e),i=s.catch(()=>{});return ii.set(t,i),i.finally(()=>{ii.get(t)===i&&ii.delete(t)}),s}var $n=new Set;async function Pg(t,e){try{return await Lg(t,e)}catch(r){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:r instanceof Error?r.message:String(r)}}}async function Lg(t,e){if(e.type==="list_projects")return{commandId:e.commandId,ok:!0,projects:Xt(t.dir)};if(e.type==="new_session"){if(!gi(t.dir,e.cwd))return{commandId:e.commandId,ok:!1,code:"project_not_allowed",message:"\u8BE5 owner \u5C1A\u672A\u767B\u8BB0\u8BE5\u76EE\u5F55\uFF0C\u8BF7\u5728\u7535\u8111\u7AEF\u8FD0\u884C djinn project add <path>"};let r=await Yr(e.adapterId);if(!r.ok)return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:r.reason};try{let{sessionId:s}=await t.forkWorker({adapterId:e.adapterId,cwd:e.cwd,aiCliArgs:[],mode:"new",origin:"remote",label:e.label});return{commandId:e.commandId,ok:!0,sessionId:s}}catch(s){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:s instanceof Error?s.message:String(s)}}}if(e.type==="list_sessions"){let r=Kt(t.dir),s;try{s=Tg(r).filter(o=>o.endsWith(".json"))}catch{s=[]}let i=[];for(let o of s){let a;try{a=JSON.parse(Ag(`${r}/${o}`,"utf8"))}catch{continue}let n=a,l=typeof n?.sessionId=="string"?n.sessionId:void 0;if(!l)continue;let u=!1;try{let _=Ct(t.dir,l);u=!!_&&Et(_.pid)}catch{u=!1}let y={sessionId:l,cwd:n.cwd,adapterId:n.adapterId,status:n.status,lastMode:n.lastMode,alive:u,createdAtMs:n.createdAtMs,lastExitAtMs:n.lastExitAtMs,label:n.label},h=Xs.safeParse(y);if(!h.success){process.stderr.write(`[djinn] list_sessions: skipping malformed session record ${o}
107
- `);continue}i.push(h.data)}return{commandId:e.commandId,ok:!0,sessions:i}}return Ig(e.sessionId,async()=>{let r=(t.readSessionCwd??(a=>dt(t.dir,a)?.cwd))(e.sessionId),s=dt(t.dir,e.sessionId);if(!r||!s)return{commandId:e.commandId,ok:!1,code:"unknown_session",message:"no such session"};let i=Ct(t.dir,e.sessionId);if($n.has(e.sessionId)||i&&Et(i.pid))return{commandId:e.commandId,ok:!1,code:"already_running",message:"session already running"};if(!gi(t.dir,r))return{commandId:e.commandId,ok:!1,code:"project_not_allowed",message:"\u5386\u53F2\u76EE\u5F55\u5DF2\u4E0D\u5728\u767D\u540D\u5355\uFF0C\u5524\u9192\u88AB\u62D2\u7EDD"};let o=await Yr(s.adapterId);if(!o.ok)return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:o.reason};try{let{sessionId:a}=await t.forkWorker({adapterId:s.adapterId,cwd:r,aiCliArgs:[],mode:"resume",sessionId:e.sessionId,origin:"remote"});return $n.add(e.sessionId),setTimeout(()=>$n.delete(e.sessionId),3e4).unref?.(),{commandId:e.commandId,ok:!0,sessionId:a}}catch(a){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:a instanceof Error?a.message:String(a)}}})}function yh(t){let e=t.log??(_=>process.stderr.write(_+`
108
- `)),r=t.env??process.env,s=t.pingIntervalMs??si(r.DJINN_CONTROL_PING_MS,2e4),i=!1,o,a=500,n=!1,l,u,y=t.serverUrl.replace(/^http/,"ws").replace(/\/$/,"")+"/v1/control",h=()=>{let _,d={headers:{authorization:`Bearer ${t.token}`}};n&&(d.ca=[...ei()]),o=new Gt(y,d),e(`[djinn] control channel connecting to ${y}${n?" (bundled CA)":""}`),o.on("message",async p=>{let b;try{b=qn.parse(JSON.parse(p.toString()))}catch{return}let c=await Pg(t.deps,b);o?.readyState===Gt.OPEN&&o.send(JSON.stringify(c))}),o.on("open",()=>{a=500,e(`[djinn] control channel connected to ${y}`);let p=o;u?.stop(),_=ri({ping:()=>p?.ping(),terminate:()=>p?.terminate(),log:e,intervalMs:s,label:"control channel"}),u=_,_.start()}),o.on("pong",()=>_?.onPong()),o.on("close",p=>{if(_?.stop(),i){e("[djinn] control channel closed by client");return}e(`[djinn] control channel closed (code=${p}); reconnecting in ${a}ms`),l=setTimeout(()=>{l=void 0,i||h()},a),l.unref?.(),a=Math.min(a*2,3e4)}),o.on("error",p=>{e(`[djinn] control channel error: ${p.message}`),!n&&Qs(p)&&(ti(r)?(n=!0,e("[djinn] control channel: cert chain error; falling back to bundled CA roots on next reconnect")):e("[djinn] control channel: cert chain error; bundled-CA fallback disabled (DJINN_TLS_BUNDLED_CA_FALLBACK=0)"))})};return h(),{close:()=>{i=!0,u?.stop(),l&&(clearTimeout(l),l=void 0),o?.close()}}}ye();import{appendFileSync as Rg}from"fs";function zn(t){return e=>{try{Rg(ao(t),e+`
109
- `)}catch{}}}Zn();import{randomUUID as eo}from"crypto";var ai=class{opts;quietTimer=null;pendingApprovals=new Set;userInputAt=0;lastEmitAt=0;lastOutputText="";disposed=!1;constructor(e){this.opts=e}onTerminalOutput(e){this.disposed||(this.lastOutputText=e,this.resetTimer())}onUserInput(){this.disposed||(this.userInputAt=Date.now(),this.lastEmitAt=0,this.pendingApprovals.clear(),this.clearTimer())}onApprovalRequested(e){this.pendingApprovals.add(e),this.clearTimer()}onApprovalResolved(e){this.pendingApprovals.delete(e)}dispose(){this.disposed=!0,this.clearTimer()}resetTimer(){this.clearTimer(),!(this.pendingApprovals.size>0)&&(this.quietTimer=setTimeout(()=>{this.checkAndEmit()},this.opts.quietWindowMs))}clearTimer(){this.quietTimer!==null&&(clearTimeout(this.quietTimer),this.quietTimer=null)}checkAndEmit(){if(this.disposed||this.pendingApprovals.size>0)return;let e=Date.now();if(e-this.userInputAt<this.opts.userInputCooldownMs||this.lastEmitAt>0&&e-this.lastEmitAt<this.opts.eventCooldownMs)return;let r=vn(this.lastOutputText);r.kind==="waiting_input"?(this.lastEmitAt=e,this.opts.onWaitingForInput(r.reason,r.confidence)):(this.lastEmitAt=e,this.opts.onWaitingForInput("quiet-window","medium"))}};var ci=class{constructor(e){this.options=e;e.waitingDetector&&(this.detector=new ai({...e.waitingDetector,onWaitingForInput:(r,s)=>{this.options.relay.send({type:"agent.waiting_for_input",reason:r,confidence:s})}}))}options;pendingApprovals=new Map;resolvedApprovalRequestIds=new Set;pendingRemoteEvents=[];runningSession;detector;async start(){this.options.relay.onEvent(e=>this.handleRemoteEvent(e)),await this.options.relay.connect?.(),this.runningSession=await this.options.adapter.spawn({args:this.options.args,cwd:this.options.cwd,env:this.options.env,command:this.options.command}),await this.options.relay.send({type:"session.started",adapterId:this.options.adapter.id,command:[this.options.command??this.options.adapter.id,...this.options.args??[]],cwd:this.options.cwd,pid:this.runningSession.pid,termSize:this.runningSession.cols&&this.runningSession.rows?{cols:this.runningSession.cols,rows:this.runningSession.rows}:void 0}),this.runningSession.onResize?.((e,r)=>{this.options.relay.send({type:"terminal.resize",cols:e,rows:r})}),await this.flushPendingRemoteEvents()}async pollOnce(){let r=await this.requireSession().read();for(let s of r)await this.forwardLocalEvent(s)}observeLocalEvents(e){for(let r of e)r.type==="approval.requested"?(this.pendingApprovals.set(r.requestId,r),this.detector?.onApprovalRequested(r.requestId)):r.type==="terminal.output"&&this.detector?.onTerminalOutput(r.text)}async handleRemoteEvent(e){let r="payload"in e?e:void 0,s=r?r.payload:e;if(!this.runningSession&&this.isSessionBoundRemoteEvent(s)){this.pendingRemoteEvents.push(r??s);return}if(s.type==="user.input"){this.detector?.onUserInput(),await this.options.adapter.writeInput(this.requireSession(),{text:s.text,textToWrite:s.textToWrite}),r&&this.options.onRemoteApplied?.(r);return}if(s.type==="approval.resolved"){await this.handleApprovalResolved(s)&&r&&this.options.onRemoteApplied?.(r);return}if(s.type==="terminal.resize"){if(!this.runningSession)return;r&&r.source==="pwa"&&this.options.resizeSession?.(s.cols,s.rows);return}}async stop(){this.detector?.dispose(),this.runningSession&&await this.options.adapter.stop(this.runningSession),await this.options.relay.close?.()}async forwardLocalEvent(e){e.type==="approval.requested"&&(this.pendingApprovals.set(e.requestId,e),this.detector?.onApprovalRequested(e.requestId)),e.type==="terminal.output"&&this.detector?.onTerminalOutput(e.text),await this.options.relay.send(e)}async handleApprovalResolved(e){if(this.resolvedApprovalRequestIds.has(e.requestId))return await this.reportRecoverableError("approval.already_resolved",`Approval request ${e.requestId} was already resolved`),!1;let r=this.pendingApprovals.get(e.requestId);if(!r)return await this.reportRecoverableError("approval.unknown_request",`Approval request ${e.requestId} is not pending`),!1;let s=this.options.adapter.resolveApprovalInput(r,e.decision,e.textToWrite);return this.resolvedApprovalRequestIds.add(e.requestId),this.pendingApprovals.delete(e.requestId),this.detector?.onApprovalResolved(e.requestId),await this.options.adapter.writeInput(this.requireSession(),s),!0}async flushPendingRemoteEvents(){for(;this.pendingRemoteEvents.length>0;){let e=this.pendingRemoteEvents.shift();e&&await this.handleRemoteEvent(e)}}isSessionBoundRemoteEvent(e){return e.type==="user.input"||e.type==="approval.resolved"}async reportRecoverableError(e,r){await this.options.relay.send({type:"error.reported",code:e,message:r,recoverable:!0})}requireSession(){if(!this.runningSession)throw new Error("Session engine has not been started");return this.runningSession}};var li=class{constructor(e){this.options=e;this.reconnectDelayMs=e.reconnectDelayMs??500,this.nextReconnectDelayMs=this.reconnectDelayMs,this.lastHandledSeq=e.initialAfterSeq??0,this.log=e.log??(r=>process.stderr.write(r+`
110
- `)),this.env=e.env??process.env,this.pingIntervalMs=e.pingIntervalMs??si(this.env.DJINN_SESSION_PING_MS,3e4)}options;eventHandlers=new Set;reconnectDelayMs;socket;keepalive;closed=!1;lastHandledSeq;processing=Promise.resolve();nextReconnectDelayMs;reconnectTimer;useBundledCa=!1;log;env;pingIntervalMs;async connect(){this.closed=!1;try{await this.openSocket()}catch{this.scheduleReconnect()}}async send(e,r){let s=this.socket;if(!s||s.readyState!==Gt.OPEN)throw new Error("Relay websocket is not connected");let i=r?.id?{id:r.id,...e}:e;await new Promise((o,a)=>{s.send(JSON.stringify(i),n=>{if(n){a(n);return}o()})})}onEvent(e){this.eventHandlers.add(e)}async close(){this.closed=!0,this.keepalive?.stop(),clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let e=this.nextReconnectDelayMs;this.nextReconnectDelayMs=Math.min(this.nextReconnectDelayMs*2,3e4),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.openSocket().catch(()=>{})},e)}async openSocket(){if(this.closed)return;let e={headers:{authorization:`Bearer ${this.options.token}`}};this.useBundledCa&&(e.ca=[...ei()]);let r=new Gt(this.streamUrl(),e);this.socket=r;let s;this.log(`[djinn] session stream connecting to ${this.streamUrl()}${this.useBundledCa?" (bundled CA)":""}`),r.on("error",i=>{this.log(`[djinn] session stream error: ${i.message}`),!this.useBundledCa&&Qs(i)&&(ti(this.env)?(this.useBundledCa=!0,this.log("[djinn] session stream: cert chain error; falling back to bundled CA roots on next reconnect")):this.log("[djinn] session stream: cert chain error; bundled-CA fallback disabled (DJINN_TLS_BUNDLED_CA_FALLBACK=0)"))}),r.on("pong",()=>s?.onPong()),r.on("message",i=>{let o=this.parseEnvelope(i);o&&this.enqueueEnvelope(o)}),r.on("close",i=>{if(s?.stop(),this.socket===r){if(this.closed){this.log("[djinn] session stream closed by client");return}if(i===4e3){this.log("[djinn] session stream closed (code=4000, replaced by newer cli); not reconnecting"),this.closed=!0;return}this.log(`[djinn] session stream closed (code=${i}); reconnecting`),this.enqueueEnvelope({id:`local-reconnecting-${Date.now()}`,seq:this.lastHandledSeq,sessionId:this.options.sessionId,source:"server",createdAt:Date.now(),payload:{type:"heartbeat",status:"reconnecting"}}),this.scheduleReconnect()}}),await new Promise((i,o)=>{r.once("open",()=>{this.log(`[djinn] session stream connected to ${this.streamUrl()}`),this.options.onConnected?.(),i()}),r.once("error",o)}),this.nextReconnectDelayMs=this.reconnectDelayMs,s=ri({ping:()=>{r.readyState===Gt.OPEN&&r.ping()},terminate:()=>r.terminate(),log:this.log,intervalMs:this.pingIntervalMs,label:"session stream"}),this.keepalive=s,s.start()}streamUrl(){let e=new URL(this.options.serverUrl),r=e.pathname.replace(/\/$/,"");return e.pathname=`${r}/v1/sessions/${encodeURIComponent(this.options.sessionId)}/stream`,e.searchParams.set("role","cli"),e.searchParams.set("afterSeq",String(this.lastHandledSeq)),e.toString()}async handleEnvelope(e){try{await Promise.all([...this.eventHandlers].map(r=>r(e))),this.lastHandledSeq=Math.max(this.lastHandledSeq,e.seq)}catch(r){let s=r instanceof Error?r.message:String(r);process.stderr.write(`Relay handler failed for seq ${e.seq} ${e.payload.type}: ${s}
111
- `)}}parseEnvelope(e){try{let r=JSON.parse(e.toString());return Wn.parse(r)}catch(r){let s=r instanceof Error?r.message:String(r);process.stderr.write(`Relay received invalid envelope: ${s}
112
- `);return}}enqueueEnvelope(e){this.processing=this.processing.then(()=>this.handleEnvelope(e),()=>this.handleEnvelope(e))}};function Kn(t){let e=(r,s)=>{let i=Number(r);return Number.isFinite(i)&&i>0?i:s};return{quietWindowMs:e(t.DJINN_WAITING_QUIET_MS,2e4),userInputCooldownMs:e(t.DJINN_WAITING_USER_COOLDOWN_MS,1e4),eventCooldownMs:e(t.DJINN_WAITING_EVENT_COOLDOWN_MS,3e5)}}var Mg=Be(Th(),1),Ah=Mg,Ih=Ah.Terminal??Ah.default?.Terminal;if(!Ih)throw new Error("@xterm/headless: Terminal export not found");var Ng=Ih;function Hg(t){let e=[];if(t.isBold()&&e.push(1),t.isDim()&&e.push(2),t.isItalic()&&e.push(3),t.isUnderline()&&e.push(4),t.isInverse()&&e.push(7),!t.isFgDefault()){if(t.isFgPalette()){let r=t.getFgColor();r<=7?e.push(30+r):r<=15?e.push(90+(r-8)):e.push(38,5,r)}else if(t.isFgRGB()){let r=t.getFgColor();e.push(38,2,r>>16&255,r>>8&255,r&255)}}if(!t.isBgDefault()){if(t.isBgPalette()){let r=t.getBgColor();r<=7?e.push(40+r):r<=15?e.push(100+(r-8)):e.push(48,5,r)}else if(t.isBgRGB()){let r=t.getBgColor();e.push(48,2,r>>16&255,r>>8&255,r&255)}}return e.length?`\x1B[${e.join(";")}m`:""}var hi=class{constructor(e,r){this.cols=e;this.rows=r;this.term=new Ng({cols:e,rows:r,allowProposedApi:!0,scrollback:0})}cols;rows;term;currentSgr=[];inAltBuffer=!1;async feed(e){let r=e.toString("utf8");this.trackModes(r),await new Promise(s=>this.term.write(r,s))}async resize(e,r){this.cols=e,this.rows=r,this.term.resize(e,r),await new Promise(s=>this.term.write("",s))}async snapshot(){await new Promise(i=>this.term.write("",i));let e=[];this.inAltBuffer&&e.push("\x1B[?1049h"),e.push("\x1B[2J\x1B[H");let r=this.term.buffer.active,s=r.getNullCell();for(let i=0;i<this.rows;i++){let o=r.getLine(i);if(!o)continue;let a=[],n=-1;for(let l=0;l<this.cols;l++){let u=o.getCell(l,s);if(!u){a.push(" ");continue}let y=u.getWidth();if(y===0)continue;let h=u.getChars(),_=Hg(u);a.push(`\x1B[0m${_}${h||" "}`),_===""&&(h===""||h===" ")||(n=a.length-1),y===2&&(l+=1)}if(!(n<0)){e.push(`\x1B[${i+1};1H`);for(let l=0;l<=n;l++)e.push(a[l]);e.push("\x1B[0m")}}return e.push(`\x1B[${r.cursorY+1};${r.cursorX+1}H`),e.push("\x1B[0m"),this.currentSgr.length&&e.push(`\x1B[${this.currentSgr.join(";")}m`),Buffer.from(e.join(""),"utf8")}trackModes(e){e.includes("\x1B[?1049h")&&(this.inAltBuffer=!0),e.includes("\x1B[?1049l")&&(this.inAltBuffer=!1);let r=/\x1b\[([0-9;]*)m/g,s;for(;(s=r.exec(e))!==null;){let i=s[1]===""?["0"]:s[1].split(";");for(let o of i)o==="0"||o===""?this.currentSgr=[]:this.currentSgr.push(o)}}};import*as Lh from"node-pty";var Ug=new Set(["CLAUDECODE","CLAUDE_CODE_CHILD_SESSION","CLAUDE_CODE_SESSION_ID","CLAUDE_CODE_ENTRYPOINT","AI_AGENT"]);function Ph(t){let e={};for(let[r,s]of Object.entries(t))Ug.has(r)||(e[r]=s);return e}async function Fg(t,e,r){return e.command?e.command:(await t.detect()).command??r}async function Rh(t){let e=t.adapter.id==="fake"||t.adapterId==="fake",r=[],s,i=t.cols,o=t.rows,a=_=>{if(r.length===0){s=_;return}for(let d of r)d(_)},n=_=>{if(r.push(_),s&&r.length===1){let d=s;s=void 0,queueMicrotask(()=>_(d))}};if(e){let _=await t.adapter.spawn({args:t.args,cwd:t.cwd,env:t.env});return{pid:_.pid,cols:t.cols,rows:t.rows,get currentCols(){return i},get currentRows(){return o},writes:_.writes,async read(){let d=await _.read();for(let p of d)if(p.type==="terminal.output"){let b=Buffer.from(p.text,"utf8");t.screen.feed(b),t.onAttachBytes(b)}return d},async write(d){await _.write(d)},async stop(){await _.stop()},resize(d,p){i=d,o=p,t.screen.resize(d,p)},onExit(d){n(d)}}}let l=await Fg(t.adapter,{command:t.command},t.adapterId),u=[],y=[],h=Lh.spawn(l,t.args,{cwd:t.cwd,env:Ph(t.env),name:"xterm-256color",cols:t.cols,rows:t.rows});return h.onData(_=>{let d=Buffer.from(_,"utf8");u.push(...t.adapter.parseOutput({text:_,stream:"pty"})),t.screen.feed(d),t.onAttachBytes(d)}),h.onExit(({exitCode:_,signal:d})=>{a({exitCode:_,signal:d?String(d):null})}),{pid:h.pid,cols:h.cols,rows:h.rows,get currentCols(){return i},get currentRows(){return o},writes:y,async read(){return u.splice(0,u.length)},async write(_){y.push(_),h.write(_)},async stop(){h.kill()},resize(_,d){i=_,o=d,h.resize(_,d),t.screen.resize(_,d)},onExit(_){n(_)}}}ye();import{createServer as jg}from"net";import{rmSync as Bh}from"fs";var Xn=0,Oh=1,Wg=1<<20;function Qn(t,e){let r=Buffer.alloc(5);return r.writeUInt8(t,0),r.writeUInt32BE(e.length,1),Buffer.concat([r,e])}function Dh(t,e){let r=Buffer.alloc(8);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),Qn(Oh,r)}var ui=class{constructor(e){this.opts=e}opts;server;conns=new Set;async listen(){Ar(this.opts.socketPath),Bh(this.opts.socketPath,{force:!0}),this.server=jg(e=>this.onConnection(e)),await new Promise((e,r)=>{let s=i=>r(i);this.server.once("error",s),this.server.listen(this.opts.socketPath,()=>{this.server.removeListener("error",s),this.server.on("error",i=>{process.stderr.write(`attach server error: ${i instanceof Error?i.message:String(i)}
113
- `)}),e()})})}onConnection(e){if(!as()){e.destroy();return}let r={socket:e,ready:!1,backlog:[],inbuf:Buffer.alloc(0)};this.conns.add(r),e.on("data",i=>this.consumeInbound(r,i));let s=()=>{this.conns.delete(r)};e.on("close",s),e.on("error",s),this.opts.snapshot().then(i=>{if(!this.conns.has(r)||!e.writable){this.conns.delete(r);return}e.write(i);for(let o of r.backlog)e.write(o);r.backlog=[],r.ready=!0}).catch(()=>this.conns.delete(r))}broadcast(e){for(let r of this.conns)r.socket.writable&&(r.ready?r.socket.write(e):r.backlog.push(e))}consumeInbound(e,r){for(e.inbuf=Buffer.concat([e.inbuf,r]);e.inbuf.length>=5;){let s=e.inbuf.readUInt8(0),i=e.inbuf.readUInt32BE(1);if(i>Wg){e.socket.destroy(),this.conns.delete(e);return}if(e.inbuf.length<5+i)break;let o=e.inbuf.subarray(5,5+i);e.inbuf=e.inbuf.subarray(5+i);try{s===Xn?this.opts.onInput(Buffer.from(o)):s===Oh&&o.length===8&&this.opts.onResize?.(o.readUInt32BE(0),o.readUInt32BE(4))}catch(a){process.stderr.write(`attach input handler error: ${a instanceof Error?a.message:String(a)}
114
- `)}}}get connectionCount(){return this.conns.size}async close(){for(let e of this.conns)e.socket.destroy();this.conns.clear(),this.server&&(await new Promise(e=>this.server.close(()=>e())),Bh(this.opts.socketPath,{force:!0}))}};jr();ye();var qg={"claude-code":jt,claude_code:jt,cursor:Vr,fake:Gr};function $g(t,e,r){return[...t==="new"?["--session-id",e]:["--resume",e],...r]}async function Mh(t){let e=et(t.dir);if(!e)throw new Error("no identity; cannot start worker");let r=qg[t.adapterId];if(!r)throw new Error(`unknown adapter: ${t.adapterId}`);let s=dt(t.dir,t.sessionId),i=t.mode==="resume"&&s?s.appliedSeq:0,o=$g(t.mode,t.sessionId,t.aiCliArgs),a=new hi(80,24),n=eo(),l=eo(),u=i,y=!1,h=()=>t.mode==="resume"&&!y,_=new to,d=(t.relayFactory??zg)({serverUrl:e.serverUrl,sessionId:t.sessionId,token:e.token,initialAfterSeq:i,onConnected:()=>{_.resendStarted(),_.resendReset()}});_.attach(d);let p=D=>{let O=dt(t.dir,t.sessionId)??{sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,origin:t.origin??"local",lastMode:t.mode,appliedSeq:u,createdAtMs:Date.now(),status:"running",...t.label?{label:t.label}:{}};Ls(t.dir,{...O,...D})},b,c,v=new ui({socketPath:Tr(t.dir,t.sessionId),snapshot:()=>a.snapshot(),onInput:D=>{b.write(D.toString("utf8"))},onResize:(D,O)=>{c("cli",D,O)}});b=await(t.spawnPty?t.spawnPty(o):Rh({adapter:r,adapterId:t.adapterId,args:o,cwd:t.cwd,env:t.env??process.env,cols:80,rows:24,screen:a,onAttachBytes:D=>v.broadcast(D)})),await v.listen(),c=(D,O,L)=>{O===b.currentCols&&L===b.currentRows||(b.resize(O,L),_.send({type:"terminal.resize",cols:O,rows:L}))};let g={...r,spawn:async()=>b},f=new ci({sessionId:t.sessionId,adapter:g,relay:_,args:o,cwd:t.cwd,env:t.env??process.env,waitingDetector:Kn(t.env??process.env),onRemoteApplied:D=>{D.payload.type==="user.input"&&(y=!0),D.seq>u&&(u=D.seq,p({appliedSeq:u}))},resizeSession:(D,O)=>{c("pwa",D,O)}});p({status:"running",appliedSeq:u,lastMode:t.mode,lastExitAtMs:void 0}),Pc(t.dir,{pid:process.pid,controlSocketPath:Tr(t.dir,t.sessionId),sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,claudeSessionId:t.sessionId,mode:t.mode,origin:t.origin??"local",startedAtMs:Date.now()}),await f.start();let m={type:"terminal.reset",generationId:n,cols:b.currentCols,rows:b.currentRows};_.rememberReset(m,l),await _.send(m,{id:l}),b.onExit(D=>{A(D)});let w,C=new Promise(D=>{w=D}),k=!1;async function A(D){if(k)return;k=!0;let O=D?.exitCode??0,L=D?.signal??null,R=O!==0||L?"crashed":"exited";await _.sendConfirmed({type:"session.status",status:"exited",exitCode:O,signal:L},2e3),p({status:R,lastExitAtMs:Date.now(),appliedSeq:u}),await v.close(),await _.close(),Es(t.dir,t.sessionId),w()}return{async pumpOnce(){let D=await b.read(),O=h()?D.filter(L=>L.type!=="approval.requested"):D;f.observeLocalEvents(O);for(let L of O)await _.send(L)},shutdown:A,done:C,applyResize:c}}function zg(t){return new li(t)}var to=class{engineHandlers=new Set;pendingConfirm=new Map;startedPayload;resetPayload;resetId;underlying;attach(e){this.underlying=e,e.onEvent(async r=>{r.id&&this.pendingConfirm.has(r.id)&&(this.pendingConfirm.get(r.id)(),this.pendingConfirm.delete(r.id)),await Promise.all([...this.engineHandlers].map(s=>s(r)))})}onEvent(e){this.engineHandlers.add(e)}async connect(){try{await this.underlying?.connect?.()}catch{}}async close(){await this.underlying?.close?.()}resendStarted(){this.startedPayload&&this.send(this.startedPayload)}rememberReset(e,r){this.resetPayload=e,this.resetId=r}resendReset(){this.resetPayload&&this.resetId&&this.send(this.resetPayload,{id:this.resetId})}async send(e,r){e.type==="session.started"&&(this.startedPayload=e);try{await this.underlying?.send(e,r)}catch{}}async sendConfirmed(e,r){let s=eo(),i=new Promise(o=>{this.pendingConfirm.set(s,o),setTimeout(()=>{this.pendingConfirm.delete(s),o()},r)});try{await this.underlying?.send(e,{id:s})}catch{}await i}};import{connect as Vg}from"net";var ro="\x1B";function Gg(){return`${ro}[?1049l${ro}[0m${ro}[?25h`}function Yg(t,e){return e.armed?t.length===1&&t[0]===100?{armed:!1,detach:!0}:{armed:!1,detach:!1}:t.length===1&&t[0]===1?{armed:!0,detach:!1}:{armed:!1,detach:!1}}async function Jg(t,e,r=5e3){let s=Date.now()+r;for(;Date.now()<s;){let i=await Fe(t,{cmd:"attach-info",sessionId:e});if(i.ok)return i.data.socketPath;await new Promise(o=>setTimeout(o,150))}}async function so(t,e){let r=await Jg(t,e);if(!r)return process.stderr.write(`cannot attach: worker for ${e} not ready
115
- `),1;let s=Vg(r),i=()=>{process.stdout.isTTY&&process.stdout.write(Gg()),process.stdin.isTTY&&process.stdin.setRawMode(!1)},o={armed:!1},a=()=>{process.stdout.isTTY&&s.write(Dh(process.stdout.columns||80,process.stdout.rows||24))},n=()=>a();return new Promise(l=>{let u=y=>{i(),process.stdin.pause(),process.stdout.off("resize",n),s.destroy(),l(y)};s.on("connect",()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume()),a(),process.stdout.on("resize",n),process.stdin.on("data",y=>{let h=Yg(y,o);if(o={armed:h.armed},h.detach){u(0);return}h.armed||s.write(Qn(Xn,y))})}),s.on("data",y=>process.stdout.write(y)),s.on("close",()=>u(0)),s.on("error",()=>u(1));for(let y of["SIGINT","SIGTERM","SIGHUP"])process.once(y,()=>u(0))})}async function o0(t,e){switch(t.command){case"new":return e.handlers.newSession(t.config,e);case"attach":return e.handlers.attach(t.config,e);case"ls":return e.handlers.ls(e);case"daemon":return e.handlers.daemon(t.config,e);case"__worker":return e.handlers.worker(t.config,e);case"pair":return e.handlers.pair(t.config,e);case"project":return e.handlers.project(t.config,e);case"update":return e.handlers.update(e)}}function a0(t){if(t.length===0)return`no sessions
103
+ `}function el(t={}){let e=t.script??V_,r=[...t.expectedInputs??[]],s;return{id:"fake",displayName:"Fake Adapter",get lastSpawnOptions(){return s},async detect(){return{available:!0,command:"fake"}},async spawn(i){s=i;let o=0,a=[];return{writes:a,async read(){let n=e[o++];return n?n.type==="output"?[{type:"terminal.output",stream:n.stream??"pty",text:n.text}]:[Y_(n)]:[]},async write(n){let l=r.shift();if(l!==void 0&&l!==n)throw new Error(`Unexpected fake input: expected ${JSON.stringify(l)}, got ${JSON.stringify(n)}`);a.push(n)},async stop(){}}},parseOutput(i){return[{type:"terminal.output",stream:i.stream??"pty",text:i.text}]},classifyPrompt(i){return{kind:"none",confidence:"low"}},resolveApprovalInput(i,o,a){return a!==void 0?{text:a,textToWrite:a}:{text:J_(o)}},async writeInput(i,o){await i.write(o.text)},async stop(i){await i.stop()}}}var Yr=el();var Z_={"claude-code":qt,claude_code:qt,cursor:Gr,fake:Yr};async function Jr(t,e){let r=Z_[t];if(!r&&!e?.detect)return{ok:!1,reason:`unknown adapter: ${t}`};let i=await(e?.detect??(()=>r.detect()))();return i.available===!1?{ok:!1,reason:i.reason??`${t} executable not found on PATH. Install it and ensure it is on your PATH.`}:{ok:!0}}cr();function Zr(t){let e=new Map(xs(t).filter(s=>ut(s.pid)).map(s=>[s.sessionId,s])),r=[];for(let s of Zc(t)){let o=e.has(s.sessionId)?"running":s.status==="running"?"exited":s.status;r.push({sessionId:s.sessionId,label:s.label,adapterId:s.adapterId,cwd:s.cwd,status:o,origin:s.origin})}return r}async function rl(t){rt(t.dir);let e=$e(t.dir),r,s=async()=>{r?.(),await new Promise(n=>o.close(()=>n())),Fs(e,{force:!0}),Fs(Lr(t.dir),{force:!0})},i={...t,onStop:s},o=K_(n=>sm(n,i));await em(o,e),rm(t.dir),Q_(Lr(t.dir),String(process.pid),{mode:384});let a=t.onStarted?.({stop:s});return a&&typeof a.cleanup=="function"&&(r=a.cleanup),{stop:s}}async function em(t,e){qe(e);try{await tl(t,e);return}catch(s){if(s.code!=="EADDRINUSE")throw s}if(await tm(e))throw new Error("daemon already running");Fs(e,{force:!0}),await tl(t,e)}function tl(t,e){return new Promise((r,s)=>{let i=o=>s(o);t.once("error",i),t.listen(e,()=>{t.removeListener("error",i),r()})})}function tm(t){return new Promise(e=>{let r=X_(t),s=i=>{r.destroy(),e(i)};r.on("connect",()=>{r.write(JSON.stringify({cmd:"ping"})+`
104
+ `)}),r.on("data",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),500)})}function rm(t){for(let e of xs(t))if(!ut(e.pid)){let r=mt(t,e.sessionId);r&&r.status==="running"&&Ds(t,{...r,status:"exited",lastExitAtMs:Date.now()}),ks(t,e.sessionId),Fs(Pr(t,e.sessionId),{force:!0})}}function sm(t,e){if(!cs()){t.destroy();return}let r="";t.on("data",async s=>{r+=s.toString();let i=r.indexOf(`
105
+ `);if(i<0)return;let o=r.slice(0,i),a;try{let n=Gc.parse(JSON.parse(o));a=await im(n,e)}catch(n){a={ok:!1,code:"bad_request",message:n instanceof Error?n.message:String(n)}}t.write(JSON.stringify(a)+`
106
+ `),t.end()})}async function im(t,e){switch(t.cmd){case"ping":return{ok:!0};case"ls":return{ok:!0,data:{sessions:Zr(e.dir)}};case"attach-info":{let r=Tt(e.dir,t.sessionId);return!r||!ut(r.pid)?{ok:!1,code:"not_found",message:"no live worker for session"}:{ok:!0,data:{socketPath:r.controlSocketPath}}}case"new":{let r=await Jr(t.adapterId);if(!r.ok)return{ok:!1,code:"spawn_failed",message:r.reason};let{sessionId:s}=await e.forkWorker({adapterId:t.adapterId,cwd:t.cwd,aiCliArgs:t.aiCliArgs,mode:"new",origin:"local",label:t.label});return{ok:!0,data:{sessionId:s}}}case"status":return{ok:!0,data:{pid:process.pid,sessions:Zr(e.dir).length}};case"stop":return setImmediate(()=>{e.onStop?.()}),{ok:!0};case"project":return t.action==="add"?(hs(e.dir,t.path),{ok:!0}):t.action==="rm"?(_o(e.dir,t.path),{ok:!0}):{ok:!0,data:{projects:Qt(e.dir)}};default:return{ok:!1,code:"bad_request",message:"unknown cmd"}}}Ts();import{readdirSync as Dg,readFileSync as Og}from"fs";var Eg=Be(Kl(),1),xg=Be(Js(),1),kg=Be(wr(),1),Tg=Be(Ln(),1),Ag=Be(Dn(),1),Ig=Be(Fn(),1),oh=Be(Qs(),1),Pg=Be(nh(),1);var Zt=oh.default;var Wn=B.enum(["cli","pwa","server"]),ah=B.enum(["starting","running","waiting_approval","exited","error"]),ch=B.object({type:B.literal("session.started"),adapterId:B.string().optional(),command:B.array(B.string()).optional(),cwd:B.string().optional(),pid:B.number().int().positive().optional(),termSize:B.object({cols:B.number(),rows:B.number()}).optional()}).strict(),lh=B.object({type:B.literal("session.status"),status:ah,exitCode:B.number().int().nullable().optional(),signal:B.string().nullable().optional(),message:B.string().optional()}).strict(),hh=B.object({type:B.literal("terminal.output"),stream:B.enum(["pty","stdout","stderr"]),text:B.string()}).strict(),uh=B.object({type:B.literal("user.input"),text:B.string(),requestId:B.string().optional(),textToWrite:B.string().optional()}).strict(),dh=B.object({type:B.literal("approval.requested"),requestId:B.string(),title:B.string(),description:B.string().optional(),rawText:B.string().optional(),choices:B.array(B.enum(["approve","deny"])),risk:B.enum(["low","medium","high","unknown"]).optional()}).strict(),fh=B.object({type:B.literal("approval.resolved"),requestId:B.string(),decision:B.enum(["approve","deny"]),reason:B.string().optional(),textToWrite:B.string().optional()}).strict(),ph=B.object({type:B.literal("error.reported"),code:B.string(),message:B.string(),recoverable:B.boolean().optional()}).strict(),_h=B.object({type:B.literal("terminal.resize"),cols:B.number(),rows:B.number()}).strict(),mh=B.object({type:B.literal("terminal.reset"),generationId:B.string(),cols:B.number().int().positive(),rows:B.number().int().positive()}).strict(),gh=B.object({type:B.literal("heartbeat"),status:B.enum(["connected","reconnecting"]),message:B.string().optional()}).strict(),vh=B.object({type:B.literal("agent.waiting_for_input"),reason:B.enum(["prompt","quiet-window"]),confidence:B.enum(["high","medium"])}).strict(),$n=B.discriminatedUnion("type",[ch,lh,hh,uh,dh,fh,ph,_h,mh,gh,vh]);var yh=B.object({t:B.enum(["plain","encrypted"]),value:B.string()}).strict(),qn=B.object({id:B.string(),seq:B.number().int().positive(),sessionId:B.string(),source:Wn,createdAt:B.number().int().nonnegative(),payload:$n,content:yh.optional()}).strict();var bh=B.object({path:B.string().min(1),label:B.string().optional()}).strict(),ti=B.object({sessionId:B.string().min(1),cwd:B.string().min(1),adapterId:B.string().min(1),status:B.enum(["running","exited","crashed"]),lastMode:B.enum(["new","resume"]),alive:B.boolean(),createdAtMs:B.number(),lastExitAtMs:B.number().optional(),label:B.string().optional()}).strict(),zn=B.discriminatedUnion("type",[B.object({type:B.literal("new_session"),commandId:B.string().min(1),cwd:B.string().min(1),adapterId:B.string().min(1),label:B.string().max(64).optional()}).strict(),B.object({type:B.literal("wake_session"),commandId:B.string().min(1),sessionId:B.string().min(1)}).strict(),B.object({type:B.literal("list_projects"),commandId:B.string().min(1)}).strict(),B.object({type:B.literal("list_sessions"),commandId:B.string().min(1)}).strict()]),wh=B.enum(["project_not_allowed","daemon_offline","daemon_replaced","spawn_failed","unknown_session","already_running"]),Lg=B.discriminatedUnion("ok",[B.object({commandId:B.string().min(1),ok:B.literal(!0),sessionId:B.string().min(1).optional(),projects:B.array(bh).optional(),sessions:B.array(ti).optional()}).strict(),B.object({commandId:B.string().min(1),ok:B.literal(!1),code:wh,message:B.string()}).strict()]);cr();me();import Rg from"tls";var Bg=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","CERT_UNTRUSTED","SELF_SIGNED_CERT_IN_CHAIN"]);function ri(t){let e=t?.code;return typeof e=="string"&&Bg.has(e)}function si(){return[...Rg.rootCertificates]}function ii(t){return t.DJINN_TLS_BUNDLED_CA_FALLBACK!=="0"}function ni(t){let e,r=!1,s=()=>{e&&(clearInterval(e),e=void 0)};return{start(){r=!1,s(),e=setInterval(()=>{if(r){t.log(`[djinn] ${t.label}: pong timeout; terminating dead connection`),t.terminate();return}r=!0,t.ping()},t.intervalMs),e.unref?.()},stop(){s(),r=!1},onPong(){r=!1}}}function oi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?r:e}var ai=new Map;function Mg(t,e){let s=(ai.get(t)??Promise.resolve()).catch(()=>{}).then(e),i=s.catch(()=>{});return ai.set(t,i),i.finally(()=>{ai.get(t)===i&&ai.delete(t)}),s}var Vn=new Set;async function Ng(t,e){try{return await Ug(t,e)}catch(r){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:r instanceof Error?r.message:String(r)}}}async function Ug(t,e){if(e.type==="list_projects")return{commandId:e.commandId,ok:!0,projects:Qt(t.dir)};if(e.type==="new_session"){if(!bi(t.dir,e.cwd))return{commandId:e.commandId,ok:!1,code:"project_not_allowed",message:"\u8BE5 owner \u5C1A\u672A\u767B\u8BB0\u8BE5\u76EE\u5F55\uFF0C\u8BF7\u5728\u7535\u8111\u7AEF\u8FD0\u884C djinn project add <path>"};let r=await Jr(e.adapterId);if(!r.ok)return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:r.reason};try{let{sessionId:s}=await t.forkWorker({adapterId:e.adapterId,cwd:e.cwd,aiCliArgs:[],mode:"new",origin:"remote",label:e.label});return{commandId:e.commandId,ok:!0,sessionId:s}}catch(s){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:s instanceof Error?s.message:String(s)}}}if(e.type==="list_sessions"){let r=tt(t.dir),s;try{s=Dg(r).filter(o=>o.endsWith(".json"))}catch{s=[]}let i=[];for(let o of s){let a;try{a=JSON.parse(Og(`${r}/${o}`,"utf8"))}catch{continue}let n=a,l=typeof n?.sessionId=="string"?n.sessionId:void 0;if(!l)continue;let u=!1;try{let _=Tt(t.dir,l);u=!!_&&ut(_.pid)}catch{u=!1}let y={sessionId:l,cwd:n.cwd,adapterId:n.adapterId,status:n.status,lastMode:n.lastMode,alive:u,createdAtMs:n.createdAtMs,lastExitAtMs:n.lastExitAtMs,label:n.label},h=ti.safeParse(y);if(!h.success){process.stderr.write(`[djinn] list_sessions: skipping malformed session record ${o}
107
+ `);continue}i.push(h.data)}return{commandId:e.commandId,ok:!0,sessions:i}}return Mg(e.sessionId,async()=>{let r=(t.readSessionCwd??(a=>mt(t.dir,a)?.cwd))(e.sessionId),s=mt(t.dir,e.sessionId);if(!r||!s)return{commandId:e.commandId,ok:!1,code:"unknown_session",message:"no such session"};let i=Tt(t.dir,e.sessionId);if(Vn.has(e.sessionId)||i&&ut(i.pid))return{commandId:e.commandId,ok:!1,code:"already_running",message:"session already running"};if(!bi(t.dir,r))return{commandId:e.commandId,ok:!1,code:"project_not_allowed",message:"\u5386\u53F2\u76EE\u5F55\u5DF2\u4E0D\u5728\u767D\u540D\u5355\uFF0C\u5524\u9192\u88AB\u62D2\u7EDD"};let o=await Jr(s.adapterId);if(!o.ok)return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:o.reason};try{let{sessionId:a}=await t.forkWorker({adapterId:s.adapterId,cwd:r,aiCliArgs:[],mode:"resume",sessionId:e.sessionId,origin:"remote"});return Vn.add(e.sessionId),setTimeout(()=>Vn.delete(e.sessionId),3e4).unref?.(),{commandId:e.commandId,ok:!0,sessionId:a}}catch(a){return{commandId:e.commandId,ok:!1,code:"spawn_failed",message:a instanceof Error?a.message:String(a)}}})}function Sh(t){let e=t.log??(_=>process.stderr.write(_+`
108
+ `)),r=t.env??process.env,s=t.pingIntervalMs??oi(r.DJINN_CONTROL_PING_MS,2e4),i=!1,o,a=500,n=!1,l,u,y=t.serverUrl.replace(/^http/,"ws").replace(/\/$/,"")+"/v1/control",h=()=>{let _,d={headers:{authorization:`Bearer ${t.token}`}};n&&(d.ca=[...si()]),o=new Zt(y,d),e(`[djinn] control channel connecting to ${y}${n?" (bundled CA)":""}`),o.on("message",async p=>{let b;try{b=zn.parse(JSON.parse(p.toString()))}catch{return}let c=await Ng(t.deps,b);o?.readyState===Zt.OPEN&&o.send(JSON.stringify(c))}),o.on("open",()=>{a=500,e(`[djinn] control channel connected to ${y}`);let p=o;u?.stop(),_=ni({ping:()=>p?.ping(),terminate:()=>p?.terminate(),log:e,intervalMs:s,label:"control channel"}),u=_,_.start()}),o.on("pong",()=>_?.onPong()),o.on("close",p=>{if(_?.stop(),i){e("[djinn] control channel closed by client");return}e(`[djinn] control channel closed (code=${p}); reconnecting in ${a}ms`),l=setTimeout(()=>{l=void 0,i||h()},a),l.unref?.(),a=Math.min(a*2,3e4)}),o.on("error",p=>{e(`[djinn] control channel error: ${p.message}`),!n&&ri(p)&&(ii(r)?(n=!0,e("[djinn] control channel: cert chain error; falling back to bundled CA roots on next reconnect")):e("[djinn] control channel: cert chain error; bundled-CA fallback disabled (DJINN_TLS_BUNDLED_CA_FALLBACK=0)"))})};return h(),{close:()=>{i=!0,u?.stop(),l&&(clearTimeout(l),l=void 0),o?.close()}}}me();import{appendFileSync as Hg}from"fs";function Gn(t){return e=>{try{Hg(uo(t),e+`
109
+ `)}catch{}}}Qn();import{randomUUID as so}from"crypto";var hi=class{opts;quietTimer=null;pendingApprovals=new Set;userInputAt=0;lastEmitAt=0;lastOutputText="";disposed=!1;constructor(e){this.opts=e}onTerminalOutput(e){this.disposed||(this.lastOutputText=e,this.resetTimer())}onUserInput(){this.disposed||(this.userInputAt=Date.now(),this.lastEmitAt=0,this.pendingApprovals.clear(),this.clearTimer())}onApprovalRequested(e){this.pendingApprovals.add(e),this.clearTimer()}onApprovalResolved(e){this.pendingApprovals.delete(e)}dispose(){this.disposed=!0,this.clearTimer()}resetTimer(){this.clearTimer(),!(this.pendingApprovals.size>0)&&(this.quietTimer=setTimeout(()=>{this.checkAndEmit()},this.opts.quietWindowMs))}clearTimer(){this.quietTimer!==null&&(clearTimeout(this.quietTimer),this.quietTimer=null)}checkAndEmit(){if(this.disposed||this.pendingApprovals.size>0)return;let e=Date.now();if(e-this.userInputAt<this.opts.userInputCooldownMs||this.lastEmitAt>0&&e-this.lastEmitAt<this.opts.eventCooldownMs)return;let r=bn(this.lastOutputText);r.kind==="waiting_input"?(this.lastEmitAt=e,this.opts.onWaitingForInput(r.reason,r.confidence)):(this.lastEmitAt=e,this.opts.onWaitingForInput("quiet-window","medium"))}};var ui=class{constructor(e){this.options=e;e.waitingDetector&&(this.detector=new hi({...e.waitingDetector,onWaitingForInput:(r,s)=>{this.options.relay.send({type:"agent.waiting_for_input",reason:r,confidence:s})}}))}options;pendingApprovals=new Map;resolvedApprovalRequestIds=new Set;pendingRemoteEvents=[];runningSession;detector;async start(){this.options.relay.onEvent(e=>this.handleRemoteEvent(e)),await this.options.relay.connect?.(),this.runningSession=await this.options.adapter.spawn({args:this.options.args,cwd:this.options.cwd,env:this.options.env,command:this.options.command}),await this.options.relay.send({type:"session.started",adapterId:this.options.adapter.id,command:[this.options.command??this.options.adapter.id,...this.options.args??[]],cwd:this.options.cwd,pid:this.runningSession.pid,termSize:this.runningSession.cols&&this.runningSession.rows?{cols:this.runningSession.cols,rows:this.runningSession.rows}:void 0}),this.runningSession.onResize?.((e,r)=>{this.options.relay.send({type:"terminal.resize",cols:e,rows:r})}),await this.flushPendingRemoteEvents()}async pollOnce(){let r=await this.requireSession().read();for(let s of r)await this.forwardLocalEvent(s)}observeLocalEvents(e){for(let r of e)r.type==="approval.requested"?(this.pendingApprovals.set(r.requestId,r),this.detector?.onApprovalRequested(r.requestId)):r.type==="terminal.output"&&this.detector?.onTerminalOutput(r.text)}async handleRemoteEvent(e){let r="payload"in e?e:void 0,s=r?r.payload:e;if(!this.runningSession&&this.isSessionBoundRemoteEvent(s)){this.pendingRemoteEvents.push(r??s);return}if(s.type==="user.input"){this.detector?.onUserInput(),await this.options.adapter.writeInput(this.requireSession(),{text:s.text,textToWrite:s.textToWrite}),r&&this.options.onRemoteApplied?.(r);return}if(s.type==="approval.resolved"){await this.handleApprovalResolved(s)&&r&&this.options.onRemoteApplied?.(r);return}if(s.type==="terminal.resize"){if(!this.runningSession)return;r&&r.source==="pwa"&&this.options.resizeSession?.(s.cols,s.rows);return}}async stop(){this.detector?.dispose(),this.runningSession&&await this.options.adapter.stop(this.runningSession),await this.options.relay.close?.()}async forwardLocalEvent(e){e.type==="approval.requested"&&(this.pendingApprovals.set(e.requestId,e),this.detector?.onApprovalRequested(e.requestId)),e.type==="terminal.output"&&this.detector?.onTerminalOutput(e.text),await this.options.relay.send(e)}async handleApprovalResolved(e){if(this.resolvedApprovalRequestIds.has(e.requestId))return await this.reportRecoverableError("approval.already_resolved",`Approval request ${e.requestId} was already resolved`),!1;let r=this.pendingApprovals.get(e.requestId);if(!r)return await this.reportRecoverableError("approval.unknown_request",`Approval request ${e.requestId} is not pending`),!1;let s=this.options.adapter.resolveApprovalInput(r,e.decision,e.textToWrite);return this.resolvedApprovalRequestIds.add(e.requestId),this.pendingApprovals.delete(e.requestId),this.detector?.onApprovalResolved(e.requestId),await this.options.adapter.writeInput(this.requireSession(),s),!0}async flushPendingRemoteEvents(){for(;this.pendingRemoteEvents.length>0;){let e=this.pendingRemoteEvents.shift();e&&await this.handleRemoteEvent(e)}}isSessionBoundRemoteEvent(e){return e.type==="user.input"||e.type==="approval.resolved"}async reportRecoverableError(e,r){await this.options.relay.send({type:"error.reported",code:e,message:r,recoverable:!0})}requireSession(){if(!this.runningSession)throw new Error("Session engine has not been started");return this.runningSession}};var di=class{constructor(e){this.options=e;this.reconnectDelayMs=e.reconnectDelayMs??500,this.nextReconnectDelayMs=this.reconnectDelayMs,this.lastHandledSeq=e.initialAfterSeq??0,this.log=e.log??(r=>process.stderr.write(r+`
110
+ `)),this.env=e.env??process.env,this.pingIntervalMs=e.pingIntervalMs??oi(this.env.DJINN_SESSION_PING_MS,3e4)}options;eventHandlers=new Set;reconnectDelayMs;socket;keepalive;closed=!1;lastHandledSeq;processing=Promise.resolve();nextReconnectDelayMs;reconnectTimer;useBundledCa=!1;log;env;pingIntervalMs;async connect(){this.closed=!1;try{await this.openSocket()}catch{this.scheduleReconnect()}}async send(e,r){let s=this.socket;if(!s||s.readyState!==Zt.OPEN)throw new Error("Relay websocket is not connected");let i=r?.id?{id:r.id,...e}:e;await new Promise((o,a)=>{s.send(JSON.stringify(i),n=>{if(n){a(n);return}o()})})}onEvent(e){this.eventHandlers.add(e)}async close(){this.closed=!0,this.keepalive?.stop(),clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let e=this.nextReconnectDelayMs;this.nextReconnectDelayMs=Math.min(this.nextReconnectDelayMs*2,3e4),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.openSocket().catch(()=>{})},e)}async openSocket(){if(this.closed)return;let e={headers:{authorization:`Bearer ${this.options.token}`}};this.useBundledCa&&(e.ca=[...si()]);let r=new Zt(this.streamUrl(),e);this.socket=r;let s;this.log(`[djinn] session stream connecting to ${this.streamUrl()}${this.useBundledCa?" (bundled CA)":""}`),r.on("error",i=>{this.log(`[djinn] session stream error: ${i.message}`),!this.useBundledCa&&ri(i)&&(ii(this.env)?(this.useBundledCa=!0,this.log("[djinn] session stream: cert chain error; falling back to bundled CA roots on next reconnect")):this.log("[djinn] session stream: cert chain error; bundled-CA fallback disabled (DJINN_TLS_BUNDLED_CA_FALLBACK=0)"))}),r.on("pong",()=>s?.onPong()),r.on("message",i=>{let o=this.parseEnvelope(i);o&&this.enqueueEnvelope(o)}),r.on("close",i=>{if(s?.stop(),this.socket===r){if(this.closed){this.log("[djinn] session stream closed by client");return}if(i===4e3){this.log("[djinn] session stream closed (code=4000, replaced by newer cli); not reconnecting"),this.closed=!0;return}this.log(`[djinn] session stream closed (code=${i}); reconnecting`),this.enqueueEnvelope({id:`local-reconnecting-${Date.now()}`,seq:this.lastHandledSeq,sessionId:this.options.sessionId,source:"server",createdAt:Date.now(),payload:{type:"heartbeat",status:"reconnecting"}}),this.scheduleReconnect()}}),await new Promise((i,o)=>{r.once("open",()=>{this.log(`[djinn] session stream connected to ${this.streamUrl()}`),this.options.onConnected?.(),i()}),r.once("error",o)}),this.nextReconnectDelayMs=this.reconnectDelayMs,s=ni({ping:()=>{r.readyState===Zt.OPEN&&r.ping()},terminate:()=>r.terminate(),log:this.log,intervalMs:this.pingIntervalMs,label:"session stream"}),this.keepalive=s,s.start()}streamUrl(){let e=new URL(this.options.serverUrl),r=e.pathname.replace(/\/$/,"");return e.pathname=`${r}/v1/sessions/${encodeURIComponent(this.options.sessionId)}/stream`,e.searchParams.set("role","cli"),e.searchParams.set("afterSeq",String(this.lastHandledSeq)),e.toString()}async handleEnvelope(e){try{await Promise.all([...this.eventHandlers].map(r=>r(e))),this.lastHandledSeq=Math.max(this.lastHandledSeq,e.seq)}catch(r){let s=r instanceof Error?r.message:String(r);process.stderr.write(`Relay handler failed for seq ${e.seq} ${e.payload.type}: ${s}
111
+ `)}}parseEnvelope(e){try{let r=JSON.parse(e.toString());return qn.parse(r)}catch(r){let s=r instanceof Error?r.message:String(r);process.stderr.write(`Relay received invalid envelope: ${s}
112
+ `);return}}enqueueEnvelope(e){this.processing=this.processing.then(()=>this.handleEnvelope(e),()=>this.handleEnvelope(e))}};function eo(t){let e=(r,s)=>{let i=Number(r);return Number.isFinite(i)&&i>0?i:s};return{quietWindowMs:e(t.DJINN_WAITING_QUIET_MS,2e4),userInputCooldownMs:e(t.DJINN_WAITING_USER_COOLDOWN_MS,1e4),eventCooldownMs:e(t.DJINN_WAITING_EVENT_COOLDOWN_MS,3e5)}}var Wg=Be(Ph(),1),Lh=Wg,Rh=Lh.Terminal??Lh.default?.Terminal;if(!Rh)throw new Error("@xterm/headless: Terminal export not found");var $g=Rh;function qg(t){let e=[];if(t.isBold()&&e.push(1),t.isDim()&&e.push(2),t.isItalic()&&e.push(3),t.isUnderline()&&e.push(4),t.isInverse()&&e.push(7),!t.isFgDefault()){if(t.isFgPalette()){let r=t.getFgColor();r<=7?e.push(30+r):r<=15?e.push(90+(r-8)):e.push(38,5,r)}else if(t.isFgRGB()){let r=t.getFgColor();e.push(38,2,r>>16&255,r>>8&255,r&255)}}if(!t.isBgDefault()){if(t.isBgPalette()){let r=t.getBgColor();r<=7?e.push(40+r):r<=15?e.push(100+(r-8)):e.push(48,5,r)}else if(t.isBgRGB()){let r=t.getBgColor();e.push(48,2,r>>16&255,r>>8&255,r&255)}}return e.length?`\x1B[${e.join(";")}m`:""}var fi=class{constructor(e,r){this.cols=e;this.rows=r;this.term=new $g({cols:e,rows:r,allowProposedApi:!0,scrollback:0})}cols;rows;term;currentSgr=[];inAltBuffer=!1;async feed(e){let r=e.toString("utf8");this.trackModes(r),await new Promise(s=>this.term.write(r,s))}async resize(e,r){this.cols=e,this.rows=r,this.term.resize(e,r),await new Promise(s=>this.term.write("",s))}async snapshot(){await new Promise(i=>this.term.write("",i));let e=[];this.inAltBuffer&&e.push("\x1B[?1049h"),e.push("\x1B[2J\x1B[H");let r=this.term.buffer.active,s=r.getNullCell();for(let i=0;i<this.rows;i++){let o=r.getLine(i);if(!o)continue;let a=[],n=-1;for(let l=0;l<this.cols;l++){let u=o.getCell(l,s);if(!u){a.push(" ");continue}let y=u.getWidth();if(y===0)continue;let h=u.getChars(),_=qg(u);a.push(`\x1B[0m${_}${h||" "}`),_===""&&(h===""||h===" ")||(n=a.length-1),y===2&&(l+=1)}if(!(n<0)){e.push(`\x1B[${i+1};1H`);for(let l=0;l<=n;l++)e.push(a[l]);e.push("\x1B[0m")}}return e.push(`\x1B[${r.cursorY+1};${r.cursorX+1}H`),e.push("\x1B[0m"),this.currentSgr.length&&e.push(`\x1B[${this.currentSgr.join(";")}m`),Buffer.from(e.join(""),"utf8")}trackModes(e){e.includes("\x1B[?1049h")&&(this.inAltBuffer=!0),e.includes("\x1B[?1049l")&&(this.inAltBuffer=!1);let r=/\x1b\[([0-9;]*)m/g,s;for(;(s=r.exec(e))!==null;){let i=s[1]===""?["0"]:s[1].split(";");for(let o of i)o==="0"||o===""?this.currentSgr=[]:this.currentSgr.push(o)}}};import*as Dh from"node-pty";var zg=new Set(["CLAUDECODE","CLAUDE_CODE_CHILD_SESSION","CLAUDE_CODE_SESSION_ID","CLAUDE_CODE_ENTRYPOINT","AI_AGENT"]);function Bh(t){let e={};for(let[r,s]of Object.entries(t))zg.has(r)||(e[r]=s);return e}async function Vg(t,e,r){return e.command?e.command:(await t.detect()).command??r}async function Oh(t){let e=t.adapter.id==="fake"||t.adapterId==="fake",r=[],s,i=t.cols,o=t.rows,a=_=>{if(r.length===0){s=_;return}for(let d of r)d(_)},n=_=>{if(r.push(_),s&&r.length===1){let d=s;s=void 0,queueMicrotask(()=>_(d))}};if(e){let _=await t.adapter.spawn({args:t.args,cwd:t.cwd,env:t.env});return{pid:_.pid,cols:t.cols,rows:t.rows,get currentCols(){return i},get currentRows(){return o},writes:_.writes,async read(){let d=await _.read();for(let p of d)if(p.type==="terminal.output"){let b=Buffer.from(p.text,"utf8");t.screen.feed(b),t.onAttachBytes(b)}return d},async write(d){await _.write(d)},async stop(){await _.stop()},resize(d,p){i=d,o=p,t.screen.resize(d,p)},onExit(d){n(d)}}}let l=await Vg(t.adapter,{command:t.command},t.adapterId),u=[],y=[],h=Dh.spawn(l,t.args,{cwd:t.cwd,env:Bh(t.env),name:"xterm-256color",cols:t.cols,rows:t.rows});return h.onData(_=>{let d=Buffer.from(_,"utf8");u.push(...t.adapter.parseOutput({text:_,stream:"pty"})),t.screen.feed(d),t.onAttachBytes(d)}),h.onExit(({exitCode:_,signal:d})=>{a({exitCode:_,signal:d?String(d):null})}),{pid:h.pid,cols:h.cols,rows:h.rows,get currentCols(){return i},get currentRows(){return o},writes:y,async read(){return u.splice(0,u.length)},async write(_){y.push(_),h.write(_)},async stop(){h.kill()},resize(_,d){i=_,o=d,h.resize(_,d),t.screen.resize(_,d)},onExit(_){n(_)}}}me();import{createServer as Gg}from"net";import{rmSync as Mh}from"fs";var to=0,Nh=1,Yg=1<<20;function ro(t,e){let r=Buffer.alloc(5);return r.writeUInt8(t,0),r.writeUInt32BE(e.length,1),Buffer.concat([r,e])}function Uh(t,e){let r=Buffer.alloc(8);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),ro(Nh,r)}var pi=class{constructor(e){this.opts=e}opts;server;conns=new Set;async listen(){qe(this.opts.socketPath),Mh(this.opts.socketPath,{force:!0}),this.server=Gg(e=>this.onConnection(e)),await new Promise((e,r)=>{let s=i=>r(i);this.server.once("error",s),this.server.listen(this.opts.socketPath,()=>{this.server.removeListener("error",s),this.server.on("error",i=>{process.stderr.write(`attach server error: ${i instanceof Error?i.message:String(i)}
113
+ `)}),e()})})}onConnection(e){if(!cs()){e.destroy();return}let r={socket:e,ready:!1,backlog:[],inbuf:Buffer.alloc(0)};this.conns.add(r),e.on("data",i=>this.consumeInbound(r,i));let s=()=>{this.conns.delete(r)};e.on("close",s),e.on("error",s),this.opts.snapshot().then(i=>{if(!this.conns.has(r)||!e.writable){this.conns.delete(r);return}e.write(i);for(let o of r.backlog)e.write(o);r.backlog=[],r.ready=!0}).catch(()=>this.conns.delete(r))}broadcast(e){for(let r of this.conns)r.socket.writable&&(r.ready?r.socket.write(e):r.backlog.push(e))}consumeInbound(e,r){for(e.inbuf=Buffer.concat([e.inbuf,r]);e.inbuf.length>=5;){let s=e.inbuf.readUInt8(0),i=e.inbuf.readUInt32BE(1);if(i>Yg){e.socket.destroy(),this.conns.delete(e);return}if(e.inbuf.length<5+i)break;let o=e.inbuf.subarray(5,5+i);e.inbuf=e.inbuf.subarray(5+i);try{s===to?this.opts.onInput(Buffer.from(o)):s===Nh&&o.length===8&&this.opts.onResize?.(o.readUInt32BE(0),o.readUInt32BE(4))}catch(a){process.stderr.write(`attach input handler error: ${a instanceof Error?a.message:String(a)}
114
+ `)}}}get connectionCount(){return this.conns.size}async close(){for(let e of this.conns)e.socket.destroy();this.conns.clear(),this.server&&(await new Promise(e=>this.server.close(()=>e())),Mh(this.opts.socketPath,{force:!0}))}};cr();me();var Jg={"claude-code":qt,claude_code:qt,cursor:Gr,fake:Yr};function Zg(t,e,r){return[...t==="new"?["--session-id",e]:["--resume",e],...r]}async function Hh(t){let e=st(t.dir);if(!e)throw new Error("no identity; cannot start worker");let r=Jg[t.adapterId];if(!r)throw new Error(`unknown adapter: ${t.adapterId}`);let s=mt(t.dir,t.sessionId),i=t.mode==="resume"&&s?s.appliedSeq:0,o=Zg(t.mode,t.sessionId,t.aiCliArgs),a=new fi(80,24),n=so(),l=so(),u=i,y=!1,h=()=>t.mode==="resume"&&!y,_=new io,d=(t.relayFactory??Kg)({serverUrl:e.serverUrl,sessionId:t.sessionId,token:e.token,initialAfterSeq:i,onConnected:()=>{_.resendStarted(),_.resendReset()}});_.attach(d);let p=O=>{let D=mt(t.dir,t.sessionId)??{sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,origin:t.origin??"local",lastMode:t.mode,appliedSeq:u,createdAtMs:Date.now(),status:"running",...t.label?{label:t.label}:{}};Ds(t.dir,{...D,...O})},b,c,v=new pi({socketPath:Pr(t.dir,t.sessionId),snapshot:()=>a.snapshot(),onInput:O=>{b.write(O.toString("utf8"))},onResize:(O,D)=>{c("cli",O,D)}});b=await(t.spawnPty?t.spawnPty(o):Oh({adapter:r,adapterId:t.adapterId,args:o,cwd:t.cwd,env:t.env??process.env,cols:80,rows:24,screen:a,onAttachBytes:O=>v.broadcast(O)})),await v.listen(),c=(O,D,L)=>{D===b.currentCols&&L===b.currentRows||(b.resize(D,L),_.send({type:"terminal.resize",cols:D,rows:L}))};let g={...r,spawn:async()=>b},f=new ui({sessionId:t.sessionId,adapter:g,relay:_,args:o,cwd:t.cwd,env:t.env??process.env,waitingDetector:eo(t.env??process.env),onRemoteApplied:O=>{O.payload.type==="user.input"&&(y=!0),O.seq>u&&(u=O.seq,p({appliedSeq:u}))},resizeSession:(O,D)=>{c("pwa",O,D)}});p({status:"running",appliedSeq:u,lastMode:t.mode,lastExitAtMs:void 0}),Dc(t.dir,{pid:process.pid,controlSocketPath:Pr(t.dir,t.sessionId),sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,claudeSessionId:t.sessionId,mode:t.mode,origin:t.origin??"local",startedAtMs:Date.now()}),await f.start();let m={type:"terminal.reset",generationId:n,cols:b.currentCols,rows:b.currentRows};_.rememberReset(m,l),await _.send(m,{id:l}),b.onExit(O=>{A(O)});let w,C=new Promise(O=>{w=O}),k=!1;async function A(O){if(k)return;k=!0;let D=O?.exitCode??0,L=O?.signal??null,R=D!==0||L?"crashed":"exited";await _.sendConfirmed({type:"session.status",status:"exited",exitCode:D,signal:L},2e3),p({status:R,lastExitAtMs:Date.now(),appliedSeq:u}),await v.close(),await _.close(),ks(t.dir,t.sessionId),w()}return{async pumpOnce(){let O=await b.read(),D=h()?O.filter(L=>L.type!=="approval.requested"):O;f.observeLocalEvents(D);for(let L of D)await _.send(L)},shutdown:A,done:C,applyResize:c}}function Kg(t){return new di(t)}var io=class{engineHandlers=new Set;pendingConfirm=new Map;startedPayload;resetPayload;resetId;underlying;attach(e){this.underlying=e,e.onEvent(async r=>{r.id&&this.pendingConfirm.has(r.id)&&(this.pendingConfirm.get(r.id)(),this.pendingConfirm.delete(r.id)),await Promise.all([...this.engineHandlers].map(s=>s(r)))})}onEvent(e){this.engineHandlers.add(e)}async connect(){try{await this.underlying?.connect?.()}catch{}}async close(){await this.underlying?.close?.()}resendStarted(){this.startedPayload&&this.send(this.startedPayload)}rememberReset(e,r){this.resetPayload=e,this.resetId=r}resendReset(){this.resetPayload&&this.resetId&&this.send(this.resetPayload,{id:this.resetId})}async send(e,r){e.type==="session.started"&&(this.startedPayload=e);try{await this.underlying?.send(e,r)}catch{}}async sendConfirmed(e,r){let s=so(),i=new Promise(o=>{this.pendingConfirm.set(s,o),setTimeout(()=>{this.pendingConfirm.delete(s),o()},r)});try{await this.underlying?.send(e,{id:s})}catch{}await i}};import{connect as Xg}from"net";var no="\x1B";function Qg(){return`${no}[?1049l${no}[0m${no}[?25h`}function e0(t,e){return e.armed?t.length===1&&t[0]===100?{armed:!1,detach:!0}:{armed:!1,detach:!1}:t.length===1&&t[0]===1?{armed:!0,detach:!1}:{armed:!1,detach:!1}}async function t0(t,e,r=5e3){let s=Date.now()+r;for(;Date.now()<s;){let i=await Fe(t,{cmd:"attach-info",sessionId:e});if(i.ok)return i.data.socketPath;await new Promise(o=>setTimeout(o,150))}}async function oo(t,e){let r=await t0(t,e);if(!r)return process.stderr.write(`cannot attach: worker for ${e} not ready
115
+ `),1;let s=Xg(r),i=()=>{process.stdout.isTTY&&process.stdout.write(Qg()),process.stdin.isTTY&&process.stdin.setRawMode(!1)},o={armed:!1},a=()=>{process.stdout.isTTY&&s.write(Uh(process.stdout.columns||80,process.stdout.rows||24))},n=()=>a();return new Promise(l=>{let u=y=>{i(),process.stdin.pause(),process.stdout.off("resize",n),s.destroy(),l(y)};s.on("connect",()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.resume()),a(),process.stdout.on("resize",n),process.stdin.on("data",y=>{let h=e0(y,o);if(o={armed:h.armed},h.detach){u(0);return}h.armed||s.write(ro(to,y))})}),s.on("data",y=>process.stdout.write(y)),s.on("close",()=>u(0)),s.on("error",()=>u(1));for(let y of["SIGINT","SIGTERM","SIGHUP"])process.once(y,()=>u(0))})}me();import{readFileSync as r0,statSync as s0}from"fs";function i0(t){let e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;let r=Math.floor(e/60);if(r<60)return`${r}m`;let s=Math.floor(r/60);if(s<24){let a=r%60;return a>0?`${s}h${a}m`:`${s}h`}let i=Math.floor(s/24),o=s%24;return o>0?`${i}d${o}h`:`${i}d`}function Fh(t,e){let r=Lr(t);try{let s=r0(r,"utf8").trim();if(Number(s)!==e)return;let i=s0(r).mtimeMs;return i0(Date.now()-i)}catch{return}}me();async function m0(t,e){switch(t.command){case"new":return e.handlers.newSession(t.config,e);case"attach":return e.handlers.attach(t.config,e);case"status":return e.handlers.status(e);case"daemon":return e.handlers.daemon(t.config,e);case"__worker":return e.handlers.worker(t.config,e);case"pair":return e.handlers.pair(t.config,e);case"project":return e.handlers.project(t.config,e);case"update":return e.handlers.update(e)}}function g0(t){if(t.length===0)return`no sessions
116
116
  `;let e=t.map(a=>({...a,label:a.label??""})),s=[{sessionId:"SESSION",label:"NAME",adapterId:"ADAPTER",cwd:"CWD",status:"STATUS",origin:"ORIGIN"},...e],i={sessionId:Math.max(...s.map(a=>a.sessionId.length)),label:Math.max(...s.map(a=>a.label.length)),adapterId:Math.max(...s.map(a=>a.adapterId.length)),status:Math.max(...s.map(a=>a.status.length)),origin:Math.max(...s.map(a=>a.origin.length))},o=(a,n)=>a.padEnd(n);return s.map(a=>[o(a.sessionId,i.sessionId),o(a.label,i.label),o(a.adapterId,i.adapterId),o(a.status,i.status),o(a.origin,i.origin),a.cwd].join(" ")).join(`
117
117
  `)+`
118
- `}var c0={async worker(t,e){let r=await Mh({dir:e.dir,sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,mode:t.mode,aiCliArgs:t.aiCliArgs,origin:t.origin,label:t.label}),s=setInterval(()=>{r.pumpOnce().catch(a=>process.stderr.write(`worker pump error: ${a}
119
- `))},150),i=()=>{clearInterval(s),process.exit(0)};r.done.then(i);let o=()=>{r.shutdown()};return process.once("SIGTERM",o),process.once("SIGINT",o),new Promise(()=>{})},async daemon(t,e){if(t.action==="run"||t.action==="run-detached"){let s=et(e.dir),i;try{i=await Qc({dir:e.dir,forkWorker:o=>Promise.resolve(fn({dir:e.dir,entry:e.entry},o)),onStarted:()=>{if(!s){zn(e.dir)("[djinn] control channel disabled: no identity (run `djinn new --invite ...` to register)");return}let o=yh({serverUrl:s.serverUrl,token:s.token,deps:{dir:e.dir,forkWorker:a=>Promise.resolve(fn({dir:e.dir,entry:e.entry},a))},log:zn(e.dir)});return{cleanup:()=>o.close()}}})}catch(o){return o instanceof Error&&/daemon already running/i.test(o.message)?(process.stdout.write(`[djinn] daemon already running; yielding
118
+ `}function lo(t){return qe(t.dir),qe(et(t.dir)),qe(tt(t.dir)),Zr(t.dir)}async function v0(t){let e=await t.ping(t.dir),r=[];if(e){let a;try{let n=await t.sendCommand(t.dir,{cmd:"status"});n.ok&&(a=n.data.pid)}catch{e=await t.ping(t.dir)}if(e){let n=a!==void 0?t.readUptime(t.dir,a):void 0,l=a!==void 0?`PID ${a}`:"PID \u672A\u77E5";r.push(`daemon: \u8FD0\u884C\u4E2D (${l}`+(n?`, \u5DF2\u8FD0\u884C ${n})`:")"))}else r.push("daemon: \u672A\u8FD0\u884C")}else r.push("daemon: \u672A\u8FD0\u884C");let s=t.supervisorInstalled(t.platform),i=t.platform==="darwin"?" (launchd)":t.platform==="linux"?" (systemd)":"";r.push("\u81EA\u542F: "+(s?`\u5DF2\u5B89\u88C5${i}`:"\u672A\u5B89\u88C5"));let o;if(e)try{let a=await t.sendCommand(t.dir,{cmd:"ls"});o=a.ok?a.data.sessions:lo(t)}catch{o=lo(t)}else o=lo(t);return r.push(`\u4F1A\u8BDD: ${o.length} \u4E2A`,""),r.join(`
119
+ `)+`
120
+ `+g0(o)}var y0={async worker(t,e){let r=await Hh({dir:e.dir,sessionId:t.sessionId,cwd:t.cwd,adapterId:t.adapterId,mode:t.mode,aiCliArgs:t.aiCliArgs,origin:t.origin,label:t.label}),s=setInterval(()=>{r.pumpOnce().catch(a=>process.stderr.write(`worker pump error: ${a}
121
+ `))},150),i=()=>{clearInterval(s),process.exit(0)};r.done.then(i);let o=()=>{r.shutdown()};return process.once("SIGTERM",o),process.once("SIGINT",o),new Promise(()=>{})},async daemon(t,e){if(t.action==="run"||t.action==="run-detached"){let s=st(e.dir),i;try{i=await rl({dir:e.dir,forkWorker:o=>Promise.resolve(_n({dir:e.dir,entry:e.entry},o)),onStarted:()=>{if(!s){Gn(e.dir)("[djinn] control channel disabled: no identity (run `djinn new --invite ...` to register)");return}let o=Sh({serverUrl:s.serverUrl,token:s.token,deps:{dir:e.dir,forkWorker:a=>Promise.resolve(_n({dir:e.dir,entry:e.entry},a))},log:Gn(e.dir)});return{cleanup:()=>o.close()}}})}catch(o){return o instanceof Error&&/daemon already running/i.test(o.message)?(process.stdout.write(`[djinn] daemon already running; yielding
120
122
  `),0):(process.stderr.write(`[djinn] daemon failed to start: ${o instanceof Error?o.message:String(o)}
121
- `),1)}return process.once("SIGTERM",()=>{i.stop().finally(()=>process.exit(0))}),process.once("SIGINT",()=>{i.stop().finally(()=>process.exit(0))}),new Promise(()=>{})}if(t.action==="install"||t.action==="uninstall"){let s={platform:process.platform,dir:e.dir,execPath:process.execPath,entry:e.entry,loadIdentity:()=>et(e.dir),pingDaemon:()=>ss(e.dir),stopDaemon:async()=>{await Fe(e.dir,{cmd:"stop"})},waitForSocketGone:()=>is(e.dir),verifySupervisorActive:()=>oi(process.platform,{uid:process.getuid?.()??0,exec:async(i,o)=>{let{execFile:a}=await import("child_process"),{promisify:n}=await import("util");try{let{stdout:l}=await n(a)(i,o);return{ok:!0,stdout:l}}catch(l){return{ok:!1,stdout:l.stdout??""}}}}),writeConfig:async(i,o)=>{let{mkdir:a,writeFile:n}=await import("fs/promises"),{dirname:l}=await import("path");await a(l(i),{recursive:!0}),await n(i,o,{mode:420})},removeConfig:async i=>{let{rm:o}=await import("fs/promises");await o(i,{force:!0})},runCommand:async(i,o)=>{let{execFile:a}=await import("child_process"),{promisify:n}=await import("util");await n(a)(i,o)}};try{return t.action==="install"?(await Yn(s),process.stdout.write(`djinn daemon installed
122
- `)):(await Jn(s),process.stdout.write(`djinn daemon uninstalled
123
+ `),1)}return process.once("SIGTERM",()=>{i.stop().finally(()=>process.exit(0))}),process.once("SIGINT",()=>{i.stop().finally(()=>process.exit(0))}),new Promise(()=>{})}if(t.action==="install"||t.action==="uninstall"){let s={platform:process.platform,dir:e.dir,execPath:process.execPath,entry:e.entry,loadIdentity:()=>st(e.dir),pingDaemon:()=>Tr(e.dir),stopDaemon:async()=>{await Fe(e.dir,{cmd:"stop"})},waitForSocketGone:()=>ns(e.dir),verifySupervisorActive:()=>li(process.platform,{uid:process.getuid?.()??0,exec:async(i,o)=>{let{execFile:a}=await import("child_process"),{promisify:n}=await import("util");try{let{stdout:l}=await n(a)(i,o);return{ok:!0,stdout:l}}catch(l){return{ok:!1,stdout:l.stdout??""}}}}),writeConfig:async(i,o)=>{let{mkdir:a,writeFile:n}=await import("fs/promises"),{dirname:l}=await import("path");await a(l(i),{recursive:!0}),await n(i,o,{mode:420})},removeConfig:async i=>{let{rm:o}=await import("fs/promises");await o(i,{force:!0})},runCommand:async(i,o)=>{let{execFile:a}=await import("child_process"),{promisify:n}=await import("util");await n(a)(i,o)}};try{return t.action==="install"?(await Kn(s),process.stdout.write(`djinn daemon installed
124
+ `)):(await Xn(s),process.stdout.write(`djinn daemon uninstalled
123
125
  `)),0}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
124
126
  `),1}}let r=await Fe(e.dir,{cmd:t.action});return process.stdout.write(`${JSON.stringify(r)}
125
- `),r.ok?0:1},async newSession(t,e){try{await mo({dir:e.dir,serverUrl:t.server,invite:t.invite,label:n0()})}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
126
- `),1}await Wr(e.dir,e.entry);let r=await Fe(e.dir,{cmd:"new",adapterId:t.adapterId,cwd:t.cwd,aiCliArgs:t.aiCliArgs,...t.label?{label:t.label}:{}});if(!r.ok)return process.stderr.write(`${r.message}
127
+ `),r.ok?0:1},async newSession(t,e){try{await bo({dir:e.dir,serverUrl:t.server,invite:t.invite,label:_0()})}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
128
+ `),1}await As(e.dir,e.entry);let r=await Fe(e.dir,{cmd:"new",adapterId:t.adapterId,cwd:t.cwd,aiCliArgs:t.aiCliArgs,...t.label?{label:t.label}:{}});if(!r.ok)return process.stderr.write(`${r.message}
127
129
  `),1;let s=r.data.sessionId;return t.detach?(process.stdout.write(`${s}
128
- `),0):so(e.dir,s)},async attach(t,e){return so(e.dir,t.sessionId)},async ls(t){await Wr(t.dir,t.entry);let e=await Fe(t.dir,{cmd:"ls"});if(!e.ok)return process.stderr.write(`${e.message}
129
- `),1;let r=e.data.sessions;return process.stdout.write(a0(r)),0},async pair(t,e){try{return await Tc({dir:e.dir,png:t.png,pngPath:t.pngPath})}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
130
- `),1}},async project(t,e){await Wr(e.dir,e.entry);let r=await Fe(e.dir,{cmd:"project",action:t.action,path:t.path});if(r.ok&&t.action==="ls"){let s=r.data?.projects??[];if(s.length===0)process.stdout.write(`no projects
130
+ `),0):oo(e.dir,s)},async attach(t,e){return oo(e.dir,t.sessionId)},async status(t){let e={dir:t.dir,ping:Tr,sendCommand:Fe,supervisorInstalled:Zn,platform:process.platform,readUptime:Fh};try{return process.stdout.write(await v0(e)),0}catch(r){return process.stderr.write(`\u72B6\u6001\u76EE\u5F55\u5F02\u5E38\u6216\u8BFB\u53D6\u5931\u8D25: ${r instanceof Error?r.message:String(r)}
131
+ `),1}},async pair(t,e){try{return await Lc({dir:e.dir,png:t.png,pngPath:t.pngPath})}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
132
+ `),1}},async project(t,e){await As(e.dir,e.entry);let r=await Fe(e.dir,{cmd:"project",action:t.action,path:t.path});if(r.ok&&t.action==="ls"){let s=r.data?.projects??[];if(s.length===0)process.stdout.write(`no projects
131
133
  `);else for(let i of s)process.stdout.write(`${i.label?`${i.label} `:""}${i.path}
132
134
  `)}else process.stdout.write(`${JSON.stringify(r)}
133
- `);return r.ok?0:1},async update(t){let{runUpdate:e}=await Promise.resolve().then(()=>(qh(),Wh)),{resolveGlobalRoot:r}=await Promise.resolve().then(()=>(no(),jh)),{isSupervisorInstalled:s,MAC_LABEL:i,SYSTEMD_UNIT_NAME:o}=await Promise.resolve().then(()=>(Zn(),xh)),{execFile:a}=await import("child_process"),{promisify:n}=await import("util"),{realpathSync:l}=await import("fs"),u=n(a),y=(()=>{try{return l(process.argv[1]??"")}catch{return process.argv[1]??""}})();return e({currentVersion:Vh,entryPath:y,resolveGlobalRoot:r,fetchLatest:async()=>(await u("npm",["view","@hown/djinn","version"])).stdout.trim(),npmInstallLatest:async()=>{await u("npm",["i","-g","@hown/djinn@latest"])},supervisorInstalled:()=>s(process.platform),restartSupervised:async()=>{if(await Fe(t.dir,{cmd:"stop"}).catch(()=>{}),!await is(t.dir))throw new Error("\u65E7 daemon \u672A\u5728\u8D85\u65F6\u5185\u9000\u51FA,\u5DF2\u4E2D\u6B62\u91CD\u542F(\u907F\u514D\u53CC daemon)");let h=process.getuid?.()??0;if(process.platform==="darwin"?await u("launchctl",["kickstart","-k",`gui/${h}/${i}`]):await u("systemctl",["--user","restart",o]),!await oi(process.platform,{uid:h,exec:async(d,p)=>{try{let{stdout:b}=await u(d,p);return{ok:!0,stdout:b}}catch(b){return{ok:!1,stdout:b.stdout??""}}}}))throw new Error("supervisor \u91CD\u542F\u540E\u672A\u5728\u8D85\u65F6\u5185\u53D8\u4E3A active")},restartUnmanaged:async()=>{if(await Fe(t.dir,{cmd:"stop"}).catch(()=>{}),!await is(t.dir))throw new Error("\u65E7 daemon \u672A\u5728\u8D85\u65F6\u5185\u9000\u51FA,\u5DF2\u4E2D\u6B62\u91CD\u542F(\u907F\u514D\u53CC daemon)");await Wr(t.dir,t.entry)},log:h=>process.stdout.write(`${h}
134
- `)})}},l0=`djinn \u2014 AI \u7F16\u7A0B CLI \u7684\u8FDC\u7A0B\u63A7\u5236\u5DE5\u5177
135
+ `);return r.ok?0:1},async update(t){let{runUpdate:e}=await Promise.resolve().then(()=>(Zh(),Jh)),{resolveGlobalRoots:r}=await Promise.resolve().then(()=>(co(),Yh)),{isSupervisorInstalled:s,MAC_LABEL:i,SYSTEMD_UNIT_NAME:o}=await Promise.resolve().then(()=>(Qn(),Ah)),{execFile:a}=await import("child_process"),{promisify:n}=await import("util"),{realpathSync:l}=await import("fs"),u=n(a),y=(()=>{try{return l(process.argv[1]??"")}catch{return process.argv[1]??""}})();return e({currentVersion:Qh,entryPath:y,resolveGlobalRoots:r,fetchLatest:async h=>(await u(h,["view","@hown/djinn","version"])).stdout.trim(),installLatest:async h=>{h==="pnpm"?await u("pnpm",["add","-g","@hown/djinn@latest"]):await u("npm",["i","-g","@hown/djinn@latest"])},supervisorInstalled:()=>s(process.platform),restartSupervised:async()=>{if(await Fe(t.dir,{cmd:"stop"}).catch(()=>{}),!await ns(t.dir))throw new Error("\u65E7 daemon \u672A\u5728\u8D85\u65F6\u5185\u9000\u51FA,\u5DF2\u4E2D\u6B62\u91CD\u542F(\u907F\u514D\u53CC daemon)");let h=process.getuid?.()??0;if(process.platform==="darwin"?await u("launchctl",["kickstart","-k",`gui/${h}/${i}`]):await u("systemctl",["--user","restart",o]),!await li(process.platform,{uid:h,exec:async(d,p)=>{try{let{stdout:b}=await u(d,p);return{ok:!0,stdout:b}}catch(b){return{ok:!1,stdout:b.stdout??""}}}}))throw new Error("supervisor \u91CD\u542F\u540E\u672A\u5728\u8D85\u65F6\u5185\u53D8\u4E3A active")},restartUnmanaged:async()=>{if(await Fe(t.dir,{cmd:"stop"}).catch(()=>{}),!await ns(t.dir))throw new Error("\u65E7 daemon \u672A\u5728\u8D85\u65F6\u5185\u9000\u51FA,\u5DF2\u4E2D\u6B62\u91CD\u542F(\u907F\u514D\u53CC daemon)");await As(t.dir,t.entry)},log:h=>process.stdout.write(`${h}
136
+ `)})}},b0=`djinn \u2014 AI \u7F16\u7A0B CLI \u7684\u8FDC\u7A0B\u63A7\u5236\u5DE5\u5177
135
137
 
136
138
  \u7528\u6CD5: djinn <\u547D\u4EE4> [\u9009\u9879]
137
139
 
@@ -142,15 +144,15 @@ ${T.join(`
142
144
  \u521B\u5EFA\u540E\u81EA\u52A8 attach,\u9664\u975E --detach\u3002
143
145
  attach <sessionId>
144
146
  \u628A\u672C\u5730\u7EC8\u7AEF\u8FDE\u63A5\u5230\u4E00\u4E2A\u6B63\u5728\u8FD0\u884C\u7684\u4F1A\u8BDD\u3002Ctrl-A d \u5206\u79BB(\u4E0D\u6740\u4F1A\u8BDD)\u3002
145
- ls \u5217\u51FA\u4F1A\u8BDD(SESSION / NAME / ADAPTER / STATUS / ORIGIN / CWD)\u3002
147
+ status \u663E\u793A daemon \u8FDB\u7A0B\u72B6\u6001(\u8FD0\u884C/PID/\u5DF2\u8FD0\u884C\u65F6\u957F)\u3001OS \u81EA\u542F\u662F\u5426\u5DF2\u5B89\u88C5,\u4EE5\u53CA\u4F1A\u8BDD\u5217\u8868\u3002
146
148
  pair \u751F\u6210\u914D\u5BF9\u4E8C\u7EF4\u7801,\u4F9B\u624B\u673A PWA \u626B\u7801\u52A0\u5165\u540C\u4E00 owner\u3002
147
149
  project <add|rm|ls> [path]
148
150
  \u7BA1\u7406\u9879\u76EE\u767D\u540D\u5355(\u63A7\u5236\u624B\u673A\u80FD\u5728\u54EA\u4E9B\u76EE\u5F55\u521B\u5EFA/\u5524\u9192\u4F1A\u8BDD)\u3002
149
- daemon <run|run-detached|status|stop|install|uninstall>
151
+ daemon <run|run-detached|stop|install|uninstall>
150
152
  \u7BA1\u7406\u5E38\u9A7B daemon\u3002install \u6CE8\u518C OS \u7EA7\u81EA\u542F(launchd / systemd)\u3002
151
153
  update
152
154
  \u628A\u5168\u5C40\u5B89\u88C5\u7684 @hown/djinn \u66F4\u65B0\u5230\u6700\u65B0\u7248,\u5E76\u91CD\u542F daemon \u542F\u7528\u65B0\u4EE3\u7801\u3002
153
155
  help \u663E\u793A\u672C\u5E2E\u52A9(\u7B49\u540C djinn --help)\u3002
154
- `;function h0(t){let e=t[2];return e===void 0||e==="--help"||e==="-h"||e==="help"?"help":e==="--version"||e==="-V"?"version":"command"}var Vh="0.1.1";async function u0(t=process.argv,e=process.env,r=po()){let s=h0(t);if(s==="help"){process.stdout.write(l0);return}if(s==="version"){process.stdout.write(`${Vh}
155
- `);return}let i;try{i=oo(t,e)}catch(n){process.stderr.write(`${n instanceof Error?n.message:String(n)}
156
- `),process.exitCode=1;return}let o=process.argv[1]??"",a=await o0(i,{dir:r,entry:o,handlers:c0});a!==0&&(process.exitCode=a)}function d0(){let t=process.argv[1];if(!t)return!1;if(t.includes("index.ts"))return!0;try{let e=i0(t);if(import.meta.url===zh($h(e)).href)return!0}catch{}return import.meta.url===zh($h(t)).href}d0()&&u0();export{o0 as dispatchCommand,u0 as main,Kn as readWaitingDetectorConfig,c0 as realHandlers,h0 as resolveTopLevel};
156
+ `;function w0(t){let e=t[2];return e===void 0||e==="--help"||e==="-h"||e==="help"?"help":e==="--version"||e==="-V"?"version":"command"}var Qh="0.1.4";async function S0(t=process.argv,e=process.env,r=vo()){let s=w0(t);if(s==="help"){process.stdout.write(b0);return}if(s==="version"){process.stdout.write(`${Qh}
157
+ `);return}let i;try{i=ho(t,e)}catch(n){process.stderr.write(`${n instanceof Error?n.message:String(n)}
158
+ `),process.exitCode=1;return}let o=process.argv[1]??"",a=await m0(i,{dir:r,entry:o,handlers:y0});a!==0&&(process.exitCode=a)}function C0(){let t=process.argv[1];if(!t)return!1;if(t.includes("index.ts"))return!0;try{let e=p0(t);if(import.meta.url===Xh(Kh(e)).href)return!0}catch{}return import.meta.url===Xh(Kh(t)).href}C0()&&S0();export{m0 as dispatchCommand,S0 as main,eo as readWaitingDetectorConfig,y0 as realHandlers,v0 as renderStatus,w0 as resolveTopLevel};