@vibelet/cli 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -1
- package/bin/vibelet.mjs +17 -10
- package/dist/index.cjs +36 -35
- package/package.json +1 -7
package/dist/index.cjs
CHANGED
|
@@ -1,60 +1,61 @@
|
|
|
1
|
-
"use strict";var cc=Object.create;var Ii=Object.defineProperty;var uc=Object.getOwnPropertyDescriptor;var dc=Object.getOwnPropertyNames;var fc=Object.getPrototypeOf,hc=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var pc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dc(e))!hc.call(t,i)&&i!==n&&Ii(t,i,{get:()=>e[i],enumerable:!(r=uc(e,i))||r.enumerable});return t};var qe=(t,e,n)=>(n=t!=null?cc(fc(t)):{},pc(e||!t||!t.__esModule?Ii(n,"default",{value:t,enumerable:!0}):n,t));var oe=y((Ap,ki)=>{"use strict";var Ai=["nodebuffer","arraybuffer","fragments"],Ci=typeof Blob<"u";Ci&&Ai.push("blob");ki.exports={BINARY_TYPES:Ai,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ci,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _t=y((Cp,Zt)=>{"use strict";var{EMPTY_BUFFER:gc}=oe(),qn=Buffer[Symbol.species];function mc(t,e){if(t.length===0)return gc;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 Pi(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function Ri(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function yc(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Wn(t){if(Wn.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),Wn.readOnly=!1),e}Zt.exports={concat:mc,mask:Pi,toArrayBuffer:yc,toBuffer:Wn,unmask:Ri};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Zt.exports.mask=function(e,n,r,i,s){s<48?Pi(e,n,r,i,s):t.mask(e,n,r,i,s)},Zt.exports.unmask=function(e,n){e.length<32?Ri(e,n):t.unmask(e,n)}}catch{}});var Mi=y((kp,Oi)=>{"use strict";var Li=Symbol("kDone"),Gn=Symbol("kRun"),jn=class{constructor(e){this[Li]=()=>{this.pending--,this[Gn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Gn]()}[Gn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Li])}}};Oi.exports=jn});var vt=y((Pp,Fi)=>{"use strict";var St=require("zlib"),Ni=_t(),_c=Mi(),{kStatusCode:Bi}=oe(),Sc=Buffer[Symbol.species],vc=Buffer.from([0,0,255,255]),Xt=Symbol("permessage-deflate"),ae=Symbol("total-length"),We=Symbol("callback"),he=Symbol("buffers"),Ge=Symbol("error"),Qt,zn=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,!Qt){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Qt=new _c(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[We];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){Qt.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){Qt.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"?St.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=St.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Xt]=this,this._inflate[ae]=0,this._inflate[he]=[],this._inflate.on("error",bc),this._inflate.on("data",Di)}this._inflate[We]=r,this._inflate.write(e),n&&this._inflate.write(vc),this._inflate.flush(()=>{let s=this._inflate[Ge];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=Ni.concat(this._inflate[he],this._inflate[ae]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ae]=0,this._inflate[he]=[],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"?St.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=St.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ae]=0,this._deflate[he]=[],this._deflate.on("data",wc)}this._deflate[We]=r,this._deflate.write(e),this._deflate.flush(St.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=Ni.concat(this._deflate[he],this._deflate[ae]);n&&(s=new Sc(s.buffer,s.byteOffset,s.length-4)),this._deflate[We]=null,this._deflate[ae]=0,this._deflate[he]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};Fi.exports=zn;function wc(t){this[he].push(t),this[ae]+=t.length}function Di(t){if(this[ae]+=t.length,this[Xt]._maxPayload<1||this[ae]<=this[Xt]._maxPayload){this[he].push(t);return}this[Ge]=new RangeError("Max payload size exceeded"),this[Ge].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ge][Bi]=1009,this.removeListener("data",Di),this.reset()}function bc(t){if(this[Xt]._inflate=null,this[Ge]){this[We](this[Ge]);return}t[Bi]=1007,this[We](t)}});var je=y((Rp,en)=>{"use strict";var{isUtf8:Ui}=require("buffer"),{hasBlob:Ec}=oe(),xc=[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 Tc(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function $n(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 Ic(t){return Ec&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}en.exports={isBlob:Ic,isValidStatusCode:Tc,isValidUTF8:$n,tokenChars:xc};if(Ui)en.exports.isValidUTF8=function(t){return t.length<24?$n(t):Ui(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");en.exports.isValidUTF8=function(e){return e.length<32?$n(e):t(e)}}catch{}});var Zn=y((Lp,$i)=>{"use strict";var{Writable:Ac}=require("stream"),Hi=vt(),{BINARY_TYPES:Cc,EMPTY_BUFFER:qi,kStatusCode:kc,kWebSocket:Pc}=oe(),{concat:Vn,toArrayBuffer:Rc,unmask:Lc}=_t(),{isValidStatusCode:Oc,isValidUTF8:Wi}=je(),tn=Buffer[Symbol.species],G=0,Gi=1,ji=2,zi=3,Yn=4,Jn=5,nn=6,Kn=class extends Ac{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Cc[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Pc]=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=G}_write(e,n,r){if(this._opcode===8&&this._state==G)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 tn(r.buffer,r.byteOffset+e,r.length-e),new tn(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 tn(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 G:this.getInfo(e);break;case Gi:this.getPayloadLength16(e);break;case ji:this.getPayloadLength64(e);break;case zi:this.getMask();break;case Yn:this.getData(e);break;case Jn:case nn: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[Hi.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=Gi:this._payloadLength===127?this._state=ji: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=zi:this._state=Yn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Yn}getData(e){let n=qi;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&&Lc(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Jn,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hi.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===G&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=G;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=Vn(r,n):this._binaryType==="arraybuffer"?i=Rc(Vn(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=G):(this._state=nn,setImmediate(()=>{this.emit("message",i,!0),this._state=G,this.startLoop(e)}))}else{let i=Vn(r,n);if(!this._skipUTF8Validation&&!Wi(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Jn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=G):(this._state=nn,setImmediate(()=>{this.emit("message",i,!1),this._state=G,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,qi),this.end();else{let r=e.readUInt16BE(0);if(!Oc(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wi(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=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=G):(this._state=nn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=G,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[kc]=i,o}};$i.exports=Kn});var er=y((Mp,Ji)=>{"use strict";var{Duplex:Op}=require("stream"),{randomFillSync:Mc}=require("crypto"),Vi=vt(),{EMPTY_BUFFER:Nc,kWebSocket:Bc,NOOP:Dc}=oe(),{isBlob:ze,isValidStatusCode:Fc}=je(),{mask:Yi,toBuffer:Ie}=_t(),j=Symbol("kByteLength"),Uc=Buffer.alloc(4),rn=8*1024,Ae,$e=rn,K=0,Hc=1,qc=2,Qn=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=K,this.onerror=Dc,this[Bc]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||Uc,n.generateMask?n.generateMask(r):($e===rn&&(Ae===void 0&&(Ae=Buffer.alloc(rn)),Mc(Ae,0,rn),$e=0),r[0]=Ae[$e++],r[1]=Ae[$e++],r[2]=Ae[$e++],r[3]=Ae[$e++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[j]!==void 0?a=n[j]:(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?(Yi(e,r,c,s,a),[c]):(Yi(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,i){let s;if(e===void 0)s=Nc;else{if(typeof e!="number"||!Fc(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={[j]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==K?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):ze(e)?(i=e.size,s=!1):(e=Ie(e),i=e.length,s=Ie.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==K?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):ze(e)?(i=e.size,s=!1):(e=Ie(e),i=e.length,s=Ie.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==K?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[Vi.extensionName],s=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ze(e)?(a=e.size,l=!1):(e=Ie(e),a=e.length,l=Ie.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={[j]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==K?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[j],this._state=qc,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Xn,this,a,i);return}this._bufferedBytes-=r[j];let o=Ie(s);n?this.dispatch(o,n,r,i):(this._state=K,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Wc,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[Vi.extensionName];this._bufferedBytes+=r[j],this._state=Hc,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Xn(this,l,i);return}this._bufferedBytes-=r[j],this._state=K,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===K&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][j],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][j],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)}};Ji.exports=Qn;function Xn(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 Wc(t,e,n){Xn(t,e,n),t.onerror(e)}});var is=y((Np,rs)=>{"use strict";var{kForOnEventAttribute:wt,kListener:tr}=oe(),Ki=Symbol("kCode"),Zi=Symbol("kData"),Qi=Symbol("kError"),Xi=Symbol("kMessage"),es=Symbol("kReason"),Ve=Symbol("kTarget"),ts=Symbol("kType"),ns=Symbol("kWasClean"),le=class{constructor(e){this[Ve]=null,this[ts]=e}get target(){return this[Ve]}get type(){return this[ts]}};Object.defineProperty(le.prototype,"target",{enumerable:!0});Object.defineProperty(le.prototype,"type",{enumerable:!0});var Ce=class extends le{constructor(e,n={}){super(e),this[Ki]=n.code===void 0?0:n.code,this[es]=n.reason===void 0?"":n.reason,this[ns]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Ki]}get reason(){return this[es]}get wasClean(){return this[ns]}};Object.defineProperty(Ce.prototype,"code",{enumerable:!0});Object.defineProperty(Ce.prototype,"reason",{enumerable:!0});Object.defineProperty(Ce.prototype,"wasClean",{enumerable:!0});var Ye=class extends le{constructor(e,n={}){super(e),this[Qi]=n.error===void 0?null:n.error,this[Xi]=n.message===void 0?"":n.message}get error(){return this[Qi]}get message(){return this[Xi]}};Object.defineProperty(Ye.prototype,"error",{enumerable:!0});Object.defineProperty(Ye.prototype,"message",{enumerable:!0});var bt=class extends le{constructor(e,n={}){super(e),this[Zi]=n.data===void 0?null:n.data}get data(){return this[Zi]}};Object.defineProperty(bt.prototype,"data",{enumerable:!0});var Gc={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[wt]&&i[tr]===e&&!i[wt])return;let r;if(t==="message")r=function(s,o){let a=new bt("message",{data:o?s:s.toString()});a[Ve]=this,sn(e,this,a)};else if(t==="close")r=function(s,o){let a=new Ce("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ve]=this,sn(e,this,a)};else if(t==="error")r=function(s){let o=new Ye("error",{error:s,message:s.message});o[Ve]=this,sn(e,this,o)};else if(t==="open")r=function(){let s=new le("open");s[Ve]=this,sn(e,this,s)};else return;r[wt]=!!n[wt],r[tr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[tr]===e&&!n[wt]){this.removeListener(t,n);break}}};rs.exports={CloseEvent:Ce,ErrorEvent:Ye,Event:le,EventTarget:Gc,MessageEvent:bt};function sn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var nr=y((Bp,ss)=>{"use strict";var{tokenChars:Et}=je();function ne(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function jc(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&&Et[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?(ne(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&&Et[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),ne(n,t.slice(l,u),!0),c===44&&(ne(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(Et[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),i=!1}else if(s)if(Et[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&&Et[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),ne(n,a,h),c===44&&(ne(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?ne(e,f,n):(a===void 0?ne(n,f,!0):r?ne(n,a,f.replace(/\\/g,"")):ne(n,a,f),ne(e,o,n)),e}function zc(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(", ")}ss.exports={format:zc,parse:jc}});var cn=y((Up,ys)=>{"use strict";var $c=require("events"),Vc=require("https"),Yc=require("http"),ls=require("net"),Jc=require("tls"),{randomBytes:Kc,createHash:Zc}=require("crypto"),{Duplex:Dp,Readable:Fp}=require("stream"),{URL:rr}=require("url"),pe=vt(),Qc=Zn(),Xc=er(),{isBlob:eu}=je(),{BINARY_TYPES:os,CLOSE_TIMEOUT:tu,EMPTY_BUFFER:on,GUID:nu,kForOnEventAttribute:ir,kListener:ru,kStatusCode:iu,kWebSocket:O,NOOP:cs}=oe(),{EventTarget:{addEventListener:su,removeEventListener:ou}}=is(),{format:au,parse:lu}=nr(),{toBuffer:cu}=_t(),us=Symbol("kAborted"),sr=[8,13],ce=["CONNECTING","OPEN","CLOSING","CLOSED"],uu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class t extends $c{constructor(e,n,r){super(),this._binaryType=os[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=on,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]),ds(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){os.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 Qc({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Xc(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",hu),i.on("drain",pu),i.on("error",gu),i.on("message",mu),i.on("ping",yu),i.on("pong",_u),s.onerror=Su,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ps),e.on("data",ln),e.on("end",gs),e.on("error",ms),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[pe.extensionName]&&this._extensions[pe.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){q(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())}),hs(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){or(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||on,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){or(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||on,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){or(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[pe.extensionName]||(i.compress=!1),this._sender.send(e||on,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(x.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(x.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ir])return e[ru];return null},set(e){for(let n of this.listeners(t))if(n[ir]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ir]:!0})}})});x.prototype.addEventListener=su;x.prototype.removeEventListener=ou;ys.exports=x;function ds(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:tu,protocolVersion:sr[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,!sr.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${sr.join(", ")})`);let s;if(e instanceof rr)s=e;else try{s=new rr(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;an(t,p);return}let c=o?443:80,u=Kc(16).toString("base64"),d=o?Vc.request:Yc.request,f=new Set,h;if(i.createConnection=i.createConnection||(o?fu:du),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 pe(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=au({[pe.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!uu.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[m,S]of Object.entries(p))r.headers[m.toLowerCase()]=S}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",()=>{q(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[us]||(g=t._req=null,an(t,p))}),g.on("response",p=>{let m=p.headers.location,S=p.statusCode;if(m&&i.followRedirects&&S>=300&&S<400){if(++t._redirects>i.maxRedirects){q(t,g,"Maximum redirects exceeded");return}g.abort();let J;try{J=new rr(m,e)}catch{let T=new SyntaxError(`Invalid URL: ${m}`);an(t,T);return}ds(t,J,n,r)}else t.emit("unexpected-response",g,p)||q(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,m,S)=>{if(t.emit("upgrade",p),t.readyState!==x.CONNECTING)return;g=t._req=null;let J=p.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){q(t,m,"Invalid Upgrade header");return}let fe=Zc("sha1").update(u+nu).digest("base64");if(p.headers["sec-websocket-accept"]!==fe){q(t,m,"Invalid Sec-WebSocket-Accept header");return}let T=p.headers["sec-websocket-protocol"],L;if(T!==void 0?f.size?f.has(T)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":f.size&&(L="Server sent no subprotocol"),L){q(t,m,L);return}T&&(t._protocol=T);let W=p.headers["sec-websocket-extensions"];if(W!==void 0){if(!h){q(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let te;try{te=lu(W)}catch{q(t,m,"Invalid Sec-WebSocket-Extensions header");return}let He=Object.keys(te);if(He.length!==1||He[0]!==pe.extensionName){q(t,m,"Server indicated an extension that was not requested");return}try{h.accept(te[pe.extensionName])}catch{q(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[pe.extensionName]=h}t.setSocket(m,S,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function an(t,e){t._readyState=x.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function du(t){return t.path=t.socketPath,ls.connect(t)}function fu(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ls.isIP(t.host)?"":t.host),Jc.connect(t)}function q(t,e,n){t._readyState=x.CLOSING;let r=new Error(n);Error.captureStackTrace(r,q),e.setHeader?(e[us]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(an,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function or(t,e,n){if(e){let r=eu(e)?e.size:cu(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ce[t.readyState]})`);process.nextTick(n,r)}}function hu(t,e){let n=this[O];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[O]!==void 0&&(n._socket.removeListener("data",ln),process.nextTick(fs,n._socket),t===1005?n.close():n.close(t,e))}function pu(){let t=this[O];t.isPaused||t._socket.resume()}function gu(t){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",ln),process.nextTick(fs,e._socket),e.close(t[iu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function as(){this[O].emitClose()}function mu(t,e){this[O].emit("message",t,e)}function yu(t){let e=this[O];e._autoPong&&e.pong(t,!this._isServer,cs),e.emit("ping",t)}function _u(t){this[O].emit("pong",t)}function fs(t){t.resume()}function Su(t){let e=this[O];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,hs(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function hs(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ps(){let t=this[O];if(this.removeListener("close",ps),this.removeListener("data",ln),this.removeListener("end",gs),t._readyState=x.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",as),t._receiver.on("finish",as))}function ln(t){this[O]._receiver.write(t)||this.pause()}function gs(){let t=this[O];t._readyState=x.CLOSING,t._receiver.end(),this.end()}function ms(){let t=this[O];this.removeListener("error",ms),this.on("error",cs),t&&(t._readyState=x.CLOSING,this.destroy())}});var ws=y((qp,vs)=>{"use strict";var Hp=cn(),{Duplex:vu}=require("stream");function _s(t){t.emit("close")}function wu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ss(t){this.removeListener("error",Ss),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function bu(t,e){let n=!0,r=new vu({...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(_s,r);return}let o=!1;t.once("error",function(l){o=!0,s(l)}),t.once("close",function(){o||s(i),process.nextTick(_s,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",wu),r.on("error",Ss),r}vs.exports=bu});var Es=y((Wp,bs)=>{"use strict";var{tokenChars:Eu}=je();function xu(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&&Eu[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}bs.exports={parse:xu}});var Ps=y((jp,ks)=>{"use strict";var Tu=require("events"),un=require("http"),{Duplex:Gp}=require("stream"),{createHash:Iu}=require("crypto"),xs=nr(),ke=vt(),Au=Es(),Cu=cn(),{CLOSE_TIMEOUT:ku,GUID:Pu,kWebSocket:Ru}=oe(),Lu=/^[+/0-9A-Za-z]{22}==$/,Ts=0,Is=1,Cs=2,ar=class extends Tu{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ku,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Cu,...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=un.createServer((r,i)=>{let s=un.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=Ou(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=Ts}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===Cs){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xt,this);return}if(e&&this.once("close",e),this._state!==Is)if(this._state=Is,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(xt,this):process.nextTick(xt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{xt(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",As);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Pe(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Pe(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!Lu.test(s)){Pe(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Pe(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Tt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Au.parse(l)}catch{Pe(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 ke(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=xs.parse(u);h[ke.extensionName]&&(f.accept(h[ke.extensionName]),d[ke.extensionName]=f)}catch{Pe(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,m)=>{if(!h)return Tt(n,g||401,p,m);this.completeUpgrade(d,s,c,e,n,r,i)});return}if(!this.options.verifyClient(f))return Tt(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[Ru])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ts)return Tt(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Iu("sha1").update(n+Pu).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[ke.extensionName]){let d=e[ke.extensionName].params,f=xs.format({[ke.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 Sc=Object.create;var Li=Object.defineProperty;var vc=Object.getOwnPropertyDescriptor;var wc=Object.getOwnPropertyNames;var bc=Object.getPrototypeOf,Ec=Object.prototype.hasOwnProperty;var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ic=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wc(e))!Ec.call(t,i)&&i!==n&&Li(t,i,{get:()=>e[i],enumerable:!(r=vc(e,i))||r.enumerable});return t};var qe=(t,e,n)=>(n=t!=null?Sc(bc(t)):{},Ic(e||!t||!t.__esModule?Li(n,"default",{value:t,enumerable:!0}):n,t));var oe=m((Yp,Ni)=>{"use strict";var Mi=["nodebuffer","arraybuffer","fragments"],Oi=typeof Blob<"u";Oi&&Mi.push("blob");Ni.exports={BINARY_TYPES:Mi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Oi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var St=m((Jp,Qt)=>{"use strict";var{EMPTY_BUFFER:Tc}=oe(),jn=Buffer[Symbol.species];function xc(t,e){if(t.length===0)return Tc;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 jn(n.buffer,n.byteOffset,r):n}function Bi(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function Di(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Ac(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function zn(t){if(zn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new jn(t):ArrayBuffer.isView(t)?e=new jn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),zn.readOnly=!1),e}Qt.exports={concat:xc,mask:Bi,toArrayBuffer:Ac,toBuffer:zn,unmask:Di};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Qt.exports.mask=function(e,n,r,i,s){s<48?Bi(e,n,r,i,s):t.mask(e,n,r,i,s)},Qt.exports.unmask=function(e,n){e.length<32?Di(e,n):t.unmask(e,n)}}catch{}});var Hi=m((Kp,Ui)=>{"use strict";var Fi=Symbol("kDone"),$n=Symbol("kRun"),Vn=class{constructor(e){this[Fi]=()=>{this.pending--,this[$n]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[$n]()}[$n](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fi])}}};Ui.exports=Vn});var wt=m((Zp,ji)=>{"use strict";var vt=require("zlib"),qi=St(),Cc=Hi(),{kStatusCode:Wi}=oe(),kc=Buffer[Symbol.species],Rc=Buffer.from([0,0,255,255]),en=Symbol("permessage-deflate"),ae=Symbol("total-length"),We=Symbol("callback"),he=Symbol("buffers"),Ge=Symbol("error"),Xt,Yn=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,!Xt){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Xt=new Cc(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[We];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){Xt.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){Xt.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"?vt.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=vt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[en]=this,this._inflate[ae]=0,this._inflate[he]=[],this._inflate.on("error",Lc),this._inflate.on("data",Gi)}this._inflate[We]=r,this._inflate.write(e),n&&this._inflate.write(Rc),this._inflate.flush(()=>{let s=this._inflate[Ge];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=qi.concat(this._inflate[he],this._inflate[ae]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ae]=0,this._inflate[he]=[],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"?vt.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=vt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ae]=0,this._deflate[he]=[],this._deflate.on("data",Pc)}this._deflate[We]=r,this._deflate.write(e),this._deflate.flush(vt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=qi.concat(this._deflate[he],this._deflate[ae]);n&&(s=new kc(s.buffer,s.byteOffset,s.length-4)),this._deflate[We]=null,this._deflate[ae]=0,this._deflate[he]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};ji.exports=Yn;function Pc(t){this[he].push(t),this[ae]+=t.length}function Gi(t){if(this[ae]+=t.length,this[en]._maxPayload<1||this[ae]<=this[en]._maxPayload){this[he].push(t);return}this[Ge]=new RangeError("Max payload size exceeded"),this[Ge].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ge][Wi]=1009,this.removeListener("data",Gi),this.reset()}function Lc(t){if(this[en]._inflate=null,this[Ge]){this[We](this[Ge]);return}t[Wi]=1007,this[We](t)}});var je=m((Qp,tn)=>{"use strict";var{isUtf8:zi}=require("buffer"),{hasBlob:Mc}=oe(),Oc=[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 Nc(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Jn(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 Bc(t){return Mc&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}tn.exports={isBlob:Bc,isValidStatusCode:Nc,isValidUTF8:Jn,tokenChars:Oc};if(zi)tn.exports.isValidUTF8=function(t){return t.length<24?Jn(t):zi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");tn.exports.isValidUTF8=function(e){return e.length<32?Jn(e):t(e)}}catch{}});var er=m((Xp,Qi)=>{"use strict";var{Writable:Dc}=require("stream"),$i=wt(),{BINARY_TYPES:Fc,EMPTY_BUFFER:Vi,kStatusCode:Uc,kWebSocket:Hc}=oe(),{concat:Kn,toArrayBuffer:qc,unmask:Wc}=St(),{isValidStatusCode:Gc,isValidUTF8:Yi}=je(),nn=Buffer[Symbol.species],G=0,Ji=1,Ki=2,Zi=3,Zn=4,Qn=5,rn=6,Xn=class extends Dc{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Fc[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Hc]=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=G}_write(e,n,r){if(this._opcode===8&&this._state==G)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 nn(r.buffer,r.byteOffset+e,r.length-e),new nn(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 nn(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 G:this.getInfo(e);break;case Ji:this.getPayloadLength16(e);break;case Ki:this.getPayloadLength64(e);break;case Zi:this.getMask();break;case Zn:this.getData(e);break;case Qn:case rn: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[$i.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=Ji:this._payloadLength===127?this._state=Ki: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=Zi:this._state=Zn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Zn}getData(e){let n=Vi;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&&Wc(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Qn,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[$i.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===G&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=G;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=Kn(r,n):this._binaryType==="arraybuffer"?i=qc(Kn(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=G):(this._state=rn,setImmediate(()=>{this.emit("message",i,!0),this._state=G,this.startLoop(e)}))}else{let i=Kn(r,n);if(!this._skipUTF8Validation&&!Yi(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Qn||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=G):(this._state=rn,setImmediate(()=>{this.emit("message",i,!1),this._state=G,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Vi),this.end();else{let r=e.readUInt16BE(0);if(!Gc(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new nn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Yi(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=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=G):(this._state=rn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=G,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[Uc]=i,o}};Qi.exports=Xn});var rr=m((tg,ts)=>{"use strict";var{Duplex:eg}=require("stream"),{randomFillSync:jc}=require("crypto"),Xi=wt(),{EMPTY_BUFFER:zc,kWebSocket:$c,NOOP:Vc}=oe(),{isBlob:ze,isValidStatusCode:Yc}=je(),{mask:es,toBuffer:xe}=St(),j=Symbol("kByteLength"),Jc=Buffer.alloc(4),sn=8*1024,Ae,$e=sn,K=0,Kc=1,Zc=2,tr=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=K,this.onerror=Vc,this[$c]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||Jc,n.generateMask?n.generateMask(r):($e===sn&&(Ae===void 0&&(Ae=Buffer.alloc(sn)),jc(Ae,0,sn),$e=0),r[0]=Ae[$e++],r[1]=Ae[$e++],r[2]=Ae[$e++],r[3]=Ae[$e++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[j]!==void 0?a=n[j]:(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?(es(e,r,c,s,a),[c]):(es(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,i){let s;if(e===void 0)s=zc;else{if(typeof e!="number"||!Yc(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={[j]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==K?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):ze(e)?(i=e.size,s=!1):(e=xe(e),i=e.length,s=xe.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==K?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):ze(e)?(i=e.size,s=!1):(e=xe(e),i=e.length,s=xe.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==K?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[Xi.extensionName],s=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ze(e)?(a=e.size,l=!1):(e=xe(e),a=e.length,l=xe.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={[j]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:o};ze(e)?this._state!==K?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==K?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[j],this._state=Zc,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(nr,this,a,i);return}this._bufferedBytes-=r[j];let o=xe(s);n?this.dispatch(o,n,r,i):(this._state=K,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(Qc,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[Xi.extensionName];this._bufferedBytes+=r[j],this._state=Kc,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");nr(this,l,i);return}this._bufferedBytes-=r[j],this._state=K,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===K&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][j],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][j],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)}};ts.exports=tr;function nr(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 Qc(t,e,n){nr(t,e,n),t.onerror(e)}});var us=m((ng,cs)=>{"use strict";var{kForOnEventAttribute:bt,kListener:ir}=oe(),ns=Symbol("kCode"),rs=Symbol("kData"),is=Symbol("kError"),ss=Symbol("kMessage"),os=Symbol("kReason"),Ve=Symbol("kTarget"),as=Symbol("kType"),ls=Symbol("kWasClean"),le=class{constructor(e){this[Ve]=null,this[as]=e}get target(){return this[Ve]}get type(){return this[as]}};Object.defineProperty(le.prototype,"target",{enumerable:!0});Object.defineProperty(le.prototype,"type",{enumerable:!0});var Ce=class extends le{constructor(e,n={}){super(e),this[ns]=n.code===void 0?0:n.code,this[os]=n.reason===void 0?"":n.reason,this[ls]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[ns]}get reason(){return this[os]}get wasClean(){return this[ls]}};Object.defineProperty(Ce.prototype,"code",{enumerable:!0});Object.defineProperty(Ce.prototype,"reason",{enumerable:!0});Object.defineProperty(Ce.prototype,"wasClean",{enumerable:!0});var Ye=class extends le{constructor(e,n={}){super(e),this[is]=n.error===void 0?null:n.error,this[ss]=n.message===void 0?"":n.message}get error(){return this[is]}get message(){return this[ss]}};Object.defineProperty(Ye.prototype,"error",{enumerable:!0});Object.defineProperty(Ye.prototype,"message",{enumerable:!0});var Et=class extends le{constructor(e,n={}){super(e),this[rs]=n.data===void 0?null:n.data}get data(){return this[rs]}};Object.defineProperty(Et.prototype,"data",{enumerable:!0});var Xc={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[bt]&&i[ir]===e&&!i[bt])return;let r;if(t==="message")r=function(s,o){let a=new Et("message",{data:o?s:s.toString()});a[Ve]=this,on(e,this,a)};else if(t==="close")r=function(s,o){let a=new Ce("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ve]=this,on(e,this,a)};else if(t==="error")r=function(s){let o=new Ye("error",{error:s,message:s.message});o[Ve]=this,on(e,this,o)};else if(t==="open")r=function(){let s=new le("open");s[Ve]=this,on(e,this,s)};else return;r[bt]=!!n[bt],r[ir]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ir]===e&&!n[bt]){this.removeListener(t,n);break}}};cs.exports={CloseEvent:Ce,ErrorEvent:Ye,Event:le,EventTarget:Xc,MessageEvent:Et};function on(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var sr=m((rg,ds)=>{"use strict";var{tokenChars:It}=je();function ne(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function eu(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&&It[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?(ne(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&&It[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),ne(n,t.slice(l,u),!0),c===44&&(ne(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(It[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),i=!1}else if(s)if(It[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&&It[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),ne(n,a,h),c===44&&(ne(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?ne(e,f,n):(a===void 0?ne(n,f,!0):r?ne(n,a,f.replace(/\\/g,"")):ne(n,a,f),ne(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(", ")}ds.exports={format:tu,parse:eu}});var un=m((og,Es)=>{"use strict";var nu=require("events"),ru=require("https"),iu=require("http"),ps=require("net"),su=require("tls"),{randomBytes:ou,createHash:au}=require("crypto"),{Duplex:ig,Readable:sg}=require("stream"),{URL:or}=require("url"),pe=wt(),lu=er(),cu=rr(),{isBlob:uu}=je(),{BINARY_TYPES:fs,CLOSE_TIMEOUT:du,EMPTY_BUFFER:an,GUID:fu,kForOnEventAttribute:ar,kListener:hu,kStatusCode:pu,kWebSocket:M,NOOP:gs}=oe(),{EventTarget:{addEventListener:gu,removeEventListener:mu}}=us(),{format:yu,parse:_u}=sr(),{toBuffer:Su}=St(),ms=Symbol("kAborted"),lr=[8,13],ce=["CONNECTING","OPEN","CLOSING","CLOSED"],vu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends nu{constructor(e,n,r){super(),this._binaryType=fs[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=an,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]),ys(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){fs.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 lu({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new cu(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[M]=this,s[M]=this,e[M]=this,i.on("conclude",Eu),i.on("drain",Iu),i.on("error",Tu),i.on("message",xu),i.on("ping",Au),i.on("pong",Cu),s.onerror=ku,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",vs),e.on("data",cn),e.on("end",ws),e.on("error",bs),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[pe.extensionName]&&this._extensions[pe.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){q(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())}),Ss(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){cr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||an,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){cr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||an,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){cr(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[pe.extensionName]||(i.compress=!1),this._sender.send(e||an,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(T,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:ce.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:ce.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:ce.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:ce.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(T.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(T.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ar])return e[hu];return null},set(e){for(let n of this.listeners(t))if(n[ar]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ar]:!0})}})});T.prototype.addEventListener=gu;T.prototype.removeEventListener=mu;Es.exports=T;function ys(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:du,protocolVersion:lr[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,!lr.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${lr.join(", ")})`);let s;if(e instanceof or)s=e;else try{s=new or(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;ln(t,p);return}let c=o?443:80,u=ou(16).toString("base64"),d=o?ru.request:iu.request,f=new Set,h;if(i.createConnection=i.createConnection||(o?bu:wu),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 pe(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=yu({[pe.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,S]of Object.entries(p))r.headers[y.toLowerCase()]=S}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",()=>{q(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[ms]||(g=t._req=null,ln(t,p))}),g.on("response",p=>{let y=p.headers.location,S=p.statusCode;if(y&&i.followRedirects&&S>=300&&S<400){if(++t._redirects>i.maxRedirects){q(t,g,"Maximum redirects exceeded");return}g.abort();let J;try{J=new or(y,e)}catch{let x=new SyntaxError(`Invalid URL: ${y}`);ln(t,x);return}ys(t,J,n,r)}else t.emit("unexpected-response",g,p)||q(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,y,S)=>{if(t.emit("upgrade",p),t.readyState!==T.CONNECTING)return;g=t._req=null;let J=p.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){q(t,y,"Invalid Upgrade header");return}let fe=au("sha1").update(u+fu).digest("base64");if(p.headers["sec-websocket-accept"]!==fe){q(t,y,"Invalid Sec-WebSocket-Accept header");return}let x=p.headers["sec-websocket-protocol"],L;if(x!==void 0?f.size?f.has(x)||(L="Server sent an invalid subprotocol"):L="Server sent a subprotocol but none was requested":f.size&&(L="Server sent no subprotocol"),L){q(t,y,L);return}x&&(t._protocol=x);let W=p.headers["sec-websocket-extensions"];if(W!==void 0){if(!h){q(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let te;try{te=_u(W)}catch{q(t,y,"Invalid Sec-WebSocket-Extensions header");return}let He=Object.keys(te);if(He.length!==1||He[0]!==pe.extensionName){q(t,y,"Server indicated an extension that was not requested");return}try{h.accept(te[pe.extensionName])}catch{q(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[pe.extensionName]=h}t.setSocket(y,S,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function ln(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function wu(t){return t.path=t.socketPath,ps.connect(t)}function bu(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ps.isIP(t.host)?"":t.host),su.connect(t)}function q(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,q),e.setHeader?(e[ms]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ln,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function cr(t,e,n){if(e){let r=uu(e)?e.size:Su(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ce[t.readyState]})`);process.nextTick(n,r)}}function Eu(t,e){let n=this[M];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[M]!==void 0&&(n._socket.removeListener("data",cn),process.nextTick(_s,n._socket),t===1005?n.close():n.close(t,e))}function Iu(){let t=this[M];t.isPaused||t._socket.resume()}function Tu(t){let e=this[M];e._socket[M]!==void 0&&(e._socket.removeListener("data",cn),process.nextTick(_s,e._socket),e.close(t[pu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function hs(){this[M].emitClose()}function xu(t,e){this[M].emit("message",t,e)}function Au(t){let e=this[M];e._autoPong&&e.pong(t,!this._isServer,gs),e.emit("ping",t)}function Cu(t){this[M].emit("pong",t)}function _s(t){t.resume()}function ku(t){let e=this[M];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,Ss(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ss(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function vs(){let t=this[M];if(this.removeListener("close",vs),this.removeListener("data",cn),this.removeListener("end",ws),t._readyState=T.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[M]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",hs),t._receiver.on("finish",hs))}function cn(t){this[M]._receiver.write(t)||this.pause()}function ws(){let t=this[M];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function bs(){let t=this[M];this.removeListener("error",bs),this.on("error",gs),t&&(t._readyState=T.CLOSING,this.destroy())}});var As=m((lg,xs)=>{"use strict";var ag=un(),{Duplex:Ru}=require("stream");function Is(t){t.emit("close")}function Pu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ts(t){this.removeListener("error",Ts),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Lu(t,e){let n=!0,r=new Ru({...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(Is,r);return}let o=!1;t.once("error",function(l){o=!0,s(l)}),t.once("close",function(){o||s(i),process.nextTick(Is,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",Pu),r.on("error",Ts),r}xs.exports=Lu});var ks=m((cg,Cs)=>{"use strict";var{tokenChars:Mu}=je();function Ou(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&&Mu[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}Cs.exports={parse:Ou}});var Bs=m((dg,Ns)=>{"use strict";var Nu=require("events"),dn=require("http"),{Duplex:ug}=require("stream"),{createHash:Bu}=require("crypto"),Rs=sr(),ke=wt(),Du=ks(),Fu=un(),{CLOSE_TIMEOUT:Uu,GUID:Hu,kWebSocket:qu}=oe(),Wu=/^[+/0-9A-Za-z]{22}==$/,Ps=0,Ls=1,Os=2,ur=class extends Nu{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Uu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Fu,...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=dn.createServer((r,i)=>{let s=dn.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=Gu(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=Ps}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===Os){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Tt,this);return}if(e&&this.once("close",e),this._state!==Ls)if(this._state=Ls,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(Tt,this):process.nextTick(Tt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Tt(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",Ms);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Re(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Re(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!Wu.test(s)){Re(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Re(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){xt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Du.parse(l)}catch{Re(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 ke(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=Rs.parse(u);h[ke.extensionName]&&(f.accept(h[ke.extensionName]),d[ke.extensionName]=f)}catch{Re(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 xt(n,g||401,p,y);this.completeUpgrade(d,s,c,e,n,r,i)});return}if(!this.options.verifyClient(f))return xt(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[qu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ps)return xt(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bu("sha1").update(n+Hu).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[ke.extensionName]){let d=e[ke.extensionName].params,f=Rs.format({[ke.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,i),s.write(c.concat(`\r
|
|
2
2
|
`).join(`\r
|
|
3
|
-
`)),s.removeListener("error",
|
|
3
|
+
`)),s.removeListener("error",Ms),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(Tt,this)})),a(u,i)}};Ns.exports=ur;function Gu(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 Tt(t){t._state=Os,t.emit("close")}function Ms(){this.destroy()}function xt(t,e,n,r){n=n||dn.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} ${dn.STATUS_CODES[e]}\r
|
|
4
4
|
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
5
5
|
`)+`\r
|
|
6
6
|
\r
|
|
7
|
-
`+n)}function
|
|
8
|
-
]))+`;ue.KANJI=new RegExp(
|
|
9
|
-
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};
|
|
10
|
-
Suggested mode is: `+
|
|
7
|
+
`+n)}function Re(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,Re),t.emit("wsClientError",o,n,e)}else xt(n,r,i,s)}});var fr=m((hg,Ds)=>{Ds.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ge=m(Pe=>{var hr,Yu=[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];Pe.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};Pe.getSymbolTotalCodewords=function(e){return Yu[e]};Pe.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Pe.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');hr=e};Pe.isKanjiModeEnabled=function(){return typeof hr<"u"};Pe.toSJIS=function(e){return hr(e)}});var fn=m(z=>{z.L={bit:1};z.M={bit:0};z.Q={bit:3};z.H={bit:2};function Ju(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return z.L;case"m":case"medium":return z.M;case"q":case"quartile":return z.Q;case"h":case"high":return z.H;default:throw new Error("Unknown EC Level: "+t)}}z.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};z.from=function(e,n){if(z.isValid(e))return e;try{return Ju(e)}catch{return n}}});var Hs=m((mg,Us)=>{function Fs(){this.buffer=[],this.length=0}Fs.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++}};Us.exports=Fs});var Ws=m((yg,qs)=>{function At(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)}At.prototype.set=function(t,e,n,r){let i=t*this.size+e;this.data[i]=n,r&&(this.reservedBit[i]=!0)};At.prototype.get=function(t,e){return this.data[t*this.size+e]};At.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};At.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};qs.exports=At});var Gs=m(hn=>{var Ku=ge().getSymbolSize;hn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Ku(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()};hn.getPositions=function(e){let n=[],r=hn.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 $s=m(zs=>{var Zu=ge().getSymbolSize,js=7;zs.getPositions=function(e){let n=Zu(e);return[[0,0],[n-js,0],[0,n-js]]}});var Vs=m(I=>{I.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Le={N1:3,N2:3,N3:40,N4:10};I.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};I.from=function(e){return I.isValid(e)?parseInt(e,10):void 0};I.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+=Le.N1+(i-5)),o=u,i=1),u=e.get(c,l),u===a?s++:(s>=5&&(r+=Le.N1+(s-5)),a=u,s=1)}i>=5&&(r+=Le.N1+(i-5)),s>=5&&(r+=Le.N1+(s-5))}return r};I.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*Le.N2};I.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*Le.N3};I.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)*Le.N4};function Qu(t,e,n){switch(t){case I.Patterns.PATTERN000:return(e+n)%2===0;case I.Patterns.PATTERN001:return e%2===0;case I.Patterns.PATTERN010:return n%3===0;case I.Patterns.PATTERN011:return(e+n)%3===0;case I.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case I.Patterns.PATTERN101:return e*n%2+e*n%3===0;case I.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case I.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}I.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,Qu(e,s,i))};I.getBestMask=function(e,n){let r=Object.keys(I.Patterns).length,i=0,s=1/0;for(let o=0;o<r;o++){n(o),I.applyMask(o,e);let a=I.getPenaltyN1(e)+I.getPenaltyN2(e)+I.getPenaltyN3(e)+I.getPenaltyN4(e);I.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var gr=m(pr=>{var me=fn(),pn=[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],gn=[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];pr.getBlocksCount=function(e,n){switch(n){case me.L:return pn[(e-1)*4+0];case me.M:return pn[(e-1)*4+1];case me.Q:return pn[(e-1)*4+2];case me.H:return pn[(e-1)*4+3];default:return}};pr.getTotalCodewordsCount=function(e,n){switch(n){case me.L:return gn[(e-1)*4+0];case me.M:return gn[(e-1)*4+1];case me.Q:return gn[(e-1)*4+2];case me.H:return gn[(e-1)*4+3];default:return}}});var Ys=m(yn=>{var Ct=new Uint8Array(512),mn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Ct[n]=e,mn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Ct[n]=Ct[n-255]})();yn.log=function(e){if(e<1)throw new Error("log("+e+")");return mn[e]};yn.exp=function(e){return Ct[e]};yn.mul=function(e,n){return e===0||n===0?0:Ct[mn[e]+mn[n]]}});var Js=m(kt=>{var mr=Ys();kt.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]^=mr.mul(e[i],n[s]);return r};kt.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]^=mr.mul(n[o],i);let s=0;for(;s<r.length&&r[s]===0;)s++;r=r.slice(s)}return r};kt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=kt.mul(n,new Uint8Array([1,mr.exp(r)]));return n}});var Qs=m((Ig,Zs)=>{var Ks=Js();function yr(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}yr.prototype.initialize=function(e){this.degree=e,this.genPoly=Ks.generateECPolynomial(this.degree)};yr.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=Ks.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};Zs.exports=yr});var _r=m(Xs=>{Xs.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Sr=m(ue=>{var eo="[0-9]+",Xu="[A-Z $%*+\\-./:]+",Rt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Rt=Rt.replace(/u/g,"\\u");var ed="(?:(?![A-Z0-9 $%*+\\-./:]|"+Rt+`)(?:.|[\r
|
|
8
|
+
]))+`;ue.KANJI=new RegExp(Rt,"g");ue.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ue.BYTE=new RegExp(ed,"g");ue.NUMERIC=new RegExp(eo,"g");ue.ALPHANUMERIC=new RegExp(Xu,"g");var td=new RegExp("^"+Rt+"$"),nd=new RegExp("^"+eo+"$"),rd=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ue.testKanji=function(e){return td.test(e)};ue.testNumeric=function(e){return nd.test(e)};ue.testAlphanumeric=function(e){return rd.test(e)}});var ye=m(C=>{var id=_r(),vr=Sr();C.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};C.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};C.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};C.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};C.MIXED={bit:-1};C.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!id.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};C.getBestModeForData=function(e){return vr.testNumeric(e)?C.NUMERIC:vr.testAlphanumeric(e)?C.ALPHANUMERIC:vr.testKanji(e)?C.KANJI:C.BYTE};C.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};C.isValid=function(e){return e&&e.bit&&e.ccBits};function sd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return C.NUMERIC;case"alphanumeric":return C.ALPHANUMERIC;case"kanji":return C.KANJI;case"byte":return C.BYTE;default:throw new Error("Unknown mode: "+t)}}C.from=function(e,n){if(C.isValid(e))return e;try{return sd(e)}catch{return n}}});var so=m(Me=>{var _n=ge(),od=gr(),to=fn(),_e=ye(),wr=_r(),ro=7973,no=_n.getBCHDigit(ro);function ad(t,e,n){for(let r=1;r<=40;r++)if(e<=Me.getCapacity(r,n,t))return r}function io(t,e){return _e.getCharCountIndicator(t,e)+4}function ld(t,e){let n=0;return t.forEach(function(r){let i=io(r.mode,e);n+=i+r.getBitsLength()}),n}function cd(t,e){for(let n=1;n<=40;n++)if(ld(t,n)<=Me.getCapacity(n,e,_e.MIXED))return n}Me.from=function(e,n){return wr.isValid(e)?parseInt(e,10):n};Me.getCapacity=function(e,n,r){if(!wr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=_e.BYTE);let i=_n.getSymbolTotalCodewords(e),s=od.getTotalCodewordsCount(e,n),o=(i-s)*8;if(r===_e.MIXED)return o;let a=o-io(r,e);switch(r){case _e.NUMERIC:return Math.floor(a/10*3);case _e.ALPHANUMERIC:return Math.floor(a/11*2);case _e.KANJI:return Math.floor(a/13);case _e.BYTE:default:return Math.floor(a/8)}};Me.getBestVersionForData=function(e,n){let r,i=to.from(n,to.M);if(Array.isArray(e)){if(e.length>1)return cd(e,i);if(e.length===0)return 1;r=e[0]}else r=e;return ad(r.mode,r.getLength(),i)};Me.getEncodedBits=function(e){if(!wr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;_n.getBCHDigit(n)-no>=0;)n^=ro<<_n.getBCHDigit(n)-no;return e<<12|n}});var co=m(lo=>{var br=ge(),ao=1335,ud=21522,oo=br.getBCHDigit(ao);lo.getEncodedBits=function(e,n){let r=e.bit<<3|n,i=r<<10;for(;br.getBCHDigit(i)-oo>=0;)i^=ao<<br.getBCHDigit(i)-oo;return(r<<10|i)^ud}});var fo=m((Rg,uo)=>{var dd=ye();function Je(t){this.mode=dd.NUMERIC,this.data=t.toString()}Je.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Je.prototype.getLength=function(){return this.data.length};Je.prototype.getBitsLength=function(){return Je.getBitsLength(this.data.length)};Je.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))};uo.exports=Je});var po=m((Pg,ho)=>{var fd=ye(),Er=["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 Ke(t){this.mode=fd.ALPHANUMERIC,this.data=t}Ke.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Ke.prototype.getLength=function(){return this.data.length};Ke.prototype.getBitsLength=function(){return Ke.getBitsLength(this.data.length)};Ke.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Er.indexOf(this.data[n])*45;r+=Er.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Er.indexOf(this.data[n]),6)};ho.exports=Ke});var mo=m((Lg,go)=>{var hd=ye();function Ze(t){this.mode=hd.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Ze.getBitsLength=function(e){return e*8};Ze.prototype.getLength=function(){return this.data.length};Ze.prototype.getBitsLength=function(){return Ze.getBitsLength(this.data.length)};Ze.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};go.exports=Ze});var _o=m((Mg,yo)=>{var pd=ye(),gd=ge();function Qe(t){this.mode=pd.KANJI,this.data=t}Qe.getBitsLength=function(e){return e*13};Qe.prototype.getLength=function(){return this.data.length};Qe.prototype.getBitsLength=function(){return Qe.getBitsLength(this.data.length)};Qe.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)}};yo.exports=Qe});var So=m((Og,Ir)=>{"use strict";var Pt={single_source_shortest_paths:function(t,e,n){var r={},i={};i[e]=0;var s=Pt.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=Pt.single_source_shortest_paths(t,e,n);return Pt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Pt.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 Ir<"u"&&(Ir.exports=Pt)});var Ao=m(Xe=>{var b=ye(),bo=fo(),Eo=po(),Io=mo(),To=_o(),Lt=Sr(),Sn=ge(),md=So();function vo(t){return unescape(encodeURIComponent(t)).length}function Mt(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 xo(t){let e=Mt(Lt.NUMERIC,b.NUMERIC,t),n=Mt(Lt.ALPHANUMERIC,b.ALPHANUMERIC,t),r,i;return Sn.isKanjiModeEnabled()?(r=Mt(Lt.BYTE,b.BYTE,t),i=Mt(Lt.KANJI,b.KANJI,t)):(r=Mt(Lt.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 Tr(t,e){switch(e){case b.NUMERIC:return bo.getBitsLength(t);case b.ALPHANUMERIC:return Eo.getBitsLength(t);case b.KANJI:return To.getBitsLength(t);case b.BYTE:return Io.getBitsLength(t)}}function yd(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 _d(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:vo(r.data)}]);break;case b.BYTE:e.push([{data:r.data,mode:b.BYTE,length:vo(r.data)}])}}return e}function Sd(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]=Tr(n[f].lastCount+c.length,c.mode)-Tr(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Tr(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 wo(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&&!Sn.isKanjiModeEnabled()&&(n=b.BYTE),n){case b.NUMERIC:return new bo(t);case b.ALPHANUMERIC:return new Eo(t);case b.KANJI:return new To(t);case b.BYTE:return new Io(t)}}Xe.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(wo(r,null)):r.data&&n.push(wo(r.data,r.mode)),n},[])};Xe.fromString=function(e,n){let r=xo(e,Sn.isKanjiModeEnabled()),i=_d(r),s=Sd(i,n),o=md.find_path(s.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(s.table[o[l]].node);return Xe.fromArray(yd(a))};Xe.rawSplit=function(e){return Xe.fromArray(xo(e,Sn.isKanjiModeEnabled()))}});var Pr=m(Co=>{var wn=ge(),xr=fn(),vd=Hs(),wd=Ws(),bd=Gs(),Ed=$s(),kr=Vs(),Rr=gr(),Id=Qs(),vn=so(),Td=co(),xd=ye(),Ar=Ao();function Ad(t,e){let n=t.size,r=Ed.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 Cd(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 kd(t,e){let n=bd.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 Rd(t,e){let n=t.size,r=vn.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 Cr(t,e,n){let r=t.size,i=Td.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 Pd(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 Ld(t,e,n){let r=new vd;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),xd.getCharCountIndicator(l.mode,t)),l.write(r)});let i=wn.getSymbolTotalCodewords(t),s=Rr.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 Md(r,t,e)}function Md(t,e,n){let r=wn.getSymbolTotalCodewords(e),i=Rr.getTotalCodewordsCount(e,n),s=r-i,o=Rr.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 Id(f),g=0,p=new Array(o),y=new Array(o),S=0,J=new Uint8Array(t.buffer);for(let te=0;te<o;te++){let He=te<l?u:d;p[te]=J.slice(g,g+He),y[te]=h.encode(p[te]),g+=He,S=Math.max(S,He)}let fe=new Uint8Array(r),x=0,L,W;for(L=0;L<S;L++)for(W=0;W<o;W++)L<p[W].length&&(fe[x++]=p[W][L]);for(L=0;L<f;L++)for(W=0;W<o;W++)fe[x++]=y[W][L];return fe}function Od(t,e,n,r){let i;if(Array.isArray(t))i=Ar.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Ar.rawSplit(t);c=vn.getBestVersionForData(u,n)}i=Ar.fromString(t,c||40)}else throw new Error("Invalid data");let s=vn.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(`
|
|
11
11
|
The chosen QR Code version cannot contain this amount of data.
|
|
12
12
|
Minimum version required to store current data is: `+s+`.
|
|
13
|
-
`);let o=bd(e,n,i),a=vn.getSymbolSize(e),l=new dd(a);return yd(l,e),_d(l),Sd(l,e),Tr(l,n,0),e>=7&&vd(l,e),wd(l,o),isNaN(r)&&(r=Ir.getBestMask(l,Tr.bind(null,l,n))),Ir.applyMask(r,l),Tr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:i}}bo.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Er.M,i,s;return typeof n<"u"&&(r=Er.from(n.errorCorrectionLevel,Er.M),i=Sn.from(n.version),s=Ir.from(n.maskPattern),n.toSJISFunc&&vn.setToSJISFunction(n.toSJISFunc)),xd(e,i,r,s)}});var kr=y((mg,xo)=>{"use strict";var Td=require("util"),Eo=require("stream"),Z=xo.exports=function(){Eo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Td.inherits(Z,Eo);Z.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))};Z.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};Z.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()))};Z.prototype.destroySoon=Z.prototype.end;Z.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Z.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Z.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))};Z.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)};Z.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 Rr=y(Pr=>{"use strict";var Se=[{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]}];Pr.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<Se.length;a++){let l=Se[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};Pr.getInterlaceIterator=function(t){return function(e,n,r){let i=e%Se[r].x.length,s=(e-i)/Se[r].x.length*8+Se[r].x[i],o=n%Se[r].y.length,a=(n-o)/Se[r].y.length*8+Se[r].y[o];return s*4+a*t*4}}});var Lr=y((_g,To)=>{"use strict";To.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 Or=y((Sg,Ao)=>{"use strict";var Id=Rr(),Ad=Lr();function Io(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var et=Ao.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=Id.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Io(a[l].width,s,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Io(n,s,o),height:r,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};et.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};et.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}};et.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}};et.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}};et.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=Ad(c,l,u);e[o]=a+d}};et.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 Po=y((vg,ko)=>{"use strict";var Cd=require("util"),Co=kr(),kd=Or(),Pd=ko.exports=function(t){Co.call(this);let e=[],n=this;this._filter=new kd(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Cd.inherits(Pd,Co)});var tt=y((wg,Ro)=>{"use strict";Ro.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 Br=y((bg,Lo)=>{"use strict";var Mr=[];(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;Mr[t]=e}})();var Nr=Lo.exports=function(){this._crc=-1};Nr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Mr[(this._crc^t[e])&255]^this._crc>>>8;return!0};Nr.prototype.crc32=function(){return this._crc^-1};Nr.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Mr[(e^t[n])&255]^e>>>8;return e^-1}});var Dr=y((Eg,Oo)=>{"use strict";var R=tt(),Rd=Br(),M=Oo.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[R.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[R.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[R.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[R.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[R.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[R.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(R.PNG_SIGNATURE.length,this._parseSignature.bind(this))};M.prototype._parseSignature=function(t){let e=R.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!==R.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Rd,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 R.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=R.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(i&R.COLORTYPE_PALETTE),color:!!(i&R.COLORTYPE_COLOR),alpha:!!(i&R.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===R.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===R.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===R.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)/R.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===R.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 Fr=y(No=>{"use strict";var Mo=Rr(),Ld=[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]}],Od=[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 Md(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 Nd(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);Ld[r](e,i,d,s),s+=r}return s}function Bd(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);Od[r](e,d,f,s)}i.resetAfterLine()}}No.dataToBitMap=function(t,e){let n=e.width,r=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=Md(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=Mo.getImagePasses(n,r),f=Mo.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=Nd(d[h],l,f,s,t,u):Bd(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 Ur=y((Tg,Bo)=>{"use strict";function Dd(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 Fd(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 Ud(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}}Bo.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?Dd(t,l,r,i,a):(o&&Fd(t,l,r,i,o),n!==8&&(n===16&&(l=Buffer.alloc(r*i*4)),Ud(t,l,r,i,n))),l}});var Uo=y((Ig,Fo)=>{"use strict";var Hd=require("util"),Hr=require("zlib"),Do=kr(),qd=Po(),Wd=Dr(),Gd=Fr(),jd=Ur(),re=Fo.exports=function(t){Do.call(this),this._parser=new Wd(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()};Hd.inherits(re,Do);re.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};re.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Hr.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,Hr.Z_MIN_CHUNK);this._inflate=Hr.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)};re.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new qd(this._bitmapInfo)};re.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};re.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};re.prototype._simpleTransparency=function(){this._metaData.alpha=!0};re.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};re.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};re.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Gd.dataToBitMap(t,this._bitmapInfo);e=jd(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var qo=y((Ag,Ho)=>{"use strict";var $=tt();Ho.exports=function(t,e,n,r){let i=[$.COLORTYPE_COLOR_ALPHA,$.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=$.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=$.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,m,S=o;switch(r.inputColorType){case $.COLORTYPE_COLOR_ALPHA:S=s[u+3],g=s[u],p=s[u+1],m=s[u+2];break;case $.COLORTYPE_COLOR:g=s[u],p=s[u+1],m=s[u+2];break;case $.COLORTYPE_ALPHA:S=s[u+1],g=s[u],p=g,m=g;break;case $.COLORTYPE_GRAYSCALE:g=s[u],p=g,m=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(i||(S/=o,g=Math.min(Math.max(Math.round((1-S)*f.red+S*g),0),o),p=Math.min(Math.max(Math.round((1-S)*f.green+S*p),0),o),m=Math.min(Math.max(Math.round((1-S)*f.blue+S*m),0),o))),{red:g,green:p,blue:m,alpha:S}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let m=h(s,u);switch(r.colorType){case $.COLORTYPE_COLOR_ALPHA:case $.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,i&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),i&&c.writeUInt16BE(m.alpha,d+6));break;case $.COLORTYPE_ALPHA:case $.COLORTYPE_GRAYSCALE:{let S=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=S,i&&(c[d+1]=m.alpha)):(c.writeUInt16BE(S,d),i&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var jo=y((Cg,Go)=>{"use strict";var Wo=Lr();function zd(t,e,n,r,i){for(let s=0;s<n;s++)r[i+s]=t[e+s]}function $d(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++)r+=Math.abs(t[s]);return r}function Vd(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 Yd(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 Jd(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 Kd(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 Zd(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 Qd(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 Xd(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]-Wo(a,l,c);r[i+o]=u}}function ef(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]-Wo(o,a,l);i+=Math.abs(c)}return i}var tf={0:zd,1:Vd,2:Jd,3:Zd,4:Xd},nf={0:$d,1:Yd,2:Kd,3:Qd,4:ef};Go.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=nf[s[h]](t,l,o,i);g<f&&(u=s[h],f=g)}}c[a]=u,a++,tf[u](t,l,o,c,a,i),a+=o,l+=o}return c}});var qr=y((kg,zo)=>{"use strict";var B=tt(),rf=Br(),sf=qo(),of=jo(),af=require("zlib"),ve=zo.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||af.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:B.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:B.COLORTYPE_COLOR_ALPHA,[B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.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")};ve.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ve.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ve.prototype.filterData=function(t,e,n){let r=sf(t,e,n,this._options),i=B.COLORTYPE_TO_BPP_MAP[this._options.colorType];return of(r,e,n,this._options,i)};ve.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(rf.crc32(r.slice(4,r.length-4)),r.length-4),r};ve.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*B.GAMMA_DIVISION),0),this._packChunk(B.TYPE_gAMA,e)};ve.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(B.TYPE_IHDR,n)};ve.prototype.packIDAT=function(t){return this._packChunk(B.TYPE_IDAT,t)};ve.prototype.packIEND=function(){return this._packChunk(B.TYPE_IEND,null)}});var Jo=y((Pg,Yo)=>{"use strict";var lf=require("util"),$o=require("stream"),cf=tt(),uf=qr(),Vo=Yo.exports=function(t){$o.call(this);let e=t||{};this._packer=new uf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};lf.inherits(Vo,$o);Vo.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(cf.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 ta=y((Ot,ea)=>{"use strict";var Ko=require("assert").ok,nt=require("zlib"),df=require("util"),Zo=require("buffer").kMaxLength;function Me(t){if(!(this instanceof Me))return new Me(t);t&&t.chunkSize<nt.Z_MIN_CHUNK&&(t.chunkSize=nt.Z_MIN_CHUNK),nt.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 ff(t){return new Me(t)}function Qo(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Me.prototype._processChunk=function(t,e,n){if(typeof n=="function")return nt.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 m=s-p;if(Ko(m>=0,"have should not go down"),m>0){let S=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.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}Ko(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>=Zo)throw Qo(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Zo.toString(16)+" bytes");let h=Buffer.concat(l,c);return Qo(this),h};df.inherits(Me,nt.Inflate);function hf(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=nt.Z_FINISH),t._processChunk(e,n)}function Xo(t,e){return hf(new Me(e),t)}ea.exports=Ot=Xo;Ot.Inflate=Me;Ot.createInflate=ff;Ot.inflateSync=Xo});var Wr=y((Rg,ra)=>{"use strict";var na=ra.exports=function(t){this._buffer=t,this._reads=[]};na.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};na.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 sa=y(ia=>{"use strict";var pf=Wr(),gf=Or();ia.process=function(t,e){let n=[],r=new pf(t);return new gf(e,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var ca=y((Og,la)=>{"use strict";var oa=!0,aa=require("zlib"),mf=ta();aa.deflateSync||(oa=!1);var yf=Wr(),_f=sa(),Sf=Dr(),vf=Fr(),wf=Ur();la.exports=function(t,e){if(!oa)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(T){n=T}let i;function s(T){i=T}function o(T){i.transColor=T}function a(T){i.palette=T}function l(){i.alpha=!0}let c;function u(T){c=T}let d=[];function f(T){d.push(T)}let h=new yf(t);if(new Sf(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 m;if(i.interlace)m=aa.inflateSync(p);else{let L=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;m=mf(p,{chunkSize:L,maxLength:L})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let S=_f.process(m,i);p=null;let J=vf.dataToBitMap(S,i);S=null;let fe=wf(J,i);return i.data=fe,i.gamma=c||0,i}});var ha=y((Mg,fa)=>{"use strict";var ua=!0,da=require("zlib");da.deflateSync||(ua=!1);var bf=tt(),Ef=qr();fa.exports=function(t,e){if(!ua)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 Ef(n),i=[];i.push(Buffer.from(bf.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=da.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 pa=y(Gr=>{"use strict";var xf=ca(),Tf=ha();Gr.read=function(t,e){return xf(t,e||{})};Gr.write=function(t,e){return Tf(t,e)}});var ya=y(ma=>{"use strict";var If=require("util"),ga=require("stream"),Af=Uo(),Cf=Jo(),kf=pa(),F=ma.PNG=function(t){ga.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 Af(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 Cf(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"))};If.inherits(F,ga);F.sync=kf;F.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)};F.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};F.prototype.write=function(t){return this._parser.write(t),!0};F.prototype.end=function(t){this._parser.end(t)};F.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};F.prototype._gamma=function(t){this.gamma=t};F.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};F.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)};F.prototype.bitblt=function(t,e,n,r,i,s,o){return F.bitblt(this,t,e,n,r,i,s,o),this};F.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}};F.prototype.adjustGamma=function(){F.adjustGamma(this)}});var Mt=y(Ne=>{function _a(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("")}}Ne.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:_a(e.color.dark||"#000000ff"),light:_a(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ne.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ne.getImageWidth=function(e,n){let r=Ne.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Ne.qrToImageData=function(e,n,r){let i=n.modules.size,s=n.modules.data,o=Ne.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 Sa=y(ie=>{var Pf=require("fs"),Rf=ya().PNG,jr=Mt();ie.render=function(e,n){let r=jr.getOptions(n),i=r.rendererOpts,s=jr.getImageWidth(e.modules.size,r);i.width=s,i.height=s;let o=new Rf(i);return jr.qrToImageData(o.data,e,r),o};ie.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ie.renderToBuffer(e,n,function(i,s){i&&r(i);let o="data:image/png;base64,";o+=s.toString("base64"),r(null,o)})};ie.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let i=ie.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()};ie.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=Pf.createWriteStream(e);a.on("error",o),a.on("close",o),ie.renderToFileStream(a,n,r)};ie.renderToFileStream=function(e,n,r){ie.render(n,r).pack().pipe(e)}});var va=y(wn=>{var Lf=Mt(),Of={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Mf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Nf(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}wn.render=function(t,e,n){let r=Lf.getOptions(e),i=Of;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(i=Mf);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+=
|
|
15
|
-
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};
|
|
13
|
+
`);let o=Ld(e,n,i),a=wn.getSymbolSize(e),l=new wd(a);return Ad(l,e),Cd(l),kd(l,e),Cr(l,n,0),e>=7&&Rd(l,e),Pd(l,o),isNaN(r)&&(r=kr.getBestMask(l,Cr.bind(null,l,n))),kr.applyMask(r,l),Cr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:i}}Co.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=xr.M,i,s;return typeof n<"u"&&(r=xr.from(n.errorCorrectionLevel,xr.M),i=vn.from(n.version),s=kr.from(n.maskPattern),n.toSJISFunc&&wn.setToSJISFunction(n.toSJISFunc)),Od(e,i,r,s)}});var Lr=m((Dg,Ro)=>{"use strict";var Nd=require("util"),ko=require("stream"),Z=Ro.exports=function(){ko.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Nd.inherits(Z,ko);Z.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))};Z.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};Z.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()))};Z.prototype.destroySoon=Z.prototype.end;Z.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Z.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Z.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))};Z.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)};Z.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 Or=m(Mr=>{"use strict";var Se=[{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]}];Mr.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<Se.length;a++){let l=Se[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};Mr.getInterlaceIterator=function(t){return function(e,n,r){let i=e%Se[r].x.length,s=(e-i)/Se[r].x.length*8+Se[r].x[i],o=n%Se[r].y.length,a=(n-o)/Se[r].y.length*8+Se[r].y[o];return s*4+a*t*4}}});var Nr=m((Ug,Po)=>{"use strict";Po.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 Br=m((Hg,Mo)=>{"use strict";var Bd=Or(),Dd=Nr();function Lo(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var et=Mo.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=Bd.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Lo(a[l].width,s,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Lo(n,s,o),height:r,lineIndex:0});o===8?this._xComparison=s:o===16?this._xComparison=s*2:this._xComparison=1};et.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};et.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}};et.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}};et.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}};et.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=Dd(c,l,u);e[o]=a+d}};et.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 Bo=m((qg,No)=>{"use strict";var Fd=require("util"),Oo=Lr(),Ud=Br(),Hd=No.exports=function(t){Oo.call(this);let e=[],n=this;this._filter=new Ud(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Fd.inherits(Hd,Oo)});var tt=m((Wg,Do)=>{"use strict";Do.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 Ur=m((Gg,Fo)=>{"use strict";var Dr=[];(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;Dr[t]=e}})();var Fr=Fo.exports=function(){this._crc=-1};Fr.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Dr[(this._crc^t[e])&255]^this._crc>>>8;return!0};Fr.prototype.crc32=function(){return this._crc^-1};Fr.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Dr[(e^t[n])&255]^e>>>8;return e^-1}});var Hr=m((jg,Uo)=>{"use strict";var P=tt(),qd=Ur(),O=Uo.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[P.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[P.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[P.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[P.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[P.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[P.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(){}};O.prototype.start=function(){this.read(P.PNG_SIGNATURE.length,this._parseSignature.bind(this))};O.prototype._parseSignature=function(t){let e=P.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))};O.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!==P.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new qd,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))};O.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};O.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};O.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))};O.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};O.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 P.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=P.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(i&P.COLORTYPE_PALETTE),color:!!(i&P.COLORTYPE_COLOR),alpha:!!(i&P.COLORTYPE_ALPHA),bpp:l,colorType:i}),this._handleChunkEnd()};O.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};O.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()};O.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};O.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===P.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===P.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===P.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};O.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};O.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/P.GAMMA_DIVISION),this._handleChunkEnd()};O.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};O.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===P.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()};O.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};O.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var qr=m(qo=>{"use strict";var Ho=Or(),Wd=[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]}],Gd=[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 jd(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 zd(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);Wd[r](e,i,d,s),s+=r}return s}function $d(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);Gd[r](e,d,f,s)}i.resetAfterLine()}}qo.dataToBitMap=function(t,e){let n=e.width,r=e.height,i=e.depth,s=e.bpp,o=e.interlace,a;i!==8&&(a=jd(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=Ho.getImagePasses(n,r),f=Ho.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=zd(d[h],l,f,s,t,u):$d(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 Wr=m(($g,Wo)=>{"use strict";function Vd(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 Yd(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 Jd(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}}Wo.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?Vd(t,l,r,i,a):(o&&Yd(t,l,r,i,o),n!==8&&(n===16&&(l=Buffer.alloc(r*i*4)),Jd(t,l,r,i,n))),l}});var zo=m((Vg,jo)=>{"use strict";var Kd=require("util"),Gr=require("zlib"),Go=Lr(),Zd=Bo(),Qd=Hr(),Xd=qr(),ef=Wr(),re=jo.exports=function(t){Go.call(this),this._parser=new Qd(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Kd.inherits(re,Go);re.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};re.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Gr.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,Gr.Z_MIN_CHUNK);this._inflate=Gr.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)};re.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Zd(this._bitmapInfo)};re.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};re.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};re.prototype._simpleTransparency=function(){this._metaData.alpha=!0};re.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};re.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};re.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Xd.dataToBitMap(t,this._bitmapInfo);e=ef(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Vo=m((Yg,$o)=>{"use strict";var $=tt();$o.exports=function(t,e,n,r){let i=[$.COLORTYPE_COLOR_ALPHA,$.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=$.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=$.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,S=o;switch(r.inputColorType){case $.COLORTYPE_COLOR_ALPHA:S=s[u+3],g=s[u],p=s[u+1],y=s[u+2];break;case $.COLORTYPE_COLOR:g=s[u],p=s[u+1],y=s[u+2];break;case $.COLORTYPE_ALPHA:S=s[u+1],g=s[u],p=g,y=g;break;case $.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||(S/=o,g=Math.min(Math.max(Math.round((1-S)*f.red+S*g),0),o),p=Math.min(Math.max(Math.round((1-S)*f.green+S*p),0),o),y=Math.min(Math.max(Math.round((1-S)*f.blue+S*y),0),o))),{red:g,green:p,blue:y,alpha:S}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let y=h(s,u);switch(r.colorType){case $.COLORTYPE_COLOR_ALPHA:case $.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 $.COLORTYPE_ALPHA:case $.COLORTYPE_GRAYSCALE:{let S=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=S,i&&(c[d+1]=y.alpha)):(c.writeUInt16BE(S,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 Ko=m((Jg,Jo)=>{"use strict";var Yo=Nr();function tf(t,e,n,r,i){for(let s=0;s<n;s++)r[i+s]=t[e+s]}function nf(t,e,n){let r=0,i=e+n;for(let s=e;s<i;s++)r+=Math.abs(t[s]);return r}function rf(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 sf(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 of(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 af(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 lf(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 cf(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 uf(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]-Yo(a,l,c);r[i+o]=u}}function df(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]-Yo(o,a,l);i+=Math.abs(c)}return i}var ff={0:tf,1:rf,2:of,3:lf,4:uf},hf={0:nf,1:sf,2:af,3:cf,4:df};Jo.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=hf[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 jr=m((Kg,Zo)=>{"use strict";var B=tt(),pf=Ur(),gf=Vo(),mf=Ko(),yf=require("zlib"),ve=Zo.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||yf.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:B.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:B.COLORTYPE_COLOR_ALPHA,[B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([B.COLORTYPE_GRAYSCALE,B.COLORTYPE_COLOR,B.COLORTYPE_COLOR_ALPHA,B.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")};ve.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ve.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ve.prototype.filterData=function(t,e,n){let r=gf(t,e,n,this._options),i=B.COLORTYPE_TO_BPP_MAP[this._options.colorType];return mf(r,e,n,this._options,i)};ve.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(pf.crc32(r.slice(4,r.length-4)),r.length-4),r};ve.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*B.GAMMA_DIVISION),0),this._packChunk(B.TYPE_gAMA,e)};ve.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(B.TYPE_IHDR,n)};ve.prototype.packIDAT=function(t){return this._packChunk(B.TYPE_IDAT,t)};ve.prototype.packIEND=function(){return this._packChunk(B.TYPE_IEND,null)}});var ta=m((Zg,ea)=>{"use strict";var _f=require("util"),Qo=require("stream"),Sf=tt(),vf=jr(),Xo=ea.exports=function(t){Qo.call(this);let e=t||{};this._packer=new vf(e),this._deflate=this._packer.createDeflate(),this.readable=!0};_f.inherits(Xo,Qo);Xo.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Sf.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 aa=m((Ot,oa)=>{"use strict";var na=require("assert").ok,nt=require("zlib"),wf=require("util"),ra=require("buffer").kMaxLength;function Oe(t){if(!(this instanceof Oe))return new Oe(t);t&&t.chunkSize<nt.Z_MIN_CHUNK&&(t.chunkSize=nt.Z_MIN_CHUNK),nt.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 bf(t){return new Oe(t)}function ia(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Oe.prototype._processChunk=function(t,e,n){if(typeof n=="function")return nt.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(na(y>=0,"have should not go down"),y>0){let S=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.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}na(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>=ra)throw ia(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+ra.toString(16)+" bytes");let h=Buffer.concat(l,c);return ia(this),h};wf.inherits(Oe,nt.Inflate);function Ef(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=nt.Z_FINISH),t._processChunk(e,n)}function sa(t,e){return Ef(new Oe(e),t)}oa.exports=Ot=sa;Ot.Inflate=Oe;Ot.createInflate=bf;Ot.inflateSync=sa});var zr=m((Qg,ca)=>{"use strict";var la=ca.exports=function(t){this._buffer=t,this._reads=[]};la.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};la.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 da=m(ua=>{"use strict";var If=zr(),Tf=Br();ua.process=function(t,e){let n=[],r=new If(t);return new Tf(e,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var ga=m((em,pa)=>{"use strict";var fa=!0,ha=require("zlib"),xf=aa();ha.deflateSync||(fa=!1);var Af=zr(),Cf=da(),kf=Hr(),Rf=qr(),Pf=Wr();pa.exports=function(t,e){if(!fa)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(x){n=x}let i;function s(x){i=x}function o(x){i.transColor=x}function a(x){i.palette=x}function l(){i.alpha=!0}let c;function u(x){c=x}let d=[];function f(x){d.push(x)}let h=new Af(t);if(new kf(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=ha.inflateSync(p);else{let L=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;y=xf(p,{chunkSize:L,maxLength:L})}if(p=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let S=Cf.process(y,i);p=null;let J=Rf.dataToBitMap(S,i);S=null;let fe=Pf(J,i);return i.data=fe,i.gamma=c||0,i}});var Sa=m((tm,_a)=>{"use strict";var ma=!0,ya=require("zlib");ya.deflateSync||(ma=!1);var Lf=tt(),Mf=jr();_a.exports=function(t,e){if(!ma)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 Mf(n),i=[];i.push(Buffer.from(Lf.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=ya.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 va=m($r=>{"use strict";var Of=ga(),Nf=Sa();$r.read=function(t,e){return Of(t,e||{})};$r.write=function(t,e){return Nf(t,e)}});var Ea=m(ba=>{"use strict";var Bf=require("util"),wa=require("stream"),Df=zo(),Ff=ta(),Uf=va(),F=ba.PNG=function(t){wa.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 Df(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 Ff(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"))};Bf.inherits(F,wa);F.sync=Uf;F.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)};F.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};F.prototype.write=function(t){return this._parser.write(t),!0};F.prototype.end=function(t){this._parser.end(t)};F.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};F.prototype._gamma=function(t){this.gamma=t};F.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};F.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)};F.prototype.bitblt=function(t,e,n,r,i,s,o){return F.bitblt(this,t,e,n,r,i,s,o),this};F.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}};F.prototype.adjustGamma=function(){F.adjustGamma(this)}});var Nt=m(Ne=>{function Ia(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("")}}Ne.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:Ia(e.color.dark||"#000000ff"),light:Ia(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ne.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ne.getImageWidth=function(e,n){let r=Ne.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Ne.qrToImageData=function(e,n,r){let i=n.modules.size,s=n.modules.data,o=Ne.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 Ta=m(ie=>{var Hf=require("fs"),qf=Ea().PNG,Vr=Nt();ie.render=function(e,n){let r=Vr.getOptions(n),i=r.rendererOpts,s=Vr.getImageWidth(e.modules.size,r);i.width=s,i.height=s;let o=new qf(i);return Vr.qrToImageData(o.data,e,r),o};ie.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ie.renderToBuffer(e,n,function(i,s){i&&r(i);let o="data:image/png;base64,";o+=s.toString("base64"),r(null,o)})};ie.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let i=ie.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()};ie.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=Hf.createWriteStream(e);a.on("error",o),a.on("close",o),ie.renderToFileStream(a,n,r)};ie.renderToFileStream=function(e,n,r){ie.render(n,r).pack().pipe(e)}});var xa=m(bn=>{var Wf=Nt(),Gf={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},jf={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function zf(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}bn.render=function(t,e,n){let r=Wf.getOptions(e),i=Gf;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(i=jf);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+=zf(f,h,i)}a+=c+`
|
|
15
|
+
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};bn.renderToFile=function(e,n,r,i){typeof i>"u"&&(i=r,r=void 0);let s=require("fs"),o=bn.render(n,r);s.writeFile(e,o,i)}});var Ca=m(Aa=>{Aa.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
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+`
|
|
17
17
|
`}return a+=l+`
|
|
18
|
-
`,typeof n=="function"&&n(null,a),a}});var
|
|
19
|
-
`+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[
|
|
20
|
-
`;return typeof r=="function"&&r(null,f),f}});var
|
|
21
|
-
`)){let i=r.indexOf("=");i>0&&(n[r.slice(0,i)]=r.slice(i+1))}return be(n.PATH??"")?rt=null:rt=n,n}catch{}return rt={},{}}function
|
|
22
|
-
`)),n}}var
|
|
18
|
+
`,typeof n=="function"&&n(null,a),a}});var La=m(Pa=>{var $f="\x1B[47m",Vf="\x1B[40m",Yr="\x1B[37m",Jr="\x1B[30m",Be="\x1B[0m",Yf=$f+Jr,Jf=Vf+Yr,Kf=function(t,e,n){return{"00":Be+" "+t,"01":Be+e+"\u2584"+t,"02":Be+n+"\u2584"+t,10:Be+e+"\u2580"+t,11:" ",12:"\u2584",20:Be+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},ka=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"},Ra=function(t,e,n,r){return ka(t,e,n,r)+ka(t,e,n,r+1)};Pa.render=function(t,e,n){let r=t.modules.size,i=t.modules.data,s=!!(e&&e.inverse),o=e&&e.inverse?Jf:Yf,c=Kf(o,s?Jr:Yr,s?Yr:Jr),u=Be+`
|
|
19
|
+
`+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[Ra(i,r,h,f)];d+=c[Ra(i,r,r,f)]+u}return d+=Be,typeof n=="function"&&n(null,d),d}});var Oa=m(Ma=>{var Zf=Ca(),Qf=La();Ma.render=function(t,e,n){return e&&e.small?Qf.render(t,e,n):Zf.render(t,e,n)}});var Zr=m(Ba=>{var Xf=Nt();function Na(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Kr(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function eh(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?Kr("M",l+n,.5+c+n):Kr("m",i,0),i=0,s=!1),l+1<e&&t[a+1]||(r+=Kr("h",o),o=0)):i++}return r}Ba.render=function(e,n,r){let i=Xf.getOptions(n),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,l=i.color.light.a?"<path "+Na(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Na(i.color.dark,"stroke")+' d="'+eh(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 Da=m(En=>{var th=Zr();En.render=th.render;En.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">'+En.render(n,r);s.writeFile(e,a,i)}});var Fa=m(In=>{var Qr=Nt();function nh(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")}}In.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=Qr.getOptions(i);let o=Qr.getImageWidth(e.modules.size,i),a=s.getContext("2d"),l=a.createImageData(o,o);return Qr.qrToImageData(l.data,e,i),nh(a,s,o),a.putImageData(l,0,0),s};In.renderToDataURL=function(e,n,r){let i=r;typeof i>"u"&&(!n||!n.getContext)&&(i=n,n=void 0),i||(i={});let s=In.render(e,n,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Ha=m(Bt=>{var ih=fr(),Xr=Pr(),Ua=Fa(),sh=Zr();function ei(t,e,n,r,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!ih())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=Xr.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Xr.create(n,r);i(null,t(l,e,r))}catch(l){i(l)}}Bt.create=Xr.create;Bt.toCanvas=ei.bind(null,Ua.render);Bt.toDataURL=ei.bind(null,Ua.renderToDataURL);Bt.toString=ei.bind(null,function(t,e,n){return sh.render(t,n)})});var ja=m(we=>{var qa=fr(),ti=Pr(),oh=Ta(),Wa=xa(),ah=Oa(),Ga=Da();function Dt(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(qa())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function lh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Tn(t){switch(t){case"svg":return Ga;case"txt":case"utf8":return Wa;case"png":case"image/png":default:return oh}}function ch(t){switch(t){case"svg":return Ga;case"terminal":return ah;case"utf8":default:return Wa}}function Ft(t,e,n){if(!n.cb)return new Promise(function(r,i){try{let s=ti.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=ti.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}we.create=ti.create;we.toCanvas=Ha().toCanvas;we.toString=function(e,n,r){let i=Dt(e,n,r),s=i.opts?i.opts.type:void 0,o=ch(s);return Ft(o.render,e,i)};we.toDataURL=function(e,n,r){let i=Dt(e,n,r),s=Tn(i.opts.type);return Ft(s.renderToDataURL,e,i)};we.toBuffer=function(e,n,r){let i=Dt(e,n,r),s=Tn(i.opts.type);return Ft(s.renderToBuffer,e,i)};we.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&&!qa())throw new Error("Too few arguments provided");let s=Dt(n,r,i),o=s.opts.type||lh(e),l=Tn(o).renderToFile.bind(null,e);return Ft(l,n,s)};we.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Dt(n,r,e.emit.bind(e,"error")),o=Tn("png").renderToFileStream.bind(null,e);Ft(o,n,i)}});var $a=m((gm,za)=>{za.exports=ja()});var fc=require("http");var ju=qe(As(),1),zu=qe(er(),1),$u=qe(rr(),1),Vu=qe(un(),1),dr=qe(Bs(),1);var Fe=require("fs/promises"),Wn=require("path"),hc=require("os"),pc=qe($a(),1);var it=require("child_process"),Va=require("fs"),U=require("path"),Ht=require("os"),uh=["fnm_multishells"],dh=6e4;function be(t){return uh.some(e=>t.includes(e))}function ri(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var rt=null;function Ya(){if(rt&&!be(rt.PATH??""))return rt;for(let t of ri())try{let e=(0,it.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 be(n.PATH??"")?rt=null:rt=n,n}catch{}return rt={},{}}function fh(t=Ya()){let e=(0,Ht.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,U.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",i=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,U.join)(e,".npm-global","bin"),(0,U.join)(e,".local","bin"),(0,U.join)(e,".claude","bin"),n],s=r.split(U.delimiter).filter(Boolean),o=new Set(s);for(let a of i)o.has(a)||(s.push(a),o.add(a));return s.join(U.delimiter)}function ni(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 xn(){let t=Ya(),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,Ht.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Ut(t,e=3e3){try{return(0,it.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:xn()}).trim()||null}catch{return null}}function hh(t){for(let e of ri())try{let n=(0,it.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function ph(){let t=(0,Ht.homedir)();return[(0,U.join)(t,".local","bin","claude"),(0,U.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,U.join)(t,".npm-global","bin","claude")]}function gh(){for(let t of ph())if(Ut(t))return t;try{let t=(0,it.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:xn()}).trim();if(t&&!t.includes("cmux")&&Ut(t))return t}catch{}}function mh(){let t=(0,Ht.homedir)(),e=[process.env.PNPM_HOME,(0,U.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,U.join)(t,".npm-global","bin","codex"),(0,U.join)(t,".local","bin","codex"),...e.map(n=>(0,U.join)(n,"codex"))]}function yh(){let t;for(let n of mh())if(Ut(n)){if(!be(n))return n;t=n}try{let n=(0,it.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:xn()}).trim();if(n&&Ut(n)){if(!be(n))return n;t=t??n}}catch{}let e=hh("codex");if(e&&Ut(e)){if(!be(e))return e;t=t??e}return t}function Ja(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>dh||!(0,Va.existsSync)(n)||be(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:be(n)})+`
|
|
22
|
+
`)),n}}var _h=Ja(gh,"claude"),Sh=Ja(yh,"codex");function vh(t,e){return{command:ri()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var _={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:ni("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:ni("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:ni("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return _h()},get codexPath(){return Sh()},isTransientPath:be,execViaLoginShell:vh,buildSanitizedEnv:xn};var Yl=require("fs/promises");var dl=require("child_process"),fl=require("fs");var Ka={debug:10,info:20,warn:30,error:40},wh=process.env.VIBE_LOG_LEVEL||"info";function Za(t,e,n){if(Ka[t]<Ka[wh])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
23
|
`):process.stdout.write(i+`
|
|
24
|
-
`)}function
|
|
25
|
-
`;
|
|
26
|
-
`)}function
|
|
27
|
-
`)
|
|
28
|
-
`)
|
|
29
|
-
`)
|
|
30
|
-
`)
|
|
24
|
+
`)}function Qa(t={}){function e(n,r,i){typeof r=="string"?Za(n,t,r):Za(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=>Qa({...t,...n})}}var N=Qa({module:"daemon"});var Cn=require("fs"),ll=require("path");var Xa=require("os"),V=require("path"),qt=(0,V.join)((0,Xa.homedir)(),".vibelet"),el=(0,V.join)(qt,"logs"),tl=(0,V.join)(qt,"data"),bh=(0,V.join)(qt,"runtime"),_m=(0,V.join)(bh,"current"),nl=(0,V.join)(qt,"identity.json"),rl=(0,V.join)(qt,"pairings.json"),An=(0,V.join)(tl,"sessions.json"),st=(0,V.join)(tl,"audit.jsonl"),il=(0,V.join)(el,"daemon.stdout.log"),sl=(0,V.join)(el,"daemon.stderr.log");var H=require("fs");function Eh(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 Wt(t,e){if(!(0,H.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,H.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=Eh(r,e.maxBytes,i,e.retainBytes),o=(0,H.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(s>0){let l=Buffer.alloc(s);(0,H.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,H.ftruncateSync)(o,0),a.length>0&&(0,H.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,H.closeSync)(o)}}function ol(t){let e=[Wt(t.auditPath,{maxBytes:t.auditMaxBytes}),Wt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Wt(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,Ih=new Set(["ts","event","source","appEvent","level"]);function Th(t={}){let e={};for(let[n,r]of Object.entries(t))Ih.has(n)||(e[n]=r);return e}function xh(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Th(n)}}function Ah(){al||((0,Cn.mkdirSync)((0,ll.dirname)(st),{recursive:!0}),al=!0)}var ii=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},i){this.write(xh(e,n,r,i))}write(e){Ah();try{let n=JSON.stringify(e)+`
|
|
25
|
+
`;Wt(st,{maxBytes:_.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,Cn.appendFileSync)(st,n)}catch{}}},v=new ii;var Y=N.child({module:"claude"}),hl="claude-permission-denial:",Ch=/\u001B\[[0-?]*[ -/]*[@-~]/g;function si(t){process.stderr.write(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
|
|
26
|
+
`)}function kh(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(`
|
|
27
|
+
`):""}function Rh(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Ph(t){if(typeof t=="string")return t;let e=kh(t);return e||(Rh(t)?"":JSON.stringify(t))}function Lh(t){return/requested permissions|haven't granted/i.test(t)}function cl(t){return t.replace(Ch,"").replace(/\s+/g," ").trim()}function Mh(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Oh(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 Nh(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function ul(t){let e=cl(t.resultText??""),n=(t.stderrLines??[]).map(cl).filter(Boolean).slice(-3),r=[e,...n].find(s=>!!s&&Oh(s));if(r)return Nh(r);let i=[e,...n].find(s=>!!s&&!Mh(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 oi(t){return t.startsWith(hl)}var kn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),Y.info({sessionId:this.sessionId,cwd:e},"session initialized"),v.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}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),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)})`;Y.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),si(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.proc=(0,dl.spawn)(_.claudePath,n,{cwd:this.cwd||void 0,stdio:["pipe","pipe","pipe"],env:_.buildSanitizedEnv()}),this.proc.on("error",i=>{let s=i.message;i.code==="ENOENT"&&this.cwd&&!(0,fl.existsSync)(this.cwd)&&(s=`Working directory does not exist: ${this.cwd}`),Y.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(`
|
|
28
|
+
`);this.buffer=s.pop();for(let o of s)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{Y.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&&(Y.debug({sessionId:this.sessionId,stderr:s},"stderr"),this.lastStderr.push(s),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(i,s)=>{Y.info({sessionId:this.sessionId,exitCode:i,signal:s},"process exited");let o=this.interrupted;this.proc=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):i&&i!==0&&!this.sawFinalResult&&(Y.error({sessionId:this.sessionId,exitCode:i,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:ul({stderrLines:this.lastStderr,exitCode:i})})),this.exitHandler?.(i)})}respondApproval(e,n){if(Y.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return Y.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+`
|
|
29
|
+
`),!0}setApprovalMode(e){this.approvalMode=e,Y.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),Y.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}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&&(Y.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=Ph(i.content);if(!s)continue;i.is_error===!0&&typeof i.tool_use_id=="string"&&Lh(s)&&this.pendingPermissionDescriptions.set(i.tool_use_id,s),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){si("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:ul({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:`${hl}${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;si("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 ml=require("child_process"),yl=require("fs");var ai=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();N.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},E=new ai;var gl=require("node:fs"),li=require("node:path"),Bh="@vibelet/cli";function pl(t){try{let e=JSON.parse((0,gl.readFileSync)(t,"utf8"));if(e.name===Bh&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Dh(){return"0.0.3"}var ot=Dh();var k=N.child({module:"codex"}),Rn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e;let i=_.codexPath,s,o=this.buildSpawnArgs();if(_.isTransientPath(i)){let l=_.execViaLoginShell("codex",o);s=l.command,o=l.args,k.info({spawnCmd:s,argsPreview:o.slice(0,2)},"spawning via login shell")}else s=i,k.info({spawnCmd:s,args:o},"spawning");v.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,ml.spawn)(s,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:_.buildSanitizedEnv()}),this.proc.on("error",l=>{let c=l.message;l.code==="ENOENT"&&e&&!(0,yl.existsSync)(e)&&(c=`Working directory does not exist: ${e}`),k.error({error:c,cwd:e},"spawn error"),v.emit("driver.error",{agent:"codex",error:c})}),this.proc.stdout.on("data",l=>{this.buffer+=l.toString();let c=this.buffer.split(`
|
|
30
|
+
`);this.buffer=c.pop();for(let u of c)if(u.trim())try{this.handleRaw(JSON.parse(u))}catch{k.warn({linePreview:u.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",l=>{let c=l.toString().trim();c&&(k.debug({stderr:c},"stderr"),this.lastStderr.push(c),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",l=>{k.info({threadId:this.threadId,exitCode:l},"process exited"),l&&l!==0&&k.error({threadId:this.threadId,exitCode:l,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null;for(let[,{reject:c}]of this.pending)c(new Error(`Codex process exited with code ${l}`));this.pending.clear(),this.exitHandler?.(l),l&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${l}`})});let a=E.startTimer("rpc.duration");if(await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ot}}),a(),this.rpcNotify("initialized",{}),n){let l=await this.rpc("thread/resume",{threadId:n});this.threadId=l?.thread?.id??n,k.info({threadId:this.threadId},"thread resumed"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let l=await this.rpc("thread/start",{cwd:e});this.threadId=l?.thread?.id??l?.threadId??"",k.info({threadId:this.threadId},"thread created"),v.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){let e=["app-server"];return this.approvalMode==="autoApprove"&&(e.push("-c",'approval_policy="never"'),e.push("-c",'sandbox_mode="danger-full-access"')),e.push("--listen","stdio://"),e}sendPrompt(e){k.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]}).then(n=>k.debug({resultPreview:JSON.stringify(n).slice(0,200)},"turn/start result")).catch(n=>{k.error({threadId:this.threadId,error:n.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:n.message})})}respondApproval(e,n){let r=Number(e);if(!this.proc?.stdin?.writable)return!1;let i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};return k.info({threadId:this.threadId,rpcId:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
|
|
31
|
+
`),!0}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,k.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;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=E.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})+`
|
|
31
32
|
`),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),k.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})+`
|
|
32
|
-
`)}handleRaw(e){if(k.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}if(!this.handler)return;let n=e.method,r=e.params;if(n==="item/commandExecution/requestApproval"&&e.id!=null){v.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:"command"}),this.handler({type:"approval.request",sessionId:this.threadId,requestId:String(e.id),toolName:"command",input:{command:r?.command??"",cwd:r?.cwd??""},description:r?.reason??""});return}switch(n&&k.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({type:"text.delta",sessionId:this.threadId,content:i}):k.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:r.output});break;case"item/started":{let i=r?.item;i?.type==="command_execution"&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:"command",input:{command:i.command??""},toolCallId:i.id??""});break}case"turn/completed":{let i=r?.usage?{inputTokens:r.usage.input_tokens??0,outputTokens:r.usage.output_tokens??0}:void 0;k.info({threadId:this.threadId},"turn completed"),v.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:i}),this.handler({type:"session.done",sessionId:this.threadId,usage:i});break}default:n&&k.debug({method:n},"unhandled notification");break}}};var
|
|
33
|
-
`)){let n=Pn(e);if(n&&!
|
|
34
|
-
`).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function
|
|
35
|
-
`).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
|
|
36
|
-
`).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=
|
|
37
|
-
`,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
|
|
38
|
-
`))if(c.trim())try{let u=JSON.parse(c);if(u.type==="user"&&u.message?.role==="user"){let d=
|
|
39
|
-
`))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=pi(l.payload.content);if(!u||c==="user"&&Pl(u))continue;r.push({role:c,content:u})}}catch(l){se.warn({error:String(l)},"failed to parse codex history line")}}}catch(s){se.warn({error:String(s)},"failed to read codex session history")}}return r}async function Ll(t,e){try{let n=await(0,P.readdir)(t,{withFileTypes:!0});for(let r of n){let i=(0,A.join)(t,r.name);if(r.isDirectory()){let s=await Ll(i,e);if(s)return s}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return i}}catch(n){se.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var ut=require("fs"),Ol=require("path");var op=500,On=class{records;debounceTimer=null;constructor(){this.records=this.loadFromDisk()}getAll(){return this.records}find(e){return this.records.find(n=>n.sessionId===e)}upsert(e){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.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()},op)}loadFromDisk(){try{let e=(0,ut.readFileSync)(In,"utf-8");return JSON.parse(e).map(n=>({...n,lastActivityAt:n.lastActivityAt??n.createdAt}))}catch{return[]}}saveToDisk(){(0,ut.mkdirSync)((0,Ol.dirname)(In),{recursive:!0}),(0,ut.writeFileSync)(In,JSON.stringify(this.records,null,2))}};var Ml=require("path"),Nl=require("os");function Mn(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Ml.join)((0,Nl.homedir)(),t.slice(2)):t}var $t=N.child({module:"push"}),ap="https://exp.host/--/api/v2/push/send",dt=new Set;function gi(t){dt.add(t),$t.info({token:t,total:dt.size},"push token registered")}function mi(t){dt.delete(t),$t.info({token:t,total:dt.size},"push token unregistered")}async function Bl(t,e,n){if(dt.size===0)return;let r=[...dt].map(i=>({to:i,sound:"default",title:t,body:e,data:n}));try{let i=await fetch(ap,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});i.ok?$t.debug({count:r.length},"push sent"):$t.error({status:i.status,statusText:i.statusText},"push send failed")}catch(i){$t.error({error:String(i)},"push send error")}}var b=N.child({module:"manager"}),lp="Done.",Dl=180;function xe(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt}}var Nn=class{constructor(e=Bl){this.pushSender=e;this.startIdleSweep()}sessions=new Map;store=new On;idleSweepInterval=null;startIdleSweep(){_.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=_.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&&(b.info({sessionId:s.sessionId,inactiveMs:a},"removing inactive session from memory"),I.increment("session.cleanup",{reason:"inactive"}),this.sessions.delete(i))}continue}if(!s.active||!s.driver||s.isResponding)continue;let o=e-s.lastActivityTs;o<n||(b.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(b.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;b.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(xe(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,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"&&ri(s.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[s.requestId]={message:e.lastUserMessage,toolName:s.toolName}:b.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=>{b.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"}),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",e.pendingApproval=void 0,this.updateGauges(),this.touchSession(e.sessionId)})}resendPendingApproval(e,n){if(!e.pendingApproval||n.readyState!==1)return;let{requestId:r,toolName:i,input:s,description:o}=e.pendingApproval;b.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<=Dl?n:`${n.slice(0,Math.max(1,Dl-3)).trimEnd()}...`:lp}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(xe(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}:{}});return e}async handle(e,n){switch(b.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"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{e.driver?.stop()}catch(n){b.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.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=Mn(i),b.info({agent:r,cwd:i,approvalMode:s,continueSession:o},"creating session");try{if(!(await(0,Fl.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 a=await jt(r,i);if(a.length>0){let l=a[0];return b.info({sessionId:l.sessionId,cwd:i},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,i,s)}b.info("continue mode: no previous sessions found, creating new")}catch(a){b.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=I.startTimer("driver.spawn"),l=this.createDriver(r),c=await l.start(i,void 0,s),u=a();b.info({sessionId:c,agent:r,spawnMs:u},"session created"),I.increment("session.create",{agent:r}),v.emit("session.create",{sessionId:c,agent:r,cwd:i,approvalMode:s});let d={sessionId:c,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:{}};this.sessions.set(c,d),this.store.upsert(xe(d)),this.updateGauges(),hi(),ai(),this.bindDriverLifecycle(d,r,"",e),this.reply(e,n,!0,{sessionId:c})}catch(a){b.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){let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await Ln(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=await h.start(c,r,u),p=f();b.info({sessionId:g,agent:i,spawnMs:p},"session resumed"),I.increment("session.resume",{agent:i}),v.emit("session.resume",{sessionId:g,agent:i,cwd:c});let m={sessionId:g,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:[],syntheticApprovalRetries:{}};this.sessions.set(g,m),this.store.upsert(xe(m)),this.updateGauges(),this.bindDriverLifecycle(m,i," (resumed)",e);let S=await Ln(r,i,c);if(S.length>0){b.info({sessionId:r,historyCount:S.length},"sending history messages");let J={type:"session.history",sessionId:g,messages:S,approvalMode:u};e.send(JSON.stringify(J))}this.reply(e,n,!0,{sessionId:g})}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>200&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-200))}async sendMessage(e,n,r,i,s,o){let a=this.sessions.get(r);if(!a||!a.driver){let l,c="",u,d="",f=new Date().toISOString(),h=new Date().toISOString(),g=this.store.find(r);if(g)l=g.agent,c=g.cwd||"",u=g.approvalMode,d=g.title,f=g.createdAt,h=g.lastActivityAt;else{let m=(await jt(s)).find(S=>S.sessionId===r);m?(l=m.agent,c=m.cwd||"",d=m.title??"",f=m.createdAt,h=m.lastActivityAt):s&&(l=s)}if(!u&&a&&(u=a.approvalMode),!l){b.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:l,source:g?"record":"scanner"},"auto-reconnecting session"),I.increment("session.reconnect",{agent:l}),v.emit("session.reconnect",{sessionId:r,agent:l,source:g?"record":"scanner"});try{let p=this.createDriver(l);await p.start(c,r,u),a?(a.approvalMode=u,a.driver=p,a.active=!0,a.clients.add(e),a.lastActivityAt=h,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=a.acceptedClientMessageIds??[],a.syntheticApprovalRetries=a.syntheticApprovalRetries??{}):(a={sessionId:r,agent:l,cwd:c,approvalMode:u,driver:p,clients:new Set([e]),title:d,createdAt:f,lastActivityAt:h,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{}},this.sessions.set(r,a)),this.bindDriverLifecycle(a,l," (reconnected)"),this.store.upsert(xe(a)),this.updateGauges()}catch(p){this.reply(e,n,!1,void 0,`Failed to reconnect: ${p}`);return}}if(a.clients.add(e),o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.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)}),ot(a.title)){let l=si(i,50);l&&l!==a.title&&(a.title=l),this.store.upsert(xe(a))}this.touchSession(a.sessionId),a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=i,o&&this.rememberAcceptedClientMessage(a,o),a.driver.sendPrompt(i),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async approve(e,n,r,i,s){let o=this.sessions.get(r);o&&(o.pendingApproval=void 0);let a=o?.syntheticApprovalRetries[i];if(o&&a&&ri(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,a);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);await i.start(e.cwd,e.sessionId,r),e.driver=i,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(xe(e)),this.updateGauges(),this.touchSession(e.sessionId),b.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),b.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(xe(s)),b.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)"),b.info({sessionId:r},"codex driver restarted with new approval mode")}catch(a){b.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}b.info({sessionId:r,agent:i.agent},"stopping session"),v.emit("session.stop",{sessionId:r,agent:i.agent}),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&&(b.info({sessionId:r,agent:i.agent},"deleting session"),i.driver?.stop(),this.sessions.delete(r)),v.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),hi(),ai(),this.reply(e,n,!0)}async sendHistory(e,n,r,i){let s=this.sessions.get(r);s&&s.clients.add(e);let o=s?.cwd??this.store.find(r)?.cwd??"",a=await Ln(r,i,o);b.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 yl({agent:r,cwd:i,search:s,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll()});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 Cn;case"codex":return new kn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){b.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"&&b.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 yi(t,e){t.action==="push.register"?e.registerToken(t.pushToken):e.unregisterToken(t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var Ul=require("child_process");function cp(t,e){return(0,Ul.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function up(t){let e=t.split(`
|
|
40
|
-
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function
|
|
41
|
-
`,"utf8")}function
|
|
42
|
-
`,"utf8")}var Bn=class{constructor(e=Za){this.pairingsPath=e;this.records=gp(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_${Si(8)}`,r=Si(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=Si(32),s={deviceId:e,deviceName:n,tokenHash:vi(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),Vt(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=vi(n);return $l(i.tokenHash,s)?(r&&(i.lastSeenAt=new Date().toISOString(),Vt(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=vi(e),i=this.records.find(s=>!s.revokedAt&&$l(s.tokenHash,r));return i?(n&&(i.lastSeenAt=new Date().toISOString(),Vt(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(),Vt(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Vt(this.pairingsPath,this.records)}};function Dn(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function mp(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Yl(t,e){return mp(t)??e}function yp(t,e){return!!(t&&e&&t===e)}function wi(t,e,n,r=!0){return t?yp(t,e)?!0:!!n(t,r):!1}var Jl=require("child_process");function bi(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Kl(t){if(!bi(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function _p(t){if(!bi(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Sp(t){if(!bi(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Ei(t){return!!t&&!_p(t)&&!Sp(t)}function gt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Zl(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function vp(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let i of r)i.internal||i.family!=="IPv4"||Ei(i.address)&&(Kl(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function wp(t){let e=JSON.parse(t),n=gt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>gt(o)).filter(o=>!!o).filter(o=>Kl(o)&&Ei(o)),i=r[0]??n,s=[...n&&n!==i?[n]:[],...r.filter(o=>o!==i)];return{canonicalHost:i,fallbackHosts:s}}function Ql(t=Jl.execFileSync){try{let e=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return wp(e)}catch{return{fallbackHosts:[]}}}function Xl(t){let e=gt(t.canonicalHost),n=gt(t.configuredCanonicalHost)||gt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...vp(t.interfaces)].map(i=>gt(i)).filter(i=>!!i).filter(i=>Ei(i)).filter((i,s,o)=>i!==n&&o.indexOf(i)===s);return{canonicalHost:n,fallbackHosts:r}}function ec(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 ee=N.child({module:"daemon"}),Yt=N.child({module:"ws"}),Jt=new Nn,D=zl(_.port),Te=new Bn,Fn=new Set,xi=new WeakSet,tc=!1,sc=Date.now(),mt=null;function yt(){let t=Ql();return Xl({canonicalHost:D.canonicalHost,configuredCanonicalHost:_.canonicalHost,configuredFallbackHosts:Zl(_.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,rc.networkInterfaces)()})}async function bp(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 Q(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function oc(){let t=Te.openWindow(),e=yt(),n=e.canonicalHost,r=D.port,i=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(_.relayUrl)try{let s=new URL(_.relayUrl);n=s.hostname,r=s.port?Number(s.port):s.protocol==="https:"?443:80,i=[e.canonicalHost,...i??[]].filter(Boolean)}catch{ee.warn({relayUrl:_.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:n,fallbackHosts:i,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function Ep(t){let e=await(0,Fe.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let i=await(0,Fe.stat)((0,Un.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 Kt=(0,nc.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${_.port}`);if(n.pathname==="/health"){let i=yt(),s={status:"ok",version:"0.0.1",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:i.canonicalHost,uptimeSeconds:Math.round((Date.now()-sc)/1e3),activeSessions:Jt.getActiveSessionCount(),pairedDevices:Te.pairedCount(),wsClients:X.clients.size,drivers:Jt.getDriverCounts(),metrics:I.snapshot()};_.relayUrl&&(s.relayUrl=_.relayUrl),Q(e,200,s);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Dn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,oc());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Dn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Te.reset(),Q(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Dn(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,{status:"stopping"}),setTimeout(()=>Ue("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let i=await bp(t);if(i.daemonId!==D.daemonId||typeof i.pairNonce!="string"||typeof i.deviceId!="string"||typeof i.deviceName!="string"){Q(e,400,{error:"invalid_pair_request"});return}if(!Te.consumeWindow(i.pairNonce)){Q(e,401,{error:"pair_window_expired"});return}let o=Te.issuePairToken(i.deviceId,i.deviceName),a=yt();Q(e,200,{daemonId:D.daemonId,displayName:D.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:D.port,deviceId:i.deviceId,pairToken:o})}catch(i){Q(e,400,{error:String(i)})}return}let r=Yl(t.headers.authorization,n.searchParams.get("token"));if(!wi(r,_.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=Mn(i);if(!(await(0,Fe.stat)(s)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,Un.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,Fe.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 v0.0.1")}),X=new lr.default({server:Kt});Kt.on("connection",t=>{Fn.add(t),t.on("close",()=>{Fn.delete(t)})});X.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${_.port}`).searchParams.get("token");if(wi(r,_.legacyToken,(i,s)=>Te.validateAnyPairToken(i,s)))xi.add(t);else if(r){t.close(4001,"Unauthorized");return}Yt.info({clients:X.clients.size},"client connected"),I.increment("ws.connect"),I.gauge("ws.clients",X.clients.size),v.emit("ws.connect",{clients:X.clients.size}),t.on("message",async i=>{try{let s=JSON.parse(ec(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(!xi.has(t)){if(o.action==="auth.hello"&&o.daemonId===D.daemonId&&Te.validatePairToken(o.deviceId,o.pairToken)){xi.add(t),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:D.daemonId,displayName:D.displayName}}));return}if(o.action==="auth.hello"){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}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);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await Ep(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"){yi(s,{registerToken:gi,unregisterToken:mi,respond:a=>t.send(JSON.stringify(a))});return}if(s.action==="push.unregister"){yi(s,{registerToken:gi,unregisterToken:mi,respond:a=>t.send(JSON.stringify(a))});return}await Jt.handle(t,o)}catch(s){Yt.error({error:String(s)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(s)}))}}),t.on("close",()=>{Yt.info({clients:X.clients.size},"client disconnected"),I.increment("ws.disconnect"),I.gauge("ws.clients",X.clients.size),v.emit("ws.disconnect",{clients:X.clients.size}),Jt.removeClient(t)}),t.on("error",i=>{Yt.error({error:i.message},"websocket error")})});function Ti(){for(let t of Fn)try{t.destroy()}catch{}Fn.clear()}function ac(){let t=el({auditPath:st,stdoutLogPath:Qa,stderrLogPath:Xa,auditMaxBytes:_.auditMaxBytes,logMaxBytes:_.daemonLogMaxBytes});t.trimmedFiles>0&&ee.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 xp(){mt||(mt=setInterval(ac,_.storageHousekeepingIntervalMs),mt.unref())}function Tp(){mt&&(clearInterval(mt),mt=null)}function Ue(t,e=0){if(!tc){tc=!0,ee.info({reason:t,exitCode:e},"shutting down"),v.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-sc)/1e3)}),I.stopPeriodicLog(),Tp(),Jt.shutdown();for(let n of X.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}X.close(n=>{n&&ee.error({error:String(n)},"websocket close error")}),Kt.close(n=>{if(n){ee.error({error:String(n)},"http close error"),Ti(),process.exit(1);return}Ti(),process.exit(e)}),setTimeout(()=>{ee.error("force exiting after shutdown timeout"),Ti(),process.exit(e||1)},3e3).unref()}}X.on("error",t=>{Yt.error({error:t.message},"wss error")});Kt.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Hl(_.port).filter(n=>n.pid!==process.pid);ee.error({port:_.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else ee.error({error:String(t)},"server error");Ue(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>Ue("SIGINT"));process.once("SIGTERM",()=>Ue("SIGTERM"));process.once("SIGHUP",()=>Ue("SIGHUP"));process.once("SIGTTIN",()=>Ue("SIGTTIN"));process.once("SIGTSTP",()=>Ue("SIGTSTP"));process.on("uncaughtException",t=>{ee.error({error:String(t),stack:t.stack},"uncaughtException"),v.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{ee.error({reason:String(t)},"unhandledRejection"),v.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});Kt.listen(_.port,async()=>{ac(),v.emit("daemon.start",{port:_.port}),I.startPeriodicLog(),xp(),ee.info({port:_.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:yt().canonicalHost,fallbackHosts:yt().fallbackHosts,claudePath:_.claudePath,codexPath:_.codexPath,auditMaxBytes:_.auditMaxBytes,daemonLogMaxBytes:_.daemonLogMaxBytes,storageHousekeepingIntervalMs:_.storageHousekeepingIntervalMs},"daemon started");let t=yt(),e=oc();process.stdout.write(`
|
|
33
|
+
`)}handleRaw(e){if(k.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}if(!this.handler)return;let n=e.method,r=e.params;if(n==="item/commandExecution/requestApproval"&&e.id!=null){v.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:"command"}),this.handler({type:"approval.request",sessionId:this.threadId,requestId:String(e.id),toolName:"command",input:{command:r?.command??"",cwd:r?.cwd??""},description:r?.reason??""});return}switch(n&&k.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({type:"text.delta",sessionId:this.threadId,content:i}):k.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:r.output});break;case"item/started":{let i=r?.item;i?.type==="command_execution"&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:"command",input:{command:i.command??""},toolCallId:i.id??""});break}case"turn/completed":{let i=r?.usage?{inputTokens:r.usage.input_tokens??0,outputTokens:r.usage.output_tokens??0}:void 0;k.info({threadId:this.threadId},"turn completed"),v.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:i}),this.handler({type:"session.done",sessionId:this.threadId,usage:i});break}default:n&&k.debug({method:n},"unhandled notification");break}}};var R=require("fs/promises"),Pl=require("fs"),Ll=require("readline"),A=require("path"),de=require("os");var Fh=new Set(["New session","Resumed session","Untitled session"]),Uh=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Hh(t){return t.replace(/\s+/g," ").trim()}function Pn(t){return typeof t!="string"?void 0:Hh(t)||void 0}function _l(t){let e=Pn(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 at(t){let e=Pn(t);return!e||Fh.has(e)||_l(e)}function qh(t){for(let e of t.replace(/\r/g,"").split(`
|
|
34
|
+
`)){let n=Pn(e);if(n&&!Wh(n)&&!Gh(n))return n}}function Wh(t){return Uh.some(e=>t.startsWith(e))}function Gh(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function jh(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 ci(t,e=80){if(typeof t!="string")return;let n=qh(t);if(!n)return;let r=jh(n),s=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!s||_l(s)))return s.length<=e?s:`${s.slice(0,Math.max(1,e-3)).trimEnd()}...`}function De(t,e){for(let n of t){let r=Pn(n);if(!(!r||at(r)))return r}return ci(e)}var vl=require("child_process"),lt=require("fs/promises"),Ee=require("path"),ui=require("os"),wl=require("util");var zh=(0,wl.promisify)(vl.execFile),$h=3e3,Gt=null;function di(){Gt=null}function Vh(t){return t.replace(/^['"]|['"]$/g,"")}function Yh(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Vh)}function bl(t){let e=Yh(t);for(let n=0;n<e.length;n+=1){let r=e[n],i=(0,Ee.basename)(r);if(i==="claude"||i==="codex")return{agent:i,args:e.slice(n+1)}}return null}function Jh(t,e){let n=bl(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 Ln(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Kh(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Zh(t){let e=Jh(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=>Kh(t.agent,i));if(n.length!==1)return null;let r=ct(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 Qh(t,e){let n=t,r=e;return(Ln(e.confidence)>Ln(t.confidence)||Ln(e.confidence)===Ln(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 Xh(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,i=e.get(r);e.set(r,i?Qh(i,n):n)}return[...e.values()]}async function fi(t,e){try{let{stdout:n}=await zh(t,e,{maxBuffer:8388608});return n}catch{return""}}async function Sl(t){if(!t.sessionFilePath)return t;let e=await jt(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function ep(t){return(await fi("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
|
|
35
|
+
`).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function tp(t){let n=(await fi("lsof",["-p",String(t),"-Fn"])).split(`
|
|
36
|
+
`).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 np(){return(await fi("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
|
|
37
|
+
`).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=bl(i);return!Number.isFinite(r)||!s?null:{pid:r,command:i,agent:s.agent}}).filter(e=>!!e)}async function rp(){let t=await np();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await ep(e.pid),sessionFiles:await tp(e.pid)})))}function ip(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function sp(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ee.join)((0,ui.homedir)(),".claude","projects",ip(e)),l=(await(0,lt.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,lt.stat)((0,Ee.join)(o,f)).catch(()=>null);h&&(!c||h.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:h.mtimeMs})})),!c)return null;let u=(0,Ee.join)(o,c.name),d=ct(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ee.join)((0,ui.homedir)(),".codex","sessions"),r=null;async function i(o){let a=await(0,lt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ee.join)(o,l.name);if(l.isDirectory())await i(c);else if(l.name.endsWith(".jsonl")){let u=await(0,lt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await jt(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 El(){if(Gt&&Date.now()<Gt.expiresAt)return Gt.value;let t=await rp(),e=await Promise.all(t.map(async r=>{let i=Zh(r);if(i)return Sl(i);let s=await sp(r.agent,r.cwd);return s?Sl({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:s.sessionId,confidence:"low",sessionFilePath:s.filePath}):null})),n=Xh(e.filter(r=>r!==null));return Gt={value:n,expiresAt:Date.now()+$h},n}var Tl=N.child({module:"inventory"}),ut={daemonActive:3,externalRunning:2,idle:1},Il={high:3,medium:2,low:1};function xl(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function op(t,e){let n=t.runtime.needsAttention?1:0;return(e.runtime.needsAttention?1:0)-n||ut[e.runtime.state]-ut[t.runtime.state]||xl(t,e)}function ap(t,e){return ut[e.state]>ut[t.state]?e:ut[e.state]<ut[t.state]?t:Il[e.confidence]>Il[t.confidence]?e:t}function lp(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function cp(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function up(t,e){return e?t?!(at(e)&&!at(t)):!0:!1}function hi(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function dp(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:hi()}}function fp(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 hp(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}}}function pp(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=up(i.title,n.title)?n.title:i.title,o=n.cwd||i.cwd,a=ap(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:cp(i.lastActivityAt,n.lastActivityAt);t.set(r,{...i,cwd:o,title:s,createdAt:lp(i.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a})}}function gp(...t){let e=new Map;for(let n of t)pp(e,n);return[...e.values()]}function mp(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&&Tl.debug({total:t.length,filtered:o.length,search:r,contentMatchIds:i?.size??0},"filter applied"),o}function yp(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 _p(t,e,n,r,i,s,o){let a=s?1/0:Math.max(1,e||50),l=gp(t.sessionRecords.map(dp),t.scannedSessions,t.runningSessions.map(y=>fp(y,t.scannedAt)),t.activeSessions.map(hp)),c=mp(l,r,i,s,o),u=c.filter(y=>y.runtime.state!=="idle").sort(op),d=c.filter(y=>y.runtime.state==="idle").sort(xl),f=yp(d,n),h=d.slice(f,f+a),p=f+h.length<d.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...u,...h],nextCursor:p}}async function pi(t){let e=new Date().toISOString(),[n,r,i]=await Promise.all([zt(t.agent,t.cwd),El(),t.search?Al(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&Tl.info({search:t.search,contentMatches:i?.size??0,scanned:n.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),_p({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:n,runningSessions:r,scannedAt:e},t.limit,t.cursor,t.agent,t.cwd,t.search,i)}var se=N.child({module:"scanner"});function Ml(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 Ol=5e3,mi=Ml(Ol),yi=Ml(Ol);function _i(){mi.clear(),yi.clear()}function Nl(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}function*Bl(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let i=t.indexOf(`
|
|
38
|
+
`,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 gi=512*1024;async function Dl(t,e){if(e<=gi)return(0,R.readFile)(t,"utf-8");let n=await(0,R.open)(t,"r");try{let r=Buffer.alloc(gi),{bytesRead:i}=await n.read(r,0,gi,0);return r.toString("utf-8",0,i)}finally{await n.close()}}function Si(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 Fl(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Si(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function vi(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 Sp=["<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 vp(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Sp.some(r=>n.startsWith(r)):!1}function wi(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=vi(t.message.content);return vp(t,e)?"":e}function Ul(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Hl(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:hi()}}function ct(t,e){let n=(0,A.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 wp(t,e){let n=await Dl(t,e),r=Bl(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=De([u.customTitle,u.summary])),!l){let d=wi(u),f=De([],d);f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||ct("claude",t)||(0,A.basename)(t,".jsonl"),cwd:i,title:o??l??De([],a)}:null}async function bp(t,e){let n=await Dl(t,e),r=Bl(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=De([u.payload?.title,u.title])),!l){let d=Fl(u),f=d&&!Ul(d)?De([],d):void 0;f&&(a=d,l=f)}if(i&&(o||l))break}return i?{sessionId:s||ct("codex",t)||(0,A.basename)(t,".jsonl"),cwd:i,title:o??l??De([],a)}:null}async function jt(t,e){let n=await(0,R.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let s=await wp(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 bp(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 Cl(t){let e=(0,A.join)((0,de.homedir)(),".claude","projects");try{let n;t?n=[Nl(t)]:n=(await(0,R.readdir)(e,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name);let r=[];for(let o of n){let a=(0,A.join)(e,o),l=await(0,R.readdir)(a).catch(()=>[]);for(let c of l)c.endsWith(".jsonl")&&r.push((0,A.join)(a,c))}return(await Promise.all(r.map(o=>jt(o,"claude")))).filter(o=>o!==null).map(o=>Hl(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return se.warn({error:String(n)},"failed to list claude sessions"),[]}}async function kl(t){let e=(0,A.join)((0,de.homedir)(),".codex","sessions");try{let n=await(0,R.readdir)(e).catch(()=>[]),r=[];for(let o of n){let a=(0,A.join)(e,o),l=await(0,R.readdir)(a).catch(()=>[]);for(let c of l){let u=(0,A.join)(a,c),d=await(0,R.readdir)(u).catch(()=>[]);for(let f of d){let h=(0,A.join)(u,f),g=await(0,R.readdir)(h).catch(()=>[]);for(let p of g)p.endsWith(".jsonl")&&r.push((0,A.join)(h,p))}}}return(await Promise.all(r.map(o=>jt(o,"codex")))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>Hl(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return se.warn({error:String(n)},"failed to list codex sessions"),[]}}async function zt(t,e){let r=`list:${(0,de.homedir)()}:${t??"all"}:${e??""}`,i=mi.get(r);if(i)return i;let s;if(t==="claude")s=await Cl(e);else if(t==="codex")s=await kl(e);else{let[o,a]=await Promise.all([Cl(e),kl(e)]);s=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return mi.set(r,s),s}async function Al(t,e){let r=`search:${(0,de.homedir)()}:${t}:${e??"all"}`,i=yi.get(r);if(i)return i;let s=new Set,o=t.toLowerCase();async function a(){let c=(0,A.join)((0,de.homedir)(),".claude","projects");try{let u=await(0,R.readdir)(c,{withFileTypes:!0}),d=[];for(let h of u){if(!h.isDirectory())continue;let g=(0,A.join)(c,h.name),p=await(0,R.readdir)(g).catch(()=>[]);for(let y of p)y.endsWith(".jsonl")&&d.push((0,A.join)(g,y))}let f=await Promise.all(d.map(h=>Rl(h,o,"claude")));for(let h of f)h&&s.add(h)}catch(u){se.warn({error:String(u)},"failed to search claude files")}}async function l(){let c=(0,A.join)((0,de.homedir)(),".codex","sessions");try{let u=[];async function d(h){let g=await(0,R.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let p of g){let y=(0,A.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=>Rl(h,o,"codex")));for(let h of f)h&&s.add(h)}catch(u){se.warn({error:String(u)},"failed to search codex files")}}return e==="claude"?await a():e==="codex"?await l():await Promise.all([a(),l()]),yi.set(r,s),s}async function Rl(t,e,n){let r=(0,Pl.createReadStream)(t,{encoding:"utf-8"}),i=(0,Ll.createInterface)({input:r,crlfDelay:1/0}),s=n==="claude"?Ep:Ip,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||ct(n,t):null}function Ep(t){return t?.type==="user"&&t.message?.role==="user"?wi(t):t?.type==="assistant"&&t.message?.role==="assistant"?vi(t.message.content):""}function Ip(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Si(t.payload.content)}let e=Fl(t);return e||""}async function $t(t,e,n){let r=[];if(e==="claude"){let i=(0,A.join)((0,de.homedir)(),".claude","projects");try{let s=n?[Nl(n)]:await(0,R.readdir)(i);for(let o of s){let a=(0,A.join)(i,o,`${t}.jsonl`);try{let l=await(0,R.readFile)(a,"utf-8");for(let c of l.split(`
|
|
39
|
+
`))if(c.trim())try{let u=JSON.parse(c);if(u.type==="user"&&u.message?.role==="user"){let d=wi(u);d&&r.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=vi(u.message.content);d&&r.push({role:"assistant",content:d})}}catch(u){se.warn({error:String(u)},"failed to parse claude history line")}if(r.length>0)break}catch(l){l.code!=="ENOENT"&&se.warn({error:String(l)},"failed to read claude session file")}}}catch(s){se.warn({error:String(s)},"failed to read claude session history")}}else if(e==="codex"){let i=(0,A.join)((0,de.homedir)(),".codex","sessions");try{let s=await ql(i,t);if(s){let o=await(0,R.readFile)(s,"utf-8");for(let a of o.split(`
|
|
40
|
+
`))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=Si(l.payload.content);if(!u||c==="user"&&Ul(u))continue;r.push({role:c,content:u})}}catch(l){se.warn({error:String(l)},"failed to parse codex history line")}}}catch(s){se.warn({error:String(s)},"failed to read codex session history")}}return r}async function ql(t,e){try{let n=await(0,R.readdir)(t,{withFileTypes:!0});for(let r of n){let i=(0,A.join)(t,r.name);if(r.isDirectory()){let s=await ql(i,e);if(s)return s}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return i}}catch(n){se.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var dt=require("fs"),Gl=require("path");var Tp=500,Wl=200;function xp(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Wl?e:e.slice(-Wl)}function Ap(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:xp(t.acceptedClientMessageIds)}}var Mn=class{records;debounceTimer=null;constructor(){this.records=this.loadFromDisk()}getAll(){return this.records}find(e){return this.records.find(n=>n.sessionId===e)}upsert(e){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.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()},Tp)}loadFromDisk(){try{let e=(0,dt.readFileSync)(An,"utf-8");return JSON.parse(e).map(Ap)}catch{return[]}}saveToDisk(){(0,dt.mkdirSync)((0,Gl.dirname)(An),{recursive:!0}),(0,dt.writeFileSync)(An,JSON.stringify(this.records,null,2))}};var jl=require("path"),zl=require("os");function On(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,jl.join)((0,zl.homedir)(),t.slice(2)):t}var Vt=N.child({module:"push"}),Cp="https://exp.host/--/api/v2/push/send",ft=new Set;function bi(t){ft.add(t),Vt.info({token:t,total:ft.size},"push token registered")}function Ei(t){ft.delete(t),Vt.info({token:t,total:ft.size},"push token unregistered")}async function $l(t,e,n){if(ft.size===0)return;let r=[...ft].map(i=>({to:i,sound:"default",title:t,body:e,data:n}));try{let i=await fetch(Cp,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});i.ok?Vt.debug({count:r.length},"push sent"):Vt.error({status:i.status,statusText:i.statusText},"push send failed")}catch(i){Vt.error({error:String(i)},"push send error")}}var w=N.child({module:"manager"}),kp="Done.",Vl=180,Bn=200;function Nn(...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>Bn&&e.splice(0,e.length-Bn));return e}function Ie(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:Nn(t.acceptedClientMessageIds),title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt}}var Dn=class{constructor(e=$l){this.pushSender=e;this.startIdleSweep()}sessions=new Map;store=new Mn;idleSweepInterval=null;startIdleSweep(){_.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=_.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"),E.increment("session.cleanup",{reason:"inactive"}),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"),E.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(Ie(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,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"&&oi(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}),E.increment("driver.exit",{agent:n,abnormal:s&&s!==0?"true":"false"}),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",e.pendingApproval=void 0,this.updateGauges(),this.touchSession(e.sessionId)})}async resolveReconnectSession(e,n,r){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=Nn(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=Nn(h.acceptedClientMessageIds,d),f="record";else if(!r){let p=(await zt(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}}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<=Vl?n:`${n.slice(0,Math.max(1,Vl-3)).trimEnd()}...`:kp}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(Ie(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++;E.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}:{}});return e}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{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.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=On(i),w.info({agent:r,cwd:i,approvalMode:s,continueSession:o},"creating session");try{if(!(await(0,Yl.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 a=await zt(r,i);if(a.length>0){let l=a[0];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=E.startTimer("driver.spawn"),l=this.createDriver(r),c=await l.start(i,void 0,s),u=a();w.info({sessionId:c,agent:r,spawnMs:u},"session created"),E.increment("session.create",{agent:r}),v.emit("session.create",{sessionId:c,agent:r,cwd:i,approvalMode:s});let d={sessionId:c,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:{}};this.sessions.set(c,d),this.store.upsert(Ie(d)),this.updateGauges(),_i(),di(),this.bindDriverLifecycle(d,r,"",e),this.reply(e,n,!0,{sessionId:c})}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){let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await $t(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=E.startTimer("driver.spawn"),h=this.createDriver(i),g=await h.start(c,r,u),p=f();w.info({sessionId:g,agent:i,spawnMs:p},"session resumed"),E.increment("session.resume",{agent:i}),v.emit("session.resume",{sessionId:g,agent:i,cwd:c});let y={sessionId:g,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:{}};this.sessions.set(g,y),this.store.upsert(Ie(y)),this.updateGauges(),this.bindDriverLifecycle(y,i," (resumed)",e);let S=await $t(r,i,c);if(S.length>0){w.info({sessionId:r,historyCount:S.length},"sending history messages");let J={type:"session.history",sessionId:g,messages:S,approvalMode:u};e.send(JSON.stringify(J))}this.reply(e,n,!0,{sessionId:g})}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>Bn&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Bn))}async sendMessage(e,n,r,i,s,o){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"),E.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);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=Nn(a.acceptedClientMessageIds,l.acceptedClientMessageIds),a.syntheticApprovalRetries=a.syntheticApprovalRetries??{}):(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:{}},this.sessions.set(r,a)),this.bindDriverLifecycle(a,l.agent," (reconnected)"),this.store.upsert(Ie(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)}),at(a.title)){let l=ci(i,50);l&&l!==a.title&&(a.title=l),this.store.upsert(Ie(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;try{l=await pi({agent:r,cwd:i,search:s,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll()})}catch(u){w.warn({error:String(u)},"failed to build reconnect snapshot session list"),l={sessions:[],nextCursor:void 0}}let c;if(o){let u=a??l.sessions.find(h=>h.sessionId===o)?.agent,d=this.sessions.get(o),f=await this.resolveReconnectSession(o,u,d);if(f){let h=await $t(o,f.agent,d?.cwd??f.cwd);c={sessionId:o,agent:f.agent,messages:h,isResponding:d?.isResponding||void 0,approvalMode:d?.approvalMode??f.approvalMode,...d?.pendingApproval?{pendingApproval:d.pendingApproval}:{}}}}E.increment("reconnect.snapshot",{activeSession:c?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:l.sessions,nextCursor:l.nextCursor,...c?{activeSession:c}:{}}})}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);o&&(o.pendingApproval=void 0);let a=o?.syntheticApprovalRetries[i];if(o&&a&&oi(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,a);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);await i.start(e.cwd,e.sessionId,r),e.driver=i,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(Ie(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(Ie(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}),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"),i.driver?.stop(),this.sessions.delete(r)),v.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),_i(),di(),this.reply(e,n,!0)}async sendHistory(e,n,r,i){let s=this.sessions.get(r);s&&s.clients.add(e);let o=s?.cwd??this.store.find(r)?.cwd??"",a=await $t(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 pi({agent:r,cwd:i,search:s,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll()});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 kn;case"codex":return new Rn;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&&E.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 Ii(t,e){t.action==="push.register"?e.registerToken(t.pushToken):e.unregisterToken(t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var Jl=require("child_process");function Rp(t,e){return(0,Jl.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function Pp(t){let e=t.split(`
|
|
41
|
+
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Kl(t,e=Rp){let n;try{n=Pp(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 ht=require("fs"),Ti=require("os"),Ql=require("crypto"),Xl=require("path");function ec(t){return(0,Ql.randomBytes)(t).toString("base64url")}function Lp(){return`d_${ec(12)}`}function Mp(){return(0,Ti.hostname)()}function Op(){let t=(0,Ti.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Np(t){return{daemonId:Lp(),daemonSecret:ec(32),displayName:Mp(),canonicalHost:Op(),port:t,createdAt:new Date().toISOString()}}function Zl(t,e){(0,ht.mkdirSync)((0,Xl.dirname)(e),{recursive:!0}),(0,ht.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
42
|
+
`,"utf8")}function tc(t,e=nl){try{let r=(0,ht.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,Zl(s,e)),s}}catch{}let n=Np(t);return Zl(n,e),n}var pt=require("crypto"),gt=require("fs"),rc=require("path");function xi(t){return(0,pt.randomBytes)(t).toString("base64url")}function Ai(t){return(0,pt.createHash)("sha256").update(t).digest("hex")}function nc(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,pt.timingSafeEqual)(n,r)}function Bp(t){try{let e=(0,gt.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 Yt(t,e){(0,gt.mkdirSync)((0,rc.dirname)(t),{recursive:!0}),(0,gt.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
43
|
+
`,"utf8")}var Fn=class{constructor(e=rl){this.pairingsPath=e;this.records=Bp(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_${xi(8)}`,r=xi(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=xi(32),s={deviceId:e,deviceName:n,tokenHash:Ai(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),Yt(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=Ai(n);return nc(i.tokenHash,s)?(r&&(i.lastSeenAt=new Date().toISOString(),Yt(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Ai(e),i=this.records.find(s=>!s.revokedAt&&nc(s.tokenHash,r));return i?(n&&(i.lastSeenAt=new Date().toISOString(),Yt(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(),Yt(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Yt(this.pairingsPath,this.records)}};function Un(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Dp(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function ic(t,e){return Dp(t)??e}function Fp(t,e){return!!(t&&e&&t===e)}function Ci(t,e,n,r=!0){return t?Fp(t,e)?!0:!!n(t,r):!1}var sc=require("child_process");function ki(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function oc(t){if(!ki(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Up(t){if(!ki(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Hp(t){if(!ki(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Ri(t){return!!t&&!Up(t)&&!Hp(t)}function mt(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function ac(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function qp(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let i of r)i.internal||i.family!=="IPv4"||Ri(i.address)&&(oc(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function Wp(t){let e=JSON.parse(t),n=mt(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>mt(o)).filter(o=>!!o).filter(o=>oc(o)&&Ri(o)),i=r[0]??n,s=[...n&&n!==i?[n]:[],...r.filter(o=>o!==i)];return{canonicalHost:i,fallbackHosts:s}}function lc(t=sc.execFileSync){try{let e=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Wp(e)}catch{return{fallbackHosts:[]}}}function cc(t){let e=mt(t.canonicalHost),n=mt(t.configuredCanonicalHost)||mt(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...qp(t.interfaces)].map(i=>mt(i)).filter(i=>!!i).filter(i=>Ri(i)).filter((i,s,o)=>i!==n&&o.indexOf(i)===s);return{canonicalHost:n,fallbackHosts:r}}function uc(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 ee=N.child({module:"daemon"}),Jt=N.child({module:"ws"}),Kt=new Dn,D=tc(_.port),Te=new Fn,qn=new Set,Hn=new WeakSet,dc=!1,gc=Date.now(),yt=null;function _t(){let t=lc();return cc({canonicalHost:D.canonicalHost,configuredCanonicalHost:_.canonicalHost,configuredFallbackHosts:ac(_.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,hc.networkInterfaces)()})}async function Gp(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 Q(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function mc(){let t=Te.openWindow(),e=_t(),n=e.canonicalHost,r=D.port,i=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(_.relayUrl)try{let s=new URL(_.relayUrl);n=s.hostname,r=s.port?Number(s.port):s.protocol==="https:"?443:80,i=[e.canonicalHost,...i??[]].filter(Boolean)}catch{ee.warn({relayUrl:_.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:n,fallbackHosts:i,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function jp(t){let e=await(0,Fe.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let i=await(0,Fe.stat)((0,Wn.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 Zt=(0,fc.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${_.port}`);if(n.pathname==="/health"){let i=_t(),s={status:"ok",version:ot,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:i.canonicalHost,uptimeSeconds:Math.round((Date.now()-gc)/1e3),activeSessions:Kt.getActiveSessionCount(),pairedDevices:Te.pairedCount(),wsClients:X.clients.size,drivers:Kt.getDriverCounts(),metrics:E.snapshot()};_.relayUrl&&(s.relayUrl=_.relayUrl),Q(e,200,s);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Un(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,mc());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Un(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Te.reset(),Q(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Un(t.socket.remoteAddress)){Q(e,403,{error:"forbidden"});return}Q(e,200,{status:"stopping"}),setTimeout(()=>Ue("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let i=await Gp(t);if(i.daemonId!==D.daemonId||typeof i.pairNonce!="string"||typeof i.deviceId!="string"||typeof i.deviceName!="string"){Q(e,400,{error:"invalid_pair_request"});return}if(!Te.consumeWindow(i.pairNonce)){Q(e,401,{error:"pair_window_expired"});return}let o=Te.issuePairToken(i.deviceId,i.deviceName),a=_t();Q(e,200,{daemonId:D.daemonId,displayName:D.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:D.port,deviceId:i.deviceId,pairToken:o})}catch(i){Q(e,400,{error:String(i)})}return}let r=ic(t.headers.authorization,n.searchParams.get("token"));if(!Ci(r,_.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=On(i);if(!(await(0,Fe.stat)(s)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,Wn.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,Fe.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${ot}`)}),X=new dr.default({server:Zt});Zt.on("connection",t=>{qn.add(t),t.on("close",()=>{qn.delete(t)})});X.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${_.port}`).searchParams.get("token");if(Ci(r,_.legacyToken,(i,s)=>Te.validateAnyPairToken(i,s)))Hn.add(t),E.increment("ws.auth.success",{mode:"query_token"});else if(r){E.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}Jt.info({clients:X.clients.size},"client connected"),E.increment("ws.connect"),E.gauge("ws.clients",X.clients.size),v.emit("ws.connect",{clients:X.clients.size,authMode:Hn.has(t)?"query_token":"pending"}),t.on("message",async i=>{try{let s=JSON.parse(uc(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(!Hn.has(t)){if(o.action==="auth.hello"&&o.daemonId===D.daemonId&&Te.validatePairToken(o.deviceId,o.pairToken)){Hn.add(t),E.increment("ws.auth.success",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:D.daemonId,displayName:D.displayName}}));return}if(o.action==="auth.hello"){E.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}E.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);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await jp(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"){Ii(s,{registerToken:bi,unregisterToken:Ei,respond:a=>t.send(JSON.stringify(a))});return}if(s.action==="push.unregister"){Ii(s,{registerToken:bi,unregisterToken:Ei,respond:a=>t.send(JSON.stringify(a))});return}await Kt.handle(t,o)}catch(s){Jt.error({error:String(s)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(s)}))}}),t.on("close",i=>{Jt.info({clients:X.clients.size,code:i},"client disconnected"),E.increment("ws.disconnect"),E.increment("ws.disconnect.code",{code:String(i)}),E.gauge("ws.clients",X.clients.size),v.emit("ws.disconnect",{clients:X.clients.size,code:i}),Kt.removeClient(t)}),t.on("error",i=>{Jt.error({error:i.message},"websocket error")})});function Pi(){for(let t of qn)try{t.destroy()}catch{}qn.clear()}function yc(){let t=ol({auditPath:st,stdoutLogPath:il,stderrLogPath:sl,auditMaxBytes:_.auditMaxBytes,logMaxBytes:_.daemonLogMaxBytes});t.trimmedFiles>0&&ee.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 zp(){yt||(yt=setInterval(yc,_.storageHousekeepingIntervalMs),yt.unref())}function $p(){yt&&(clearInterval(yt),yt=null)}function Ue(t,e=0){if(!dc){dc=!0,ee.info({reason:t,exitCode:e},"shutting down"),v.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-gc)/1e3)}),E.stopPeriodicLog(),$p(),Kt.shutdown();for(let n of X.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}X.close(n=>{n&&ee.error({error:String(n)},"websocket close error")}),Zt.close(n=>{if(n){ee.error({error:String(n)},"http close error"),Pi(),process.exit(1);return}Pi(),process.exit(e)}),setTimeout(()=>{ee.error("force exiting after shutdown timeout"),Pi(),process.exit(e||1)},3e3).unref()}}X.on("error",t=>{Jt.error({error:t.message},"wss error")});Zt.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Kl(_.port).filter(n=>n.pid!==process.pid);ee.error({port:_.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else ee.error({error:String(t)},"server error");Ue(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>Ue("SIGINT"));process.once("SIGTERM",()=>Ue("SIGTERM"));process.once("SIGHUP",()=>Ue("SIGHUP"));process.once("SIGTTIN",()=>Ue("SIGTTIN"));process.once("SIGTSTP",()=>Ue("SIGTSTP"));process.on("uncaughtException",t=>{ee.error({error:String(t),stack:t.stack},"uncaughtException"),v.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{ee.error({reason:String(t)},"unhandledRejection"),v.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});Zt.listen(_.port,async()=>{yc(),v.emit("daemon.start",{port:_.port}),E.startPeriodicLog(),zp(),ee.info({port:_.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:_t().canonicalHost,fallbackHosts:_t().fallbackHosts,claudePath:_.claudePath,codexPath:_.codexPath,auditMaxBytes:_.auditMaxBytes,daemonLogMaxBytes:_.daemonLogMaxBytes,storageHousekeepingIntervalMs:_.storageHousekeepingIntervalMs},"daemon started");let t=_t(),e=mc();process.stdout.write(`
|
|
43
44
|
\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
|
|
44
|
-
\u2551 Vibelet Daemon
|
|
45
|
+
\u2551 Vibelet Daemon v${ot} \u2551
|
|
45
46
|
\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
|
|
46
47
|
\u2551 Port: ${String(_.port).padEnd(28)}\u2551
|
|
47
48
|
\u2551 ID: ${D.daemonId.slice(0,28).padEnd(28)}\u2551
|
|
48
49
|
\u2551 Host: ${t.canonicalHost.slice(0,28).padEnd(28)}\u2551
|
|
49
50
|
\u255A\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\u255D
|
|
50
51
|
|
|
51
|
-
Pair with: npx @vibelet/cli
|
|
52
|
+
Pair with: npx @vibelet/cli or npx vibelet
|
|
52
53
|
Host: ${t.canonicalHost}
|
|
53
54
|
Fallbacks: ${t.fallbackHosts.join(", ")||"(none)"}
|
|
54
55
|
|
|
55
56
|
Claude: ${_.claudePath}
|
|
56
57
|
Codex: ${_.codexPath}
|
|
57
|
-
`);try{let n=await
|
|
58
|
+
`);try{let n=await pc.default.toString(JSON.stringify(e),{type:"terminal",small:!0});process.stdout.write(`
|
|
58
59
|
Scan this QR code with Vibelet app:
|
|
59
60
|
|
|
60
61
|
${n}
|