@vibelet/cli 0.0.5 → 0.0.6

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.cjs +42 -42
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,29 +1,29 @@
1
- "use strict";var $c=Object.create;var Yi=Object.defineProperty;var Vc=Object.getOwnPropertyDescriptor;var Yc=Object.getOwnPropertyNames;var Jc=Object.getPrototypeOf,Kc=Object.prototype.hasOwnProperty;var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Xc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yc(e))!Kc.call(t,i)&&i!==n&&Yi(t,i,{get:()=>e[i],enumerable:!(r=Vc(e,i))||r.enumerable});return t};var ze=(t,e,n)=>(n=t!=null?$c(Jc(t)):{},Xc(e||!t||!t.__esModule?Yi(n,"default",{value:t,enumerable:!0}):n,t));var ce=m((Rg,Xi)=>{"use strict";var Ji=["nodebuffer","arraybuffer","fragments"],Ki=typeof Blob<"u";Ki&&Ji.push("blob");Xi.exports={BINARY_TYPES:Ji,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ki,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var xt=m((Pg,an)=>{"use strict";var{EMPTY_BUFFER:Zc}=ce(),Qn=Buffer[Symbol.species];function Qc(t,e){if(t.length===0)return Zc;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let s=t[i];n.set(s,r),r+=s.length}return r<e?new Qn(n.buffer,n.byteOffset,r):n}function Zi(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function Qi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function eu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function er(t){if(er.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Qn(t):ArrayBuffer.isView(t)?e=new Qn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),er.readOnly=!1),e}an.exports={concat:Qc,mask:Zi,toArrayBuffer:eu,toBuffer:er,unmask:Qi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");an.exports.mask=function(e,n,r,i,s){s<48?Zi(e,n,r,i,s):t.mask(e,n,r,i,s)},an.exports.unmask=function(e,n){e.length<32?Qi(e,n):t.unmask(e,n)}}catch{}});var ns=m((Lg,ts)=>{"use strict";var es=Symbol("kDone"),tr=Symbol("kRun"),nr=class{constructor(e){this[es]=()=>{this.pending--,this[tr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[tr]()}[tr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[es])}}};ts.exports=nr});var At=m((Ng,os)=>{"use strict";var Et=require("zlib"),rs=xt(),tu=ns(),{kStatusCode:is}=ce(),nu=Buffer[Symbol.species],ru=Buffer.from([0,0,255,255]),cn=Symbol("permessage-deflate"),ue=Symbol("total-length"),$e=Symbol("callback"),ge=Symbol("buffers"),Ve=Symbol("error"),ln,rr=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!ln){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ln=new tu(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[$e];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){ln.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){ln.add(i=>{this._compress(e,n,(s,o)=>{i(),r(s,o)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Et.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[cn]=this,this._inflate[ue]=0,this._inflate[ge]=[],this._inflate.on("error",su),this._inflate.on("data",ss)}this._inflate[$e]=r,this._inflate.write(e),n&&this._inflate.write(ru),this._inflate.flush(()=>{let s=this._inflate[Ve];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=rs.concat(this._inflate[ge],this._inflate[ue]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ue]=0,this._inflate[ge]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Et.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ue]=0,this._deflate[ge]=[],this._deflate.on("data",iu)}this._deflate[$e]=r,this._deflate.write(e),this._deflate.flush(Et.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=rs.concat(this._deflate[ge],this._deflate[ue]);n&&(s=new nu(s.buffer,s.byteOffset,s.length-4)),this._deflate[$e]=null,this._deflate[ue]=0,this._deflate[ge]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};os.exports=rr;function iu(t){this[ge].push(t),this[ue]+=t.length}function ss(t){if(this[ue]+=t.length,this[cn]._maxPayload<1||this[ue]<=this[cn]._maxPayload){this[ge].push(t);return}this[Ve]=new RangeError("Max payload size exceeded"),this[Ve].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ve][is]=1009,this.removeListener("data",ss),this.reset()}function su(t){if(this[cn]._inflate=null,this[Ve]){this[$e](this[Ve]);return}t[is]=1007,this[$e](t)}});var Ye=m((Og,un)=>{"use strict";var{isUtf8:as}=require("buffer"),{hasBlob:ou}=ce(),au=[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 lu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ir(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function cu(t){return ou&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}un.exports={isBlob:cu,isValidStatusCode:lu,isValidUTF8:ir,tokenChars:au};if(as)un.exports.isValidUTF8=function(t){return t.length<24?ir(t):as(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");un.exports.isValidUTF8=function(e){return e.length<32?ir(e):t(e)}}catch{}});var cr=m((Mg,ps)=>{"use strict";var{Writable:uu}=require("stream"),ls=At(),{BINARY_TYPES:du,EMPTY_BUFFER:cs,kStatusCode:fu,kWebSocket:hu}=ce(),{concat:sr,toArrayBuffer:pu,unmask:gu}=xt(),{isValidStatusCode:mu,isValidUTF8:us}=Ye(),dn=Buffer[Symbol.species],V=0,ds=1,fs=2,hs=3,or=4,ar=5,fn=6,lr=class extends uu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||du[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[hu]=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=V}_write(e,n,r){if(this._opcode===8&&this._state==V)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new dn(r.buffer,r.byteOffset+e,r.length-e),new dn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new dn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case V:this.getInfo(e);break;case ds:this.getPayloadLength16(e);break;case fs:this.getPayloadLength64(e);break;case hs:this.getMask();break;case or:this.getData(e);break;case ar:case fn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[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 r=(n[0]&64)===64;if(r&&!this._extensions[ls.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){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=r}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(r){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=(n[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=ds:this._payloadLength===127?this._state=fs: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 n=this.consume(8),r=n.readUInt32BE(0);if(r>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=r*Math.pow(2,32)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=hs:this._state=or}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=or}getData(e){let n=cs;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&gu(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ar,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[ls.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return n(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(s)}this.dataMessage(n),this._state===V&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=V;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=sr(r,n):this._binaryType==="arraybuffer"?i=pu(sr(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=V):(this._state=fn,setImmediate(()=>{this.emit("message",i,!0),this._state=V,this.startLoop(e)}))}else{let i=sr(r,n);if(!this._skipUTF8Validation&&!us(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===ar||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=V):(this._state=fn,setImmediate(()=>{this.emit("message",i,!1),this._state=V,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,cs),this.end();else{let r=e.readUInt16BE(0);if(!mu(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new dn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!us(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=V;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=V):(this._state=fn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=V,this.startLoop(n)}))}createError(e,n,r,i,s){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=s,o[fu]=i,o}};ps.exports=lr});var fr=m((Dg,ys)=>{"use strict";var{Duplex:Bg}=require("stream"),{randomFillSync:yu}=require("crypto"),gs=At(),{EMPTY_BUFFER:_u,kWebSocket:Su,NOOP:vu}=ce(),{isBlob:Je,isValidStatusCode:wu}=Ye(),{mask:ms,toBuffer:ke}=xt(),Y=Symbol("kByteLength"),bu=Buffer.alloc(4),hn=8*1024,Re,Ke=hn,ee=0,Iu=1,xu=2,ur=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ee,this.onerror=vu,this[Su]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||bu,n.generateMask?n.generateMask(r):(Ke===hn&&(Re===void 0&&(Re=Buffer.alloc(hn)),yu(Re,0,hn),Ke=0),r[0]=Re[Ke++],r[1]=Re[Ke++],r[2]=Re[Ke++],r[3]=Re[Ke++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[Y]!==void 0?a=n[Y]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(s+=8,l=127):a>125&&(s+=2,l=126);let c=Buffer.allocUnsafe(i?a+s:s);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[s-4]=r[0],c[s-3]=r[1],c[s-2]=r[2],c[s-1]=r[3],o?[c,e]:i?(ms(e,r,c,s,a),[c]):(ms(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,i){let s;if(e===void 0)s=_u;else{if(typeof e!="number"||!wu(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof n=="string"?s.write(n,2):s.set(n,2)}}let o={[Y]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ee?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):Je(e)?(i=e.size,s=!1):(e=ke(e),i=e.length,s=ke.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Y]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Je(e)?this._state!==ee?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ee?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):Je(e)?(i=e.size,s=!1):(e=ke(e),i=e.length,s=ke.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Y]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Je(e)?this._state!==ee?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ee?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[gs.extensionName],s=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Je(e)?(a=e.size,l=!1):(e=ke(e),a=e.length,l=ke.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),n.fin&&(this._firstFragment=!0);let c={[Y]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};Je(e)?this._state!==ee?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ee?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[Y],this._state=xu,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(dr,this,a,i);return}this._bufferedBytes-=r[Y];let o=ke(s);n?this.dispatch(o,n,r,i):(this._state=ee,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Eu,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[gs.extensionName];this._bufferedBytes+=r[Y],this._state=Iu,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");dr(this,l,i);return}this._bufferedBytes-=r[Y],this._state=ee,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===ee&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Y],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Y],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};ys.exports=ur;function dr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],s=i[i.length-1];typeof s=="function"&&s(e)}}function Eu(t,e,n){dr(t,e,n),t.onerror(e)}});var As=m((Hg,Es)=>{"use strict";var{kForOnEventAttribute:Ct,kListener:hr}=ce(),_s=Symbol("kCode"),Ss=Symbol("kData"),vs=Symbol("kError"),ws=Symbol("kMessage"),bs=Symbol("kReason"),Xe=Symbol("kTarget"),Is=Symbol("kType"),xs=Symbol("kWasClean"),de=class{constructor(e){this[Xe]=null,this[Is]=e}get target(){return this[Xe]}get type(){return this[Is]}};Object.defineProperty(de.prototype,"target",{enumerable:!0});Object.defineProperty(de.prototype,"type",{enumerable:!0});var Pe=class extends de{constructor(e,n={}){super(e),this[_s]=n.code===void 0?0:n.code,this[bs]=n.reason===void 0?"":n.reason,this[xs]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[_s]}get reason(){return this[bs]}get wasClean(){return this[xs]}};Object.defineProperty(Pe.prototype,"code",{enumerable:!0});Object.defineProperty(Pe.prototype,"reason",{enumerable:!0});Object.defineProperty(Pe.prototype,"wasClean",{enumerable:!0});var Ze=class extends de{constructor(e,n={}){super(e),this[vs]=n.error===void 0?null:n.error,this[ws]=n.message===void 0?"":n.message}get error(){return this[vs]}get message(){return this[ws]}};Object.defineProperty(Ze.prototype,"error",{enumerable:!0});Object.defineProperty(Ze.prototype,"message",{enumerable:!0});var Tt=class extends de{constructor(e,n={}){super(e),this[Ss]=n.data===void 0?null:n.data}get data(){return this[Ss]}};Object.defineProperty(Tt.prototype,"data",{enumerable:!0});var Au={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[Ct]&&i[hr]===e&&!i[Ct])return;let r;if(t==="message")r=function(s,o){let a=new Tt("message",{data:o?s:s.toString()});a[Xe]=this,pn(e,this,a)};else if(t==="close")r=function(s,o){let a=new Pe("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Xe]=this,pn(e,this,a)};else if(t==="error")r=function(s){let o=new Ze("error",{error:s,message:s.message});o[Xe]=this,pn(e,this,o)};else if(t==="open")r=function(){let s=new de("open");s[Xe]=this,pn(e,this,s)};else return;r[Ct]=!!n[Ct],r[hr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[hr]===e&&!n[Ct]){this.removeListener(t,n);break}}};Es.exports={CloseEvent:Pe,ErrorEvent:Ze,Event:de,EventTarget:Au,MessageEvent:Tt};function pn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var pr=m((Fg,Cs)=>{"use strict";var{tokenChars:kt}=Ye();function se(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Cu(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,s=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&kt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);c===44?(se(e,h,n),n=Object.create(null)):o=h,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&kt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),se(n,t.slice(l,u),!0),c===44&&(se(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(kt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),i=!1}else if(s)if(kt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)s=!1,u=d;else if(c===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)s=!0;else if(u===-1&&kt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);r&&(h=h.replace(/\\/g,""),r=!1),se(n,a,h),c===44&&(se(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?se(e,f,n):(a===void 0?se(n,f,!0):r?se(n,a,f.replace(/\\/g,"")):se(n,a,f),se(e,o,n)),e}function Tu(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let s=r[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Cs.exports={format:Tu,parse:Cu}});var _n=m((Wg,Fs)=>{"use strict";var ku=require("events"),Ru=require("https"),Pu=require("http"),Rs=require("net"),Lu=require("tls"),{randomBytes:Nu,createHash:Ou}=require("crypto"),{Duplex:Ug,Readable:qg}=require("stream"),{URL:gr}=require("url"),me=At(),Mu=cr(),Bu=fr(),{isBlob:Du}=Ye(),{BINARY_TYPES:Ts,CLOSE_TIMEOUT:Hu,EMPTY_BUFFER:gn,GUID:Fu,kForOnEventAttribute:mr,kListener:Uu,kStatusCode:qu,kWebSocket:O,NOOP:Ps}=ce(),{EventTarget:{addEventListener:Wu,removeEventListener:ju}}=As(),{format:Gu,parse:zu}=pr(),{toBuffer:$u}=xt(),Ls=Symbol("kAborted"),yr=[8,13],fe=["CONNECTING","OPEN","CLOSING","CLOSED"],Vu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,E=class t extends ku{constructor(e,n,r){super(),this._binaryType=Ts[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=gn,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,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Ns(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ts.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,n,r){let i=new Mu({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Bu(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[O]=this,s[O]=this,e[O]=this,i.on("conclude",Ku),i.on("drain",Xu),i.on("error",Zu),i.on("message",Qu),i.on("ping",ed),i.on("pong",td),s.onerror=nd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Bs),e.on("data",yn),e.on("end",Ds),e.on("error",Hs),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[me.extensionName]&&this._extensions[me.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){z(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,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ms(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){_r(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||gn,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){_r(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||gn,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){_r(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[me.extensionName]||(i.compress=!1),this._sender.send(e||gn,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(E,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(E.prototype,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(E,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(E.prototype,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(E,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(E.prototype,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(E,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});Object.defineProperty(E.prototype,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(E.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(E.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[mr])return e[Uu];return null},set(e){for(let n of this.listeners(t))if(n[mr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[mr]:!0})}})});E.prototype.addEventListener=Wu;E.prototype.removeEventListener=ju;Fs.exports=E;function Ns(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Hu,protocolVersion:yr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,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,!yr.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${yr.join(", ")})`);let s;if(e instanceof gr)s=e;else try{s=new gr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;mn(t,p);return}let c=o?443:80,u=Nu(16).toString("base64"),d=o?Ru.request:Pu.request,f=new Set,h;if(i.createConnection=i.createConnection||(o?Ju:Yu),i.defaultPort=i.defaultPort||c,i.port=s.port||c,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new me(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Gu({[me.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!Vu.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){let p=i.path.split(":");i.socketPath=p[0],i.path=p[1]}let g;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[y,_]of Object.entries(p))r.headers[y.toLowerCase()]=_}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,p||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=t._req=d(i),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(i);i.timeout&&g.on("timeout",()=>{z(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[Ls]||(g=t._req=null,mn(t,p))}),g.on("response",p=>{let y=p.headers.location,_=p.statusCode;if(y&&i.followRedirects&&_>=300&&_<400){if(++t._redirects>i.maxRedirects){z(t,g,"Maximum redirects exceeded");return}g.abort();let G;try{G=new gr(y,e)}catch{let C=new SyntaxError(`Invalid URL: ${y}`);mn(t,C);return}Ns(t,G,n,r)}else t.emit("unexpected-response",g,p)||z(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,y,_)=>{if(t.emit("upgrade",p),t.readyState!==E.CONNECTING)return;g=t._req=null;let G=p.headers.upgrade;if(G===void 0||G.toLowerCase()!=="websocket"){z(t,y,"Invalid Upgrade header");return}let re=Ou("sha1").update(u+Fu).digest("base64");if(p.headers["sec-websocket-accept"]!==re){z(t,y,"Invalid Sec-WebSocket-Accept header");return}let C=p.headers["sec-websocket-protocol"],N;if(C!==void 0?f.size?f.has(C)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":f.size&&(N="Server sent no subprotocol"),N){z(t,y,N);return}C&&(t._protocol=C);let $=p.headers["sec-websocket-extensions"];if($!==void 0){if(!h){z(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ie;try{ie=zu($)}catch{z(t,y,"Invalid Sec-WebSocket-Extensions header");return}let Ge=Object.keys(ie);if(Ge.length!==1||Ge[0]!==me.extensionName){z(t,y,"Server indicated an extension that was not requested");return}try{h.accept(ie[me.extensionName])}catch{z(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[me.extensionName]=h}t.setSocket(y,_,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function mn(t,e){t._readyState=E.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Yu(t){return t.path=t.socketPath,Rs.connect(t)}function Ju(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Rs.isIP(t.host)?"":t.host),Lu.connect(t)}function z(t,e,n){t._readyState=E.CLOSING;let r=new Error(n);Error.captureStackTrace(r,z),e.setHeader?(e[Ls]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(mn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function _r(t,e,n){if(e){let r=Du(e)?e.size:$u(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${fe[t.readyState]})`);process.nextTick(n,r)}}function Ku(t,e){let n=this[O];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[O]!==void 0&&(n._socket.removeListener("data",yn),process.nextTick(Os,n._socket),t===1005?n.close():n.close(t,e))}function Xu(){let t=this[O];t.isPaused||t._socket.resume()}function Zu(t){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",yn),process.nextTick(Os,e._socket),e.close(t[qu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ks(){this[O].emitClose()}function Qu(t,e){this[O].emit("message",t,e)}function ed(t){let e=this[O];e._autoPong&&e.pong(t,!this._isServer,Ps),e.emit("ping",t)}function td(t){this[O].emit("pong",t)}function Os(t){t.resume()}function nd(t){let e=this[O];e.readyState!==E.CLOSED&&(e.readyState===E.OPEN&&(e._readyState=E.CLOSING,Ms(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ms(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Bs(){let t=this[O];if(this.removeListener("close",Bs),this.removeListener("data",yn),this.removeListener("end",Ds),t._readyState=E.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[O]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ks),t._receiver.on("finish",ks))}function yn(t){this[O]._receiver.write(t)||this.pause()}function Ds(){let t=this[O];t._readyState=E.CLOSING,t._receiver.end(),this.end()}function Hs(){let t=this[O];this.removeListener("error",Hs),this.on("error",Ps),t&&(t._readyState=E.CLOSING,this.destroy())}});var js=m((Gg,Ws)=>{"use strict";var jg=_n(),{Duplex:rd}=require("stream");function Us(t){t.emit("close")}function id(){!this.destroyed&&this._writableState.finished&&this.destroy()}function qs(t){this.removeListener("error",qs),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function sd(t,e){let n=!0,r=new rd({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&r._readableState.objectMode?s.toString():s;r.push(a)||t.pause()}),t.once("error",function(s){r.destroyed||(n=!1,r.destroy(s))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Us,r);return}let o=!1;t.once("error",function(l){o=!0,s(l)}),t.once("close",function(){o||s(i),process.nextTick(Us,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,s,o)});return}t.send(i,o)},r.on("end",id),r.on("error",qs),r}Ws.exports=sd});var zs=m((zg,Gs)=>{"use strict";var{tokenChars:od}=Ye();function ad(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&od[o]===1)n===-1&&(n=i);else if(i!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=i);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(n,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Gs.exports={parse:ad}});var Zs=m((Vg,Xs)=>{"use strict";var ld=require("events"),Sn=require("http"),{Duplex:$g}=require("stream"),{createHash:cd}=require("crypto"),$s=pr(),Le=At(),ud=zs(),dd=_n(),{CLOSE_TIMEOUT:fd,GUID:hd,kWebSocket:pd}=ce(),gd=/^[+/0-9A-Za-z]{22}==$/,Vs=0,Ys=1,Ks=2,Sr=class extends ld{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dd,...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=Sn.createServer((r,i)=>{let s=Sn.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=md(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Vs}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===Ks){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Rt,this);return}if(e&&this.once("close",e),this._state!==Ys)if(this._state=Ys,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(Rt,this):process.nextTick(Rt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Rt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Js);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ne(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ne(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!gd.test(s)){Ne(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ne(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Pt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=ud.parse(l)}catch{Ne(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new Le(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=$s.parse(u);h[Le.extensionName]&&(f.accept(h[Le.extensionName]),d[Le.extensionName]=f)}catch{Ne(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,g,p,y)=>{if(!h)return Pt(n,g||401,p,y);this.completeUpgrade(d,s,c,e,n,r,i)});return}if(!this.options.verifyClient(f))return Pt(n,401)}this.completeUpgrade(d,s,c,e,n,r,i)}completeUpgrade(e,n,r,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[pd])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Vs)return Pt(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${cd("sha1").update(n+hd).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[Le.extensionName]){let d=e[Le.extensionName].params,f=$s.format({[Le.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,i),s.write(c.concat(`\r
1
+ "use strict";var Yc=Object.create;var Ys=Object.defineProperty;var Jc=Object.getOwnPropertyDescriptor;var Kc=Object.getOwnPropertyNames;var Xc=Object.getPrototypeOf,Zc=Object.prototype.hasOwnProperty;var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Qc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Kc(e))!Zc.call(t,s)&&s!==n&&Ys(t,s,{get:()=>e[s],enumerable:!(r=Jc(e,s))||r.enumerable});return t};var ze=(t,e,n)=>(n=t!=null?Yc(Xc(t)):{},Qc(e||!t||!t.__esModule?Ys(n,"default",{value:t,enumerable:!0}):n,t));var ce=m((Lg,Xs)=>{"use strict";var Js=["nodebuffer","arraybuffer","fragments"],Ks=typeof Blob<"u";Ks&&Js.push("blob");Xs.exports={BINARY_TYPES:Js,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ks,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var xt=m((Ng,an)=>{"use strict";var{EMPTY_BUFFER:eu}=ce(),Qn=Buffer[Symbol.species];function tu(t,e){if(t.length===0)return eu;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Qn(n.buffer,n.byteOffset,r):n}function Zs(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Qs(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function nu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function er(t){if(er.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Qn(t):ArrayBuffer.isView(t)?e=new Qn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),er.readOnly=!1),e}an.exports={concat:tu,mask:Zs,toArrayBuffer:nu,toBuffer:er,unmask:Qs};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");an.exports.mask=function(e,n,r,s,i){i<48?Zs(e,n,r,s,i):t.mask(e,n,r,s,i)},an.exports.unmask=function(e,n){e.length<32?Qs(e,n):t.unmask(e,n)}}catch{}});var ni=m((Og,ti)=>{"use strict";var ei=Symbol("kDone"),tr=Symbol("kRun"),nr=class{constructor(e){this[ei]=()=>{this.pending--,this[tr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[tr]()}[tr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ei])}}};ti.exports=nr});var At=m((Mg,oi)=>{"use strict";var Et=require("zlib"),ri=xt(),ru=ni(),{kStatusCode:si}=ce(),su=Buffer[Symbol.species],iu=Buffer.from([0,0,255,255]),cn=Symbol("permessage-deflate"),ue=Symbol("total-length"),$e=Symbol("callback"),ge=Symbol("buffers"),Ve=Symbol("error"),ln,rr=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!ln){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ln=new ru(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[$e];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){ln.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){ln.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Et.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[cn]=this,this._inflate[ue]=0,this._inflate[ge]=[],this._inflate.on("error",au),this._inflate.on("data",ii)}this._inflate[$e]=r,this._inflate.write(e),n&&this._inflate.write(iu),this._inflate.flush(()=>{let i=this._inflate[Ve];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=ri.concat(this._inflate[ge],this._inflate[ue]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ue]=0,this._inflate[ge]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Et.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ue]=0,this._deflate[ge]=[],this._deflate.on("data",ou)}this._deflate[$e]=r,this._deflate.write(e),this._deflate.flush(Et.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ri.concat(this._deflate[ge],this._deflate[ue]);n&&(i=new su(i.buffer,i.byteOffset,i.length-4)),this._deflate[$e]=null,this._deflate[ue]=0,this._deflate[ge]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};oi.exports=rr;function ou(t){this[ge].push(t),this[ue]+=t.length}function ii(t){if(this[ue]+=t.length,this[cn]._maxPayload<1||this[ue]<=this[cn]._maxPayload){this[ge].push(t);return}this[Ve]=new RangeError("Max payload size exceeded"),this[Ve].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ve][si]=1009,this.removeListener("data",ii),this.reset()}function au(t){if(this[cn]._inflate=null,this[Ve]){this[$e](this[Ve]);return}t[si]=1007,this[$e](t)}});var Ye=m((Bg,un)=>{"use strict";var{isUtf8:ai}=require("buffer"),{hasBlob:lu}=ce(),cu=[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 uu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function sr(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function du(t){return lu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}un.exports={isBlob:du,isValidStatusCode:uu,isValidUTF8:sr,tokenChars:cu};if(ai)un.exports.isValidUTF8=function(t){return t.length<24?sr(t):ai(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");un.exports.isValidUTF8=function(e){return e.length<32?sr(e):t(e)}}catch{}});var cr=m((Dg,pi)=>{"use strict";var{Writable:fu}=require("stream"),li=At(),{BINARY_TYPES:hu,EMPTY_BUFFER:ci,kStatusCode:pu,kWebSocket:gu}=ce(),{concat:ir,toArrayBuffer:mu,unmask:yu}=xt(),{isValidStatusCode:_u,isValidUTF8:ui}=Ye(),dn=Buffer[Symbol.species],V=0,di=1,fi=2,hi=3,or=4,ar=5,fn=6,lr=class extends fu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||hu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[gu]=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=V}_write(e,n,r){if(this._opcode===8&&this._state==V)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new dn(r.buffer,r.byteOffset+e,r.length-e),new dn(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new dn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case V:this.getInfo(e);break;case di:this.getPayloadLength16(e);break;case fi:this.getPayloadLength64(e);break;case hi:this.getMask();break;case or:this.getData(e);break;case ar:case fn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[li.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=di:this._payloadLength===127?this._state=fi: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 n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=hi:this._state=or}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=or}getData(e){let n=ci;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&yu(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ar,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[li.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===V&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=V;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ir(r,n):this._binaryType==="arraybuffer"?s=mu(ir(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=V):(this._state=fn,setImmediate(()=>{this.emit("message",s,!0),this._state=V,this.startLoop(e)}))}else{let s=ir(r,n);if(!this._skipUTF8Validation&&!ui(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ar||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=V):(this._state=fn,setImmediate(()=>{this.emit("message",s,!1),this._state=V,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ci),this.end();else{let r=e.readUInt16BE(0);if(!_u(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new dn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ui(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=V;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=V):(this._state=fn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=V,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[pu]=s,o}};pi.exports=lr});var fr=m((Fg,yi)=>{"use strict";var{Duplex:Hg}=require("stream"),{randomFillSync:Su}=require("crypto"),gi=At(),{EMPTY_BUFFER:vu,kWebSocket:wu,NOOP:bu}=ce(),{isBlob:Je,isValidStatusCode:Iu}=Ye(),{mask:mi,toBuffer:ke}=xt(),Y=Symbol("kByteLength"),xu=Buffer.alloc(4),hn=8*1024,Re,Ke=hn,ee=0,Eu=1,Au=2,ur=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ee,this.onerror=bu,this[wu]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||xu,n.generateMask?n.generateMask(r):(Ke===hn&&(Re===void 0&&(Re=Buffer.alloc(hn)),Su(Re,0,hn),Ke=0),r[0]=Re[Ke++],r[1]=Re[Ke++],r[2]=Re[Ke++],r[3]=Re[Ke++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Y]!==void 0?a=n[Y]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(mi(e,r,c,i,a),[c]):(mi(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=vu;else{if(typeof e!="number"||!Iu(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Y]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ee?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Je(e)?(s=e.size,i=!1):(e=ke(e),s=e.length,i=ke.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Y]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Je(e)?this._state!==ee?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ee?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Je(e)?(s=e.size,i=!1):(e=ke(e),s=e.length,i=ke.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Y]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Je(e)?this._state!==ee?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ee?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[gi.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Je(e)?(a=e.size,l=!1):(e=ke(e),a=e.length,l=ke.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Y]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};Je(e)?this._state!==ee?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ee?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Y],this._state=Au,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(dr,this,a,s);return}this._bufferedBytes-=r[Y];let o=ke(i);n?this.dispatch(o,n,r,s):(this._state=ee,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Cu,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[gi.extensionName];this._bufferedBytes+=r[Y],this._state=Eu,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");dr(this,l,s);return}this._bufferedBytes-=r[Y],this._state=ee,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ee&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Y],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Y],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};yi.exports=ur;function dr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Cu(t,e,n){dr(t,e,n),t.onerror(e)}});var Ai=m((Ug,Ei)=>{"use strict";var{kForOnEventAttribute:Ct,kListener:hr}=ce(),_i=Symbol("kCode"),Si=Symbol("kData"),vi=Symbol("kError"),wi=Symbol("kMessage"),bi=Symbol("kReason"),Xe=Symbol("kTarget"),Ii=Symbol("kType"),xi=Symbol("kWasClean"),de=class{constructor(e){this[Xe]=null,this[Ii]=e}get target(){return this[Xe]}get type(){return this[Ii]}};Object.defineProperty(de.prototype,"target",{enumerable:!0});Object.defineProperty(de.prototype,"type",{enumerable:!0});var Pe=class extends de{constructor(e,n={}){super(e),this[_i]=n.code===void 0?0:n.code,this[bi]=n.reason===void 0?"":n.reason,this[xi]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[_i]}get reason(){return this[bi]}get wasClean(){return this[xi]}};Object.defineProperty(Pe.prototype,"code",{enumerable:!0});Object.defineProperty(Pe.prototype,"reason",{enumerable:!0});Object.defineProperty(Pe.prototype,"wasClean",{enumerable:!0});var Ze=class extends de{constructor(e,n={}){super(e),this[vi]=n.error===void 0?null:n.error,this[wi]=n.message===void 0?"":n.message}get error(){return this[vi]}get message(){return this[wi]}};Object.defineProperty(Ze.prototype,"error",{enumerable:!0});Object.defineProperty(Ze.prototype,"message",{enumerable:!0});var Tt=class extends de{constructor(e,n={}){super(e),this[Si]=n.data===void 0?null:n.data}get data(){return this[Si]}};Object.defineProperty(Tt.prototype,"data",{enumerable:!0});var Tu={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ct]&&s[hr]===e&&!s[Ct])return;let r;if(t==="message")r=function(i,o){let a=new Tt("message",{data:o?i:i.toString()});a[Xe]=this,pn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Pe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Xe]=this,pn(e,this,a)};else if(t==="error")r=function(i){let o=new Ze("error",{error:i,message:i.message});o[Xe]=this,pn(e,this,o)};else if(t==="open")r=function(){let i=new de("open");i[Xe]=this,pn(e,this,i)};else return;r[Ct]=!!n[Ct],r[hr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[hr]===e&&!n[Ct]){this.removeListener(t,n);break}}};Ei.exports={CloseEvent:Pe,ErrorEvent:Ze,Event:de,EventTarget:Tu,MessageEvent:Tt};function pn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var pr=m((qg,Ci)=>{"use strict";var{tokenChars:kt}=Ye();function ie(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function ku(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&kt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);c===44?(ie(e,h,n),n=Object.create(null)):o=h,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&kt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),ie(n,t.slice(l,u),!0),c===44&&(ie(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(kt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(kt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&kt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);r&&(h=h.replace(/\\/g,""),r=!1),ie(n,a,h),c===44&&(ie(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?ie(e,f,n):(a===void 0?ie(n,f,!0):r?ie(n,a,f.replace(/\\/g,"")):ie(n,a,f),ie(e,o,n)),e}function Ru(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ci.exports={format:Ru,parse:ku}});var _n=m((Gg,Fi)=>{"use strict";var Pu=require("events"),Lu=require("https"),Nu=require("http"),Ri=require("net"),Ou=require("tls"),{randomBytes:Mu,createHash:Bu}=require("crypto"),{Duplex:Wg,Readable:jg}=require("stream"),{URL:gr}=require("url"),me=At(),Du=cr(),Hu=fr(),{isBlob:Fu}=Ye(),{BINARY_TYPES:Ti,CLOSE_TIMEOUT:Uu,EMPTY_BUFFER:gn,GUID:qu,kForOnEventAttribute:mr,kListener:Wu,kStatusCode:ju,kWebSocket:O,NOOP:Pi}=ce(),{EventTarget:{addEventListener:Gu,removeEventListener:zu}}=Ai(),{format:$u,parse:Vu}=pr(),{toBuffer:Yu}=xt(),Li=Symbol("kAborted"),yr=[8,13],fe=["CONNECTING","OPEN","CLOSING","CLOSED"],Ju=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,E=class t extends Pu{constructor(e,n,r){super(),this._binaryType=Ti[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=gn,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,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Ni(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ti.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,n,r){let s=new Du({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Hu(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[O]=this,i[O]=this,e[O]=this,s.on("conclude",Zu),s.on("drain",Qu),s.on("error",ed),s.on("message",td),s.on("ping",nd),s.on("pong",rd),i.onerror=sd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Bi),e.on("data",yn),e.on("end",Di),e.on("error",Hi),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[me.extensionName]&&this._extensions[me.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){z(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,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Mi(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){_r(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||gn,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){_r(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||gn,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){_r(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[me.extensionName]||(s.compress=!1),this._sender.send(e||gn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(E,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(E.prototype,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(E,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(E.prototype,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(E,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(E.prototype,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(E,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});Object.defineProperty(E.prototype,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(E.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(E.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[mr])return e[Wu];return null},set(e){for(let n of this.listeners(t))if(n[mr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[mr]:!0})}})});E.prototype.addEventListener=Gu;E.prototype.removeEventListener=zu;Fi.exports=E;function Ni(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Uu,protocolVersion:yr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,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=s.autoPong,t._closeTimeout=s.closeTimeout,!yr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${yr.join(", ")})`);let i;if(e instanceof gr)i=e;else try{i=new gr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;mn(t,p);return}let c=o?443:80,u=Mu(16).toString("base64"),d=o?Lu.request:Nu.request,f=new Set,h;if(s.createConnection=s.createConnection||(o?Xu:Ku),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new me(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=$u({[me.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!Ju.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[y,_]of Object.entries(p))r.headers[y.toLowerCase()]=_}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{z(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[Li]||(g=t._req=null,mn(t,p))}),g.on("response",p=>{let y=p.headers.location,_=p.statusCode;if(y&&s.followRedirects&&_>=300&&_<400){if(++t._redirects>s.maxRedirects){z(t,g,"Maximum redirects exceeded");return}g.abort();let G;try{G=new gr(y,e)}catch{let C=new SyntaxError(`Invalid URL: ${y}`);mn(t,C);return}Ni(t,G,n,r)}else t.emit("unexpected-response",g,p)||z(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,y,_)=>{if(t.emit("upgrade",p),t.readyState!==E.CONNECTING)return;g=t._req=null;let G=p.headers.upgrade;if(G===void 0||G.toLowerCase()!=="websocket"){z(t,y,"Invalid Upgrade header");return}let re=Bu("sha1").update(u+qu).digest("base64");if(p.headers["sec-websocket-accept"]!==re){z(t,y,"Invalid Sec-WebSocket-Accept header");return}let C=p.headers["sec-websocket-protocol"],N;if(C!==void 0?f.size?f.has(C)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":f.size&&(N="Server sent no subprotocol"),N){z(t,y,N);return}C&&(t._protocol=C);let $=p.headers["sec-websocket-extensions"];if($!==void 0){if(!h){z(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let se;try{se=Vu($)}catch{z(t,y,"Invalid Sec-WebSocket-Extensions header");return}let Ge=Object.keys(se);if(Ge.length!==1||Ge[0]!==me.extensionName){z(t,y,"Server indicated an extension that was not requested");return}try{h.accept(se[me.extensionName])}catch{z(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[me.extensionName]=h}t.setSocket(y,_,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function mn(t,e){t._readyState=E.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ku(t){return t.path=t.socketPath,Ri.connect(t)}function Xu(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ri.isIP(t.host)?"":t.host),Ou.connect(t)}function z(t,e,n){t._readyState=E.CLOSING;let r=new Error(n);Error.captureStackTrace(r,z),e.setHeader?(e[Li]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(mn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function _r(t,e,n){if(e){let r=Fu(e)?e.size:Yu(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${fe[t.readyState]})`);process.nextTick(n,r)}}function Zu(t,e){let n=this[O];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[O]!==void 0&&(n._socket.removeListener("data",yn),process.nextTick(Oi,n._socket),t===1005?n.close():n.close(t,e))}function Qu(){let t=this[O];t.isPaused||t._socket.resume()}function ed(t){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",yn),process.nextTick(Oi,e._socket),e.close(t[ju])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ki(){this[O].emitClose()}function td(t,e){this[O].emit("message",t,e)}function nd(t){let e=this[O];e._autoPong&&e.pong(t,!this._isServer,Pi),e.emit("ping",t)}function rd(t){this[O].emit("pong",t)}function Oi(t){t.resume()}function sd(t){let e=this[O];e.readyState!==E.CLOSED&&(e.readyState===E.OPEN&&(e._readyState=E.CLOSING,Mi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Mi(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Bi(){let t=this[O];if(this.removeListener("close",Bi),this.removeListener("data",yn),this.removeListener("end",Di),t._readyState=E.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[O]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",ki),t._receiver.on("finish",ki))}function yn(t){this[O]._receiver.write(t)||this.pause()}function Di(){let t=this[O];t._readyState=E.CLOSING,t._receiver.end(),this.end()}function Hi(){let t=this[O];this.removeListener("error",Hi),this.on("error",Pi),t&&(t._readyState=E.CLOSING,this.destroy())}});var ji=m(($g,Wi)=>{"use strict";var zg=_n(),{Duplex:id}=require("stream");function Ui(t){t.emit("close")}function od(){!this.destroyed&&this._writableState.finished&&this.destroy()}function qi(t){this.removeListener("error",qi),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function ad(t,e){let n=!0,r=new id({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Ui,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Ui,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",od),r.on("error",qi),r}Wi.exports=ad});var zi=m((Vg,Gi)=>{"use strict";var{tokenChars:ld}=Ye();function cd(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&ld[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Gi.exports={parse:cd}});var Zi=m((Jg,Xi)=>{"use strict";var ud=require("events"),Sn=require("http"),{Duplex:Yg}=require("stream"),{createHash:dd}=require("crypto"),$i=pr(),Le=At(),fd=zi(),hd=_n(),{CLOSE_TIMEOUT:pd,GUID:gd,kWebSocket:md}=ce(),yd=/^[+/0-9A-Za-z]{22}==$/,Vi=0,Yi=1,Ki=2,Sr=class extends ud{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:pd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hd,...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=Sn.createServer((r,s)=>{let i=Sn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=_d(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Vi}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===Ki){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Rt,this);return}if(e&&this.once("close",e),this._state!==Yi)if(this._state=Yi,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(Rt,this):process.nextTick(Rt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Rt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Ji);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ne(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ne(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!yd.test(i)){Ne(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ne(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Pt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=fd.parse(l)}catch{Ne(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new Le(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=$i.parse(u);h[Le.extensionName]&&(f.accept(h[Le.extensionName]),d[Le.extensionName]=f)}catch{Ne(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,g,p,y)=>{if(!h)return Pt(n,g||401,p,y);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Pt(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[md])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Vi)return Pt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dd("sha1").update(n+gd).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[Le.extensionName]){let d=e[Le.extensionName].params,f=$i.format({[Le.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
2
2
  `).join(`\r
3
- `)),s.removeListener("error",Js),u.setSocket(s,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Rt,this)})),a(u,i)}};Xs.exports=Sr;function md(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Rt(t){t._state=Ks,t.emit("close")}function Js(){this.destroy()}function Pt(t,e,n,r){n=n||Sn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Sn.STATUS_CODES[e]}\r
4
- `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
3
+ `)),i.removeListener("error",Ji),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Rt,this)})),a(u,s)}};Xi.exports=Sr;function _d(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Rt(t){t._state=Ki,t.emit("close")}function Ji(){this.destroy()}function Pt(t,e,n,r){n=n||Sn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Sn.STATUS_CODES[e]}\r
4
+ `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function Ne(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,Ne),t.emit("wsClientError",o,n,e)}else Pt(n,r,i,s)}});var wr=m((Jg,Qs)=>{Qs.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ye=m(Oe=>{var br,wd=[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];Oe.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};Oe.getSymbolTotalCodewords=function(e){return wd[e]};Oe.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Oe.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');br=e};Oe.isKanjiModeEnabled=function(){return typeof br<"u"};Oe.toSJIS=function(e){return br(e)}});var vn=m(J=>{J.L={bit:1};J.M={bit:0};J.Q={bit:3};J.H={bit:2};function bd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return J.L;case"m":case"medium":return J.M;case"q":case"quartile":return J.Q;case"h":case"high":return J.H;default:throw new Error("Unknown EC Level: "+t)}}J.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};J.from=function(e,n){if(J.isValid(e))return e;try{return bd(e)}catch{return n}}});var no=m((Zg,to)=>{function eo(){this.buffer=[],this.length=0}eo.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 n=0;n<e;n++)this.putBit((t>>>e-n-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++}};to.exports=eo});var io=m((Qg,ro)=>{function Lt(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)}Lt.prototype.set=function(t,e,n,r){let i=t*this.size+e;this.data[i]=n,r&&(this.reservedBit[i]=!0)};Lt.prototype.get=function(t,e){return this.data[t*this.size+e]};Lt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Lt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ro.exports=Lt});var so=m(wn=>{var Id=ye().getSymbolSize;wn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Id(e),i=r===145?26:Math.ceil((r-13)/(2*n-2))*2,s=[r-7];for(let o=1;o<n-1;o++)s[o]=s[o-1]-i;return s.push(6),s.reverse()};wn.getPositions=function(e){let n=[],r=wn.getRowColCoords(e),i=r.length;for(let s=0;s<i;s++)for(let o=0;o<i;o++)s===0&&o===0||s===0&&o===i-1||s===i-1&&o===0||n.push([r[s],r[o]]);return n}});var lo=m(ao=>{var xd=ye().getSymbolSize,oo=7;ao.getPositions=function(e){let n=xd(e);return[[0,0],[n-oo,0],[0,n-oo]]}});var co=m(x=>{x.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Me={N1:3,N2:3,N3:40,N4:10};x.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};x.from=function(e){return x.isValid(e)?parseInt(e,10):void 0};x.getPenaltyN1=function(e){let n=e.size,r=0,i=0,s=0,o=null,a=null;for(let l=0;l<n;l++){i=s=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?i++:(i>=5&&(r+=Me.N1+(i-5)),o=u,i=1),u=e.get(c,l),u===a?s++:(s>=5&&(r+=Me.N1+(s-5)),a=u,s=1)}i>=5&&(r+=Me.N1+(i-5)),s>=5&&(r+=Me.N1+(s-5))}return r};x.getPenaltyN2=function(e){let n=e.size,r=0;for(let i=0;i<n-1;i++)for(let s=0;s<n-1;s++){let o=e.get(i,s)+e.get(i,s+1)+e.get(i+1,s)+e.get(i+1,s+1);(o===4||o===0)&&r++}return r*Me.N2};x.getPenaltyN3=function(e){let n=e.size,r=0,i=0,s=0;for(let o=0;o<n;o++){i=s=0;for(let a=0;a<n;a++)i=i<<1&2047|e.get(o,a),a>=10&&(i===1488||i===93)&&r++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&r++}return r*Me.N3};x.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let s=0;s<r;s++)n+=e.data[s];return Math.abs(Math.ceil(n*100/r/5)-10)*Me.N4};function Ed(t,e,n){switch(t){case x.Patterns.PATTERN000:return(e+n)%2===0;case x.Patterns.PATTERN001:return e%2===0;case x.Patterns.PATTERN010:return n%3===0;case x.Patterns.PATTERN011:return(e+n)%3===0;case x.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case x.Patterns.PATTERN101:return e*n%2+e*n%3===0;case x.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case x.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}x.applyMask=function(e,n){let r=n.size;for(let i=0;i<r;i++)for(let s=0;s<r;s++)n.isReserved(s,i)||n.xor(s,i,Ed(e,s,i))};x.getBestMask=function(e,n){let r=Object.keys(x.Patterns).length,i=0,s=1/0;for(let o=0;o<r;o++){n(o),x.applyMask(o,e);let a=x.getPenaltyN1(e)+x.getPenaltyN2(e)+x.getPenaltyN3(e)+x.getPenaltyN4(e);x.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var xr=m(Ir=>{var _e=vn(),bn=[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],In=[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];Ir.getBlocksCount=function(e,n){switch(n){case _e.L:return bn[(e-1)*4+0];case _e.M:return bn[(e-1)*4+1];case _e.Q:return bn[(e-1)*4+2];case _e.H:return bn[(e-1)*4+3];default:return}};Ir.getTotalCodewordsCount=function(e,n){switch(n){case _e.L:return In[(e-1)*4+0];case _e.M:return In[(e-1)*4+1];case _e.Q:return In[(e-1)*4+2];case _e.H:return In[(e-1)*4+3];default:return}}});var uo=m(En=>{var Nt=new Uint8Array(512),xn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Nt[n]=e,xn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Nt[n]=Nt[n-255]})();En.log=function(e){if(e<1)throw new Error("log("+e+")");return xn[e]};En.exp=function(e){return Nt[e]};En.mul=function(e,n){return e===0||n===0?0:Nt[xn[e]+xn[n]]}});var fo=m(Ot=>{var Er=uo();Ot.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let i=0;i<e.length;i++)for(let s=0;s<n.length;s++)r[i+s]^=Er.mul(e[i],n[s]);return r};Ot.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let i=r[0];for(let o=0;o<n.length;o++)r[o]^=Er.mul(n[o],i);let s=0;for(;s<r.length&&r[s]===0;)s++;r=r.slice(s)}return r};Ot.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Ot.mul(n,new Uint8Array([1,Er.exp(r)]));return n}});var go=m((om,po)=>{var ho=fo();function Ar(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ar.prototype.initialize=function(e){this.degree=e,this.genPoly=ho.generateECPolynomial(this.degree)};Ar.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=ho.mod(n,this.genPoly),i=this.degree-r.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(r,i),s}return r};po.exports=Ar});var Cr=m(mo=>{mo.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Tr=m(he=>{var yo="[0-9]+",Ad="[A-Z $%*+\\-./:]+",Mt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Mt=Mt.replace(/u/g,"\\u");var Cd="(?:(?![A-Z0-9 $%*+\\-./:]|"+Mt+`)(?:.|[\r
8
- ]))+`;he.KANJI=new RegExp(Mt,"g");he.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");he.BYTE=new RegExp(Cd,"g");he.NUMERIC=new RegExp(yo,"g");he.ALPHANUMERIC=new RegExp(Ad,"g");var Td=new RegExp("^"+Mt+"$"),kd=new RegExp("^"+yo+"$"),Rd=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");he.testKanji=function(e){return Td.test(e)};he.testNumeric=function(e){return kd.test(e)};he.testAlphanumeric=function(e){return Rd.test(e)}});var Se=m(R=>{var Pd=Cr(),kr=Tr();R.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};R.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};R.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};R.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};R.MIXED={bit:-1};R.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Pd.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};R.getBestModeForData=function(e){return kr.testNumeric(e)?R.NUMERIC:kr.testAlphanumeric(e)?R.ALPHANUMERIC:kr.testKanji(e)?R.KANJI:R.BYTE};R.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};R.isValid=function(e){return e&&e.bit&&e.ccBits};function Ld(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return R.NUMERIC;case"alphanumeric":return R.ALPHANUMERIC;case"kanji":return R.KANJI;case"byte":return R.BYTE;default:throw new Error("Unknown mode: "+t)}}R.from=function(e,n){if(R.isValid(e))return e;try{return Ld(e)}catch{return n}}});var bo=m(Be=>{var An=ye(),Nd=xr(),_o=vn(),ve=Se(),Rr=Cr(),vo=7973,So=An.getBCHDigit(vo);function Od(t,e,n){for(let r=1;r<=40;r++)if(e<=Be.getCapacity(r,n,t))return r}function wo(t,e){return ve.getCharCountIndicator(t,e)+4}function Md(t,e){let n=0;return t.forEach(function(r){let i=wo(r.mode,e);n+=i+r.getBitsLength()}),n}function Bd(t,e){for(let n=1;n<=40;n++)if(Md(t,n)<=Be.getCapacity(n,e,ve.MIXED))return n}Be.from=function(e,n){return Rr.isValid(e)?parseInt(e,10):n};Be.getCapacity=function(e,n,r){if(!Rr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=ve.BYTE);let i=An.getSymbolTotalCodewords(e),s=Nd.getTotalCodewordsCount(e,n),o=(i-s)*8;if(r===ve.MIXED)return o;let a=o-wo(r,e);switch(r){case ve.NUMERIC:return Math.floor(a/10*3);case ve.ALPHANUMERIC:return Math.floor(a/11*2);case ve.KANJI:return Math.floor(a/13);case ve.BYTE:default:return Math.floor(a/8)}};Be.getBestVersionForData=function(e,n){let r,i=_o.from(n,_o.M);if(Array.isArray(e)){if(e.length>1)return Bd(e,i);if(e.length===0)return 1;r=e[0]}else r=e;return Od(r.mode,r.getLength(),i)};Be.getEncodedBits=function(e){if(!Rr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;An.getBCHDigit(n)-So>=0;)n^=vo<<An.getBCHDigit(n)-So;return e<<12|n}});var Ao=m(Eo=>{var Pr=ye(),xo=1335,Dd=21522,Io=Pr.getBCHDigit(xo);Eo.getEncodedBits=function(e,n){let r=e.bit<<3|n,i=r<<10;for(;Pr.getBCHDigit(i)-Io>=0;)i^=xo<<Pr.getBCHDigit(i)-Io;return(r<<10|i)^Dd}});var To=m((fm,Co)=>{var Hd=Se();function Qe(t){this.mode=Hd.NUMERIC,this.data=t.toString()}Qe.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Qe.prototype.getLength=function(){return this.data.length};Qe.prototype.getBitsLength=function(){return Qe.getBitsLength(this.data.length)};Qe.prototype.write=function(e){let n,r,i;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),i=parseInt(r,10),e.put(i,10);let s=this.data.length-n;s>0&&(r=this.data.substr(n),i=parseInt(r,10),e.put(i,s*3+1))};Co.exports=Qe});var Ro=m((hm,ko)=>{var Fd=Se(),Lr=["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 et(t){this.mode=Fd.ALPHANUMERIC,this.data=t}et.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};et.prototype.getLength=function(){return this.data.length};et.prototype.getBitsLength=function(){return et.getBitsLength(this.data.length)};et.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Lr.indexOf(this.data[n])*45;r+=Lr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Lr.indexOf(this.data[n]),6)};ko.exports=et});var Lo=m((pm,Po)=>{var Ud=Se();function tt(t){this.mode=Ud.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}tt.getBitsLength=function(e){return e*8};tt.prototype.getLength=function(){return this.data.length};tt.prototype.getBitsLength=function(){return tt.getBitsLength(this.data.length)};tt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Po.exports=tt});var Oo=m((gm,No)=>{var qd=Se(),Wd=ye();function nt(t){this.mode=qd.KANJI,this.data=t}nt.getBitsLength=function(e){return e*13};nt.prototype.getLength=function(){return this.data.length};nt.prototype.getBitsLength=function(){return nt.getBitsLength(this.data.length)};nt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Wd.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
- Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};No.exports=nt});var Mo=m((mm,Nr)=>{"use strict";var Bt={single_source_shortest_paths:function(t,e,n){var r={},i={};i[e]=0;var s=Bt.PriorityQueue.make();s.push(e,0);for(var o,a,l,c,u,d,f,h,g;!s.empty();){o=s.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,h=i[l],g=typeof i[l]>"u",(g||h>f)&&(i[l]=f,s.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof i[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,i;r;)n.push(r),i=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Bt.single_source_shortest_paths(t,e,n);return Bt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Bt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Nr<"u"&&(Nr.exports=Bt)});var jo=m(rt=>{var b=Se(),Ho=To(),Fo=Ro(),Uo=Lo(),qo=Oo(),Dt=Tr(),Cn=ye(),jd=Mo();function Bo(t){return unescape(encodeURIComponent(t)).length}function Ht(t,e,n){let r=[],i;for(;(i=t.exec(n))!==null;)r.push({data:i[0],index:i.index,mode:e,length:i[0].length});return r}function Wo(t){let e=Ht(Dt.NUMERIC,b.NUMERIC,t),n=Ht(Dt.ALPHANUMERIC,b.ALPHANUMERIC,t),r,i;return Cn.isKanjiModeEnabled()?(r=Ht(Dt.BYTE,b.BYTE,t),i=Ht(Dt.KANJI,b.KANJI,t)):(r=Ht(Dt.BYTE_KANJI,b.BYTE,t),i=[]),e.concat(n,r,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Or(t,e){switch(e){case b.NUMERIC:return Ho.getBitsLength(t);case b.ALPHANUMERIC:return Fo.getBitsLength(t);case b.KANJI:return qo.getBitsLength(t);case b.BYTE:return Uo.getBitsLength(t)}}function Gd(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function zd(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case b.NUMERIC:e.push([r,{data:r.data,mode:b.ALPHANUMERIC,length:r.length},{data:r.data,mode:b.BYTE,length:r.length}]);break;case b.ALPHANUMERIC:e.push([r,{data:r.data,mode:b.BYTE,length:r.length}]);break;case b.KANJI:e.push([r,{data:r.data,mode:b.BYTE,length:Bo(r.data)}]);break;case b.BYTE:e.push([{data:r.data,mode:b.BYTE,length:Bo(r.data)}])}}return e}function $d(t,e){let n={},r={start:{}},i=["start"];for(let s=0;s<t.length;s++){let o=t[s],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+s+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<i.length;d++){let f=i[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=Or(n[f].lastCount+c.length,c.mode)-Or(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Or(c.length,c.mode)+4+b.getCharCountIndicator(c.mode,e))}}i=a}for(let s=0;s<i.length;s++)r[i[s]].end=0;return{map:r,table:n}}function Do(t,e){let n,r=b.getBestModeForData(t);if(n=b.from(e,r),n!==b.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+b.toString(n)+`.
10
- Suggested mode is: `+b.toString(r));switch(n===b.KANJI&&!Cn.isKanjiModeEnabled()&&(n=b.BYTE),n){case b.NUMERIC:return new Ho(t);case b.ALPHANUMERIC:return new Fo(t);case b.KANJI:return new qo(t);case b.BYTE:return new Uo(t)}}rt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Do(r,null)):r.data&&n.push(Do(r.data,r.mode)),n},[])};rt.fromString=function(e,n){let r=Wo(e,Cn.isKanjiModeEnabled()),i=zd(r),s=$d(i,n),o=jd.find_path(s.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(s.table[o[l]].node);return rt.fromArray(Gd(a))};rt.rawSplit=function(e){return rt.fromArray(Wo(e,Cn.isKanjiModeEnabled()))}});var Ur=m(Go=>{var kn=ye(),Mr=vn(),Vd=no(),Yd=io(),Jd=so(),Kd=lo(),Hr=co(),Fr=xr(),Xd=go(),Tn=bo(),Zd=Ao(),Qd=Se(),Br=jo();function ef(t,e){let n=t.size,r=Kd.getPositions(e);for(let i=0;i<r.length;i++){let s=r[i][0],o=r[i][1];for(let a=-1;a<=7;a++)if(!(s+a<=-1||n<=s+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(s+a,o+l,!0,!0):t.set(s+a,o+l,!1,!0))}}function tf(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function nf(t,e){let n=Jd.getPositions(e);for(let r=0;r<n.length;r++){let i=n[r][0],s=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(i+o,s+a,!0,!0):t.set(i+o,s+a,!1,!0)}}function rf(t,e){let n=t.size,r=Tn.getEncodedBits(e),i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+n-8-3,o=(r>>a&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function Dr(t,e,n){let r=t.size,i=Zd.getEncodedBits(e,n),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(r-15+s,8,o,!0),s<8?t.set(8,r-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(r-8,8,1,!0)}function sf(t,e){let n=t.size,r=-1,i=n-1,s=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(i,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(i,a-l,c),s--,s===-1&&(o++,s=7)}if(i+=r,i<0||n<=i){i-=r,r=-r;break}}}function of(t,e,n){let r=new Vd;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Qd.getCharCountIndicator(l.mode,t)),l.write(r)});let i=kn.getSymbolTotalCodewords(t),s=Fr.getTotalCodewordsCount(t,e),o=(i-s)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return af(r,t,e)}function af(t,e,n){let r=kn.getSymbolTotalCodewords(e),i=Fr.getTotalCodewordsCount(e,n),s=r-i,o=Fr.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(s/o),d=u+1,f=c-u,h=new Xd(f),g=0,p=new Array(o),y=new Array(o),_=0,G=new Uint8Array(t.buffer);for(let ie=0;ie<o;ie++){let Ge=ie<l?u:d;p[ie]=G.slice(g,g+Ge),y[ie]=h.encode(p[ie]),g+=Ge,_=Math.max(_,Ge)}let re=new Uint8Array(r),C=0,N,$;for(N=0;N<_;N++)for($=0;$<o;$++)N<p[$].length&&(re[C++]=p[$][N]);for(N=0;N<f;N++)for($=0;$<o;$++)re[C++]=y[$][N];return re}function lf(t,e,n,r){let i;if(Array.isArray(t))i=Br.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Br.rawSplit(t);c=Tn.getBestVersionForData(u,n)}i=Br.fromString(t,c||40)}else throw new Error("Invalid data");let s=Tn.getBestVersionForData(i,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
7
+ `+n)}function Ne(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ne),t.emit("wsClientError",o,n,e)}else Pt(n,r,s,i)}});var wr=m((Xg,Qi)=>{Qi.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ye=m(Oe=>{var br,Id=[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];Oe.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};Oe.getSymbolTotalCodewords=function(e){return Id[e]};Oe.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Oe.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');br=e};Oe.isKanjiModeEnabled=function(){return typeof br<"u"};Oe.toSJIS=function(e){return br(e)}});var vn=m(J=>{J.L={bit:1};J.M={bit:0};J.Q={bit:3};J.H={bit:2};function xd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return J.L;case"m":case"medium":return J.M;case"q":case"quartile":return J.Q;case"h":case"high":return J.H;default:throw new Error("Unknown EC Level: "+t)}}J.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};J.from=function(e,n){if(J.isValid(e))return e;try{return xd(e)}catch{return n}}});var no=m((em,to)=>{function eo(){this.buffer=[],this.length=0}eo.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 n=0;n<e;n++)this.putBit((t>>>e-n-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++}};to.exports=eo});var so=m((tm,ro)=>{function Lt(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)}Lt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Lt.prototype.get=function(t,e){return this.data[t*this.size+e]};Lt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Lt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ro.exports=Lt});var io=m(wn=>{var Ed=ye().getSymbolSize;wn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Ed(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};wn.getPositions=function(e){let n=[],r=wn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var lo=m(ao=>{var Ad=ye().getSymbolSize,oo=7;ao.getPositions=function(e){let n=Ad(e);return[[0,0],[n-oo,0],[0,n-oo]]}});var co=m(x=>{x.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Me={N1:3,N2:3,N3:40,N4:10};x.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};x.from=function(e){return x.isValid(e)?parseInt(e,10):void 0};x.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=Me.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=Me.N1+(i-5)),a=u,i=1)}s>=5&&(r+=Me.N1+(s-5)),i>=5&&(r+=Me.N1+(i-5))}return r};x.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*Me.N2};x.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*Me.N3};x.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*Me.N4};function Cd(t,e,n){switch(t){case x.Patterns.PATTERN000:return(e+n)%2===0;case x.Patterns.PATTERN001:return e%2===0;case x.Patterns.PATTERN010:return n%3===0;case x.Patterns.PATTERN011:return(e+n)%3===0;case x.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case x.Patterns.PATTERN101:return e*n%2+e*n%3===0;case x.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case x.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}x.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,Cd(e,i,s))};x.getBestMask=function(e,n){let r=Object.keys(x.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),x.applyMask(o,e);let a=x.getPenaltyN1(e)+x.getPenaltyN2(e)+x.getPenaltyN3(e)+x.getPenaltyN4(e);x.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var xr=m(Ir=>{var _e=vn(),bn=[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],In=[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];Ir.getBlocksCount=function(e,n){switch(n){case _e.L:return bn[(e-1)*4+0];case _e.M:return bn[(e-1)*4+1];case _e.Q:return bn[(e-1)*4+2];case _e.H:return bn[(e-1)*4+3];default:return}};Ir.getTotalCodewordsCount=function(e,n){switch(n){case _e.L:return In[(e-1)*4+0];case _e.M:return In[(e-1)*4+1];case _e.Q:return In[(e-1)*4+2];case _e.H:return In[(e-1)*4+3];default:return}}});var uo=m(En=>{var Nt=new Uint8Array(512),xn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Nt[n]=e,xn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Nt[n]=Nt[n-255]})();En.log=function(e){if(e<1)throw new Error("log("+e+")");return xn[e]};En.exp=function(e){return Nt[e]};En.mul=function(e,n){return e===0||n===0?0:Nt[xn[e]+xn[n]]}});var fo=m(Ot=>{var Er=uo();Ot.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=Er.mul(e[s],n[i]);return r};Ot.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=Er.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Ot.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Ot.mul(n,new Uint8Array([1,Er.exp(r)]));return n}});var go=m((lm,po)=>{var ho=fo();function Ar(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ar.prototype.initialize=function(e){this.degree=e,this.genPoly=ho.generateECPolynomial(this.degree)};Ar.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=ho.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};po.exports=Ar});var Cr=m(mo=>{mo.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Tr=m(he=>{var yo="[0-9]+",Td="[A-Z $%*+\\-./:]+",Mt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Mt=Mt.replace(/u/g,"\\u");var kd="(?:(?![A-Z0-9 $%*+\\-./:]|"+Mt+`)(?:.|[\r
8
+ ]))+`;he.KANJI=new RegExp(Mt,"g");he.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");he.BYTE=new RegExp(kd,"g");he.NUMERIC=new RegExp(yo,"g");he.ALPHANUMERIC=new RegExp(Td,"g");var Rd=new RegExp("^"+Mt+"$"),Pd=new RegExp("^"+yo+"$"),Ld=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");he.testKanji=function(e){return Rd.test(e)};he.testNumeric=function(e){return Pd.test(e)};he.testAlphanumeric=function(e){return Ld.test(e)}});var Se=m(R=>{var Nd=Cr(),kr=Tr();R.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};R.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};R.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};R.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};R.MIXED={bit:-1};R.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Nd.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};R.getBestModeForData=function(e){return kr.testNumeric(e)?R.NUMERIC:kr.testAlphanumeric(e)?R.ALPHANUMERIC:kr.testKanji(e)?R.KANJI:R.BYTE};R.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};R.isValid=function(e){return e&&e.bit&&e.ccBits};function Od(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return R.NUMERIC;case"alphanumeric":return R.ALPHANUMERIC;case"kanji":return R.KANJI;case"byte":return R.BYTE;default:throw new Error("Unknown mode: "+t)}}R.from=function(e,n){if(R.isValid(e))return e;try{return Od(e)}catch{return n}}});var bo=m(Be=>{var An=ye(),Md=xr(),_o=vn(),ve=Se(),Rr=Cr(),vo=7973,So=An.getBCHDigit(vo);function Bd(t,e,n){for(let r=1;r<=40;r++)if(e<=Be.getCapacity(r,n,t))return r}function wo(t,e){return ve.getCharCountIndicator(t,e)+4}function Dd(t,e){let n=0;return t.forEach(function(r){let s=wo(r.mode,e);n+=s+r.getBitsLength()}),n}function Hd(t,e){for(let n=1;n<=40;n++)if(Dd(t,n)<=Be.getCapacity(n,e,ve.MIXED))return n}Be.from=function(e,n){return Rr.isValid(e)?parseInt(e,10):n};Be.getCapacity=function(e,n,r){if(!Rr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=ve.BYTE);let s=An.getSymbolTotalCodewords(e),i=Md.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===ve.MIXED)return o;let a=o-wo(r,e);switch(r){case ve.NUMERIC:return Math.floor(a/10*3);case ve.ALPHANUMERIC:return Math.floor(a/11*2);case ve.KANJI:return Math.floor(a/13);case ve.BYTE:default:return Math.floor(a/8)}};Be.getBestVersionForData=function(e,n){let r,s=_o.from(n,_o.M);if(Array.isArray(e)){if(e.length>1)return Hd(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Bd(r.mode,r.getLength(),s)};Be.getEncodedBits=function(e){if(!Rr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;An.getBCHDigit(n)-So>=0;)n^=vo<<An.getBCHDigit(n)-So;return e<<12|n}});var Ao=m(Eo=>{var Pr=ye(),xo=1335,Fd=21522,Io=Pr.getBCHDigit(xo);Eo.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Pr.getBCHDigit(s)-Io>=0;)s^=xo<<Pr.getBCHDigit(s)-Io;return(r<<10|s)^Fd}});var To=m((pm,Co)=>{var Ud=Se();function Qe(t){this.mode=Ud.NUMERIC,this.data=t.toString()}Qe.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Qe.prototype.getLength=function(){return this.data.length};Qe.prototype.getBitsLength=function(){return Qe.getBitsLength(this.data.length)};Qe.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Co.exports=Qe});var Ro=m((gm,ko)=>{var qd=Se(),Lr=["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 et(t){this.mode=qd.ALPHANUMERIC,this.data=t}et.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};et.prototype.getLength=function(){return this.data.length};et.prototype.getBitsLength=function(){return et.getBitsLength(this.data.length)};et.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Lr.indexOf(this.data[n])*45;r+=Lr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Lr.indexOf(this.data[n]),6)};ko.exports=et});var Lo=m((mm,Po)=>{var Wd=Se();function tt(t){this.mode=Wd.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}tt.getBitsLength=function(e){return e*8};tt.prototype.getLength=function(){return this.data.length};tt.prototype.getBitsLength=function(){return tt.getBitsLength(this.data.length)};tt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Po.exports=tt});var Oo=m((ym,No)=>{var jd=Se(),Gd=ye();function nt(t){this.mode=jd.KANJI,this.data=t}nt.getBitsLength=function(e){return e*13};nt.prototype.getLength=function(){return this.data.length};nt.prototype.getBitsLength=function(){return nt.getBitsLength(this.data.length)};nt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Gd.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};No.exports=nt});var Mo=m((_m,Nr)=>{"use strict";var Bt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Bt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,h=s[l],g=typeof s[l]>"u",(g||h>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Bt.single_source_shortest_paths(t,e,n);return Bt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Bt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Nr<"u"&&(Nr.exports=Bt)});var jo=m(rt=>{var b=Se(),Ho=To(),Fo=Ro(),Uo=Lo(),qo=Oo(),Dt=Tr(),Cn=ye(),zd=Mo();function Bo(t){return unescape(encodeURIComponent(t)).length}function Ht(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function Wo(t){let e=Ht(Dt.NUMERIC,b.NUMERIC,t),n=Ht(Dt.ALPHANUMERIC,b.ALPHANUMERIC,t),r,s;return Cn.isKanjiModeEnabled()?(r=Ht(Dt.BYTE,b.BYTE,t),s=Ht(Dt.KANJI,b.KANJI,t)):(r=Ht(Dt.BYTE_KANJI,b.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Or(t,e){switch(e){case b.NUMERIC:return Ho.getBitsLength(t);case b.ALPHANUMERIC:return Fo.getBitsLength(t);case b.KANJI:return qo.getBitsLength(t);case b.BYTE:return Uo.getBitsLength(t)}}function $d(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Vd(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case b.NUMERIC:e.push([r,{data:r.data,mode:b.ALPHANUMERIC,length:r.length},{data:r.data,mode:b.BYTE,length:r.length}]);break;case b.ALPHANUMERIC:e.push([r,{data:r.data,mode:b.BYTE,length:r.length}]);break;case b.KANJI:e.push([r,{data:r.data,mode:b.BYTE,length:Bo(r.data)}]);break;case b.BYTE:e.push([{data:r.data,mode:b.BYTE,length:Bo(r.data)}])}}return e}function Yd(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=Or(n[f].lastCount+c.length,c.mode)-Or(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Or(c.length,c.mode)+4+b.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function Do(t,e){let n,r=b.getBestModeForData(t);if(n=b.from(e,r),n!==b.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+b.toString(n)+`.
10
+ Suggested mode is: `+b.toString(r));switch(n===b.KANJI&&!Cn.isKanjiModeEnabled()&&(n=b.BYTE),n){case b.NUMERIC:return new Ho(t);case b.ALPHANUMERIC:return new Fo(t);case b.KANJI:return new qo(t);case b.BYTE:return new Uo(t)}}rt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Do(r,null)):r.data&&n.push(Do(r.data,r.mode)),n},[])};rt.fromString=function(e,n){let r=Wo(e,Cn.isKanjiModeEnabled()),s=Vd(r),i=Yd(s,n),o=zd.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return rt.fromArray($d(a))};rt.rawSplit=function(e){return rt.fromArray(Wo(e,Cn.isKanjiModeEnabled()))}});var Ur=m(Go=>{var kn=ye(),Mr=vn(),Jd=no(),Kd=so(),Xd=io(),Zd=lo(),Hr=co(),Fr=xr(),Qd=go(),Tn=bo(),ef=Ao(),tf=Se(),Br=jo();function nf(t,e){let n=t.size,r=Zd.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function rf(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function sf(t,e){let n=Xd.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function of(t,e){let n=t.size,r=Tn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Dr(t,e,n){let r=t.size,s=ef.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function af(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function lf(t,e,n){let r=new Jd;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),tf.getCharCountIndicator(l.mode,t)),l.write(r)});let s=kn.getSymbolTotalCodewords(t),i=Fr.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return cf(r,t,e)}function cf(t,e,n){let r=kn.getSymbolTotalCodewords(e),s=Fr.getTotalCodewordsCount(e,n),i=r-s,o=Fr.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,h=new Qd(f),g=0,p=new Array(o),y=new Array(o),_=0,G=new Uint8Array(t.buffer);for(let se=0;se<o;se++){let Ge=se<l?u:d;p[se]=G.slice(g,g+Ge),y[se]=h.encode(p[se]),g+=Ge,_=Math.max(_,Ge)}let re=new Uint8Array(r),C=0,N,$;for(N=0;N<_;N++)for($=0;$<o;$++)N<p[$].length&&(re[C++]=p[$][N]);for(N=0;N<f;N++)for($=0;$<o;$++)re[C++]=y[$][N];return re}function uf(t,e,n,r){let s;if(Array.isArray(t))s=Br.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Br.rawSplit(t);c=Tn.getBestVersionForData(u,n)}s=Br.fromString(t,c||40)}else throw new Error("Invalid data");let i=Tn.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
11
11
  The chosen QR Code version cannot contain this amount of data.
12
- Minimum version required to store current data is: `+s+`.
13
- `);let o=of(e,n,i),a=kn.getSymbolSize(e),l=new Yd(a);return ef(l,e),tf(l),nf(l,e),Dr(l,n,0),e>=7&&rf(l,e),sf(l,o),isNaN(r)&&(r=Hr.getBestMask(l,Dr.bind(null,l,n))),Hr.applyMask(r,l),Dr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:i}}Go.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Mr.M,i,s;return typeof n<"u"&&(r=Mr.from(n.errorCorrectionLevel,Mr.M),i=Tn.from(n.version),s=Hr.from(n.maskPattern),n.toSJISFunc&&kn.setToSJISFunction(n.toSJISFunc)),lf(e,i,r,s)}});var qr=m((Sm,$o)=>{"use strict";var cf=require("util"),zo=require("stream"),te=$o.exports=function(){zo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};cf.inherits(te,zo);te.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))};te.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};te.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()))};te.prototype.destroySoon=te.prototype.end;te.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};te.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};te.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))};te.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let i=this._buffers[n++],s=Math.min(i.length,t.length-e);i.copy(r,e,0,s),e+=s,s!==i.length&&(this._buffers[--n]=i.slice(s))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};te.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 jr=m(Wr=>{"use strict";var we=[{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]}];Wr.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,s=(t-r)/8,o=(e-i)/8;for(let a=0;a<we.length;a++){let l=we[a],c=s*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<i;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Wr.getInterlaceIterator=function(t){return function(e,n,r){let i=e%we[r].x.length,s=(e-i)/we[r].x.length*8+we[r].x[i],o=n%we[r].y.length,a=(n-o)/we[r].y.length*8+we[r].y[o];return s*4+a*t*4}}});var Gr=m((wm,Vo)=>{"use strict";Vo.exports=function(e,n,r){let i=e+n-r,s=Math.abs(i-e),o=Math.abs(i-n),a=Math.abs(i-r);return s<=o&&s<=a?e:o<=a?n:r}});var zr=m((bm,Jo)=>{"use strict";var uf=jr(),df=Gr();function Yo(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var it=Jo.exports=function(t,e){let n=t.width,r=t.height,i=t.interlace,s=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=uf.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Yo(a[l].width,s,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Yo(n,s,o),height:r,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};it.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};it.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let s=0;s<n;s++){let o=t[1+s],a=s>i?e[s-r]:0;e[s]=o+a}};it.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let s=t[1+i],o=r?r[i]:0;e[i]=s+o}};it.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=s?s[o]:0,c=o>i?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};it.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=s?s[o]:0,c=o>i?e[o-r]:0,u=o>i&&s?s[o-r]:0,d=df(c,l,u);e[o]=a+d}};it.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Zo=m((Im,Xo)=>{"use strict";var ff=require("util"),Ko=qr(),hf=zr(),pf=Xo.exports=function(t){Ko.call(this);let e=[],n=this;this._filter=new hf(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};ff.inherits(pf,Ko)});var st=m((xm,Qo)=>{"use strict";Qo.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 Yr=m((Em,ea)=>{"use strict";var $r=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;$r[t]=e}})();var Vr=ea.exports=function(){this._crc=-1};Vr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=$r[(this._crc^t[e])&255]^this._crc>>>8;return!0};Vr.prototype.crc32=function(){return this._crc^-1};Vr.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=$r[(e^t[n])&255]^e>>>8;return e^-1}});var Jr=m((Am,ta)=>{"use strict";var L=st(),gf=Yr(),M=ta.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[L.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[L.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[L.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[L.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[L.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[L.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(){}};M.prototype.start=function(){this.read(L.PNG_SIGNATURE.length,this._parseSignature.bind(this))};M.prototype._parseSignature=function(t){let e=L.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};M.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(t[s]);let i=!!(t[4]&32);if(!this._hasIHDR&&n!==L.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new gf,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};M.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};M.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};M.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};M.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};M.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],s=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(i in L.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(s!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=i;let l=L.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(i&L.COLORTYPE_PALETTE),color:!!(i&L.COLORTYPE_COLOR),alpha:!!(i&L.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};M.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};M.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};M.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};M.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===L.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===L.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===L.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};M.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};M.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/L.GAMMA_DIVISION),this._handleChunkEnd()};M.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};M.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===L.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};M.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};M.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Kr=m(ra=>{"use strict";var na=jr(),mf=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],yf=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function _f(t,e){let n=[],r=0;function i(){if(r===t.length)throw new Error("Ran out of data");let s=t[r];r++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((s<<8)+f);break;case 4:f=s&15,h=s>>4,n.push(h,f);break;case 2:u=s&3,d=s>>2&3,f=s>>4&3,h=s>>6&3,n.push(h,f,d,u);break;case 1:o=s&1,a=s>>1&1,l=s>>2&1,c=s>>3&1,u=s>>4&1,d=s>>5&1,f=s>>6&1,h=s>>7&1,n.push(h,f,d,u,c,l,a,o);break}}return{get:function(s){for(;n.length<s;)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function Sf(t,e,n,r,i,s){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);mf[r](e,i,d,s),s+=r}return s}function vf(t,e,n,r,i,s){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=i.get(r),f=n(u,c,l);yf[r](e,d,f,s)}i.resetAfterLine()}}ra.dataToBitMap=function(t,e){let n=e.width,r=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=_f(t,i));let l;i<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,u=0,d,f;if(o)d=na.getImagePasses(n,r),f=na.getInterlaceIterator(n,r);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)i===8?u=Sf(d[h],l,f,s,t,u):vf(d[h],l,f,s,a,c);if(i===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Xr=m((Tm,ia)=>{"use strict";function wf(t,e,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=i[t[s]];if(!l)throw new Error("index "+t[s]+" not in palette");for(let c=0;c<4;c++)e[s+c]=l[c];s+=4}}function bf(t,e,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(i.length===1?i[0]===t[s]&&(l=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(l=!0),l)for(let c=0;c<4;c++)e[s+c]=0;s+=4}}function If(t,e,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*s/o+.5);a+=4}}ia.exports=function(t,e){let n=e.depth,r=e.width,i=e.height,s=e.colorType,o=e.transColor,a=e.palette,l=t;return s===3?wf(t,l,r,i,a):(o&&bf(t,l,r,i,o),n!==8&&(n===16&&(l=Buffer.alloc(r*i*4)),If(t,l,r,i,n))),l}});var aa=m((km,oa)=>{"use strict";var xf=require("util"),Zr=require("zlib"),sa=qr(),Ef=Zo(),Af=Jr(),Cf=Kr(),Tf=Xr(),oe=oa.exports=function(t){sa.call(this),this._parser=new Af(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()};xf.inherits(oe,sa);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=Zr.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,Zr.Z_MIN_CHUNK);this._inflate=Zr.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){i&&s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){i&&(a.length>i&&(a=a.slice(0,i)),i-=a.length,o(a))}),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 Ef(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 n=Cf.dataToBitMap(t,this._bitmapInfo);e=Tf(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var ca=m((Rm,la)=>{"use strict";var K=st();la.exports=function(t,e,n,r){let i=[K.COLORTYPE_COLOR_ALPHA,K.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let s=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=K.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=K.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,p,y,_=o;switch(r.inputColorType){case K.COLORTYPE_COLOR_ALPHA:_=s[u+3],g=s[u],p=s[u+1],y=s[u+2];break;case K.COLORTYPE_COLOR:g=s[u],p=s[u+1],y=s[u+2];break;case K.COLORTYPE_ALPHA:_=s[u+1],g=s[u],p=g,y=g;break;case K.COLORTYPE_GRAYSCALE:g=s[u],p=g,y=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(i||(_/=o,g=Math.min(Math.max(Math.round((1-_)*f.red+_*g),0),o),p=Math.min(Math.max(Math.round((1-_)*f.green+_*p),0),o),y=Math.min(Math.max(Math.round((1-_)*f.blue+_*y),0),o))),{red:g,green:p,blue:y,alpha:_}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let y=h(s,u);switch(r.colorType){case K.COLORTYPE_COLOR_ALPHA:case K.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,i&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),i&&c.writeUInt16BE(y.alpha,d+6));break;case K.COLORTYPE_ALPHA:case K.COLORTYPE_GRAYSCALE:{let _=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=_,i&&(c[d+1]=y.alpha)):(c.writeUInt16BE(_,d),i&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var fa=m((Pm,da)=>{"use strict";var ua=Gr();function kf(t,e,n,r,i){for(let s=0;s<n;s++)r[i+s]=t[e+s]}function Rf(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++)r+=Math.abs(t[s]);return r}function Pf(t,e,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?t[e+o-s]:0,l=t[e+o]-a;r[i+o]=l}}function Lf(t,e,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?t[e+s-r]:0,a=t[e+s]-o;i+=Math.abs(a)}return i}function Nf(t,e,n,r,i){for(let s=0;s<n;s++){let o=e>0?t[e+s-n]:0,a=t[e+s]-o;r[i+s]=a}}function Of(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++){let o=e>0?t[s-n]:0,a=t[s]-o;r+=Math.abs(a)}return r}function Mf(t,e,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?t[e+o-s]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[i+o]=c}}function Bf(t,e,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?t[e+s-r]:0,a=e>0?t[e+s-n]:0,l=t[e+s]-(o+a>>1);i+=Math.abs(l)}return i}function Df(t,e,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?t[e+o-s]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=s?t[e+o-(n+s)]:0,u=t[e+o]-ua(a,l,c);r[i+o]=u}}function Hf(t,e,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?t[e+s-r]:0,a=e>0?t[e+s-n]:0,l=e>0&&s>=r?t[e+s-(n+r)]:0,c=t[e+s]-ua(o,a,l);i+=Math.abs(c)}return i}var Ff={0:kf,1:Pf,2:Nf,3:Mf,4:Df},Uf={0:Rf,1:Lf,2:Of,3:Bf,4:Hf};da.exports=function(t,e,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType=="number")s=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(i*=2);let o=e*i,a=0,l=0,c=Buffer.alloc((o+1)*n),u=s[0];for(let d=0;d<n;d++){if(s.length>1){let f=1/0;for(let h=0;h<s.length;h++){let g=Uf[s[h]](t,l,o,i);g<f&&(u=s[h],f=g)}}c[a]=u,a++,Ff[u](t,l,o,c,a,i),a+=o,l+=o}return c}});var Qr=m((Lm,ha)=>{"use strict";var H=st(),qf=Yr(),Wf=ca(),jf=fa(),Gf=require("zlib"),be=ha.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||Gf.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:H.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:H.COLORTYPE_COLOR_ALPHA,[H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.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")};be.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};be.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};be.prototype.filterData=function(t,e,n){let r=Wf(t,e,n,this._options),i=H.COLORTYPE_TO_BPP_MAP[this._options.colorType];return jf(r,e,n,this._options,i)};be.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(qf.crc32(r.slice(4,r.length-4)),r.length-4),r};be.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*H.GAMMA_DIVISION),0),this._packChunk(H.TYPE_gAMA,e)};be.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(H.TYPE_IHDR,n)};be.prototype.packIDAT=function(t){return this._packChunk(H.TYPE_IDAT,t)};be.prototype.packIEND=function(){return this._packChunk(H.TYPE_IEND,null)}});var ya=m((Nm,ma)=>{"use strict";var zf=require("util"),pa=require("stream"),$f=st(),Vf=Qr(),ga=ma.exports=function(t){pa.call(this);let e=t||{};this._packer=new Vf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};zf.inherits(ga,pa);ga.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from($f.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Ia=m((Ft,ba)=>{"use strict";var _a=require("assert").ok,ot=require("zlib"),Yf=require("util"),Sa=require("buffer").kMaxLength;function De(t){if(!(this instanceof De))return new De(t);t&&t.chunkSize<ot.Z_MIN_CHUNK&&(t.chunkSize=ot.Z_MIN_CHUNK),ot.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 Jf(t){return new De(t)}function va(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}De.prototype._processChunk=function(t,e,n){if(typeof n=="function")return ot.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,p){if(r._hadError)return;let y=s-p;if(_a(y>=0,"have should not go down"),y>0){let _=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,_.length>o&&(_=_.slice(0,o)),l.push(_),c+=_.length,o-=_.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=i-g,i=g,!0):!1}_a(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Sa)throw va(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Sa.toString(16)+" bytes");let h=Buffer.concat(l,c);return va(this),h};Yf.inherits(De,ot.Inflate);function Kf(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=ot.Z_FINISH),t._processChunk(e,n)}function wa(t,e){return Kf(new De(e),t)}ba.exports=Ft=wa;Ft.Inflate=De;Ft.createInflate=Jf;Ft.inflateSync=wa});var ei=m((Om,Ea)=>{"use strict";var xa=Ea.exports=function(t){this._buffer=t,this._reads=[]};xa.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};xa.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 Ca=m(Aa=>{"use strict";var Xf=ei(),Zf=zr();Aa.process=function(t,e){let n=[],r=new Xf(t);return new Zf(e,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Pa=m((Bm,Ra)=>{"use strict";var Ta=!0,ka=require("zlib"),Qf=Ia();ka.deflateSync||(Ta=!1);var eh=ei(),th=Ca(),nh=Jr(),rh=Kr(),ih=Xr();Ra.exports=function(t,e){if(!Ta)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(C){n=C}let i;function s(C){i=C}function o(C){i.transColor=C}function a(C){i.palette=C}function l(){i.alpha=!0}let c;function u(C){c=C}let d=[];function f(C){d.push(C)}let h=new eh(t);if(new nh(e,{read:h.read.bind(h),error:r,metadata:s,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let y;if(i.interlace)y=ka.inflateSync(p);else{let N=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;y=Qf(p,{chunkSize:N,maxLength:N})}if(p=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let _=th.process(y,i);p=null;let G=rh.dataToBitMap(_,i);_=null;let re=ih(G,i);return i.data=re,i.gamma=c||0,i}});var Ma=m((Dm,Oa)=>{"use strict";var La=!0,Na=require("zlib");Na.deflateSync||(La=!1);var sh=st(),oh=Qr();Oa.exports=function(t,e){if(!La)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new oh(n),i=[];i.push(Buffer.from(sh.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma&&i.push(r.packGAMA(t.gamma));let s=r.filterData(t.data,t.width,t.height),o=Na.deflateSync(s,r.getDeflateOptions());if(s=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return i.push(r.packIDAT(o)),i.push(r.packIEND()),Buffer.concat(i)}});var Ba=m(ti=>{"use strict";var ah=Pa(),lh=Ma();ti.read=function(t,e){return ah(t,e||{})};ti.write=function(t,e){return lh(t,e)}});var Fa=m(Ha=>{"use strict";var ch=require("util"),Da=require("stream"),uh=aa(),dh=ya(),fh=Ba(),U=Ha.PNG=function(t){Da.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 uh(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 dh(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"))};ch.inherits(U,Da);U.sync=fh;U.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)};U.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};U.prototype.write=function(t){return this._parser.write(t),!0};U.prototype.end=function(t){this._parser.end(t)};U.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};U.prototype._gamma=function(t){this.gamma=t};U.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};U.bitblt=function(t,e,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>t.width||r>t.height||n+i>t.width||r+s>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+i>e.width||a+s>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<s;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+i<<2)};U.prototype.bitblt=function(t,e,n,r,i,s,o){return U.bitblt(this,t,e,n,r,i,s,o),this};U.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let s=t.data[r+i]/255;s=Math.pow(s,1/2.2/t.gamma),t.data[r+i]=Math.round(s*255)}}t.gamma=0}};U.prototype.adjustGamma=function(){U.adjustGamma(this)}});var Ut=m(He=>{function Ua(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(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}He.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:r,scale:r?4:i,margin:n,color:{dark:Ua(e.color.dark||"#000000ff"),light:Ua(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};He.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};He.getImageWidth=function(e,n){let r=He.getScale(e,n);return Math.floor((e+n.margin*2)*r)};He.qrToImageData=function(e,n,r){let i=n.modules.size,s=n.modules.data,o=He.getScale(i,r),a=Math.floor((i+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),p=Math.floor((d-l)/o);h=c[s[g*i+p]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var qa=m(ae=>{var hh=require("fs"),ph=Fa().PNG,ni=Ut();ae.render=function(e,n){let r=ni.getOptions(n),i=r.rendererOpts,s=ni.getImageWidth(e.modules.size,r);i.width=s,i.height=s;let o=new ph(i);return ni.qrToImageData(o.data,e,r),o};ae.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ae.renderToBuffer(e,n,function(i,s){i&&r(i);let o="data:image/png;base64,";o+=s.toString("base64"),r(null,o)})};ae.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let i=ae.render(e,n),s=[];i.on("error",r),i.on("data",function(o){s.push(o)}),i.on("end",function(){r(null,Buffer.concat(s))}),i.pack()};ae.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=!1,o=(...l)=>{s||(s=!0,i.apply(null,l))},a=hh.createWriteStream(e);a.on("error",o),a.on("close",o),ae.renderToFileStream(a,n,r)};ae.renderToFileStream=function(e,n,r){ae.render(n,r).pack().pipe(e)}});var Wa=m(Rn=>{var gh=Ut(),mh={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},yh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function _h(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Rn.render=function(t,e,n){let r=gh.getOptions(e),i=mh;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(i=yh);let s=t.modules.size,o=t.modules.data,a="",l=Array(s+r.margin*2+1).join(i.WW);l=Array(r.margin/2+1).join(l+`
14
- `);let c=Array(r.margin+1).join(i.WW);a+=l;for(let u=0;u<s;u+=2){a+=c;for(let d=0;d<s;d++){let f=o[u*s+d],h=o[(u+1)*s+d];a+=_h(f,h,i)}a+=c+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Rn.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=require("fs"),o=Rn.render(n,r);s.writeFile(e,o,i)}});var Ga=m(ja=>{ja.render=function(t,e,n){let r=t.modules.size,i=t.modules.data,s="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
16
- `;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=i[u*r+d]?s:o;a+=c+`
12
+ Minimum version required to store current data is: `+i+`.
13
+ `);let o=lf(e,n,s),a=kn.getSymbolSize(e),l=new Kd(a);return nf(l,e),rf(l),sf(l,e),Dr(l,n,0),e>=7&&of(l,e),af(l,o),isNaN(r)&&(r=Hr.getBestMask(l,Dr.bind(null,l,n))),Hr.applyMask(r,l),Dr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Go.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Mr.M,s,i;return typeof n<"u"&&(r=Mr.from(n.errorCorrectionLevel,Mr.M),s=Tn.from(n.version),i=Hr.from(n.maskPattern),n.toSJISFunc&&kn.setToSJISFunction(n.toSJISFunc)),uf(e,s,r,i)}});var qr=m((wm,$o)=>{"use strict";var df=require("util"),zo=require("stream"),te=$o.exports=function(){zo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};df.inherits(te,zo);te.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))};te.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};te.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()))};te.prototype.destroySoon=te.prototype.end;te.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};te.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};te.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))};te.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};te.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 jr=m(Wr=>{"use strict";var we=[{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]}];Wr.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<we.length;a++){let l=we[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Wr.getInterlaceIterator=function(t){return function(e,n,r){let s=e%we[r].x.length,i=(e-s)/we[r].x.length*8+we[r].x[s],o=n%we[r].y.length,a=(n-o)/we[r].y.length*8+we[r].y[o];return i*4+a*t*4}}});var Gr=m((Im,Vo)=>{"use strict";Vo.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var zr=m((xm,Jo)=>{"use strict";var ff=jr(),hf=Gr();function Yo(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var st=Jo.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=ff.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Yo(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Yo(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};st.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};st.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};st.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};st.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};st.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=hf(c,l,u);e[o]=a+d}};st.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var Zo=m((Em,Xo)=>{"use strict";var pf=require("util"),Ko=qr(),gf=zr(),mf=Xo.exports=function(t){Ko.call(this);let e=[],n=this;this._filter=new gf(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};pf.inherits(mf,Ko)});var it=m((Am,Qo)=>{"use strict";Qo.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 Yr=m((Cm,ea)=>{"use strict";var $r=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;$r[t]=e}})();var Vr=ea.exports=function(){this._crc=-1};Vr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=$r[(this._crc^t[e])&255]^this._crc>>>8;return!0};Vr.prototype.crc32=function(){return this._crc^-1};Vr.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=$r[(e^t[n])&255]^e>>>8;return e^-1}});var Jr=m((Tm,ta)=>{"use strict";var L=it(),yf=Yr(),M=ta.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[L.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[L.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[L.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[L.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[L.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[L.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(){}};M.prototype.start=function(){this.read(L.PNG_SIGNATURE.length,this._parseSignature.bind(this))};M.prototype._parseSignature=function(t){let e=L.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};M.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==L.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new yf,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};M.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};M.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};M.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};M.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};M.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in L.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=L.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&L.COLORTYPE_PALETTE),color:!!(s&L.COLORTYPE_COLOR),alpha:!!(s&L.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};M.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};M.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};M.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};M.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===L.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===L.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===L.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};M.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};M.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/L.GAMMA_DIVISION),this._handleChunkEnd()};M.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};M.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===L.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};M.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};M.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Kr=m(ra=>{"use strict";var na=jr(),_f=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Sf=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function vf(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function wf(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);_f[r](e,s,d,i),i+=r}return i}function bf(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);Sf[r](e,d,f,i)}s.resetAfterLine()}}ra.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=vf(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=na.getImagePasses(n,r),f=na.getInterlaceIterator(n,r);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)s===8?u=wf(d[h],l,f,i,t,u):bf(d[h],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Xr=m((Rm,sa)=>{"use strict";function If(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function xf(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function Ef(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}sa.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?If(t,l,r,s,a):(o&&xf(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Ef(t,l,r,s,n))),l}});var aa=m((Pm,oa)=>{"use strict";var Af=require("util"),Zr=require("zlib"),ia=qr(),Cf=Zo(),Tf=Jr(),kf=Kr(),Rf=Xr(),oe=oa.exports=function(t){ia.call(this),this._parser=new Tf(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()};Af.inherits(oe,ia);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=Zr.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,Zr.Z_MIN_CHUNK);this._inflate=Zr.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),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 Cf(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 n=kf.dataToBitMap(t,this._bitmapInfo);e=Rf(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var ca=m((Lm,la)=>{"use strict";var K=it();la.exports=function(t,e,n,r){let s=[K.COLORTYPE_COLOR_ALPHA,K.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=K.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=K.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,p,y,_=o;switch(r.inputColorType){case K.COLORTYPE_COLOR_ALPHA:_=i[u+3],g=i[u],p=i[u+1],y=i[u+2];break;case K.COLORTYPE_COLOR:g=i[u],p=i[u+1],y=i[u+2];break;case K.COLORTYPE_ALPHA:_=i[u+1],g=i[u],p=g,y=g;break;case K.COLORTYPE_GRAYSCALE:g=i[u],p=g,y=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(_/=o,g=Math.min(Math.max(Math.round((1-_)*f.red+_*g),0),o),p=Math.min(Math.max(Math.round((1-_)*f.green+_*p),0),o),y=Math.min(Math.max(Math.round((1-_)*f.blue+_*y),0),o))),{red:g,green:p,blue:y,alpha:_}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let y=h(i,u);switch(r.colorType){case K.COLORTYPE_COLOR_ALPHA:case K.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,s&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),s&&c.writeUInt16BE(y.alpha,d+6));break;case K.COLORTYPE_ALPHA:case K.COLORTYPE_GRAYSCALE:{let _=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=_,s&&(c[d+1]=y.alpha)):(c.writeUInt16BE(_,d),s&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var fa=m((Nm,da)=>{"use strict";var ua=Gr();function Pf(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Lf(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Nf(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function Of(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function Mf(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function Bf(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function Df(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function Hf(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Ff(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-ua(a,l,c);r[s+o]=u}}function Uf(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-ua(o,a,l);s+=Math.abs(c)}return s}var qf={0:Pf,1:Nf,2:Mf,3:Df,4:Ff},Wf={0:Lf,1:Of,2:Bf,3:Hf,4:Uf};da.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=Wf[i[h]](t,l,o,s);g<f&&(u=i[h],f=g)}}c[a]=u,a++,qf[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Qr=m((Om,ha)=>{"use strict";var H=it(),jf=Yr(),Gf=ca(),zf=fa(),$f=require("zlib"),be=ha.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||$f.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:H.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:H.COLORTYPE_COLOR_ALPHA,[H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.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")};be.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};be.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};be.prototype.filterData=function(t,e,n){let r=Gf(t,e,n,this._options),s=H.COLORTYPE_TO_BPP_MAP[this._options.colorType];return zf(r,e,n,this._options,s)};be.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(jf.crc32(r.slice(4,r.length-4)),r.length-4),r};be.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*H.GAMMA_DIVISION),0),this._packChunk(H.TYPE_gAMA,e)};be.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(H.TYPE_IHDR,n)};be.prototype.packIDAT=function(t){return this._packChunk(H.TYPE_IDAT,t)};be.prototype.packIEND=function(){return this._packChunk(H.TYPE_IEND,null)}});var ya=m((Mm,ma)=>{"use strict";var Vf=require("util"),pa=require("stream"),Yf=it(),Jf=Qr(),ga=ma.exports=function(t){pa.call(this);let e=t||{};this._packer=new Jf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Vf.inherits(ga,pa);ga.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Yf.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Ia=m((Ft,ba)=>{"use strict";var _a=require("assert").ok,ot=require("zlib"),Kf=require("util"),Sa=require("buffer").kMaxLength;function De(t){if(!(this instanceof De))return new De(t);t&&t.chunkSize<ot.Z_MIN_CHUNK&&(t.chunkSize=ot.Z_MIN_CHUNK),ot.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 Xf(t){return new De(t)}function va(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}De.prototype._processChunk=function(t,e,n){if(typeof n=="function")return ot.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,p){if(r._hadError)return;let y=i-p;if(_a(y>=0,"have should not go down"),y>0){let _=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,_.length>o&&(_=_.slice(0,o)),l.push(_),c+=_.length,o-=_.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=s-g,s=g,!0):!1}_a(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Sa)throw va(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Sa.toString(16)+" bytes");let h=Buffer.concat(l,c);return va(this),h};Kf.inherits(De,ot.Inflate);function Zf(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=ot.Z_FINISH),t._processChunk(e,n)}function wa(t,e){return Zf(new De(e),t)}ba.exports=Ft=wa;Ft.Inflate=De;Ft.createInflate=Xf;Ft.inflateSync=wa});var es=m((Bm,Ea)=>{"use strict";var xa=Ea.exports=function(t){this._buffer=t,this._reads=[]};xa.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};xa.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 Ca=m(Aa=>{"use strict";var Qf=es(),eh=zr();Aa.process=function(t,e){let n=[],r=new Qf(t);return new eh(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Pa=m((Hm,Ra)=>{"use strict";var Ta=!0,ka=require("zlib"),th=Ia();ka.deflateSync||(Ta=!1);var nh=es(),rh=Ca(),sh=Jr(),ih=Kr(),oh=Xr();Ra.exports=function(t,e){if(!Ta)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(C){n=C}let s;function i(C){s=C}function o(C){s.transColor=C}function a(C){s.palette=C}function l(){s.alpha=!0}let c;function u(C){c=C}let d=[];function f(C){d.push(C)}let h=new nh(t);if(new sh(e,{read:h.read.bind(h),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let y;if(s.interlace)y=ka.inflateSync(p);else{let N=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=th(p,{chunkSize:N,maxLength:N})}if(p=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let _=rh.process(y,s);p=null;let G=ih.dataToBitMap(_,s);_=null;let re=oh(G,s);return s.data=re,s.gamma=c||0,s}});var Ma=m((Fm,Oa)=>{"use strict";var La=!0,Na=require("zlib");Na.deflateSync||(La=!1);var ah=it(),lh=Qr();Oa.exports=function(t,e){if(!La)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new lh(n),s=[];s.push(Buffer.from(ah.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=Na.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var Ba=m(ts=>{"use strict";var ch=Pa(),uh=Ma();ts.read=function(t,e){return ch(t,e||{})};ts.write=function(t,e){return uh(t,e)}});var Fa=m(Ha=>{"use strict";var dh=require("util"),Da=require("stream"),fh=aa(),hh=ya(),ph=Ba(),U=Ha.PNG=function(t){Da.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 fh(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 hh(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"))};dh.inherits(U,Da);U.sync=ph;U.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)};U.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};U.prototype.write=function(t){return this._parser.write(t),!0};U.prototype.end=function(t){this._parser.end(t)};U.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};U.prototype._gamma=function(t){this.gamma=t};U.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};U.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};U.prototype.bitblt=function(t,e,n,r,s,i,o){return U.bitblt(this,t,e,n,r,s,i,o),this};U.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};U.prototype.adjustGamma=function(){U.adjustGamma(this)}});var Ut=m(He=>{function Ua(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(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}He.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:Ua(e.color.dark||"#000000ff"),light:Ua(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};He.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};He.getImageWidth=function(e,n){let r=He.getScale(e,n);return Math.floor((e+n.margin*2)*r)};He.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=He.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),p=Math.floor((d-l)/o);h=c[i[g*s+p]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var qa=m(ae=>{var gh=require("fs"),mh=Fa().PNG,ns=Ut();ae.render=function(e,n){let r=ns.getOptions(n),s=r.rendererOpts,i=ns.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new mh(s);return ns.qrToImageData(o.data,e,r),o};ae.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ae.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};ae.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=ae.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};ae.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=gh.createWriteStream(e);a.on("error",o),a.on("close",o),ae.renderToFileStream(a,n,r)};ae.renderToFileStream=function(e,n,r){ae.render(n,r).pack().pipe(e)}});var Wa=m(Rn=>{var yh=Ut(),_h={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Sh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function vh(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Rn.render=function(t,e,n){let r=yh.getOptions(e),s=_h;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Sh);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
+ `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],h=o[(u+1)*i+d];a+=vh(f,h,s)}a+=c+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Rn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Rn.render(n,r);i.writeFile(e,o,s)}});var Ga=m(ja=>{ja.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
16
+ `;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=s[u*r+d]?i:o;a+=c+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var Ya=m(Va=>{var Sh="\x1B[47m",vh="\x1B[40m",ri="\x1B[37m",ii="\x1B[30m",Fe="\x1B[0m",wh=Sh+ii,bh=vh+ri,Ih=function(t,e,n){return{"00":Fe+" "+t,"01":Fe+e+"\u2584"+t,"02":Fe+n+"\u2584"+t,10:Fe+e+"\u2580"+t,11:" ",12:"\u2584",20:Fe+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},za=function(t,e,n,r){let i=e+1;if(n>=i||r>=i||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let s=r*e+n;return t[s]?"2":"1"},$a=function(t,e,n,r){return za(t,e,n,r)+za(t,e,n,r+1)};Va.render=function(t,e,n){let r=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?bh:wh,c=Ih(o,s?ii:ri,s?ri:ii),u=Fe+`
19
- `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[$a(i,r,h,f)];d+=c[$a(i,r,r,f)]+u}return d+=Fe,typeof n=="function"&&n(null,d),d}});var Ka=m(Ja=>{var xh=Ga(),Eh=Ya();Ja.render=function(t,e,n){return e&&e.small?Eh.render(t,e,n):xh.render(t,e,n)}});var oi=m(Za=>{var Ah=Ut();function Xa(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function si(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Ch(t,e,n){let r="",i=0,s=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!s&&(s=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=s?si("M",l+n,.5+c+n):si("m",i,0),i=0,s=!1),l+1<e&&t[a+1]||(r+=si("h",o),o=0)):i++}return r}Za.render=function(e,n,r){let i=Ah.getOptions(n),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,l=i.color.light.a?"<path "+Xa(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Xa(i.color.dark,"stroke")+' d="'+Ch(o,s,i.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
- `;return typeof r=="function"&&r(null,f),f}});var Qa=m(Pn=>{var Th=oi();Pn.render=Th.render;Pn.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=require("fs"),a='<?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">'+Pn.render(n,r);s.writeFile(e,a,i)}});var el=m(Ln=>{var ai=Ut();function kh(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function Rh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ln.render=function(e,n,r){let i=r,s=n;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),n||(s=Rh()),i=ai.getOptions(i);let o=ai.getImageWidth(e.modules.size,i),a=s.getContext("2d"),l=a.createImageData(o,o);return ai.qrToImageData(l.data,e,i),kh(a,s,o),a.putImageData(l,0,0),s};Ln.renderToDataURL=function(e,n,r){let i=r;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),i||(i={});let s=Ln.render(e,n,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var nl=m(qt=>{var Ph=wr(),li=Ur(),tl=el(),Lh=oi();function ci(t,e,n,r,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!Ph())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=r,r=void 0):(i=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=li.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=li.create(n,r);i(null,t(l,e,r))}catch(l){i(l)}}qt.create=li.create;qt.toCanvas=ci.bind(null,tl.render);qt.toDataURL=ci.bind(null,tl.renderToDataURL);qt.toString=ci.bind(null,function(t,e,n){return Lh.render(t,n)})});var ol=m(Ie=>{var rl=wr(),ui=Ur(),Nh=qa(),il=Wa(),Oh=Ka(),sl=Qa();function Wt(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(rl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Mh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Nn(t){switch(t){case"svg":return sl;case"txt":case"utf8":return il;case"png":case"image/png":default:return Nh}}function Bh(t){switch(t){case"svg":return sl;case"terminal":return Oh;case"utf8":default:return il}}function jt(t,e,n){if(!n.cb)return new Promise(function(r,i){try{let s=ui.create(e,n.opts);return t(s,n.opts,function(o,a){return o?i(o):r(a)})}catch(s){i(s)}});try{let r=ui.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Ie.create=ui.create;Ie.toCanvas=nl().toCanvas;Ie.toString=function(e,n,r){let i=Wt(e,n,r),s=i.opts?i.opts.type:void 0,o=Bh(s);return jt(o.render,e,i)};Ie.toDataURL=function(e,n,r){let i=Wt(e,n,r),s=Nn(i.opts.type);return jt(s.renderToDataURL,e,i)};Ie.toBuffer=function(e,n,r){let i=Wt(e,n,r),s=Nn(i.opts.type);return jt(s.renderToBuffer,e,i)};Ie.toFile=function(e,n,r,i){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!rl())throw new Error("Too few arguments provided");let s=Wt(n,r,i),o=s.opts.type||Mh(e),l=Nn(o).renderToFile.bind(null,e);return jt(l,n,s)};Ie.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Wt(n,r,e.emit.bind(e,"error")),o=Nn("png").renderToFileStream.bind(null,e);jt(o,n,i)}});var ll=m((Xm,al)=>{al.exports=ol()});var Fc=require("http");var yd=ze(js(),1),_d=ze(cr(),1),Sd=ze(fr(),1),vd=ze(_n(),1),vr=ze(Zs(),1);var We=require("fs/promises"),Xn=require("path"),Uc=require("os"),qc=ze(ll(),1);var lt=require("child_process"),cl=require("fs"),q=require("path"),zt=require("os"),Dh=["fnm_multishells"],Hh=6e4;function xe(t){return Dh.some(e=>t.includes(e))}function fi(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var at=null;function ul(){if(at&&!xe(at.PATH??""))return at;for(let t of fi())try{let e=(0,lt.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
21
- `)){let i=r.indexOf("=");i>0&&(n[r.slice(0,i)]=r.slice(i+1))}return xe(n.PATH??"")?at=null:at=n,n}catch{}return at={},{}}function Fh(t=ul()){let e=(0,zt.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,q.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",i=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,q.join)(e,".npm-global","bin"),(0,q.join)(e,".local","bin"),(0,q.join)(e,".claude","bin"),n],s=r.split(q.delimiter).filter(Boolean),o=new Set(s);for(let a of i)o.has(a)||(s.push(a),o.add(a));return s.join(q.delimiter)}function di(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function On(){let t=ul(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=Fh(t),e.HOME||(e.HOME=(0,zt.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Gt(t,e=3e3){try{return(0,lt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:On()}).trim()||null}catch{return null}}function Uh(t){for(let e of fi())try{let n=(0,lt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function qh(){let t=(0,zt.homedir)();return[(0,q.join)(t,".local","bin","claude"),(0,q.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,q.join)(t,".npm-global","bin","claude")]}function Wh(){for(let t of qh())if(Gt(t))return t;try{let t=(0,lt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:On()}).trim();if(t&&!t.includes("cmux")&&Gt(t))return t}catch{}}function jh(){let t=(0,zt.homedir)(),e=[process.env.PNPM_HOME,(0,q.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,q.join)(t,".npm-global","bin","codex"),(0,q.join)(t,".local","bin","codex"),...e.map(n=>(0,q.join)(n,"codex"))]}function Gh(){let t;for(let n of jh())if(Gt(n)){if(!xe(n))return n;t=n}try{let n=(0,lt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:On()}).trim();if(n&&Gt(n)){if(!xe(n))return n;t=t??n}}catch{}let e=Uh("codex");if(e&&Gt(e)){if(!xe(e))return e;t=t??e}return t}function dl(t,e){let n=null,r=0;return()=>{let i=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[i])return process.env[i];let s=Date.now();return(!n||s-r>Hh||!(0,cl.existsSync)(n)||xe(n))&&(n=t()??e,r=s,process.stdout.write(JSON.stringify({level:"info",ts:new Date().toISOString(),module:"config",msg:"binary resolved",name:e,path:n,transient:xe(n)})+`
22
- `)),n}}var zh=dl(Wh,"claude"),$h=dl(Gh,"codex");function Vh(t,e){return{command:fi()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Number(process.env.VIBE_IDLE_TIMEOUT_MS)||1800*1e3,auditMaxBytes:di("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:di("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:di("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return zh()},get codexPath(){return $h()},isTransientPath:xe,execViaLoginShell:Vh,buildSanitizedEnv:On};var Hi=require("crypto"),wc=require("fs/promises");var Ll=require("child_process"),Nl=require("fs");var Mn=require("fs"),pl=require("os"),hi=require("path"),fl={debug:10,info:20,warn:30,error:40},Yh=process.env.VIBE_LOG_LEVEL||"info";var gl=(0,hi.join)((0,pl.homedir)(),".vibe-remote"),Jh=(0,hi.join)(gl,"daemon.log");try{(0,Mn.mkdirSync)(gl,{recursive:!0})}catch{}function hl(t,e,n){if(fl[t]<fl[Yh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},i=JSON.stringify(r);t==="error"||t==="warn"?process.stderr.write(i+`
23
- `):process.stdout.write(i+`
24
- `);try{(0,Mn.appendFileSync)(Jh,i+`
25
- `)}catch{}}function ml(t={}){function e(n,r,i){typeof r=="string"?hl(n,t,r):hl(n,{...t,...r},i)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>ml({...t,...n})}}var B=ml({module:"daemon"});var Dn=require("fs"),Al=require("path");var yl=require("os"),X=require("path"),$t=(0,X.join)((0,yl.homedir)(),".vibelet"),_l=(0,X.join)($t,"logs"),Sl=(0,X.join)($t,"data"),Kh=(0,X.join)($t,"runtime"),ey=(0,X.join)(Kh,"current"),vl=(0,X.join)($t,"identity.json"),wl=(0,X.join)($t,"pairings.json"),Bn=(0,X.join)(Sl,"sessions.json"),ct=(0,X.join)(Sl,"audit.jsonl"),bl=(0,X.join)(_l,"daemon.stdout.log"),Il=(0,X.join)(_l,"daemon.stderr.log");var j=require("fs");function Xh(t,e,n,r){let i=Math.max(0,e-n),s=Math.floor(e*.75);return Math.max(0,Math.min(t,i,r??s))}function Vt(t,e){if(!(0,j.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,j.statSync)(t).size,i=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+i<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let s=Xh(r,e.maxBytes,i,e.retainBytes),o=(0,j.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(s>0){let l=Buffer.alloc(s);(0,j.readSync)(o,l,0,s,r-s);let c=0;if(r>s){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,j.ftruncateSync)(o,0),a.length>0&&(0,j.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,j.closeSync)(o)}}function xl(t){let e=[Vt(t.auditPath,{maxBytes:t.auditMaxBytes}),Vt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Vt(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var El=!1,Zh=new Set(["ts","event","source","appEvent","level"]);function Qh(t={}){let e={};for(let[n,r]of Object.entries(t))Zh.has(n)||(e[n]=r);return e}function ep(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Qh(n)}}function tp(){El||((0,Dn.mkdirSync)((0,Al.dirname)(ct),{recursive:!0}),El=!0)}var pi=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},i){this.write(ep(e,n,r,i))}write(e){tp();try{let n=JSON.stringify(e)+`
26
- `;Vt(ct,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,Dn.appendFileSync)(ct,n)}catch{}}},v=new pi;var Ee=require("fs"),Cl=require("os"),Yt=require("path"),Tl=require("crypto"),gi="claude-hook:",Jt="x-vibelet-claude-hook-secret",Kt={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function np(t,e){return`#!/usr/bin/env node
18
+ `,typeof n=="function"&&n(null,a),a}});var Ya=m(Va=>{var wh="\x1B[47m",bh="\x1B[40m",rs="\x1B[37m",ss="\x1B[30m",Fe="\x1B[0m",Ih=wh+ss,xh=bh+rs,Eh=function(t,e,n){return{"00":Fe+" "+t,"01":Fe+e+"\u2584"+t,"02":Fe+n+"\u2584"+t,10:Fe+e+"\u2580"+t,11:" ",12:"\u2584",20:Fe+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},za=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},$a=function(t,e,n,r){return za(t,e,n,r)+za(t,e,n,r+1)};Va.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?xh:Ih,c=Eh(o,i?ss:rs,i?rs:ss),u=Fe+`
19
+ `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[$a(s,r,h,f)];d+=c[$a(s,r,r,f)]+u}return d+=Fe,typeof n=="function"&&n(null,d),d}});var Ka=m(Ja=>{var Ah=Ga(),Ch=Ya();Ja.render=function(t,e,n){return e&&e.small?Ch.render(t,e,n):Ah.render(t,e,n)}});var os=m(Za=>{var Th=Ut();function Xa(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function is(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function kh(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?is("M",l+n,.5+c+n):is("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=is("h",o),o=0)):s++}return r}Za.render=function(e,n,r){let s=Th.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+Xa(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Xa(s.color.dark,"stroke")+' d="'+kh(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
+ `;return typeof r=="function"&&r(null,f),f}});var Qa=m(Pn=>{var Rh=os();Pn.render=Rh.render;Pn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?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">'+Pn.render(n,r);i.writeFile(e,a,s)}});var el=m(Ln=>{var as=Ut();function Ph(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function Lh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ln.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=Lh()),s=as.getOptions(s);let o=as.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return as.qrToImageData(l.data,e,s),Ph(a,i,o),a.putImageData(l,0,0),i};Ln.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Ln.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var nl=m(qt=>{var Nh=wr(),ls=Ur(),tl=el(),Oh=os();function cs(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Nh())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=ls.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=ls.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}qt.create=ls.create;qt.toCanvas=cs.bind(null,tl.render);qt.toDataURL=cs.bind(null,tl.renderToDataURL);qt.toString=cs.bind(null,function(t,e,n){return Oh.render(t,n)})});var ol=m(Ie=>{var rl=wr(),us=Ur(),Mh=qa(),sl=Wa(),Bh=Ka(),il=Qa();function Wt(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(rl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Dh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Nn(t){switch(t){case"svg":return il;case"txt":case"utf8":return sl;case"png":case"image/png":default:return Mh}}function Hh(t){switch(t){case"svg":return il;case"terminal":return Bh;case"utf8":default:return sl}}function jt(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=us.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=us.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Ie.create=us.create;Ie.toCanvas=nl().toCanvas;Ie.toString=function(e,n,r){let s=Wt(e,n,r),i=s.opts?s.opts.type:void 0,o=Hh(i);return jt(o.render,e,s)};Ie.toDataURL=function(e,n,r){let s=Wt(e,n,r),i=Nn(s.opts.type);return jt(i.renderToDataURL,e,s)};Ie.toBuffer=function(e,n,r){let s=Wt(e,n,r),i=Nn(s.opts.type);return jt(i.renderToBuffer,e,s)};Ie.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!rl())throw new Error("Too few arguments provided");let i=Wt(n,r,s),o=i.opts.type||Dh(e),l=Nn(o).renderToFile.bind(null,e);return jt(l,n,i)};Ie.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Wt(n,r,e.emit.bind(e,"error")),o=Nn("png").renderToFileStream.bind(null,e);jt(o,n,s)}});var ll=m((Qm,al)=>{al.exports=ol()});var qc=require("http");var Sd=ze(ji(),1),vd=ze(cr(),1),wd=ze(fr(),1),bd=ze(_n(),1),vr=ze(Zi(),1);var We=require("fs/promises"),Xn=require("path"),Wc=require("os"),jc=ze(ll(),1);var lt=require("child_process"),ul=require("fs"),q=require("path"),zt=require("os"),Fh=["fnm_multishells"],Uh=6e4;function xe(t){return Fh.some(e=>t.includes(e))}function fs(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var at=null;function dl(){if(at&&!xe(at.PATH??""))return at;for(let t of fs())try{let e=(0,lt.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
21
+ `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return xe(n.PATH??"")?at=null:at=n,n}catch{}return at={},{}}function qh(t=dl()){let e=(0,zt.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,q.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",s=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,q.join)(e,".npm-global","bin"),(0,q.join)(e,".local","bin"),(0,q.join)(e,".claude","bin"),n],i=r.split(q.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(q.delimiter)}function ds(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function On(){let t=dl(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=qh(t),e.HOME||(e.HOME=(0,zt.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Gt(t,e=3e3){try{return(0,lt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:On()}).trim()||null}catch{return null}}function Wh(t){for(let e of fs())try{let n=(0,lt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function jh(){let t=(0,zt.homedir)();return[(0,q.join)(t,".local","bin","claude"),(0,q.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,q.join)(t,".npm-global","bin","claude")]}function Gh(){for(let t of jh())if(Gt(t))return t;try{let t=(0,lt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:On()}).trim();if(t&&!t.includes("cmux")&&Gt(t))return t}catch{}}function zh(){let t=(0,zt.homedir)(),e=[process.env.PNPM_HOME,(0,q.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,q.join)(t,".npm-global","bin","codex"),(0,q.join)(t,".local","bin","codex"),...e.map(n=>(0,q.join)(n,"codex"))]}function $h(){let t;for(let n of zh())if(Gt(n)){if(!xe(n))return n;t=n}try{let n=(0,lt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:On()}).trim();if(n&&Gt(n)){if(!xe(n))return n;t=t??n}}catch{}let e=Wh("codex");if(e&&Gt(e)){if(!xe(e))return e;t=t??e}return t}function fl(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();return(!n||i-r>Uh||!(0,ul.existsSync)(n)||xe(n))&&(n=t()??e,r=i,process.stdout.write(JSON.stringify({level:"info",ts:new Date().toISOString(),module:"config",msg:"binary resolved",name:e,path:n,transient:xe(n)})+`
22
+ `)),n}}var Vh=fl(Gh,"claude"),Yh=fl($h,"codex");function Jh(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var cl=Jh();function Kh(t,e){return{command:fs()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:cl.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:cl["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Number(process.env.VIBE_IDLE_TIMEOUT_MS)||1800*1e3,auditMaxBytes:ds("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:ds("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:ds("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return Vh()},get codexPath(){return Yh()},isTransientPath:xe,execViaLoginShell:Kh,buildSanitizedEnv:On};var Hs=require("crypto"),bc=require("fs/promises");var Nl=require("child_process"),Ol=require("fs");var Mn=require("fs"),gl=require("os"),hs=require("path"),hl={debug:10,info:20,warn:30,error:40},Xh=process.env.VIBE_LOG_LEVEL||"info";var ml=(0,hs.join)((0,gl.homedir)(),".vibe-remote"),Zh=(0,hs.join)(ml,"daemon.log");try{(0,Mn.mkdirSync)(ml,{recursive:!0})}catch{}function pl(t,e,n){if(hl[t]<hl[Xh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);t==="error"||t==="warn"?process.stderr.write(s+`
23
+ `):process.stdout.write(s+`
24
+ `);try{(0,Mn.appendFileSync)(Zh,s+`
25
+ `)}catch{}}function yl(t={}){function e(n,r,s){typeof r=="string"?pl(n,t,r):pl(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>yl({...t,...n})}}var B=yl({module:"daemon"});var Dn=require("fs"),Cl=require("path");var _l=require("os"),X=require("path"),$t=(0,X.join)((0,_l.homedir)(),".vibelet"),Sl=(0,X.join)($t,"logs"),vl=(0,X.join)($t,"data"),Qh=(0,X.join)($t,"runtime"),ny=(0,X.join)(Qh,"current"),wl=(0,X.join)($t,"identity.json"),bl=(0,X.join)($t,"pairings.json"),Bn=(0,X.join)(vl,"sessions.json"),ct=(0,X.join)(vl,"audit.jsonl"),Il=(0,X.join)(Sl,"daemon.stdout.log"),xl=(0,X.join)(Sl,"daemon.stderr.log");var j=require("fs");function ep(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function Vt(t,e){if(!(0,j.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,j.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=ep(r,e.maxBytes,s,e.retainBytes),o=(0,j.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,j.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,j.ftruncateSync)(o,0),a.length>0&&(0,j.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,j.closeSync)(o)}}function El(t){let e=[Vt(t.auditPath,{maxBytes:t.auditMaxBytes}),Vt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Vt(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var Al=!1,tp=new Set(["ts","event","source","appEvent","level"]);function np(t={}){let e={};for(let[n,r]of Object.entries(t))tp.has(n)||(e[n]=r);return e}function rp(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...np(n)}}function sp(){Al||((0,Dn.mkdirSync)((0,Cl.dirname)(ct),{recursive:!0}),Al=!0)}var ps=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(rp(e,n,r,s))}write(e){sp();try{let n=JSON.stringify(e)+`
26
+ `;Vt(ct,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,Dn.appendFileSync)(ct,n)}catch{}}},v=new ps;var Ee=require("fs"),Tl=require("os"),Yt=require("path"),kl=require("crypto"),gs="claude-hook:",Jt="x-vibelet-claude-hook-secret",Kt={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function ip(t,e){return`#!/usr/bin/env node
27
27
  const http = require('http');
28
28
  const chunks = [];
29
29
  process.stdin.on('data', (chunk) => chunks.push(chunk));
@@ -44,7 +44,7 @@ process.stdin.on('end', () => {
44
44
  req.end(body);
45
45
  });
46
46
  process.stdin.resume();
47
- `}function rp(t,e){return`#!/usr/bin/env node
47
+ `}function op(t,e){return`#!/usr/bin/env node
48
48
  const http = require('http');
49
49
  const fallback = ${JSON.stringify(JSON.stringify(Kt))};
50
50
  const chunks = [];
@@ -80,26 +80,26 @@ process.stdin.on('end', () => {
80
80
  req.end(body);
81
81
  });
82
82
  process.stdin.resume();
83
- `}function kl(t,e){let n=(0,Yt.join)((0,Cl.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Tl.randomUUID)()}`);(0,Ee.mkdirSync)(n,{recursive:!0});let r=(0,Yt.join)(n,"settings.json"),i=(0,Yt.join)(n,"session_hook_forwarder.cjs"),s=(0,Yt.join)(n,"permission_hook_forwarder.cjs");return(0,Ee.writeFileSync)(i,np(t,e),"utf8"),(0,Ee.writeFileSync)(s,rp(t,e),"utf8"),(0,Ee.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:i,permissionScriptPath:s}}function Hn(t){if(t)try{(0,Ee.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Z=B.child({module:"claude"}),Ol="claude-permission-denial:",ip=/\u001B\[[0-?]*[ -/]*[@-~]/g;function mi(t){process.stderr.write(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
84
- `)}function sp(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
85
- `):""}function op(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function ap(t){if(typeof t=="string")return t;let e=sp(t);return e||(op(t)?"":JSON.stringify(t))}function lp(t){return/requested permissions|haven't granted/i.test(t)}function Rl(t){return t.replace(ip,"").replace(/\s+/g," ").trim()}function cp(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function up(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function dp(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Pl(t){let e=Rl(t.resultText??""),n=(t.stderrLines??[]).map(Rl).filter(Boolean).slice(-3),r=[e,...n].find(s=>!!s&&up(s));if(r)return dp(r);let i=[e,...n].find(s=>!!s&&!cp(s));return i?t.exitCode!=null&&i!==e?`Claude exited with code ${t.exitCode}: ${i}`:i:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Fn(t){return t.startsWith(Ol)}var Xt=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),Z.info({sessionId:this.sessionId,cwd:e},"session initialized"),v.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),Hn(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=kl(this.hookPort,this.hookSecret),n.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;Z.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),mi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.proc=(0,Ll.spawn)(S.claudePath,n,{cwd:this.cwd||void 0,stdio:["pipe","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",i=>{let s=i.message;i.code==="ENOENT"&&this.cwd&&!(0,Nl.existsSync)(this.cwd)&&(s=`Working directory does not exist: ${this.cwd}`),Z.error({sessionId:this.sessionId,error:s,cwd:this.cwd},"spawn error"),v.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:s}),this.handler?.({type:"error",sessionId:this.sessionId,message:s})}),this.buffer="",this.proc.stdout.on("data",i=>{this.buffer+=i.toString();let s=this.buffer.split(`
86
- `);this.buffer=s.pop();for(let o of s)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{Z.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",i=>{let s=i.toString().trim();s&&(Z.debug({sessionId:this.sessionId,stderr:s},"stderr"),this.lastStderr.push(s),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(i,s)=>{Z.info({sessionId:this.sessionId,exitCode:i,signal:s},"process exited");let o=this.interrupted;this.proc=null,Hn(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):i&&i!==0&&!this.sawFinalResult&&(Z.error({sessionId:this.sessionId,exitCode:i,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Pl({stderrLines:this.lastStderr,exitCode:i})})),this.exitHandler?.(i)})}respondApproval(e,n){if(Z.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return Z.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
87
- `),!0}setApprovalMode(e){this.approvalMode=e,Z.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),Z.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Hn(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(Z.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),v.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{let r=e.message?.content;if(!Array.isArray(r))break;for(let i of r)i.type==="tool_use"&&this.handler({type:"tool.call",sessionId:this.sessionId,toolName:i.name,input:i.input??{},toolCallId:i.id});break}case"user":{let r=e.message?.content;if(!Array.isArray(r))break;for(let i of r)if(i.type==="tool_result"){let s=ap(i.content);if(!s)continue;if(i.is_error===!0&&typeof i.tool_use_id=="string"&&lp(s)){this.pendingPermissionDescriptions.set(i.tool_use_id,s);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i.tool_use_id,output:s})}break}case"control_request":{let r=e.request;r?.subtype==="can_use_tool"&&(v.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){mi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Pl({resultText:r,stderrLines:this.lastStderr})});break}let i=Array.isArray(e.permission_denials)?e.permission_denials:[];if(i.length>0){let a=i[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;v.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Ol}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let s=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;mi("Claude finished. Run `claude --continue` to continue on desktop."),v.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:s,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:s,usage:o});break}}}};var Ul=require("child_process"),ql=require("fs");var yi=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),i=JSON.stringify(n),s=r.find(o=>JSON.stringify(o.labels)===i);s?s.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),i=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return i.count++,i.totalMs+=r,i.minMs=Math.min(i.minMs,r),i.maxMs=Math.max(i.maxMs,r),i.lastMs=r,this.timers.set(e,i),r}}snapshot(){let e={};for(let[i,s]of this.counters)e[i]=s.map(o=>({...o}));let n={};for(let[i,s]of this.timers)n[i]={...s,minMs:s.minMs===1/0?0:s.minMs};let r={};for(let[i,s]of this.gauges)r[i]=s;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();B.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},I=new yi;var Bl=require("node:fs"),_i=require("node:path"),fp="@vibelet/cli";function Ml(t){try{let e=JSON.parse((0,Bl.readFileSync)(t,"utf8"));if(e.name===fp&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function hp(){return"0.0.5"}var ut=hp();var A=B.child({module:"codex"});function Q(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function k(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function pp(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Si(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function vi(t,e){let n={};for(let[r,i]of Object.entries(t))e.includes(r)||(n[r]=i);return n}function Wl(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function jl(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Dl(t,e){if(!Array.isArray(t))return null;for(let n of t){let r=Q(n);if(!r)continue;let i=k(r.id),s=Array.isArray(r.options)?r.options.map(c=>Q(c)).filter(c=>!!c):[];if(!i||s.length===0)continue;let o=s.map(c=>k(c.label)).filter(c=>!!c);if(o.length===0)continue;let a=e?o.find(c=>Wl(c)):o.find(c=>jl(c)),l=e?o[0]:o[o.length-1];return{questionId:i,label:a??l}}return null}function gp(t){let e=Dl(t,!0),n=Dl(t,!1);return!e||!n?null:e.questionId!==n.questionId?{questionId:e.questionId,approveLabel:e.label,denyLabel:n.label}:{questionId:e.questionId,approveLabel:e.label,denyLabel:n.label}}function mp(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(i=>Q(i)).filter(i=>!!i).flatMap(i=>(Array.isArray(i.options)?i.options:[]).map(o=>Q(o)).filter(o=>!!o).map(o=>k(o.label)).filter(o=>!!o)),n=e.some(i=>Wl(i)),r=e.some(i=>jl(i));return n&&r}function Hl(t){let e=pp(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:vi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:vi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=k(t.server),r=k(t.tool)??k(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:Q(t.arguments)??Q(t.input)??{}}:null}return null}function yp(t){if(!Array.isArray(t))return"";for(let e of t){let n=Q(e);if(!n)continue;let r=k(n.question)??k(n.header);if(r)return r}return""}function Fl(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var Un=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear();let i=S.codexPath,s,o=this.buildSpawnArgs();if(S.isTransientPath(i)){let c=S.execViaLoginShell("codex",o);s=c.command,o=c.args,A.info({spawnCmd:s,argsPreview:o.slice(0,2)},"spawning via login shell")}else s=i,A.info({spawnCmd:s,args:o},"spawning");v.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Ul.spawn)(s,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,ql.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),A.error({error:u,cwd:e},"spawn error"),v.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
88
- `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{A.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(A.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{A.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&A.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=I.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ut},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=Fl(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,A.info({threadId:this.threadId},"thread resumed"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",A.info({threadId:this.threadId},"thread created"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let n=Fl(this.approvalMode,this.cwd||process.cwd());A.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:n.approvalPolicy,sandboxPolicy:n.sandboxPolicy}).then(r=>A.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result")).catch(r=>{A.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),i=r?.rpcId??Number(e);if(!Number.isFinite(i))return!1;let s;if(!r)s=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":s={decision:n?"accept":"decline"};break;case"request-user-input-approval":s={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":s={decision:n?"approved":"denied"};break;default:s={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return A.info({threadId:this.threadId,rpcId:i,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:i,result:s})+`
89
- `),!0}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,A.info({approvalMode:e},"approval mode updated (takes effect on restart)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,i=I.startTimer("rpc.duration");return new Promise((s,o)=>{if(this.pending.set(r,{resolve:a=>{i(),s(a)},reject:a=>{i(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),i(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
90
- `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),A.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),i(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
83
+ `}function Rl(t,e){let n=(0,Yt.join)((0,Tl.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,kl.randomUUID)()}`);(0,Ee.mkdirSync)(n,{recursive:!0});let r=(0,Yt.join)(n,"settings.json"),s=(0,Yt.join)(n,"session_hook_forwarder.cjs"),i=(0,Yt.join)(n,"permission_hook_forwarder.cjs");return(0,Ee.writeFileSync)(s,ip(t,e),"utf8"),(0,Ee.writeFileSync)(i,op(t,e),"utf8"),(0,Ee.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function Hn(t){if(t)try{(0,Ee.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Z=B.child({module:"claude"}),Ml="claude-permission-denial:",ap=/\u001B\[[0-?]*[ -/]*[@-~]/g;function ms(t){process.stderr.write(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
84
+ `)}function lp(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
85
+ `):""}function cp(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function up(t){if(typeof t=="string")return t;let e=lp(t);return e||(cp(t)?"":JSON.stringify(t))}function dp(t){return/requested permissions|haven't granted/i.test(t)}function Pl(t){return t.replace(ap,"").replace(/\s+/g," ").trim()}function fp(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function hp(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function pp(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Ll(t){let e=Pl(t.resultText??""),n=(t.stderrLines??[]).map(Pl).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&hp(i));if(r)return pp(r);let s=[e,...n].find(i=>!!i&&!fp(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Fn(t){return t.startsWith(Ml)}var Xt=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),Z.info({sessionId:this.sessionId,cwd:e},"session initialized"),v.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),Hn(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Rl(this.hookPort,this.hookSecret),n.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;Z.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),ms(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.proc=(0,Nl.spawn)(S.claudePath,n,{cwd:this.cwd||void 0,stdio:["pipe","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",s=>{let i=s.message;s.code==="ENOENT"&&this.cwd&&!(0,Ol.existsSync)(this.cwd)&&(i=`Working directory does not exist: ${this.cwd}`),Z.error({sessionId:this.sessionId,error:i,cwd:this.cwd},"spawn error"),v.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:i}),this.handler?.({type:"error",sessionId:this.sessionId,message:i})}),this.buffer="",this.proc.stdout.on("data",s=>{this.buffer+=s.toString();let i=this.buffer.split(`
86
+ `);this.buffer=i.pop();for(let o of i)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{Z.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",s=>{let i=s.toString().trim();i&&(Z.debug({sessionId:this.sessionId,stderr:i},"stderr"),this.lastStderr.push(i),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(s,i)=>{Z.info({sessionId:this.sessionId,exitCode:s,signal:i},"process exited");let o=this.interrupted;this.proc=null,Hn(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):s&&s!==0&&!this.sawFinalResult&&(Z.error({sessionId:this.sessionId,exitCode:s,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Ll({stderrLines:this.lastStderr,exitCode:s})})),this.exitHandler?.(s)})}respondApproval(e,n){if(Z.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return Z.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
87
+ `),!0}setApprovalMode(e){this.approvalMode=e,Z.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),Z.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Hn(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(Z.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),v.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id});break}case"user":{let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=up(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&dp(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{let r=e.request;r?.subtype==="can_use_tool"&&(v.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){ms("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Ll({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;v.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Ml}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;ms("Claude finished. Run `claude --continue` to continue on desktop."),v.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var ql=require("child_process"),Wl=require("fs");var ys=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();B.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},I=new ys;var Dl=require("node:fs"),_s=require("node:path"),gp="@vibelet/cli";function Bl(t){try{let e=JSON.parse((0,Dl.readFileSync)(t,"utf8"));if(e.name===gp&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function mp(){return"0.0.6"}var ut=mp();var A=B.child({module:"codex"});function Q(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function k(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function yp(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Ss(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function vs(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function jl(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Gl(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Hl(t,e){if(!Array.isArray(t))return null;for(let n of t){let r=Q(n);if(!r)continue;let s=k(r.id),i=Array.isArray(r.options)?r.options.map(c=>Q(c)).filter(c=>!!c):[];if(!s||i.length===0)continue;let o=i.map(c=>k(c.label)).filter(c=>!!c);if(o.length===0)continue;let a=e?o.find(c=>jl(c)):o.find(c=>Gl(c)),l=e?o[0]:o[o.length-1];return{questionId:s,label:a??l}}return null}function _p(t){let e=Hl(t,!0),n=Hl(t,!1);return!e||!n?null:e.questionId!==n.questionId?{questionId:e.questionId,approveLabel:e.label,denyLabel:n.label}:{questionId:e.questionId,approveLabel:e.label,denyLabel:n.label}}function Sp(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>Q(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>Q(o)).filter(o=>!!o).map(o=>k(o.label)).filter(o=>!!o)),n=e.some(s=>jl(s)),r=e.some(s=>Gl(s));return n&&r}function Fl(t){let e=yp(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:vs(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:vs(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=k(t.server),r=k(t.tool)??k(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:Q(t.arguments)??Q(t.input)??{}}:null}return null}function vp(t){if(!Array.isArray(t))return"";for(let e of t){let n=Q(e);if(!n)continue;let r=k(n.question)??k(n.header);if(r)return r}return""}function Ul(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var Un=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear();let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,A.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,A.info({spawnCmd:i,args:o},"spawning");v.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,ql.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,Wl.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),A.error({error:u,cwd:e},"spawn error"),v.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
88
+ `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{A.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(A.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{A.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&A.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=I.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ut},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=Ul(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,A.info({threadId:this.threadId},"thread resumed"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",A.info({threadId:this.threadId},"thread created"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let n=Ul(this.approvalMode,this.cwd||process.cwd());A.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:n.approvalPolicy,sandboxPolicy:n.sandboxPolicy}).then(r=>A.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result")).catch(r=>{A.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return A.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
89
+ `),!0}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,A.info({approvalMode:e},"approval mode updated (takes effect on restart)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=I.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
90
+ `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),A.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
91
91
  `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
92
- `)}resolveToolContext(e){let n=Q(e?.item)??e??null,r=Si(n);if(!r)return null;let i=n?Hl(n):null;if(i)return this.toolContextByCallId.set(r,i),{callId:r,toolContext:i};let s=this.toolContextByCallId.get(r);return s?{callId:r,toolContext:s}:null}createFallbackInput(e,n){return e?vi(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),v.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){A.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r})}handleServerRequest(e,n,r){let i=String(n),s=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(i,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:s?.toolContext.toolName??"Bash",input:s?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(i,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:s?.toolContext.toolName??"Patch",input:s?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!mp(o)){A.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=gp(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(i,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:s?.toolContext.toolName??"Bash",input:s?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},yp(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(i,{kind:"exec-command-legacy",rpcId:n,toolName:s?.toolContext.toolName??"Bash",input:s?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(i,{kind:"apply-patch-legacy",rpcId:n,toolName:s?.toolContext.toolName??"Patch",input:s?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/permissions/requestApproval"){A.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}A.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(A.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let i=this.pending.get(e.id);this.pending.delete(e.id),e.error?i.reject(new Error(e.error.message??"RPC error")):i.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=Q(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&A.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let i=r?.text??r?.delta??r?.content??"";i&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:i}):i||A.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let i=Q(r?.item),s=Si(i),o=i?Hl(i):null;s&&o&&(this.toolContextByCallId.set(s,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:s}));break}case"item/completed":{let i=Q(r?.item)??r,s=Si(i);s&&this.toolContextByCallId.delete(s);break}case"turn/completed":{let i=Q(r?.usage),s=i?{inputTokens:Number(i.input_tokens??i.inputTokens??0),outputTokens:Number(i.output_tokens??i.outputTokens??0)}:void 0;A.info({threadId:this.threadId},"turn completed"),v.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:s}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:s});break}default:n&&A.debug({method:n},"unhandled notification");break}}};var P=require("fs/promises"),nc=require("fs"),rc=require("readline"),T=require("path"),pe=require("os");var _p=new Set(["New session","Resumed session","Untitled session"]),Sp=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function vp(t){return t.replace(/\s+/g," ").trim()}function qn(t){return typeof t!="string"?void 0:vp(t)||void 0}function Gl(t){let e=qn(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function dt(t){let e=qn(t);return!e||_p.has(e)||Gl(e)}function wp(t){for(let e of t.replace(/\r/g,"").split(`
93
- `)){let n=qn(e);if(n&&!bp(n)&&!Ip(n))return n}}function bp(t){return Sp.some(e=>t.startsWith(e))}function Ip(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function xp(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function wi(t,e=80){if(typeof t!="string")return;let n=wp(t);if(!n)return;let r=xp(n),s=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!s||Gl(s)))return s.length<=e?s:`${s.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Ue(t,e){for(let n of t){let r=qn(n);if(!(!r||dt(r)))return r}return wi(e)}var $l=require("child_process"),ft=require("fs/promises"),Ae=require("path"),bi=require("os"),Vl=require("util");var Ep=(0,Vl.promisify)($l.execFile),Ap=3e3,Zt=null;function Ii(){Zt=null}function Cp(t){return t.replace(/^['"]|['"]$/g,"")}function Tp(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Cp)}function xi(t){let e=Tp(t);for(let n=0;n<e.length;n+=1){let r=e[n],i=(0,Ae.basename)(r);if(i==="claude"||i==="codex")return{agent:i,args:e.slice(n+1)}}return null}function kp(t,e){let n=xi(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let i=0;i<r.length;i+=1){let s=r[i];if((s==="--resume"||s==="--session-id")&&r[i+1]&&!r[i+1].startsWith("-"))return r[i+1];if(s.startsWith("--resume="))return s.slice(9);if(s.startsWith("--session-id="))return s.slice(13)}return null}if(r[0]!=="resume")return null;for(let i=1;i<r.length;i+=1){let s=r[i];if(!s.startsWith("-"))return s}return null}function Wn(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Rp(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Pp(t,e){let n=xi(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function Lp(t){let e=kp(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(i=>Rp(t.agent,i));if(n.length!==1)return null;let r=ht(t.agent,n[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",sessionFilePath:n[0]}:null}function Np(t,e){let n=t,r=e;return(Wn(e.confidence)>Wn(t.confidence)||Wn(e.confidence)===Wn(t.confidence)&&e.pid<t.pid)&&(n=e,r=t),{...n,cwd:n.cwd||r.cwd,title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath}}function Op(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,i=e.get(r);e.set(r,i?Np(i,n):n)}return[...e.values()]}async function Ei(t,e){try{let{stdout:n}=await Ep(t,e,{maxBuffer:8388608});return n}catch{return""}}async function zl(t){if(!t.sessionFilePath)return t;let e=await Qt(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function Mp(t){return(await Ei("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
94
- `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Bp(t){let n=(await Ei("lsof",["-p",String(t),"-Fn"])).split(`
95
- `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function Dp(){return(await Ei("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
96
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),i=n[2],s=xi(i);return!Number.isFinite(r)||!s?null:{pid:r,command:i,agent:s.agent}}).filter(e=>!!e)}async function Hp(){let t=await Dp();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await Mp(e.pid),sessionFiles:await Bp(e.pid)})))}function Fp(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Up(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ae.join)((0,bi.homedir)(),".claude","projects",Fp(e)),l=(await(0,ft.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let h=await(0,ft.stat)((0,Ae.join)(o,f)).catch(()=>null);h&&(!c||h.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:h.mtimeMs})})),!c)return null;let u=(0,Ae.join)(o,c.name),d=ht(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ae.join)((0,bi.homedir)(),".codex","sessions"),r=null;async function i(o){let a=await(0,ft.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ae.join)(o,l.name);if(l.isDirectory())await i(c);else if(l.name.endsWith(".jsonl")){let u=await(0,ft.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await Qt(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await i(n);let s=r;return s?{sessionId:s.sessionId,filePath:s.path}:null}catch{return null}}async function Yl(){if(Zt&&Date.now()<Zt.expiresAt)return Zt.value;let t=await Hp(),e=await Promise.all(t.map(async r=>{let i=Lp(r);if(i)return zl(i);if(Pp(r.agent,r.command))return null;let s=await Up(r.agent,r.cwd);return s?zl({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:s.sessionId,confidence:"low",sessionFilePath:s.filePath}):null})),n=Op(e.filter(r=>r!==null));return Zt={value:n,expiresAt:Date.now()+Ap},n}var Kl=B.child({module:"inventory"}),pt={daemonActive:3,externalRunning:2,idle:1},Jl={high:3,medium:2,low:1};function Xl(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function qp(t,e){let n=t.runtime.needsAttention?1:0;return(e.runtime.needsAttention?1:0)-n||pt[e.runtime.state]-pt[t.runtime.state]||Xl(t,e)}function Wp(t,e){return pt[e.state]>pt[t.state]?e:pt[e.state]<pt[t.state]?t:Jl[e.confidence]>Jl[t.confidence]?e:t}function jp(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Gp(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function zp(t,e){return e?t?!(dt(e)&&!dt(t)):!0:!1}function Ai(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function $p(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:Ai(),managed:t.managed}}function Vp(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",pid:t.pid,command:t.command}}}function Yp(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed}}function Jp(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,i=t.get(r);if(!i){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let s=zp(i.title,n.title)?n.title:i.title,o=n.cwd||i.cwd,a=Wp(i.runtime,n.runtime),l=i.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=i.sources.includes("process")&&!i.sources.includes("daemon"),d=c?i.lastActivityAt:u?n.lastActivityAt:Gp(i.lastActivityAt,n.lastActivityAt);t.set(r,{...i,cwd:o,title:s,createdAt:jp(i.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:i.managed||n.managed})}}function Kp(...t){let e=new Map;for(let n of t)Jp(e,n);return[...e.values()]}function Xp(t,e,n,r,i){let s=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(s){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(s)||c.includes(s),d=i?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&Kl.info({total:t.length,filtered:o.length,search:r,contentMatchIds:i?.size??0},"filter applied"),o}function Zp(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let i=n+r>>1,s=t[i];(e.lastActivityAt.localeCompare(s.lastActivityAt)||s.sessionId.localeCompare(e.sessionId))>0?r=i:n=i+1}if(n>0){let i=t[n-1];if(i.lastActivityAt===e.lastActivityAt&&i.sessionId===e.sessionId)return n}return 0}function Qp(t,e,n,r,i,s,o){let a=s?1/0:Math.max(1,e||50),l=Kp(t.sessionRecords.map($p),t.scannedSessions,t.runningSessions.map(_=>Vp(_,t.scannedAt)),t.activeSessions.map(Yp)),c=t.deletedSessionIds?.size?l.filter(_=>!t.deletedSessionIds?.has(_.sessionId)):l,u=Xp(c,r,i,s,o),d=u.filter(_=>_.runtime.state!=="idle"||_.managed).sort(qp),f=u.filter(_=>_.runtime.state==="idle"&&!_.managed).sort(Xl),h=Zp(f,n),g=f.slice(h,h+a),y=h+g.length<f.length&&g.length>0?{lastActivityAt:g[g.length-1].lastActivityAt,sessionId:g[g.length-1].sessionId}:void 0;return{sessions:n?g:[...d,...g],nextCursor:y}}async function Ci(t){let e=new Date().toISOString(),[n,r,i]=await Promise.all([en(t.agent,t.cwd),Yl(),t.search?Zl(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&Kl.info({search:t.search,contentMatches:i?.size??0,scanned:n.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Qp({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:n,runningSessions:r,scannedAt:e,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,t.search,i)}var le=B.child({module:"scanner"});function ic(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var sc=5e3,ki=ic(sc),Ri=ic(sc);function Li(){ki.clear(),Ri.clear()}function Pi(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}function*oc(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let i=t.indexOf(`
97
- `,n);i===-1&&(i=t.length);let s=t.substring(n,i);n=i+1,!(s.length===0||s.trim().length===0)&&(yield s,r+=1)}}var Ti=512*1024;async function ac(t,e){if(e<=Ti)return(0,P.readFile)(t,"utf-8");let n=await(0,P.open)(t,"r");try{let r=Buffer.alloc(Ti),{bytesRead:i}=await n.read(r,0,Ti,0);return r.toString("utf-8",0,i)}finally{await n.close()}}function Ni(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function lc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Ni(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Oi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}var eg=["<task-notification>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","<system-reminder>","<environment_context>","# AGENTS.md instructions for "];function tg(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?eg.some(r=>n.startsWith(r)):!1}function Mi(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Oi(t.message.content);return tg(t,e)?"":e}function cc(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function uc(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:Ai()}}function ht(t,e){let n=(0,T.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function ng(t,e){let n=await ac(t,e),r=oc(n,64),i="",s="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!i&&typeof u.cwd=="string"&&(i=u.cwd),!s&&typeof u.sessionId=="string"&&(s=u.sessionId),o||(o=Ue([u.customTitle,u.summary])),!l){let d=Mi(u),f=Ue([],d);f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||ht("claude",t)||(0,T.basename)(t,".jsonl"),cwd:i,title:o??l??Ue([],a)}:null}async function rg(t,e){let n=await ac(t,e),r=oc(n,96),i="",s="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(i||(i=u.payload?.cwd??u.cwd??""),s||(s=u.payload?.id??u.id??""),o||(o=Ue([u.payload?.title,u.title])),!l){let d=lc(u),f=d&&!cc(d)?Ue([],d):void 0;f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||ht("codex",t)||(0,T.basename)(t,".jsonl"),cwd:i,title:o??l??Ue([],a)}:null}async function Qt(t,e){let n=await(0,P.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let s=await ng(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let i=await rg(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Ql(t){let e=(0,T.join)((0,pe.homedir)(),".claude","projects");try{let n;t?n=[Pi(t)]:n=(await(0,P.readdir)(e,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name);let r=[];for(let o of n){let a=(0,T.join)(e,o),l=await(0,P.readdir)(a).catch(()=>[]);for(let c of l)c.endsWith(".jsonl")&&r.push((0,T.join)(a,c))}return(await Promise.all(r.map(o=>Qt(o,"claude")))).filter(o=>o!==null).map(o=>uc(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return le.warn({error:String(n)},"failed to list claude sessions"),[]}}async function ec(t){let e=(0,T.join)((0,pe.homedir)(),".codex","sessions");try{let n=await(0,P.readdir)(e).catch(()=>[]),r=[];for(let o of n){let a=(0,T.join)(e,o),l=await(0,P.readdir)(a).catch(()=>[]);for(let c of l){let u=(0,T.join)(a,c),d=await(0,P.readdir)(u).catch(()=>[]);for(let f of d){let h=(0,T.join)(u,f),g=await(0,P.readdir)(h).catch(()=>[]);for(let p of g)p.endsWith(".jsonl")&&r.push((0,T.join)(h,p))}}}return(await Promise.all(r.map(o=>Qt(o,"codex")))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>uc(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return le.warn({error:String(n)},"failed to list codex sessions"),[]}}async function en(t,e){let r=`list:${(0,pe.homedir)()}:${t??"all"}:${e??""}`,i=ki.get(r);if(i)return i;let s;if(t==="claude")s=await Ql(e);else if(t==="codex")s=await ec(e);else{let[o,a]=await Promise.all([Ql(e),ec(e)]);s=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return ki.set(r,s),s}async function Zl(t,e){let r=`search:${(0,pe.homedir)()}:${t}:${e??"all"}`,i=Ri.get(r);if(i)return i;let s=new Set,o=t.toLowerCase();async function a(){let c=(0,T.join)((0,pe.homedir)(),".claude","projects");try{let u=await(0,P.readdir)(c,{withFileTypes:!0}),d=[];for(let h of u){if(!h.isDirectory())continue;let g=(0,T.join)(c,h.name),p=await(0,P.readdir)(g).catch(()=>[]);for(let y of p)y.endsWith(".jsonl")&&d.push((0,T.join)(g,y))}let f=await Promise.all(d.map(h=>tc(h,o,"claude")));for(let h of f)h&&s.add(h)}catch(u){le.warn({error:String(u)},"failed to search claude files")}}async function l(){let c=(0,T.join)((0,pe.homedir)(),".codex","sessions");try{let u=[];async function d(h){let g=await(0,P.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let p of g){let y=(0,T.join)(h,p.name);p.isDirectory()?await d(y):p.name.endsWith(".jsonl")&&u.push(y)}}await d(c);let f=await Promise.all(u.map(h=>tc(h,o,"codex")));for(let h of f)h&&s.add(h)}catch(u){le.warn({error:String(u)},"failed to search codex files")}}return e==="claude"?await a():e==="codex"?await l():await Promise.all([a(),l()]),Ri.set(r,s),s}async function tc(t,e,n){let r=(0,nc.createReadStream)(t,{encoding:"utf-8"}),i=(0,rc.createInterface)({input:r,crlfDelay:1/0}),s=n==="claude"?ig:sg,o="",a=!1;try{for await(let l of i){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=s(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{i.close(),r.destroy()}return a?o||ht(n,t):null}function ig(t){return t?.type==="user"&&t.message?.role==="user"?Mi(t):t?.type==="assistant"&&t.message?.role==="assistant"?Oi(t.message.content):""}function sg(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Ni(t.payload.content)}let e=lc(t);return e||""}async function tn(t,e,n){let r=[];if(e==="claude"){let i=(0,T.join)((0,pe.homedir)(),".claude","projects");try{let s=n?[Pi(n)]:[],o=await(0,P.readdir)(i).catch(()=>[]),a=n?[...s,...o.filter(l=>l!==Pi(n))]:o;for(let l of a){let c=(0,T.join)(i,l,`${t}.jsonl`);try{let u=await(0,P.readFile)(c,"utf-8");for(let d of u.split(`
98
- `))if(d.trim())try{let f=JSON.parse(d);if(f.type==="user"&&f.message?.role==="user"){let h=Mi(f);h&&r.push({role:"user",content:h})}else if(f.type==="assistant"&&f.message?.role==="assistant"){let h=Oi(f.message.content);h&&r.push({role:"assistant",content:h})}}catch(f){le.warn({error:String(f)},"failed to parse claude history line")}if(r.length>0)break}catch(u){u.code!=="ENOENT"&&le.warn({error:String(u)},"failed to read claude session file")}}}catch(s){le.warn({error:String(s)},"failed to read claude session history")}}else if(e==="codex"){let i=(0,T.join)((0,pe.homedir)(),".codex","sessions");try{let s=await dc(i,t);if(s){let o=await(0,P.readFile)(s,"utf-8");for(let a of o.split(`
99
- `))if(a.trim())try{let l=JSON.parse(a);if(l.type==="response_item"&&l.payload?.type==="message"){let c=l.payload.role;if(c!=="user"&&c!=="assistant")continue;let u=Ni(l.payload.content);if(!u||c==="user"&&cc(u))continue;r.push({role:c,content:u})}}catch(l){le.warn({error:String(l)},"failed to parse codex history line")}}}catch(s){le.warn({error:String(s)},"failed to read codex session history")}}return r}async function dc(t,e){try{let n=await(0,P.readdir)(t,{withFileTypes:!0});for(let r of n){let i=(0,T.join)(t,r.name);if(r.isDirectory()){let s=await dc(i,e);if(s)return s}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return i}}catch(n){le.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var gt=require("fs"),pc=require("path");var og=500,fc=200;function ag(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=fc?e:e.slice(-fc)}function lg(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function hc(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:ag(t.acceptedClientMessageIds)}}function cg(t){if(Array.isArray(t))return{records:t.map(hc),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(hc):[],deletedSessionIds:lg(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var jn=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},og)}loadFromDisk(){try{let e=(0,gt.readFileSync)(Bn,"utf-8");return cg(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,gt.mkdirSync)((0,pc.dirname)(Bn),{recursive:!0}),(0,gt.writeFileSync)(Bn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var gc=require("path"),mc=require("os");function Gn(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,gc.join)((0,mc.homedir)(),t.slice(2)):t}var nn=B.child({module:"push"}),ug="https://exp.host/--/api/v2/push/send",mt=new Set;function Bi(t){mt.add(t),nn.info({token:t,total:mt.size},"push token registered")}function Di(t){mt.delete(t),nn.info({token:t,total:mt.size},"push token unregistered")}async function yc(t,e,n){if(mt.size===0)return;let r=[...mt].map(i=>({to:i,sound:"default",title:t,body:e,data:n}));try{let i=await fetch(ug,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});i.ok?nn.debug({count:r.length},"push sent"):nn.error({status:i.status,statusText:i.statusText},"push send failed")}catch(i){nn.error({error:String(i)},"push send error")}}var w=B.child({module:"manager"}),dg="Done.",_c=180,$n=200;function zn(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>$n&&e.splice(0,e.length-$n));return e}function Ce(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:zn(t.acceptedClientMessageIds),title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed}}function Sc(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Fn(e)}function fg(t){return t.startsWith(gi)}function vc(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var Vn=class{constructor(e=yc){this.pushSender=e;this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new jn;idleSweepInterval=null;startIdleSweep(){S.idleTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=S.idleTimeoutMs;if(n<=0)return;let r=3600*1e3;for(let[i,s]of this.sessions){if(!s.active&&!s.driver){if(s.clients.size===0){let a=e-s.lastActivityTs;a>=r&&(w.info({sessionId:s.sessionId,inactiveMs:a},"removing inactive session from memory"),I.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(s),this.sessions.delete(i))}continue}if(!s.active||!s.driver||s.isResponding)continue;let o=e-s.lastActivityTs;o<n||(w.info({sessionId:s.sessionId,agent:s.agent,idleMs:o,timeoutMs:n},"stopping idle driver"),I.increment("driver.idle_timeout",{agent:s.agent}),v.emit("driver.idle_timeout",{sessionId:s.sessionId,agent:s.agent,idleMs:o}),s.driver.stop(),s.active=!1,s.driver=null,this.updateGauges(),this.touchSession(s.sessionId))}}bindDriverLifecycle(e,n,r,i){e.driver?.onMessage(s=>{if(w.debug({agent:n,context:r,msgType:s.type,sessionId:e.sessionId},"driver message received"),s.type!=="response"&&s.sessionId&&s.sessionId!==e.sessionId&&!this.sessions.has(s.sessionId)){let o=e.sessionId;w.info({oldSessionId:o,newSessionId:s.sessionId},"session ID updated"),this.store.remove(o),this.sessions.delete(o),e.sessionId=s.sessionId,this.sessions.set(s.sessionId,e),this.store.upsert(Ce(e)),i&&this.reply(i,`id_update_${Date.now()}`,!0,{sessionId:s.sessionId,oldSessionId:o})}(s.type==="session.done"||s.type==="session.interrupted")&&(e.isResponding=!1,(s.type==="session.interrupted"||!Sc(e))&&(e.pendingApproval=void 0)),s.type==="approval.request"&&(e.pendingApproval={requestId:s.requestId,toolName:s.toolName,input:s.input,description:s.description}),n==="claude"&&s.type==="approval.request"&&Fn(s.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[s.requestId]={message:e.lastUserMessage,toolName:s.toolName}:w.warn({sessionId:e.sessionId,requestId:s.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,s.type!=="text.delta"),this.broadcast(e.sessionId,s)}),e.driver?.onExit?.(s=>{w.info({agent:n,context:r,exitCode:s,sessionId:e.sessionId},"driver exited"),v.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:s}),I.increment("driver.exit",{agent:n,abnormal:s&&s!==0?"true":"false"});let o=s===0&&Sc(e);this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId)})}configureDriverBeforeStart(e,n,r){if(e!=="claude"||!(n instanceof Xt))return;let i=r??(0,Hi.randomUUID)().replace(/-/g,"");return n.configureHookBridge(S.port,i),i}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=Kt){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&fg(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),Kt;if(r.approvalMode==="autoApprove")return vc(!0);let s=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!s)return Kt;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${gi}${l.trim()||(0,Hi.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${s}.`,f,h=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:h,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:s,input:a,description:d},v.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:s}),this.touchSession(r.sessionId),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:s,input:a,description:d}),h}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let i=new Date().toISOString(),s=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.title??"",c=r?.createdAt??i,u=r?.lastActivityAt??i,d=zn(r?.acceptedClientMessageIds),f=r?"memory":"client",h=this.store.find(e);if(h)s=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.title||l,c=h.createdAt||c,u=h.lastActivityAt||u,d=zn(h.acceptedClientMessageIds,d),f="record";else if(!r){let p=(await en(n??s)).find(y=>y.sessionId===e);p&&(s=p.agent,o=p.cwd||o,l=p.title??l,c=p.createdAt,u=p.lastActivityAt,f="scanner")}if(!s&&n&&(s=n,f=r?"memory":"client"),!!s)return{agent:s,cwd:o,approvalMode:a,title:l,createdAt:c,lastActivityAt:u,acceptedClientMessageIds:d,source:f,managed:r?.managed??h?.managed}}resendPendingApproval(e,n){if(!e.pendingApproval||n.readyState!==1)return;let{requestId:r,toolName:i,input:s,description:o}=e.pendingApproval;w.info({sessionId:e.sessionId,requestId:r,toolName:i},"resending pending approval to reconnected client");let a={type:"approval.request",sessionId:e.sessionId,requestId:r,toolName:i,input:s,description:o};n.send(JSON.stringify(a))}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=_c?n:`${n.slice(0,Math.max(1,_c-3)).trimEnd()}...`:dg}touchSession(e,n=!0){let r=new Date().toISOString(),i=this.sessions.get(e);if(i){i.lastActivityAt=r,i.lastActivityTs=Date.now(),n&&this.store.upsert(Ce(i));return}let s=this.store.find(e);s&&this.store.upsert({...s,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;I.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return en(e,n)}async handle(e,n){switch(w.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor);break}}removeClient(e){for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){w.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}async createSession(e,n,r,i,s,o){i=Gn(i),w.info({agent:r,cwd:i,approvalMode:s,continueSession:o},"creating session");try{if(!(await(0,wc.stat)(i)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${i}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${i}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(r,i)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return w.info({sessionId:l.sessionId,cwd:i},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,i,s);w.info("continue mode: no previous sessions found, creating new")}catch(a){w.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=I.startTimer("driver.spawn"),l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l),u=await l.start(i,void 0,s),d=a();w.info({sessionId:u,agent:r,spawnMs:d},"session created"),I.increment("session.create",{agent:r}),v.emit("session.create",{sessionId:u,agent:r,cwd:i,approvalMode:s});let f={sessionId:u,agent:r,cwd:i,approvalMode:s,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(Ce(f)),this.updateGauges(),Li(),Ii(),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){w.error({agent:r,cwd:i,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,i,s,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await tn(r,i,a.cwd);if(f.length>0){let h={type:"session.history",sessionId:r,messages:f,isResponding:a.isResponding||void 0,approvalMode:a.approvalMode};e.send(JSON.stringify(h))}this.resendPendingApproval(a,e),this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=s||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=I.startTimer("driver.spawn"),h=this.createDriver(i),g=this.configureDriverBeforeStart(i,h),p=await h.start(c,r,u),y=f();w.info({sessionId:p,agent:i,spawnMs:y},"session resumed"),I.increment("session.resume",{agent:i}),v.emit("session.resume",{sessionId:p,agent:i,cwd:c});let _={sessionId:p,agent:i,cwd:c,approvalMode:u,driver:h,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],syntheticApprovalRetries:{},managed:l?.managed,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(p,_),this.registerClaudeHookSession(_),this.store.upsert(Ce(_)),this.updateGauges(),this.bindDriverLifecycle(_,i," (resumed)",e);let G=await tn(r,i,c);if(G.length>0){w.info({sessionId:r,historyCount:G.length},"sending history messages");let re={type:"session.history",sessionId:p,messages:G,approvalMode:u};e.send(JSON.stringify(re))}this.reply(e,n,!0,{sessionId:p})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>$n&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-$n))}async sendMessage(e,n,r,i,s,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(!a||!a.driver){let l=await this.resolveReconnectSession(r,s,a);if(!l){w.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:r,agent:l.agent,source:l.source},"auto-reconnecting session"),I.increment("session.reconnect",{agent:l.agent,source:l.source}),v.emit("session.reconnect",{sessionId:r,agent:l.agent,source:l.source});try{let c=this.createDriver(l.agent),u=this.configureDriverBeforeStart(l.agent,c,a?.claudeHookSecret);await c.start(l.cwd,r,l.approvalMode),a?(a.approvalMode=l.approvalMode,a.driver=c,a.active=!0,a.clients.add(e),a.lastActivityAt=l.lastActivityAt,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=zn(a.acceptedClientMessageIds,l.acceptedClientMessageIds),a.syntheticApprovalRetries=a.syntheticApprovalRetries??{},a.claudeHookSecret=u??a.claudeHookSecret,a.pendingClaudeHookApprovals=a.pendingClaudeHookApprovals??new Map):(a={sessionId:r,agent:l.agent,cwd:l.cwd,approvalMode:l.approvalMode,driver:c,clients:new Set([e]),title:l.title,createdAt:l.createdAt,lastActivityAt:l.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l.acceptedClientMessageIds,syntheticApprovalRetries:{},managed:l.managed,claudeHookSecret:u,pendingClaudeHookApprovals:new Map},this.sessions.set(r,a)),this.registerClaudeHookSession(a),this.bindDriverLifecycle(a,l.agent," (reconnected)"),this.store.upsert(Ce(a)),this.updateGauges()}catch(c){this.reply(e,n,!1,void 0,`Failed to reconnect: ${c}`);return}}if(a.clients.add(e),o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(w.info({sessionId:r,clients:a.clients.size,hasDriver:!!a.driver,active:a.active},"sending message"),v.emit("session.send",{sessionId:r,agent:a.agent,messagePreview:i.slice(0,100)}),dt(a.title)){let l=wi(i,50);l&&l!==a.title&&(a.title=l),this.store.upsert(Ce(a))}o&&this.rememberAcceptedClientMessage(a,o),this.touchSession(a.sessionId),a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=i,a.driver.sendPrompt(i),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,i,s,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await Ci({agent:r,cwd:i,search:s,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(d){w.warn({error:String(d)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}let u;if(o&&!l.has(o)){let d=a??c.sessions.find(g=>g.sessionId===o)?.agent,f=this.sessions.get(o),h=await this.resolveReconnectSession(o,d,f);if(h){let g=await tn(o,h.agent,f?.cwd??h.cwd);u={sessionId:o,agent:h.agent,messages:g,isResponding:f?.isResponding||void 0,approvalMode:f?.approvalMode??h.approvalMode,...f?.pendingApproval?{pendingApproval:f.pendingApproval}:{}}}}I.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,...u?{activeSession:u}:{}}})}catch(l){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}async approve(e,n,r,i,s){let o=this.sessions.get(r),a=o?.pendingClaudeHookApprovals.get(i);if(o&&a){o.pendingApproval=void 0,v.emit("approval.response",{sessionId:r,requestId:i,approved:s}),this.touchSession(o.sessionId),a.resolve(vc(s)),o.isResponding=!0,this.reply(e,n,!0);return}o&&(o.pendingApproval=void 0);let l=o?.syntheticApprovalRetries[i];if(o&&l&&Fn(i)){delete o.syntheticApprovalRetries[i],v.emit("approval.response",{sessionId:r,requestId:i,approved:s}),this.touchSession(o.sessionId),this.reply(e,n,!0),s&&await this.retrySyntheticClaudeApproval(o,l);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(v.emit("approval.response",{sessionId:r,requestId:i,approved:s}),this.touchSession(o.sessionId),!o.driver.respondApproval(i,s)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.isResponding=!0,this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",i=this.createDriver(e.agent),s=this.configureDriverBeforeStart(e.agent,i,e.claudeHookSecret);await i.start(e.cwd,e.sessionId,r),e.driver=i,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.claudeHookSecret=s??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(Ce(e)),this.updateGauges(),this.touchSession(e.sessionId),w.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),i.sendPrompt(n.message)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,this.updateGauges(),this.touchSession(e.sessionId),w.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,i){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}let o=s.approvalMode;if(s.approvalMode=i,this.store.upsert(Ce(s)),w.info({sessionId:r,agent:s.agent,oldMode:o,newMode:i},"approval mode changed"),s.driver&&(s.driver.setApprovalMode(i),s.agent==="codex"&&s.active&&o!==i))try{s.driver.stop();let a=this.createDriver("codex");await a.start(s.cwd,s.sessionId,i),s.driver=a,this.bindDriverLifecycle(s,"codex"," (mode change)"),w.info({sessionId:r},"codex driver restarted with new approval mode")}catch(a){w.error({sessionId:r,error:String(a)},"failed to restart codex after approval mode change"),s.driver=null,s.active=!1,this.updateGauges()}this.reply(e,n,!0,{approvalMode:i})}interrupt(e,n,r){let i=this.sessions.get(r);if(!i?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}v.emit("session.interrupt",{sessionId:r,agent:i.agent}),i.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:r,agent:i.agent},"stopping session"),v.emit("session.stop",{sessionId:r,agent:i.agent}),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),i.active=!1,i.driver=null,this.updateGauges(),this.touchSession(i.sessionId),this.reply(e,n,!0)}deleteSession(e,n,r){let i=this.sessions.get(r);i&&(w.info({sessionId:r,agent:i.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(i),i.driver?.stop(),this.unregisterClaudeHookSession(i),this.sessions.delete(r)),v.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Li(),Ii(),this.reply(e,n,!0)}async sendHistory(e,n,r,i){let s=this.sessions.get(r);if(!s&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}s&&s.clients.add(e);let o=s?.cwd??this.store.find(r)?.cwd??"",a=await tn(r,i,o);w.info({sessionId:r,historyCount:a.length,isResponding:s?.isResponding,approvalMode:s?.approvalMode},"sending history");let l={type:"session.history",sessionId:r,messages:a,isResponding:s?.isResponding||void 0,approvalMode:s?.approvalMode};e.send(JSON.stringify(l)),s&&this.resendPendingApproval(s,e),this.reply(e,n,!0)}async listSessions(e,n,r,i,s,o=50,a){try{let l=await Ci({agent:r,cwd:i,search:s,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,l)}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new Xt;case"codex":return new Un;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){w.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let i=JSON.stringify(n),s=r.clients.size,o=0,a=0;for(let l of r.clients)l.readyState===1?(l.send(i),o++):a++;if(a>0&&I.increment("broadcast.fail"),n.type!=="text.delta"&&w.debug({sessionId:e,msgType:n.type,sent:o,total:s},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let l=r.title||e,c=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(l,c,{sessionId:e,agent:r.agent});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,i,s){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:i,error:s};e.send(JSON.stringify(o))}};function Fi(t,e){t.action==="push.register"?e.registerToken(t.pushToken):e.unregisterToken(t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var bc=require("child_process");function hg(t,e){return(0,bc.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function pg(t){let e=t.split(`
100
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Ic(t,e=hg){let n;try{n=pg(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let i=e("ps",["-p",String(r),"-o","command="]);return i?{pid:r,command:i}:{pid:r}}catch{return{pid:r}}})}var yt=require("fs"),Ui=require("os"),Ec=require("crypto"),Ac=require("path");function Cc(t){return(0,Ec.randomBytes)(t).toString("base64url")}function gg(){return`d_${Cc(12)}`}function mg(){return(0,Ui.hostname)()}function yg(){let t=(0,Ui.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function _g(t){return{daemonId:gg(),daemonSecret:Cc(32),displayName:mg(),canonicalHost:yg(),port:t,createdAt:new Date().toISOString()}}function xc(t,e){(0,yt.mkdirSync)((0,Ac.dirname)(e),{recursive:!0}),(0,yt.writeFileSync)(e,JSON.stringify(t,null,2)+`
101
- `,"utf8")}function Tc(t,e=vl){try{let r=(0,yt.readFileSync)(e,"utf8"),i=JSON.parse(r);if(typeof i.daemonId=="string"&&typeof i.daemonSecret=="string"&&typeof i.displayName=="string"&&typeof i.canonicalHost=="string"&&typeof i.createdAt=="string"){let s={daemonId:i.daemonId,daemonSecret:i.daemonSecret,displayName:i.displayName,canonicalHost:i.canonicalHost,port:typeof i.port=="number"&&Number.isFinite(i.port)?i.port:t,createdAt:i.createdAt};return s.port!==t&&(s.port=t,xc(s,e)),s}}catch{}let n=_g(t);return xc(n,e),n}var _t=require("crypto"),St=require("fs"),Rc=require("path");function qi(t){return(0,_t.randomBytes)(t).toString("base64url")}function Wi(t){return(0,_t.createHash)("sha256").update(t).digest("hex")}function kc(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,_t.timingSafeEqual)(n,r)}function Sg(t){try{let e=(0,St.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function rn(t,e){(0,St.mkdirSync)((0,Rc.dirname)(t),{recursive:!0}),(0,St.writeFileSync)(t,JSON.stringify(e,null,2)+`
102
- `,"utf8")}var Yn=class{constructor(e=wl){this.pairingsPath=e;this.records=Sg(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let n=`pair_${qi(8)}`,r=qi(24),i=new Date(Date.now()+e).toISOString(),s={pairingId:n,pairNonce:r,expiresAt:i};return this.windows.set(r,s),s}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),i=qi(32),s={deviceId:e,deviceName:n,tokenHash:Wi(i),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=s:this.records.unshift(s),rn(this.pairingsPath,this.records),i}validatePairToken(e,n,r=!0){let i=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!i)return!1;let s=Wi(n);return kc(i.tokenHash,s)?(r&&(i.lastSeenAt=new Date().toISOString(),rn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Wi(e),i=this.records.find(s=>!s.revokedAt&&kc(s.tokenHash,r));return i?(n&&(i.lastSeenAt=new Date().toISOString(),rn(this.pairingsPath,this.records)),i):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),rn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),rn(this.pairingsPath,this.records)}};function vt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function vg(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Pc(t,e){return vg(t)??e}function wg(t,e){return!!(t&&e&&t===e)}function ji(t,e,n,r=!0){return t?wg(t,e)?!0:!!n(t,r):!1}var Lc=require("child_process");function Gi(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Nc(t){if(!Gi(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function bg(t){if(!Gi(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Ig(t){if(!Gi(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function zi(t){return!!t&&!bg(t)&&!Ig(t)}function wt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Oc(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function xg(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let i of r)i.internal||i.family!=="IPv4"||zi(i.address)&&(Nc(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Eg(t){let e=JSON.parse(t),n=wt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>wt(o)).filter(o=>!!o).filter(o=>Nc(o)&&zi(o)),i=r[0]??n,s=[...n&&n!==i?[n]:[],...r.filter(o=>o!==i)];return{canonicalHost:i,fallbackHosts:s}}function Mc(t=Lc.execFileSync){try{let e=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Eg(e)}catch{return{fallbackHosts:[]}}}function Bc(t){let e=wt(t.canonicalHost),n=wt(t.configuredCanonicalHost)||wt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...xg(t.interfaces)].map(i=>wt(i)).filter(i=>!!i).filter(i=>zi(i)).filter((i,s,o)=>i!==n&&o.indexOf(i)===s);return{canonicalHost:n,fallbackHosts:r}}function Dc(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=B.child({module:"daemon"}),sn=B.child({module:"ws"}),qe=new Vn,F=Tc(S.port),Te=new Yn,Kn=new Set,Jn=new WeakSet,Hc=!1,Wc=Date.now(),bt=null;function It(){let t=Mc();return Bc({canonicalHost:F.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Oc(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Uc.networkInterfaces)()})}async function $i(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function D(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function jc(){let t=Te.openWindow(),e=It(),n=e.canonicalHost,r=F.port,i=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(S.relayUrl)try{let s=new URL(S.relayUrl);n=s.hostname,r=s.port?Number(s.port):s.protocol==="https:"?443:80,i=[e.canonicalHost,...i??[]].filter(Boolean)}catch{W.warn({relayUrl:S.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:F.daemonId,displayName:F.displayName,canonicalHost:n,fallbackHosts:i,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function Ag(t){let e=await(0,We.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let i=await(0,We.stat)((0,Xn.join)(t,r)).catch(()=>null);i&&n.push({name:r,isDirectory:i.isDirectory()})}return n.sort((r,i)=>r.isDirectory!==i.isDirectory?r.isDirectory?-1:1:r.name.localeCompare(i.name)),{entries:n}}var on=(0,Fc.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let i=It(),s={status:"ok",version:ut,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:i.canonicalHost,uptimeSeconds:Math.round((Date.now()-Wc)/1e3),activeSessions:qe.getActiveSessionCount(),pairedDevices:Te.pairedCount(),wsClients:ne.clients.size,drivers:qe.getDriverCounts(),metrics:I.snapshot()};S.relayUrl&&(s.relayUrl=S.relayUrl),D(e,200,s);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,jc());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}Te.reset(),D(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,{status:"stopping"}),setTimeout(()=>je("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let i=await $i(t),s=t.headers[Jt],o=Array.isArray(s)?s[0]:s;qe.handleClaudeSessionStartHook(o,i),D(e,200,{ok:!0})}catch(i){D(e,400,{error:String(i)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let i=await $i(t),s=t.headers[Jt],o=Array.isArray(s)?s[0]:s,a=await qe.handleClaudePermissionHook(o,i);D(e,200,a)}catch(i){D(e,400,{error:String(i)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let i=await $i(t);if(i.daemonId!==F.daemonId||typeof i.pairNonce!="string"||typeof i.deviceId!="string"||typeof i.deviceName!="string"){D(e,400,{error:"invalid_pair_request"});return}if(!Te.consumeWindow(i.pairNonce)){D(e,401,{error:"pair_window_expired"});return}let o=Te.issuePairToken(i.deviceId,i.deviceName),a=It();D(e,200,{daemonId:F.daemonId,displayName:F.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:F.port,deviceId:i.deviceId,pairToken:o})}catch(i){D(e,400,{error:String(i)})}return}let r=Pc(t.headers.authorization,n.searchParams.get("token"));if(!ji(r,S.legacyToken,(i,s)=>Te.validateAnyPairToken(i,s),!1)){e.writeHead(401),e.end("Unauthorized");return}if(n.pathname==="/file"){let i=n.searchParams.get("path");if(!i){e.writeHead(400),e.end("Missing path parameter");return}try{let s=Gn(i);if(!(await(0,We.stat)(s)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,Xn.extname)(s).toLowerCase(),c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".pdf":"application/pdf"}[a]||"application/octet-stream",u=await(0,We.readFile)(s);e.writeHead(200,{"Content-Type":c,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${ut}`)}),ne=new vr.default({server:on});on.on("connection",t=>{Kn.add(t),t.on("close",()=>{Kn.delete(t)})});ne.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(ji(r,S.legacyToken,(i,s)=>Te.validateAnyPairToken(i,s)))Jn.add(t),I.increment("ws.auth.success",{mode:"query_token"});else if(r){I.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}sn.info({clients:ne.clients.size},"client connected"),I.increment("ws.connect"),I.gauge("ws.clients",ne.clients.size),v.emit("ws.connect",{clients:ne.clients.size,authMode:Jn.has(t)?"query_token":"pending"}),t.on("message",async i=>{try{let s=JSON.parse(Dc(i));if(!s||typeof s.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(s.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=s;if(!Jn.has(t)){if(o.action==="auth.hello"&&o.daemonId===F.daemonId&&Te.validatePairToken(o.deviceId,o.pairToken)){Jn.add(t),I.increment("ws.auth.success",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:F.daemonId,displayName:F.displayName}}));return}if(o.action==="auth.hello"){I.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}I.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)v.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?W.error:a.level==="warn"?W.warn:W.info).call(W,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await Ag(o.path);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(s.action==="push.register"){Fi(s,{registerToken:Bi,unregisterToken:Di,respond:a=>t.send(JSON.stringify(a))});return}if(s.action==="push.unregister"){Fi(s,{registerToken:Bi,unregisterToken:Di,respond:a=>t.send(JSON.stringify(a))});return}await qe.handle(t,o)}catch(s){sn.error({error:String(s)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(s)}))}}),t.on("close",i=>{sn.info({clients:ne.clients.size,code:i},"client disconnected"),I.increment("ws.disconnect"),I.increment("ws.disconnect.code",{code:String(i)}),I.gauge("ws.clients",ne.clients.size),v.emit("ws.disconnect",{clients:ne.clients.size,code:i}),qe.removeClient(t)}),t.on("error",i=>{sn.error({error:i.message},"websocket error")})});function Vi(){for(let t of Kn)try{t.destroy()}catch{}Kn.clear()}function Gc(){let t=xl({auditPath:ct,stdoutLogPath:bl,stderrLogPath:Il,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&W.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function Cg(){bt||(bt=setInterval(Gc,S.storageHousekeepingIntervalMs),bt.unref())}function Tg(){bt&&(clearInterval(bt),bt=null)}function je(t,e=0){if(!Hc){Hc=!0,W.info({reason:t,exitCode:e},"shutting down"),v.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Wc)/1e3)}),I.stopPeriodicLog(),Tg(),qe.shutdown();for(let n of ne.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ne.close(n=>{n&&W.error({error:String(n)},"websocket close error")}),on.close(n=>{if(n){W.error({error:String(n)},"http close error"),Vi(),process.exit(1);return}Vi(),process.exit(e)}),setTimeout(()=>{W.error("force exiting after shutdown timeout"),Vi(),process.exit(e||1)},3e3).unref()}}ne.on("error",t=>{sn.error({error:t.message},"wss error")});on.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Ic(S.port).filter(n=>n.pid!==process.pid);W.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else W.error({error:String(t)},"server error");je(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>je("SIGINT"));process.once("SIGTERM",()=>je("SIGTERM"));process.once("SIGHUP",()=>je("SIGHUP"));process.once("SIGTTIN",()=>je("SIGTTIN"));process.once("SIGTSTP",()=>je("SIGTSTP"));process.on("uncaughtException",t=>{W.error({error:String(t),stack:t.stack},"uncaughtException"),v.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{W.error({reason:String(t)},"unhandledRejection"),v.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});on.listen(S.port,async()=>{Gc(),v.emit("daemon.start",{port:S.port}),I.startPeriodicLog(),Cg(),W.info({port:S.port,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:It().canonicalHost,fallbackHosts:It().fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs},"daemon started");let t=It(),e=jc();process.stdout.write(`
92
+ `)}resolveToolContext(e){let n=Q(e?.item)??e??null,r=Ss(n);if(!r)return null;let s=n?Fl(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?vs(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),v.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){A.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!Sp(o)){A.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=_p(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},vp(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/permissions/requestApproval"){A.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}A.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(A.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=Q(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&A.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||A.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=Q(r?.item),i=Ss(s),o=s?Fl(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=Q(r?.item)??r,i=Ss(s);i&&this.toolContextByCallId.delete(i);break}case"turn/completed":{let s=Q(r?.usage),i=s?{inputTokens:Number(s.input_tokens??s.inputTokens??0),outputTokens:Number(s.output_tokens??s.outputTokens??0)}:void 0;A.info({threadId:this.threadId},"turn completed"),v.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:i}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:i});break}default:n&&A.debug({method:n},"unhandled notification");break}}};var P=require("fs/promises"),rc=require("fs"),sc=require("readline"),T=require("path"),pe=require("os");var wp=new Set(["New session","Resumed session","Untitled session"]),bp=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Ip(t){return t.replace(/\s+/g," ").trim()}function qn(t){return typeof t!="string"?void 0:Ip(t)||void 0}function zl(t){let e=qn(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function dt(t){let e=qn(t);return!e||wp.has(e)||zl(e)}function xp(t){for(let e of t.replace(/\r/g,"").split(`
93
+ `)){let n=qn(e);if(n&&!Ep(n)&&!Ap(n))return n}}function Ep(t){return bp.some(e=>t.startsWith(e))}function Ap(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Cp(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function ws(t,e=80){if(typeof t!="string")return;let n=xp(t);if(!n)return;let r=Cp(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||zl(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Ue(t,e){for(let n of t){let r=qn(n);if(!(!r||dt(r)))return r}return ws(e)}var Vl=require("child_process"),ft=require("fs/promises"),Ae=require("path"),bs=require("os"),Yl=require("util");var Tp=(0,Yl.promisify)(Vl.execFile),kp=3e3,Zt=null;function Is(){Zt=null}function Rp(t){return t.replace(/^['"]|['"]$/g,"")}function Pp(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Rp)}function xs(t){let e=Pp(t);for(let n=0;n<e.length;n+=1){let r=e[n],s=(0,Ae.basename)(r);if(s==="claude"||s==="codex")return{agent:s,args:e.slice(n+1)}}return null}function Lp(t,e){let n=xs(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function Wn(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Np(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Op(t,e){let n=xs(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function Mp(t){let e=Lp(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(s=>Np(t.agent,s));if(n.length!==1)return null;let r=ht(t.agent,n[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",sessionFilePath:n[0]}:null}function Bp(t,e){let n=t,r=e;return(Wn(e.confidence)>Wn(t.confidence)||Wn(e.confidence)===Wn(t.confidence)&&e.pid<t.pid)&&(n=e,r=t),{...n,cwd:n.cwd||r.cwd,title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath}}function Dp(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Bp(s,n):n)}return[...e.values()]}async function Es(t,e){try{let{stdout:n}=await Tp(t,e,{maxBuffer:8388608});return n}catch{return""}}async function $l(t){if(!t.sessionFilePath)return t;let e=await Qt(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function Hp(t){return(await Es("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
94
+ `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Fp(t){let n=(await Es("lsof",["-p",String(t),"-Fn"])).split(`
95
+ `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function Up(){return(await Es("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
96
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2],i=xs(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function qp(){let t=await Up();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await Hp(e.pid),sessionFiles:await Fp(e.pid)})))}function Wp(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function jp(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ae.join)((0,bs.homedir)(),".claude","projects",Wp(e)),l=(await(0,ft.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let h=await(0,ft.stat)((0,Ae.join)(o,f)).catch(()=>null);h&&(!c||h.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:h.mtimeMs})})),!c)return null;let u=(0,Ae.join)(o,c.name),d=ht(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ae.join)((0,bs.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,ft.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ae.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,ft.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await Qt(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(n);let i=r;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function Jl(){if(Zt&&Date.now()<Zt.expiresAt)return Zt.value;let t=await qp(),e=await Promise.all(t.map(async r=>{let s=Mp(r);if(s)return $l(s);if(Op(r.agent,r.command))return null;let i=await jp(r.agent,r.cwd);return i?$l({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=Dp(e.filter(r=>r!==null));return Zt={value:n,expiresAt:Date.now()+kp},n}var Xl=B.child({module:"inventory"}),pt={daemonActive:3,externalRunning:2,idle:1},Kl={high:3,medium:2,low:1};function Zl(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Gp(t,e){let n=t.runtime.needsAttention?1:0;return(e.runtime.needsAttention?1:0)-n||pt[e.runtime.state]-pt[t.runtime.state]||Zl(t,e)}function zp(t,e){return pt[e.state]>pt[t.state]?e:pt[e.state]<pt[t.state]?t:Kl[e.confidence]>Kl[t.confidence]?e:t}function $p(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Vp(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function Yp(t,e){return e?t?!(dt(e)&&!dt(t)):!0:!1}function As(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Jp(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:As(),managed:t.managed}}function Kp(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",pid:t.pid,command:t.command}}}function Xp(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed}}function Zp(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=Yp(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=zp(s.runtime,n.runtime),l=s.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?n.lastActivityAt:Vp(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:$p(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed})}}function Qp(...t){let e=new Map;for(let n of t)Zp(e,n);return[...e.values()]}function eg(t,e,n,r,s){let i=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&Xl.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function tg(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function ng(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=Qp(t.sessionRecords.map(Jp),t.scannedSessions,t.runningSessions.map(_=>Kp(_,t.scannedAt)),t.activeSessions.map(Xp)),c=t.deletedSessionIds?.size?l.filter(_=>!t.deletedSessionIds?.has(_.sessionId)):l,u=eg(c,r,s,i,o),d=u.filter(_=>_.runtime.state!=="idle"||_.managed).sort(Gp),f=u.filter(_=>_.runtime.state==="idle"&&!_.managed).sort(Zl),h=tg(f,n),g=f.slice(h,h+a),y=h+g.length<f.length&&g.length>0?{lastActivityAt:g[g.length-1].lastActivityAt,sessionId:g[g.length-1].sessionId}:void 0;return{sessions:n?g:[...d,...g],nextCursor:y}}async function Cs(t){let e=new Date().toISOString(),[n,r,s]=await Promise.all([en(t.agent,t.cwd),Jl(),t.search?Ql(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&Xl.info({search:t.search,contentMatches:s?.size??0,scanned:n.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),ng({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:n,runningSessions:r,scannedAt:e,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,t.search,s)}var le=B.child({module:"scanner"});function ic(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var oc=5e3,ks=ic(oc),Rs=ic(oc);function Ls(){ks.clear(),Rs.clear()}function Ps(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}function*ac(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
97
+ `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var Ts=512*1024;async function lc(t,e){if(e<=Ts)return(0,P.readFile)(t,"utf-8");let n=await(0,P.open)(t,"r");try{let r=Buffer.alloc(Ts),{bytesRead:s}=await n.read(r,0,Ts,0);return r.toString("utf-8",0,s)}finally{await n.close()}}function Ns(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function cc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Ns(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Os(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}var rg=["<task-notification>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","<system-reminder>","<environment_context>","# AGENTS.md instructions for "];function sg(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?rg.some(r=>n.startsWith(r)):!1}function Ms(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Os(t.message.content);return sg(t,e)?"":e}function uc(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function dc(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:As()}}function ht(t,e){let n=(0,T.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function ig(t,e){let n=await lc(t,e),r=ac(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=Ue([u.customTitle,u.summary])),!l){let d=Ms(u),f=Ue([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||ht("claude",t)||(0,T.basename)(t,".jsonl"),cwd:s,title:o??l??Ue([],a)}:null}async function og(t,e){let n=await lc(t,e),r=ac(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=Ue([u.payload?.title,u.title])),!l){let d=cc(u),f=d&&!uc(d)?Ue([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||ht("codex",t)||(0,T.basename)(t,".jsonl"),cwd:s,title:o??l??Ue([],a)}:null}async function Qt(t,e){let n=await(0,P.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await ig(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await og(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function ec(t){let e=(0,T.join)((0,pe.homedir)(),".claude","projects");try{let n;t?n=[Ps(t)]:n=(await(0,P.readdir)(e,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name);let r=[];for(let o of n){let a=(0,T.join)(e,o),l=await(0,P.readdir)(a).catch(()=>[]);for(let c of l)c.endsWith(".jsonl")&&r.push((0,T.join)(a,c))}return(await Promise.all(r.map(o=>Qt(o,"claude")))).filter(o=>o!==null).map(o=>dc(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return le.warn({error:String(n)},"failed to list claude sessions"),[]}}async function tc(t){let e=(0,T.join)((0,pe.homedir)(),".codex","sessions");try{let n=await(0,P.readdir)(e).catch(()=>[]),r=[];for(let o of n){let a=(0,T.join)(e,o),l=await(0,P.readdir)(a).catch(()=>[]);for(let c of l){let u=(0,T.join)(a,c),d=await(0,P.readdir)(u).catch(()=>[]);for(let f of d){let h=(0,T.join)(u,f),g=await(0,P.readdir)(h).catch(()=>[]);for(let p of g)p.endsWith(".jsonl")&&r.push((0,T.join)(h,p))}}}return(await Promise.all(r.map(o=>Qt(o,"codex")))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>dc(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return le.warn({error:String(n)},"failed to list codex sessions"),[]}}async function en(t,e){let r=`list:${(0,pe.homedir)()}:${t??"all"}:${e??""}`,s=ks.get(r);if(s)return s;let i;if(t==="claude")i=await ec(e);else if(t==="codex")i=await tc(e);else{let[o,a]=await Promise.all([ec(e),tc(e)]);i=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return ks.set(r,i),i}async function Ql(t,e){let r=`search:${(0,pe.homedir)()}:${t}:${e??"all"}`,s=Rs.get(r);if(s)return s;let i=new Set,o=t.toLowerCase();async function a(){let c=(0,T.join)((0,pe.homedir)(),".claude","projects");try{let u=await(0,P.readdir)(c,{withFileTypes:!0}),d=[];for(let h of u){if(!h.isDirectory())continue;let g=(0,T.join)(c,h.name),p=await(0,P.readdir)(g).catch(()=>[]);for(let y of p)y.endsWith(".jsonl")&&d.push((0,T.join)(g,y))}let f=await Promise.all(d.map(h=>nc(h,o,"claude")));for(let h of f)h&&i.add(h)}catch(u){le.warn({error:String(u)},"failed to search claude files")}}async function l(){let c=(0,T.join)((0,pe.homedir)(),".codex","sessions");try{let u=[];async function d(h){let g=await(0,P.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let p of g){let y=(0,T.join)(h,p.name);p.isDirectory()?await d(y):p.name.endsWith(".jsonl")&&u.push(y)}}await d(c);let f=await Promise.all(u.map(h=>nc(h,o,"codex")));for(let h of f)h&&i.add(h)}catch(u){le.warn({error:String(u)},"failed to search codex files")}}return e==="claude"?await a():e==="codex"?await l():await Promise.all([a(),l()]),Rs.set(r,i),i}async function nc(t,e,n){let r=(0,rc.createReadStream)(t,{encoding:"utf-8"}),s=(0,sc.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?ag:lg,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||ht(n,t):null}function ag(t){return t?.type==="user"&&t.message?.role==="user"?Ms(t):t?.type==="assistant"&&t.message?.role==="assistant"?Os(t.message.content):""}function lg(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Ns(t.payload.content)}let e=cc(t);return e||""}async function tn(t,e,n){let r=[];if(e==="claude"){let s=(0,T.join)((0,pe.homedir)(),".claude","projects");try{let i=n?[Ps(n)]:[],o=await(0,P.readdir)(s).catch(()=>[]),a=n?[...i,...o.filter(l=>l!==Ps(n))]:o;for(let l of a){let c=(0,T.join)(s,l,`${t}.jsonl`);try{let u=await(0,P.readFile)(c,"utf-8");for(let d of u.split(`
98
+ `))if(d.trim())try{let f=JSON.parse(d);if(f.type==="user"&&f.message?.role==="user"){let h=Ms(f);h&&r.push({role:"user",content:h})}else if(f.type==="assistant"&&f.message?.role==="assistant"){let h=Os(f.message.content);h&&r.push({role:"assistant",content:h})}}catch(f){le.warn({error:String(f)},"failed to parse claude history line")}if(r.length>0)break}catch(u){u.code!=="ENOENT"&&le.warn({error:String(u)},"failed to read claude session file")}}}catch(i){le.warn({error:String(i)},"failed to read claude session history")}}else if(e==="codex"){let s=(0,T.join)((0,pe.homedir)(),".codex","sessions");try{let i=await fc(s,t);if(i){let o=await(0,P.readFile)(i,"utf-8");for(let a of o.split(`
99
+ `))if(a.trim())try{let l=JSON.parse(a);if(l.type==="response_item"&&l.payload?.type==="message"){let c=l.payload.role;if(c!=="user"&&c!=="assistant")continue;let u=Ns(l.payload.content);if(!u||c==="user"&&uc(u))continue;r.push({role:c,content:u})}}catch(l){le.warn({error:String(l)},"failed to parse codex history line")}}}catch(i){le.warn({error:String(i)},"failed to read codex session history")}}return r}async function fc(t,e){try{let n=await(0,P.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,T.join)(t,r.name);if(r.isDirectory()){let i=await fc(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){le.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var gt=require("fs"),gc=require("path");var cg=500,hc=200;function ug(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=hc?e:e.slice(-hc)}function dg(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function pc(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:ug(t.acceptedClientMessageIds)}}function fg(t){if(Array.isArray(t))return{records:t.map(pc),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(pc):[],deletedSessionIds:dg(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var jn=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},cg)}loadFromDisk(){try{let e=(0,gt.readFileSync)(Bn,"utf-8");return fg(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,gt.mkdirSync)((0,gc.dirname)(Bn),{recursive:!0}),(0,gt.writeFileSync)(Bn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var mc=require("path"),yc=require("os");function Gn(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,mc.join)((0,yc.homedir)(),t.slice(2)):t}var nn=B.child({module:"push"}),hg="https://exp.host/--/api/v2/push/send",mt=new Set;function Bs(t){mt.add(t),nn.info({token:t,total:mt.size},"push token registered")}function Ds(t){mt.delete(t),nn.info({token:t,total:mt.size},"push token unregistered")}async function _c(t,e,n){if(mt.size===0)return;let r=[...mt].map(s=>({to:s,sound:"default",title:t,body:e,data:n}));try{let s=await fetch(hg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});s.ok?nn.debug({count:r.length},"push sent"):nn.error({status:s.status,statusText:s.statusText},"push send failed")}catch(s){nn.error({error:String(s)},"push send error")}}var w=B.child({module:"manager"}),pg="Done.",Sc=180,$n=200;function zn(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>$n&&e.splice(0,e.length-$n));return e}function Ce(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:zn(t.acceptedClientMessageIds),title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed}}function vc(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Fn(e)}function gg(t){return t.startsWith(gs)}function wc(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var Vn=class{constructor(e=_c){this.pushSender=e;this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new jn;idleSweepInterval=null;startIdleSweep(){S.idleTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=S.idleTimeoutMs;if(n<=0)return;let r=3600*1e3;for(let[s,i]of this.sessions){if(!i.active&&!i.driver){if(i.clients.size===0){let a=e-i.lastActivityTs;a>=r&&(w.info({sessionId:i.sessionId,inactiveMs:a},"removing inactive session from memory"),I.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(i),this.sessions.delete(s))}continue}if(!i.active||!i.driver||i.isResponding)continue;let o=e-i.lastActivityTs;o<n||(w.info({sessionId:i.sessionId,agent:i.agent,idleMs:o,timeoutMs:n},"stopping idle driver"),I.increment("driver.idle_timeout",{agent:i.agent}),v.emit("driver.idle_timeout",{sessionId:i.sessionId,agent:i.agent,idleMs:o}),i.driver.stop(),i.active=!1,i.driver=null,this.updateGauges(),this.touchSession(i.sessionId))}}bindDriverLifecycle(e,n,r,s){e.driver?.onMessage(i=>{if(w.debug({agent:n,context:r,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)){let o=e.sessionId;w.info({oldSessionId:o,newSessionId:i.sessionId},"session ID updated"),this.store.remove(o),this.sessions.delete(o),e.sessionId=i.sessionId,this.sessions.set(i.sessionId,e),this.store.upsert(Ce(e)),s&&this.reply(s,`id_update_${Date.now()}`,!0,{sessionId:i.sessionId,oldSessionId:o})}(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!vc(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"&&(e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description}),n==="claude"&&i.type==="approval.request"&&Fn(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:w.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),this.broadcast(e.sessionId,i)}),e.driver?.onExit?.(i=>{w.info({agent:n,context:r,exitCode:i,sessionId:e.sessionId},"driver exited"),v.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:i}),I.increment("driver.exit",{agent:n,abnormal:i&&i!==0?"true":"false"});let o=i===0&&vc(e);this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId)})}configureDriverBeforeStart(e,n,r){if(e!=="claude"||!(n instanceof Xt))return;let s=r??(0,Hs.randomUUID)().replace(/-/g,"");return n.configureHookBridge(S.port,s),s}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=Kt){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&gg(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),Kt;if(r.approvalMode==="autoApprove")return wc(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return Kt;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${gs}${l.trim()||(0,Hs.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:h,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},v.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.title??"",c=r?.createdAt??s,u=r?.lastActivityAt??s,d=zn(r?.acceptedClientMessageIds),f=r?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.title||l,c=h.createdAt||c,u=h.lastActivityAt||u,d=zn(h.acceptedClientMessageIds,d),f="record";else if(!r){let p=(await en(n??i)).find(y=>y.sessionId===e);p&&(i=p.agent,o=p.cwd||o,l=p.title??l,c=p.createdAt,u=p.lastActivityAt,f="scanner")}if(!i&&n&&(i=n,f=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,title:l,createdAt:c,lastActivityAt:u,acceptedClientMessageIds:d,source:f,managed:r?.managed??h?.managed}}resendPendingApproval(e,n){if(!e.pendingApproval||n.readyState!==1)return;let{requestId:r,toolName:s,input:i,description:o}=e.pendingApproval;w.info({sessionId:e.sessionId,requestId:r,toolName:s},"resending pending approval to reconnected client");let a={type:"approval.request",sessionId:e.sessionId,requestId:r,toolName:s,input:i,description:o};n.send(JSON.stringify(a))}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Sc?n:`${n.slice(0,Math.max(1,Sc-3)).trimEnd()}...`:pg}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(Ce(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;I.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return en(e,n)}async handle(e,n){switch(w.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor);break}}removeClient(e){for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){w.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}async createSession(e,n,r,s,i,o){s=Gn(s),w.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,bc.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return w.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,s,i);w.info("continue mode: no previous sessions found, creating new")}catch(a){w.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=I.startTimer("driver.spawn"),l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l),u=await l.start(s,void 0,i),d=a();w.info({sessionId:u,agent:r,spawnMs:d},"session created"),I.increment("session.create",{agent:r}),v.emit("session.create",{sessionId:u,agent:r,cwd:s,approvalMode:i});let f={sessionId:u,agent:r,cwd:s,approvalMode:i,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(Ce(f)),this.updateGauges(),Ls(),Is(),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){w.error({agent:r,cwd:s,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await tn(r,s,a.cwd);if(f.length>0){let h={type:"session.history",sessionId:r,messages:f,isResponding:a.isResponding||void 0,approvalMode:a.approvalMode};e.send(JSON.stringify(h))}this.resendPendingApproval(a,e),this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=I.startTimer("driver.spawn"),h=this.createDriver(s),g=this.configureDriverBeforeStart(s,h),p=await h.start(c,r,u),y=f();w.info({sessionId:p,agent:s,spawnMs:y},"session resumed"),I.increment("session.resume",{agent:s}),v.emit("session.resume",{sessionId:p,agent:s,cwd:c});let _={sessionId:p,agent:s,cwd:c,approvalMode:u,driver:h,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],syntheticApprovalRetries:{},managed:l?.managed,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(p,_),this.registerClaudeHookSession(_),this.store.upsert(Ce(_)),this.updateGauges(),this.bindDriverLifecycle(_,s," (resumed)",e);let G=await tn(r,s,c);if(G.length>0){w.info({sessionId:r,historyCount:G.length},"sending history messages");let re={type:"session.history",sessionId:p,messages:G,approvalMode:u};e.send(JSON.stringify(re))}this.reply(e,n,!0,{sessionId:p})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>$n&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-$n))}async sendMessage(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(!a||!a.driver){let l=await this.resolveReconnectSession(r,i,a);if(!l){w.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:r,agent:l.agent,source:l.source},"auto-reconnecting session"),I.increment("session.reconnect",{agent:l.agent,source:l.source}),v.emit("session.reconnect",{sessionId:r,agent:l.agent,source:l.source});try{let c=this.createDriver(l.agent),u=this.configureDriverBeforeStart(l.agent,c,a?.claudeHookSecret);await c.start(l.cwd,r,l.approvalMode),a?(a.approvalMode=l.approvalMode,a.driver=c,a.active=!0,a.clients.add(e),a.lastActivityAt=l.lastActivityAt,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=zn(a.acceptedClientMessageIds,l.acceptedClientMessageIds),a.syntheticApprovalRetries=a.syntheticApprovalRetries??{},a.claudeHookSecret=u??a.claudeHookSecret,a.pendingClaudeHookApprovals=a.pendingClaudeHookApprovals??new Map):(a={sessionId:r,agent:l.agent,cwd:l.cwd,approvalMode:l.approvalMode,driver:c,clients:new Set([e]),title:l.title,createdAt:l.createdAt,lastActivityAt:l.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l.acceptedClientMessageIds,syntheticApprovalRetries:{},managed:l.managed,claudeHookSecret:u,pendingClaudeHookApprovals:new Map},this.sessions.set(r,a)),this.registerClaudeHookSession(a),this.bindDriverLifecycle(a,l.agent," (reconnected)"),this.store.upsert(Ce(a)),this.updateGauges()}catch(c){this.reply(e,n,!1,void 0,`Failed to reconnect: ${c}`);return}}if(a.clients.add(e),o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(w.info({sessionId:r,clients:a.clients.size,hasDriver:!!a.driver,active:a.active},"sending message"),v.emit("session.send",{sessionId:r,agent:a.agent,messagePreview:s.slice(0,100)}),dt(a.title)){let l=ws(s,50);l&&l!==a.title&&(a.title=l),this.store.upsert(Ce(a))}o&&this.rememberAcceptedClientMessage(a,o),this.touchSession(a.sessionId),a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=s,a.driver.sendPrompt(s),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await Cs({agent:r,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(d){w.warn({error:String(d)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}let u;if(o&&!l.has(o)){let d=a??c.sessions.find(g=>g.sessionId===o)?.agent,f=this.sessions.get(o),h=await this.resolveReconnectSession(o,d,f);if(h){let g=await tn(o,h.agent,f?.cwd??h.cwd);u={sessionId:o,agent:h.agent,messages:g,isResponding:f?.isResponding||void 0,approvalMode:f?.approvalMode??h.approvalMode,...f?.pendingApproval?{pendingApproval:f.pendingApproval}:{}}}}I.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,...u?{activeSession:u}:{}}})}catch(l){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingClaudeHookApprovals.get(s);if(o&&a){o.pendingApproval=void 0,v.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),a.resolve(wc(i)),o.isResponding=!0,this.reply(e,n,!0);return}o&&(o.pendingApproval=void 0);let l=o?.syntheticApprovalRetries[s];if(o&&l&&Fn(s)){delete o.syntheticApprovalRetries[s],v.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,l);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(v.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.isResponding=!0,this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(Ce(e)),this.updateGauges(),this.touchSession(e.sessionId),w.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,this.updateGauges(),this.touchSession(e.sessionId),w.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){this.reply(e,n,!1,void 0,"Session not found");return}let o=i.approvalMode;if(i.approvalMode=s,this.store.upsert(Ce(i)),w.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&(i.driver.setApprovalMode(s),i.agent==="codex"&&i.active&&o!==s))try{i.driver.stop();let a=this.createDriver("codex");await a.start(i.cwd,i.sessionId,s),i.driver=a,this.bindDriverLifecycle(i,"codex"," (mode change)"),w.info({sessionId:r},"codex driver restarted with new approval mode")}catch(a){w.error({sessionId:r,error:String(a)},"failed to restart codex after approval mode change"),i.driver=null,i.active=!1,this.updateGauges()}this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}v.emit("session.interrupt",{sessionId:r,agent:s.agent}),s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}w.info({sessionId:r,agent:s.agent},"stopping session"),v.emit("session.stop",{sessionId:r,agent:s.agent}),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,this.updateGauges(),this.touchSession(s.sessionId),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(w.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),this.unregisterClaudeHookSession(s),this.sessions.delete(r)),v.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Ls(),Is(),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r);if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let o=i?.cwd??this.store.find(r)?.cwd??"",a=await tn(r,s,o);w.info({sessionId:r,historyCount:a.length,isResponding:i?.isResponding,approvalMode:i?.approvalMode},"sending history");let l={type:"session.history",sessionId:r,messages:a,isResponding:i?.isResponding||void 0,approvalMode:i?.approvalMode};e.send(JSON.stringify(l)),i&&this.resendPendingApproval(i,e),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await Cs({agent:r,cwd:s,search:i,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,l)}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new Xt;case"codex":return new Un;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){w.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=r.clients.size,o=0,a=0;for(let l of r.clients)l.readyState===1?(l.send(s),o++):a++;if(a>0&&I.increment("broadcast.fail"),n.type!=="text.delta"&&w.debug({sessionId:e,msgType:n.type,sent:o,total:i},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let l=r.title||e,c=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(l,c,{sessionId:e,agent:r.agent});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function Fs(t,e){t.action==="push.register"?e.registerToken(t.pushToken):e.unregisterToken(t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var Ic=require("child_process");function mg(t,e){return(0,Ic.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function yg(t){let e=t.split(`
100
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function xc(t,e=mg){let n;try{n=yg(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var yt=require("fs"),Us=require("os"),Ac=require("crypto"),Cc=require("path");function Tc(t){return(0,Ac.randomBytes)(t).toString("base64url")}function _g(){return`d_${Tc(12)}`}function Sg(){return(0,Us.hostname)()}function vg(){let t=(0,Us.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function wg(t){return{daemonId:_g(),daemonSecret:Tc(32),displayName:Sg(),canonicalHost:vg(),port:t,createdAt:new Date().toISOString()}}function Ec(t,e){(0,yt.mkdirSync)((0,Cc.dirname)(e),{recursive:!0}),(0,yt.writeFileSync)(e,JSON.stringify(t,null,2)+`
101
+ `,"utf8")}function kc(t,e=wl){try{let r=(0,yt.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,Ec(i,e)),i}}catch{}let n=wg(t);return Ec(n,e),n}var _t=require("crypto"),St=require("fs"),Pc=require("path");function qs(t){return(0,_t.randomBytes)(t).toString("base64url")}function Ws(t){return(0,_t.createHash)("sha256").update(t).digest("hex")}function Rc(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,_t.timingSafeEqual)(n,r)}function bg(t){try{let e=(0,St.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function rn(t,e){(0,St.mkdirSync)((0,Pc.dirname)(t),{recursive:!0}),(0,St.writeFileSync)(t,JSON.stringify(e,null,2)+`
102
+ `,"utf8")}var Yn=class{constructor(e=bl){this.pairingsPath=e;this.records=bg(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let n=`pair_${qs(8)}`,r=qs(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:n,pairNonce:r,expiresAt:s};return this.windows.set(r,i),i}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=qs(32),i={deviceId:e,deviceName:n,tokenHash:Ws(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),rn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=Ws(n);return Rc(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),rn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Ws(e),s=this.records.find(i=>!i.revokedAt&&Rc(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),rn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),rn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),rn(this.pairingsPath,this.records)}};function vt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Ig(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Lc(t,e){return Ig(t)??e}function xg(t,e){return!!(t&&e&&t===e)}function js(t,e,n,r=!0){return t?xg(t,e)?!0:!!n(t,r):!1}var Oc=require("child_process");function Gs(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Mc(t){if(!Gs(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Eg(t){if(!Gs(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Ag(t){if(!Gs(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function zs(t){return!!t&&!Eg(t)&&!Ag(t)}function wt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Bc(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Cg(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||zs(s.address)&&(Mc(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function Nc(t){let e=JSON.parse(t),n=wt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>wt(o)).filter(o=>!!o).filter(o=>Mc(o)&&zs(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Dc(t=Oc.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Nc(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Nc(n)}catch{return{fallbackHosts:[]}}}function Hc(t){let e=wt(t.canonicalHost),n=wt(t.configuredCanonicalHost)||wt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Cg(t.interfaces)].map(s=>wt(s)).filter(s=>!!s).filter(s=>zs(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function Fc(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=B.child({module:"daemon"}),sn=B.child({module:"ws"}),qe=new Vn,F=kc(S.port),Te=new Yn,Kn=new Set,Jn=new WeakSet,Uc=!1,Gc=Date.now(),bt=null;function It(){let t=Dc();return Hc({canonicalHost:F.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Bc(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Wc.networkInterfaces)()})}async function $s(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function D(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function zc(){let t=Te.openWindow(),e=It(),n=e.canonicalHost,r=F.port,s=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(S.relayUrl)try{let i=new URL(S.relayUrl);n=i.hostname,r=i.port?Number(i.port):i.protocol==="https:"?443:80,s=[e.canonicalHost,...s??[]].filter(Boolean)}catch{W.warn({relayUrl:S.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:F.daemonId,displayName:F.displayName,canonicalHost:n,fallbackHosts:s,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function Tg(t){let e=await(0,We.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let s=await(0,We.stat)((0,Xn.join)(t,r)).catch(()=>null);s&&n.push({name:r,isDirectory:s.isDirectory()})}return n.sort((r,s)=>r.isDirectory!==s.isDirectory?r.isDirectory?-1:1:r.name.localeCompare(s.name)),{entries:n}}var on=(0,qc.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=It(),i={status:"ok",version:ut,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Gc)/1e3),activeSessions:qe.getActiveSessionCount(),pairedDevices:Te.pairedCount(),wsClients:ne.clients.size,drivers:qe.getDriverCounts(),metrics:I.snapshot()};S.relayUrl&&(i.relayUrl=S.relayUrl),D(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,zc());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}Te.reset(),D(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,{status:"stopping"}),setTimeout(()=>je("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await $s(t),i=t.headers[Jt],o=Array.isArray(i)?i[0]:i;qe.handleClaudeSessionStartHook(o,s),D(e,200,{ok:!0})}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!vt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await $s(t),i=t.headers[Jt],o=Array.isArray(i)?i[0]:i,a=await qe.handleClaudePermissionHook(o,s);D(e,200,a)}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await $s(t);if(s.daemonId!==F.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){D(e,400,{error:"invalid_pair_request"});return}if(!Te.consumeWindow(s.pairNonce)){D(e,401,{error:"pair_window_expired"});return}let o=Te.issuePairToken(s.deviceId,s.deviceName),a=It();D(e,200,{daemonId:F.daemonId,displayName:F.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:F.port,deviceId:s.deviceId,pairToken:o})}catch(s){D(e,400,{error:String(s)})}return}let r=Lc(t.headers.authorization,n.searchParams.get("token"));if(!js(r,S.legacyToken,(s,i)=>Te.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(n.pathname==="/file"){let s=n.searchParams.get("path");if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let i=Gn(s);if(!(await(0,We.stat)(i)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,Xn.extname)(i).toLowerCase(),c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".pdf":"application/pdf"}[a]||"application/octet-stream",u=await(0,We.readFile)(i);e.writeHead(200,{"Content-Type":c,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${ut}`)}),ne=new vr.default({server:on});on.on("connection",t=>{Kn.add(t),t.on("close",()=>{Kn.delete(t)})});ne.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(js(r,S.legacyToken,(s,i)=>Te.validateAnyPairToken(s,i)))Jn.add(t),I.increment("ws.auth.success",{mode:"query_token"});else if(r){I.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}sn.info({clients:ne.clients.size},"client connected"),I.increment("ws.connect"),I.gauge("ws.clients",ne.clients.size),v.emit("ws.connect",{clients:ne.clients.size,authMode:Jn.has(t)?"query_token":"pending"}),t.on("message",async s=>{try{let i=JSON.parse(Fc(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!Jn.has(t)){if(o.action==="auth.hello"&&o.daemonId===F.daemonId&&Te.validatePairToken(o.deviceId,o.pairToken)){Jn.add(t),I.increment("ws.auth.success",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:F.daemonId,displayName:F.displayName}}));return}if(o.action==="auth.hello"){I.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}I.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)v.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?W.error:a.level==="warn"?W.warn:W.info).call(W,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await Tg(o.path);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){Fs(i,{registerToken:Bs,unregisterToken:Ds,respond:a=>t.send(JSON.stringify(a))});return}if(i.action==="push.unregister"){Fs(i,{registerToken:Bs,unregisterToken:Ds,respond:a=>t.send(JSON.stringify(a))});return}await qe.handle(t,o)}catch(i){sn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{sn.info({clients:ne.clients.size,code:s},"client disconnected"),I.increment("ws.disconnect"),I.increment("ws.disconnect.code",{code:String(s)}),I.gauge("ws.clients",ne.clients.size),v.emit("ws.disconnect",{clients:ne.clients.size,code:s}),qe.removeClient(t)}),t.on("error",s=>{sn.error({error:s.message},"websocket error")})});function Vs(){for(let t of Kn)try{t.destroy()}catch{}Kn.clear()}function $c(){let t=El({auditPath:ct,stdoutLogPath:Il,stderrLogPath:xl,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&W.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function kg(){bt||(bt=setInterval($c,S.storageHousekeepingIntervalMs),bt.unref())}function Rg(){bt&&(clearInterval(bt),bt=null)}function je(t,e=0){if(!Uc){Uc=!0,W.info({reason:t,exitCode:e},"shutting down"),v.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Gc)/1e3)}),I.stopPeriodicLog(),Rg(),qe.shutdown();for(let n of ne.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ne.close(n=>{n&&W.error({error:String(n)},"websocket close error")}),on.close(n=>{if(n){W.error({error:String(n)},"http close error"),Vs(),process.exit(1);return}Vs(),process.exit(e)}),setTimeout(()=>{W.error("force exiting after shutdown timeout"),Vs(),process.exit(e||1)},3e3).unref()}}ne.on("error",t=>{sn.error({error:t.message},"wss error")});on.on("error",t=>{if(t.code==="EADDRINUSE"){let e=xc(S.port).filter(n=>n.pid!==process.pid);W.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else W.error({error:String(t)},"server error");je(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>je("SIGINT"));process.once("SIGTERM",()=>je("SIGTERM"));process.once("SIGHUP",()=>je("SIGHUP"));process.once("SIGTTIN",()=>je("SIGTTIN"));process.once("SIGTSTP",()=>je("SIGTSTP"));process.on("uncaughtException",t=>{W.error({error:String(t),stack:t.stack},"uncaughtException"),v.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{W.error({reason:String(t)},"unhandledRejection"),v.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});on.listen(S.port,async()=>{$c(),v.emit("daemon.start",{port:S.port}),I.startPeriodicLog(),kg(),W.info({port:S.port,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:It().canonicalHost,fallbackHosts:It().fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs},"daemon started");let t=It(),e=zc();process.stdout.write(`
103
103
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
104
104
  \u2551 Vibelet Daemon v${ut} \u2551
105
105
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
@@ -114,7 +114,7 @@ Fallbacks: ${t.fallbackHosts.join(", ")||"(none)"}
114
114
 
115
115
  Claude: ${S.claudePath}
116
116
  Codex: ${S.codexPath}
117
- `);try{let n=await qc.default.toString(JSON.stringify(e),{type:"terminal",small:!0});process.stdout.write(`
117
+ `);try{let n=await jc.default.toString(JSON.stringify(e),{type:"terminal",small:!0});process.stdout.write(`
118
118
  Scan this QR code with Vibelet app:
119
119
 
120
120
  ${n}