vibelet 0.1.20 → 0.1.21
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/bin/vibelet.mjs +21 -1
- package/dist/index.cjs +38 -38
- package/package.json +19 -1
package/dist/index.cjs
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
"use strict";var Ou=Object.create;var Ei=Object.defineProperty;var Bu=Object.getOwnPropertyDescriptor;var Du=Object.getOwnPropertyNames;var Hu=Object.getPrototypeOf,Fu=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Uu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Du(e))!Fu.call(t,s)&&s!==n&&Ei(t,s,{get:()=>e[s],enumerable:!(r=Bu(e,s))||r.enumerable});return t};var Je=(t,e,n)=>(n=t!=null?Ou(Hu(t)):{},Uu(e||!t||!t.__esModule?Ei(n,"default",{value:t,enumerable:!0}):n,t));var pe=S((sy,Pi)=>{"use strict";var Ci=["nodebuffer","arraybuffer","fragments"],Ri=typeof Blob<"u";Ri&&Ci.push("blob");Pi.exports={BINARY_TYPES:Ci,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ri,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Lt=S((iy,bn)=>{"use strict";var{EMPTY_BUFFER:qu}=pe(),Cr=Buffer[Symbol.species];function ju(t,e){if(t.length===0)return qu;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Cr(n.buffer,n.byteOffset,r):n}function Li(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Mi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Wu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Rr(t){if(Rr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Cr(t):ArrayBuffer.isView(t)?e=new Cr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Rr.readOnly=!1),e}bn.exports={concat:ju,mask:Li,toArrayBuffer:Wu,toBuffer:Rr,unmask:Mi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");bn.exports.mask=function(e,n,r,s,i){i<48?Li(e,n,r,s,i):t.mask(e,n,r,s,i)},bn.exports.unmask=function(e,n){e.length<32?Mi(e,n):t.unmask(e,n)}}catch{}});var Bi=S((oy,Oi)=>{"use strict";var Ni=Symbol("kDone"),Pr=Symbol("kRun"),Lr=class{constructor(e){this[Ni]=()=>{this.pending--,this[Pr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Pr]()}[Pr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ni])}}};Oi.exports=Lr});var Nt=S((ay,Ui)=>{"use strict";var Mt=require("zlib"),Di=Lt(),Gu=Bi(),{kStatusCode:Hi}=pe(),Vu=Buffer[Symbol.species],$u=Buffer.from([0,0,255,255]),An=Symbol("permessage-deflate"),he=Symbol("total-length"),Ke=Symbol("callback"),ve=Symbol("buffers"),Xe=Symbol("error"),In,Mr=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,!In){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;In=new Gu(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ke];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){In.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){In.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Mt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Mt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[An]=this,this._inflate[he]=0,this._inflate[ve]=[],this._inflate.on("error",Yu),this._inflate.on("data",Fi)}this._inflate[Ke]=r,this._inflate.write(e),n&&this._inflate.write($u),this._inflate.flush(()=>{let i=this._inflate[Xe];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Di.concat(this._inflate[ve],this._inflate[he]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[he]=0,this._inflate[ve]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Mt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Mt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[he]=0,this._deflate[ve]=[],this._deflate.on("data",zu)}this._deflate[Ke]=r,this._deflate.write(e),this._deflate.flush(Mt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Di.concat(this._deflate[ve],this._deflate[he]);n&&(i=new Vu(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ke]=null,this._deflate[he]=0,this._deflate[ve]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ui.exports=Mr;function zu(t){this[ve].push(t),this[he]+=t.length}function Fi(t){if(this[he]+=t.length,this[An]._maxPayload<1||this[he]<=this[An]._maxPayload){this[ve].push(t);return}this[Xe]=new RangeError("Max payload size exceeded"),this[Xe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Xe][Hi]=1009,this.removeListener("data",Fi),this.reset()}function Yu(t){if(this[An]._inflate=null,this[Xe]){this[Ke](this[Xe]);return}t[Hi]=1007,this[Ke](t)}});var Ze=S((ly,xn)=>{"use strict";var{isUtf8:qi}=require("buffer"),{hasBlob:Ju}=pe(),Ku=[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 Xu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Nr(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 Zu(t){return Ju&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}xn.exports={isBlob:Zu,isValidStatusCode:Xu,isValidUTF8:Nr,tokenChars:Ku};if(qi)xn.exports.isValidUTF8=function(t){return t.length<24?Nr(t):qi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");xn.exports.isValidUTF8=function(e){return e.length<32?Nr(e):t(e)}}catch{}});var Fr=S((cy,Yi)=>{"use strict";var{Writable:Qu}=require("stream"),ji=Nt(),{BINARY_TYPES:ed,EMPTY_BUFFER:Wi,kStatusCode:td,kWebSocket:nd}=pe(),{concat:Or,toArrayBuffer:rd,unmask:sd}=Lt(),{isValidStatusCode:id,isValidUTF8:Gi}=Ze(),Tn=Buffer[Symbol.species],X=0,Vi=1,$i=2,zi=3,Br=4,Dr=5,kn=6,Hr=class extends Qu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ed[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[nd]=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=X}_write(e,n,r){if(this._opcode===8&&this._state==X)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],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new 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 X:this.getInfo(e);break;case Vi:this.getPayloadLength16(e);break;case $i:this.getPayloadLength64(e);break;case zi:this.getMask();break;case Br:this.getData(e);break;case Dr:case kn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[ji.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Vi:this._payloadLength===127?this._state=$i:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=zi:this._state=Br}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Br}getData(e){let n=Wi;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&&sd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Dr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[ji.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Or(r,n):this._binaryType==="arraybuffer"?s=rd(Or(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=kn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Or(r,n);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Dr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=kn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Wi),this.end();else{let r=e.readUInt16BE(0);if(!id(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=kn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[td]=s,o}};Yi.exports=Hr});var jr=S((dy,Xi)=>{"use strict";var{Duplex:uy}=require("stream"),{randomFillSync:od}=require("crypto"),Ji=Nt(),{EMPTY_BUFFER:ad,kWebSocket:ld,NOOP:cd}=pe(),{isBlob:Qe,isValidStatusCode:ud}=Ze(),{mask:Ki,toBuffer:Ne}=Lt(),Z=Symbol("kByteLength"),dd=Buffer.alloc(4),En=8*1024,Oe,et=En,ne=0,fd=1,pd=2,Ur=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ne,this.onerror=cd,this[ld]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||dd,n.generateMask?n.generateMask(r):(et===En&&(Oe===void 0&&(Oe=Buffer.alloc(En)),od(Oe,0,En),et=0),r[0]=Oe[et++],r[1]=Oe[et++],r[2]=Oe[et++],r[3]=Oe[et++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Z]!==void 0?a=n[Z]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ki(e,r,c,i,a),[c]):(Ki(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=ad;else{if(typeof e!="number"||!ud(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Z]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ne?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Qe(e)?(s=e.size,i=!1):(e=Ne(e),s=e.length,i=Ne.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Qe(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Qe(e)?(s=e.size,i=!1):(e=Ne(e),s=e.length,i=Ne.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Qe(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Ji.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Qe(e)?(a=e.size,l=!1):(e=Ne(e),a=e.length,l=Ne.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Z]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};Qe(e)?this._state!==ne?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ne?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Z],this._state=pd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(qr,this,a,s);return}this._bufferedBytes-=r[Z];let o=Ne(i);n?this.dispatch(o,n,r,s):(this._state=ne,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(hd,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Ji.extensionName];this._bufferedBytes+=r[Z],this._state=fd,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");qr(this,l,s);return}this._bufferedBytes-=r[Z],this._state=ne,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ne&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Z],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Z],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)}};Xi.exports=Ur;function qr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function hd(t,e,n){qr(t,e,n),t.onerror(e)}});var oo=S((fy,io)=>{"use strict";var{kForOnEventAttribute:Ot,kListener:Wr}=pe(),Zi=Symbol("kCode"),Qi=Symbol("kData"),eo=Symbol("kError"),to=Symbol("kMessage"),no=Symbol("kReason"),tt=Symbol("kTarget"),ro=Symbol("kType"),so=Symbol("kWasClean"),ge=class{constructor(e){this[tt]=null,this[ro]=e}get target(){return this[tt]}get type(){return this[ro]}};Object.defineProperty(ge.prototype,"target",{enumerable:!0});Object.defineProperty(ge.prototype,"type",{enumerable:!0});var Be=class extends ge{constructor(e,n={}){super(e),this[Zi]=n.code===void 0?0:n.code,this[no]=n.reason===void 0?"":n.reason,this[so]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Zi]}get reason(){return this[no]}get wasClean(){return this[so]}};Object.defineProperty(Be.prototype,"code",{enumerable:!0});Object.defineProperty(Be.prototype,"reason",{enumerable:!0});Object.defineProperty(Be.prototype,"wasClean",{enumerable:!0});var nt=class extends ge{constructor(e,n={}){super(e),this[eo]=n.error===void 0?null:n.error,this[to]=n.message===void 0?"":n.message}get error(){return this[eo]}get message(){return this[to]}};Object.defineProperty(nt.prototype,"error",{enumerable:!0});Object.defineProperty(nt.prototype,"message",{enumerable:!0});var Bt=class extends ge{constructor(e,n={}){super(e),this[Qi]=n.data===void 0?null:n.data}get data(){return this[Qi]}};Object.defineProperty(Bt.prototype,"data",{enumerable:!0});var gd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ot]&&s[Wr]===e&&!s[Ot])return;let r;if(t==="message")r=function(i,o){let a=new Bt("message",{data:o?i:i.toString()});a[tt]=this,Cn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Be("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[tt]=this,Cn(e,this,a)};else if(t==="error")r=function(i){let o=new nt("error",{error:i,message:i.message});o[tt]=this,Cn(e,this,o)};else if(t==="open")r=function(){let i=new ge("open");i[tt]=this,Cn(e,this,i)};else return;r[Ot]=!!n[Ot],r[Wr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Wr]===e&&!n[Ot]){this.removeListener(t,n);break}}};io.exports={CloseEvent:Be,ErrorEvent:nt,Event:ge,EventTarget:gd,MessageEvent:Bt};function Cn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Gr=S((py,ao)=>{"use strict";var{tokenChars:Dt}=Ze();function ce(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function md(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Dt[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 p=t.slice(l,u);c===44?(ce(e,p,n),n=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Dt[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),ce(n,t.slice(l,u),!0),c===44&&(ce(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Dt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Dt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Dt[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 p=t.slice(l,u);r&&(p=p.replace(/\\/g,""),r=!1),ce(n,a,p),c===44&&(ce(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?ce(e,f,n):(a===void 0?ce(n,f,!0):r?ce(n,a,f.replace(/\\/g,"")):ce(n,a,f),ce(e,o,n)),e}function yd(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ao.exports={format:yd,parse:md}});var Mn=S((my,_o)=>{"use strict";var Sd=require("events"),vd=require("https"),_d=require("http"),uo=require("net"),wd=require("tls"),{randomBytes:bd,createHash:Id}=require("crypto"),{Duplex:hy,Readable:gy}=require("stream"),{URL:Vr}=require("url"),_e=Nt(),Ad=Fr(),xd=jr(),{isBlob:Td}=Ze(),{BINARY_TYPES:lo,CLOSE_TIMEOUT:kd,EMPTY_BUFFER:Rn,GUID:Ed,kForOnEventAttribute:$r,kListener:Cd,kStatusCode:Rd,kWebSocket:D,NOOP:fo}=pe(),{EventTarget:{addEventListener:Pd,removeEventListener:Ld}}=oo(),{format:Md,parse:Nd}=Gr(),{toBuffer:Od}=Lt(),po=Symbol("kAborted"),zr=[8,13],me=["CONNECTING","OPEN","CLOSING","CLOSED"],Bd=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends Sd{constructor(e,n,r){super(),this._binaryType=lo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=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]),ho(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){lo.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Ad({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new xd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[D]=this,i[D]=this,e[D]=this,s.on("conclude",Fd),s.on("drain",Ud),s.on("error",qd),s.on("message",jd),s.on("ping",Wd),s.on("pong",Gd),i.onerror=Vd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",yo),e.on("data",Ln),e.on("end",So),e.on("error",vo),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[_e.extensionName]&&this._extensions[_e.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){Y(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())}),mo(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){Yr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Rn,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){Yr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Rn,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){Yr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[_e.extensionName]||(s.compress=!1),this._sender.send(e||Rn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(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:me.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:me.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:me.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:me.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:me.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:me.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:me.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:me.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[$r])return e[Cd];return null},set(e){for(let n of this.listeners(t))if(n[$r]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[$r]:!0})}})});T.prototype.addEventListener=Pd;T.prototype.removeEventListener=Ld;_o.exports=T;function ho(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kd,protocolVersion:zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${zr.join(", ")})`);let i;if(e instanceof Vr)i=e;else try{i=new Vr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let h=new SyntaxError(l);if(t._redirects===0)throw h;Pn(t,h);return}let c=o?443:80,u=bd(16).toString("base64"),d=o?vd.request:_d.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?Hd:Dd),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new _e(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Md({[_e.extensionName]:p.offer()})),n.length){for(let h of n){if(typeof h!="string"||!Bd.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let h=s.path.split(":");s.socketPath=h[0],s.path=h[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[y,m]of Object.entries(h))r.headers[y.toLowerCase()]=m}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,h||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[po]||(g=t._req=null,Pn(t,h))}),g.on("response",h=>{let y=h.headers.location,m=h.statusCode;if(y&&s.followRedirects&&m>=300&&m<400){if(++t._redirects>s.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let E;try{E=new Vr(y,e)}catch{let C=new SyntaxError(`Invalid URL: ${y}`);Pn(t,C);return}ho(t,E,n,r)}else t.emit("unexpected-response",g,h)||Y(t,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,y,m)=>{if(t.emit("upgrade",h),t.readyState!==T.CONNECTING)return;g=t._req=null;let E=h.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){Y(t,y,"Invalid Upgrade header");return}let ae=Id("sha1").update(u+Ed).digest("base64");if(h.headers["sec-websocket-accept"]!==ae){Y(t,y,"Invalid Sec-WebSocket-Accept header");return}let C=h.headers["sec-websocket-protocol"],B;if(C!==void 0?f.size?f.has(C)||(B="Server sent an invalid subprotocol"):B="Server sent a subprotocol but none was requested":f.size&&(B="Server sent no subprotocol"),B){Y(t,y,B);return}C&&(t._protocol=C);let K=h.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){Y(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let le;try{le=Nd(K)}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}let Ye=Object.keys(le);if(Ye.length!==1||Ye[0]!==_e.extensionName){Y(t,y,"Server indicated an extension that was not requested");return}try{p.accept(le[_e.extensionName])}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[_e.extensionName]=p}t.setSocket(y,m,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Pn(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Dd(t){return t.path=t.socketPath,uo.connect(t)}function Hd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=uo.isIP(t.host)?"":t.host),wd.connect(t)}function Y(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[po]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Yr(t,e,n){if(e){let r=Td(e)?e.size:Od(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${me[t.readyState]})`);process.nextTick(n,r)}}function Fd(t,e){let n=this[D];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[D]!==void 0&&(n._socket.removeListener("data",Ln),process.nextTick(go,n._socket),t===1005?n.close():n.close(t,e))}function Ud(){let t=this[D];t.isPaused||t._socket.resume()}function qd(t){let e=this[D];e._socket[D]!==void 0&&(e._socket.removeListener("data",Ln),process.nextTick(go,e._socket),e.close(t[Rd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function co(){this[D].emitClose()}function jd(t,e){this[D].emit("message",t,e)}function Wd(t){let e=this[D];e._autoPong&&e.pong(t,!this._isServer,fo),e.emit("ping",t)}function Gd(t){this[D].emit("pong",t)}function go(t){t.resume()}function Vd(t){let e=this[D];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,mo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function mo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function yo(){let t=this[D];if(this.removeListener("close",yo),this.removeListener("data",Ln),this.removeListener("end",So),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[D]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",co),t._receiver.on("finish",co))}function Ln(t){this[D]._receiver.write(t)||this.pause()}function So(){let t=this[D];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function vo(){let t=this[D];this.removeListener("error",vo),this.on("error",fo),t&&(t._readyState=T.CLOSING,this.destroy())}});var Ao=S((Sy,Io)=>{"use strict";var yy=Mn(),{Duplex:$d}=require("stream");function wo(t){t.emit("close")}function zd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function bo(t){this.removeListener("error",bo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Yd(t,e){let n=!0,r=new $d({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(wo,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(wo,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",zd),r.on("error",bo),r}Io.exports=Yd});var To=S((vy,xo)=>{"use strict";var{tokenChars:Jd}=Ze();function Kd(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Jd[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}xo.exports={parse:Kd}});var Mo=S((wy,Lo)=>{"use strict";var Xd=require("events"),Nn=require("http"),{Duplex:_y}=require("stream"),{createHash:Zd}=require("crypto"),ko=Gr(),De=Nt(),Qd=To(),ef=Mn(),{CLOSE_TIMEOUT:tf,GUID:nf,kWebSocket:rf}=pe(),sf=/^[+/0-9A-Za-z]{22}==$/,Eo=0,Co=1,Po=2,Jr=class extends Xd{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:tf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ef,...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=Nn.createServer((r,s)=>{let i=Nn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=of(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Eo}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===Po){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ht,this);return}if(e&&this.once("close",e),this._state!==Co)if(this._state=Co,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(Ht,this):process.nextTick(Ht,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ht(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Ro);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){He(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){He(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!sf.test(i)){He(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){He(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ft(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Qd.parse(l)}catch{He(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 De(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=ko.parse(u);p[De.extensionName]&&(f.accept(p[De.extensionName]),d[De.extensionName]=f)}catch{He(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,(p,g,h,y)=>{if(!p)return Ft(n,g||401,h,y);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Ft(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[rf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Eo)return Ft(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Zd("sha1").update(n+nf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[De.extensionName]){let d=e[De.extensionName].params,f=ko.format({[De.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
1
|
+
"use strict";var Du=Object.create;var Ei=Object.defineProperty;var Hu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var Uu=Object.getPrototypeOf,qu=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ju=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fu(e))!qu.call(t,s)&&s!==n&&Ei(t,s,{get:()=>e[s],enumerable:!(r=Hu(e,s))||r.enumerable});return t};var Xe=(t,e,n)=>(n=t!=null?Du(Uu(t)):{},ju(e||!t||!t.__esModule?Ei(n,"default",{value:t,enumerable:!0}):n,t));var pe=S((dy,Pi)=>{"use strict";var Ci=["nodebuffer","arraybuffer","fragments"],Ri=typeof Blob<"u";Ri&&Ci.push("blob");Pi.exports={BINARY_TYPES:Ci,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ri,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Lt=S((fy,wn)=>{"use strict";var{EMPTY_BUFFER:Wu}=pe(),Pr=Buffer[Symbol.species];function Gu(t,e){if(t.length===0)return Wu;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Pr(n.buffer,n.byteOffset,r):n}function Li(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Mi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Vu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Lr(t){if(Lr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Pr(t):ArrayBuffer.isView(t)?e=new Pr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Lr.readOnly=!1),e}wn.exports={concat:Gu,mask:Li,toArrayBuffer:Vu,toBuffer:Lr,unmask:Mi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");wn.exports.mask=function(e,n,r,s,i){i<48?Li(e,n,r,s,i):t.mask(e,n,r,s,i)},wn.exports.unmask=function(e,n){e.length<32?Mi(e,n):t.unmask(e,n)}}catch{}});var Bi=S((py,Oi)=>{"use strict";var Ni=Symbol("kDone"),Mr=Symbol("kRun"),Nr=class{constructor(e){this[Ni]=()=>{this.pending--,this[Mr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Mr]()}[Mr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ni])}}};Oi.exports=Nr});var Nt=S((hy,Ui)=>{"use strict";var Mt=require("zlib"),Di=Lt(),$u=Bi(),{kStatusCode:Hi}=pe(),zu=Buffer[Symbol.species],Yu=Buffer.from([0,0,255,255]),An=Symbol("permessage-deflate"),he=Symbol("total-length"),Ze=Symbol("callback"),_e=Symbol("buffers"),Qe=Symbol("error"),In,Or=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,!In){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;In=new $u(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ze];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){In.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){In.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Mt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Mt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[An]=this,this._inflate[he]=0,this._inflate[_e]=[],this._inflate.on("error",Ku),this._inflate.on("data",Fi)}this._inflate[Ze]=r,this._inflate.write(e),n&&this._inflate.write(Yu),this._inflate.flush(()=>{let i=this._inflate[Qe];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Di.concat(this._inflate[_e],this._inflate[he]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[he]=0,this._inflate[_e]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Mt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Mt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[he]=0,this._deflate[_e]=[],this._deflate.on("data",Ju)}this._deflate[Ze]=r,this._deflate.write(e),this._deflate.flush(Mt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Di.concat(this._deflate[_e],this._deflate[he]);n&&(i=new zu(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ze]=null,this._deflate[he]=0,this._deflate[_e]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ui.exports=Or;function Ju(t){this[_e].push(t),this[he]+=t.length}function Fi(t){if(this[he]+=t.length,this[An]._maxPayload<1||this[he]<=this[An]._maxPayload){this[_e].push(t);return}this[Qe]=new RangeError("Max payload size exceeded"),this[Qe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Qe][Hi]=1009,this.removeListener("data",Fi),this.reset()}function Ku(t){if(this[An]._inflate=null,this[Qe]){this[Ze](this[Qe]);return}t[Hi]=1007,this[Ze](t)}});var et=S((gy,xn)=>{"use strict";var{isUtf8:qi}=require("buffer"),{hasBlob:Xu}=pe(),Zu=[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 Qu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Br(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 ed(t){return Xu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}xn.exports={isBlob:ed,isValidStatusCode:Qu,isValidUTF8:Br,tokenChars:Zu};if(qi)xn.exports.isValidUTF8=function(t){return t.length<24?Br(t):qi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");xn.exports.isValidUTF8=function(e){return e.length<32?Br(e):t(e)}}catch{}});var qr=S((my,Yi)=>{"use strict";var{Writable:td}=require("stream"),ji=Nt(),{BINARY_TYPES:nd,EMPTY_BUFFER:Wi,kStatusCode:rd,kWebSocket:sd}=pe(),{concat:Dr,toArrayBuffer:id,unmask:od}=Lt(),{isValidStatusCode:ad,isValidUTF8:Gi}=et(),Tn=Buffer[Symbol.species],X=0,Vi=1,$i=2,zi=3,Hr=4,Fr=5,kn=6,Ur=class extends td{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||nd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[sd]=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=X}_write(e,n,r){if(this._opcode===8&&this._state==X)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],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new 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 X:this.getInfo(e);break;case Vi:this.getPayloadLength16(e);break;case $i:this.getPayloadLength64(e);break;case zi:this.getMask();break;case Hr:this.getData(e);break;case Fr:case kn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[ji.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Vi:this._payloadLength===127?this._state=$i:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=zi:this._state=Hr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Hr}getData(e){let n=Wi;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&&od(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Fr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[ji.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Dr(r,n):this._binaryType==="arraybuffer"?s=id(Dr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=kn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Dr(r,n);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Fr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=kn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Wi),this.end();else{let r=e.readUInt16BE(0);if(!ad(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=kn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[rd]=s,o}};Yi.exports=Ur});var Gr=S((Sy,Xi)=>{"use strict";var{Duplex:yy}=require("stream"),{randomFillSync:ld}=require("crypto"),Ji=Nt(),{EMPTY_BUFFER:cd,kWebSocket:ud,NOOP:dd}=pe(),{isBlob:tt,isValidStatusCode:fd}=et(),{mask:Ki,toBuffer:Oe}=Lt(),Z=Symbol("kByteLength"),pd=Buffer.alloc(4),En=8*1024,Be,nt=En,ne=0,hd=1,gd=2,jr=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=ne,this.onerror=dd,this[ud]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||pd,n.generateMask?n.generateMask(r):(nt===En&&(Be===void 0&&(Be=Buffer.alloc(En)),ld(Be,0,En),nt=0),r[0]=Be[nt++],r[1]=Be[nt++],r[2]=Be[nt++],r[3]=Be[nt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Z]!==void 0?a=n[Z]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ki(e,r,c,i,a),[c]):(Ki(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=cd;else{if(typeof e!="number"||!fd(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Z]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ne?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):tt(e)?(s=e.size,i=!1):(e=Oe(e),s=e.length,i=Oe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};tt(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):tt(e)?(s=e.size,i=!1):(e=Oe(e),s=e.length,i=Oe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};tt(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ne?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Ji.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):tt(e)?(a=e.size,l=!1):(e=Oe(e),a=e.length,l=Oe.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Z]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};tt(e)?this._state!==ne?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ne?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Z],this._state=gd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Wr,this,a,s);return}this._bufferedBytes-=r[Z];let o=Oe(i);n?this.dispatch(o,n,r,s):(this._state=ne,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(md,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Ji.extensionName];this._bufferedBytes+=r[Z],this._state=hd,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Wr(this,l,s);return}this._bufferedBytes-=r[Z],this._state=ne,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ne&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Z],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Z],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)}};Xi.exports=jr;function Wr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function md(t,e,n){Wr(t,e,n),t.onerror(e)}});var oo=S((vy,io)=>{"use strict";var{kForOnEventAttribute:Ot,kListener:Vr}=pe(),Zi=Symbol("kCode"),Qi=Symbol("kData"),eo=Symbol("kError"),to=Symbol("kMessage"),no=Symbol("kReason"),rt=Symbol("kTarget"),ro=Symbol("kType"),so=Symbol("kWasClean"),ge=class{constructor(e){this[rt]=null,this[ro]=e}get target(){return this[rt]}get type(){return this[ro]}};Object.defineProperty(ge.prototype,"target",{enumerable:!0});Object.defineProperty(ge.prototype,"type",{enumerable:!0});var De=class extends ge{constructor(e,n={}){super(e),this[Zi]=n.code===void 0?0:n.code,this[no]=n.reason===void 0?"":n.reason,this[so]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Zi]}get reason(){return this[no]}get wasClean(){return this[so]}};Object.defineProperty(De.prototype,"code",{enumerable:!0});Object.defineProperty(De.prototype,"reason",{enumerable:!0});Object.defineProperty(De.prototype,"wasClean",{enumerable:!0});var st=class extends ge{constructor(e,n={}){super(e),this[eo]=n.error===void 0?null:n.error,this[to]=n.message===void 0?"":n.message}get error(){return this[eo]}get message(){return this[to]}};Object.defineProperty(st.prototype,"error",{enumerable:!0});Object.defineProperty(st.prototype,"message",{enumerable:!0});var Bt=class extends ge{constructor(e,n={}){super(e),this[Qi]=n.data===void 0?null:n.data}get data(){return this[Qi]}};Object.defineProperty(Bt.prototype,"data",{enumerable:!0});var yd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ot]&&s[Vr]===e&&!s[Ot])return;let r;if(t==="message")r=function(i,o){let a=new Bt("message",{data:o?i:i.toString()});a[rt]=this,Cn(e,this,a)};else if(t==="close")r=function(i,o){let a=new De("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[rt]=this,Cn(e,this,a)};else if(t==="error")r=function(i){let o=new st("error",{error:i,message:i.message});o[rt]=this,Cn(e,this,o)};else if(t==="open")r=function(){let i=new ge("open");i[rt]=this,Cn(e,this,i)};else return;r[Ot]=!!n[Ot],r[Vr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Vr]===e&&!n[Ot]){this.removeListener(t,n);break}}};io.exports={CloseEvent:De,ErrorEvent:st,Event:ge,EventTarget:yd,MessageEvent:Bt};function Cn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var $r=S((_y,ao)=>{"use strict";var{tokenChars:Dt}=et();function ce(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Sd(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Dt[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 p=t.slice(l,u);c===44?(ce(e,p,n),n=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Dt[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),ce(n,t.slice(l,u),!0),c===44&&(ce(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Dt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Dt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Dt[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 p=t.slice(l,u);r&&(p=p.replace(/\\/g,""),r=!1),ce(n,a,p),c===44&&(ce(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?ce(e,f,n):(a===void 0?ce(n,f,!0):r?ce(n,a,f.replace(/\\/g,"")):ce(n,a,f),ce(e,o,n)),e}function vd(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ao.exports={format:vd,parse:Sd}});var Mn=S((Iy,_o)=>{"use strict";var _d=require("events"),bd=require("https"),wd=require("http"),uo=require("net"),Id=require("tls"),{randomBytes:Ad,createHash:xd}=require("crypto"),{Duplex:by,Readable:wy}=require("stream"),{URL:zr}=require("url"),be=Nt(),Td=qr(),kd=Gr(),{isBlob:Ed}=et(),{BINARY_TYPES:lo,CLOSE_TIMEOUT:Cd,EMPTY_BUFFER:Rn,GUID:Rd,kForOnEventAttribute:Yr,kListener:Pd,kStatusCode:Ld,kWebSocket:D,NOOP:fo}=pe(),{EventTarget:{addEventListener:Md,removeEventListener:Nd}}=oo(),{format:Od,parse:Bd}=$r(),{toBuffer:Dd}=Lt(),po=Symbol("kAborted"),Jr=[8,13],me=["CONNECTING","OPEN","CLOSING","CLOSED"],Hd=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends _d{constructor(e,n,r){super(),this._binaryType=lo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=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]),ho(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){lo.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Td({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new kd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[D]=this,i[D]=this,e[D]=this,s.on("conclude",qd),s.on("drain",jd),s.on("error",Wd),s.on("message",Gd),s.on("ping",Vd),s.on("pong",$d),i.onerror=zd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",yo),e.on("data",Ln),e.on("end",So),e.on("error",vo),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[be.extensionName]&&this._extensions[be.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){Y(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())}),mo(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){Kr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Rn,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){Kr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Rn,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){Kr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[be.extensionName]||(s.compress=!1),this._sender.send(e||Rn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(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:me.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:me.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:me.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:me.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:me.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:me.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:me.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:me.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[Yr])return e[Pd];return null},set(e){for(let n of this.listeners(t))if(n[Yr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Yr]:!0})}})});T.prototype.addEventListener=Md;T.prototype.removeEventListener=Nd;_o.exports=T;function ho(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Cd,protocolVersion:Jr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Jr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Jr.join(", ")})`);let i;if(e instanceof zr)i=e;else try{i=new zr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let h=new SyntaxError(l);if(t._redirects===0)throw h;Pn(t,h);return}let c=o?443:80,u=Ad(16).toString("base64"),d=o?bd.request:wd.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?Ud:Fd),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new be(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Od({[be.extensionName]:p.offer()})),n.length){for(let h of n){if(typeof h!="string"||!Hd.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let h=s.path.split(":");s.socketPath=h[0],s.path=h[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[y,m]of Object.entries(h))r.headers[y.toLowerCase()]=m}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,h||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[po]||(g=t._req=null,Pn(t,h))}),g.on("response",h=>{let y=h.headers.location,m=h.statusCode;if(y&&s.followRedirects&&m>=300&&m<400){if(++t._redirects>s.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let E;try{E=new zr(y,e)}catch{let C=new SyntaxError(`Invalid URL: ${y}`);Pn(t,C);return}ho(t,E,n,r)}else t.emit("unexpected-response",g,h)||Y(t,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,y,m)=>{if(t.emit("upgrade",h),t.readyState!==T.CONNECTING)return;g=t._req=null;let E=h.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){Y(t,y,"Invalid Upgrade header");return}let ae=xd("sha1").update(u+Rd).digest("base64");if(h.headers["sec-websocket-accept"]!==ae){Y(t,y,"Invalid Sec-WebSocket-Accept header");return}let C=h.headers["sec-websocket-protocol"],B;if(C!==void 0?f.size?f.has(C)||(B="Server sent an invalid subprotocol"):B="Server sent a subprotocol but none was requested":f.size&&(B="Server sent no subprotocol"),B){Y(t,y,B);return}C&&(t._protocol=C);let K=h.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){Y(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let le;try{le=Bd(K)}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}let Ke=Object.keys(le);if(Ke.length!==1||Ke[0]!==be.extensionName){Y(t,y,"Server indicated an extension that was not requested");return}try{p.accept(le[be.extensionName])}catch{Y(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[be.extensionName]=p}t.setSocket(y,m,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Pn(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Fd(t){return t.path=t.socketPath,uo.connect(t)}function Ud(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=uo.isIP(t.host)?"":t.host),Id.connect(t)}function Y(t,e,n){t._readyState=T.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[po]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Kr(t,e,n){if(e){let r=Ed(e)?e.size:Dd(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${me[t.readyState]})`);process.nextTick(n,r)}}function qd(t,e){let n=this[D];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[D]!==void 0&&(n._socket.removeListener("data",Ln),process.nextTick(go,n._socket),t===1005?n.close():n.close(t,e))}function jd(){let t=this[D];t.isPaused||t._socket.resume()}function Wd(t){let e=this[D];e._socket[D]!==void 0&&(e._socket.removeListener("data",Ln),process.nextTick(go,e._socket),e.close(t[Ld])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function co(){this[D].emitClose()}function Gd(t,e){this[D].emit("message",t,e)}function Vd(t){let e=this[D];e._autoPong&&e.pong(t,!this._isServer,fo),e.emit("ping",t)}function $d(t){this[D].emit("pong",t)}function go(t){t.resume()}function zd(t){let e=this[D];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,mo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function mo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function yo(){let t=this[D];if(this.removeListener("close",yo),this.removeListener("data",Ln),this.removeListener("end",So),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[D]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",co),t._receiver.on("finish",co))}function Ln(t){this[D]._receiver.write(t)||this.pause()}function So(){let t=this[D];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function vo(){let t=this[D];this.removeListener("error",vo),this.on("error",fo),t&&(t._readyState=T.CLOSING,this.destroy())}});var Ao=S((xy,Io)=>{"use strict";var Ay=Mn(),{Duplex:Yd}=require("stream");function bo(t){t.emit("close")}function Jd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function wo(t){this.removeListener("error",wo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Kd(t,e){let n=!0,r=new Yd({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(bo,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(bo,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Jd),r.on("error",wo),r}Io.exports=Kd});var To=S((Ty,xo)=>{"use strict";var{tokenChars:Xd}=et();function Zd(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Xd[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}xo.exports={parse:Zd}});var Mo=S((Ey,Lo)=>{"use strict";var Qd=require("events"),Nn=require("http"),{Duplex:ky}=require("stream"),{createHash:ef}=require("crypto"),ko=$r(),He=Nt(),tf=To(),nf=Mn(),{CLOSE_TIMEOUT:rf,GUID:sf,kWebSocket:of}=pe(),af=/^[+/0-9A-Za-z]{22}==$/,Eo=0,Co=1,Po=2,Xr=class extends Qd{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:rf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nf,...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=Nn.createServer((r,s)=>{let i=Nn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=lf(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Eo}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===Po){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ht,this);return}if(e&&this.once("close",e),this._state!==Co)if(this._state=Co,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(Ht,this):process.nextTick(Ht,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Ht(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Ro);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Fe(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Fe(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!af.test(i)){Fe(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Fe(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ft(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=tf.parse(l)}catch{Fe(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 He(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=ko.parse(u);p[He.extensionName]&&(f.accept(p[He.extensionName]),d[He.extensionName]=f)}catch{Fe(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,(p,g,h,y)=>{if(!p)return Ft(n,g||401,h,y);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Ft(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[of])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Eo)return Ft(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ef("sha1").update(n+sf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[He.extensionName]){let d=e[He.extensionName].params,f=ko.format({[He.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
2
2
|
`).join(`\r
|
|
3
|
-
`)),i.removeListener("error",Ro),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ht,this)})),a(u,s)}};Lo.exports=
|
|
3
|
+
`)),i.removeListener("error",Ro),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ht,this)})),a(u,s)}};Lo.exports=Xr;function lf(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 Ht(t){t._state=Po,t.emit("close")}function Ro(){this.destroy()}function Ft(t,e,n,r){n=n||Nn.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} ${Nn.STATUS_CODES[e]}\r
|
|
4
4
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
5
5
|
`)+`\r
|
|
6
6
|
\r
|
|
7
|
-
`+n)}function
|
|
8
|
-
]))+`;ye.KANJI=new RegExp(Wt,"g");ye.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ye.BYTE=new RegExp(
|
|
9
|
-
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};pa.exports=
|
|
10
|
-
Suggested mode is: `+I.toString(r));switch(n===I.KANJI&&!jn.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new Sa(t);case I.ALPHANUMERIC:return new va(t);case I.KANJI:return new
|
|
7
|
+
`+n)}function Fe(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Fe),t.emit("wsClientError",o,n,e)}else Ft(n,r,s,i)}});var Qr=S((Ry,No)=>{No.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var we=S(Ue=>{var es,pf=[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];Ue.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};Ue.getSymbolTotalCodewords=function(e){return pf[e]};Ue.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ue.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');es=e};Ue.isKanjiModeEnabled=function(){return typeof es<"u"};Ue.toSJIS=function(e){return es(e)}});var On=S(Q=>{Q.L={bit:1};Q.M={bit:0};Q.Q={bit:3};Q.H={bit:2};function hf(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return Q.L;case"m":case"medium":return Q.M;case"q":case"quartile":return Q.Q;case"h":case"high":return Q.H;default:throw new Error("Unknown EC Level: "+t)}}Q.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};Q.from=function(e,n){if(Q.isValid(e))return e;try{return hf(e)}catch{return n}}});var Do=S((My,Bo)=>{function Oo(){this.buffer=[],this.length=0}Oo.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++}};Bo.exports=Oo});var Fo=S((Ny,Ho)=>{function Ut(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)}Ut.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Ut.prototype.get=function(t,e){return this.data[t*this.size+e]};Ut.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Ut.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ho.exports=Ut});var Uo=S(Bn=>{var gf=we().getSymbolSize;Bn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=gf(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};Bn.getPositions=function(e){let n=[],r=Bn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var Wo=S(jo=>{var mf=we().getSymbolSize,qo=7;jo.getPositions=function(e){let n=mf(e);return[[0,0],[n-qo,0],[0,n-qo]]}});var Go=S(A=>{A.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var qe={N1:3,N2:3,N3:40,N4:10};A.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};A.from=function(e){return A.isValid(e)?parseInt(e,10):void 0};A.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=qe.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=qe.N1+(i-5)),a=u,i=1)}s>=5&&(r+=qe.N1+(s-5)),i>=5&&(r+=qe.N1+(i-5))}return r};A.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*qe.N2};A.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*qe.N3};A.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*qe.N4};function yf(t,e,n){switch(t){case A.Patterns.PATTERN000:return(e+n)%2===0;case A.Patterns.PATTERN001:return e%2===0;case A.Patterns.PATTERN010:return n%3===0;case A.Patterns.PATTERN011:return(e+n)%3===0;case A.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case A.Patterns.PATTERN101:return e*n%2+e*n%3===0;case A.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case A.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}A.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,yf(e,i,s))};A.getBestMask=function(e,n){let r=Object.keys(A.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),A.applyMask(o,e);let a=A.getPenaltyN1(e)+A.getPenaltyN2(e)+A.getPenaltyN3(e)+A.getPenaltyN4(e);A.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var ns=S(ts=>{var Ie=On(),Dn=[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],Hn=[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];ts.getBlocksCount=function(e,n){switch(n){case Ie.L:return Dn[(e-1)*4+0];case Ie.M:return Dn[(e-1)*4+1];case Ie.Q:return Dn[(e-1)*4+2];case Ie.H:return Dn[(e-1)*4+3];default:return}};ts.getTotalCodewordsCount=function(e,n){switch(n){case Ie.L:return Hn[(e-1)*4+0];case Ie.M:return Hn[(e-1)*4+1];case Ie.Q:return Hn[(e-1)*4+2];case Ie.H:return Hn[(e-1)*4+3];default:return}}});var Vo=S(Un=>{var qt=new Uint8Array(512),Fn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)qt[n]=e,Fn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)qt[n]=qt[n-255]})();Un.log=function(e){if(e<1)throw new Error("log("+e+")");return Fn[e]};Un.exp=function(e){return qt[e]};Un.mul=function(e,n){return e===0||n===0?0:qt[Fn[e]+Fn[n]]}});var $o=S(jt=>{var rs=Vo();jt.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=rs.mul(e[s],n[i]);return r};jt.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=rs.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};jt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=jt.mul(n,new Uint8Array([1,rs.exp(r)]));return n}});var Jo=S((qy,Yo)=>{var zo=$o();function ss(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}ss.prototype.initialize=function(e){this.degree=e,this.genPoly=zo.generateECPolynomial(this.degree)};ss.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=zo.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};Yo.exports=ss});var is=S(Ko=>{Ko.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var os=S(ye=>{var Xo="[0-9]+",Sf="[A-Z $%*+\\-./:]+",Wt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Wt=Wt.replace(/u/g,"\\u");var vf="(?:(?![A-Z0-9 $%*+\\-./:]|"+Wt+`)(?:.|[\r
|
|
8
|
+
]))+`;ye.KANJI=new RegExp(Wt,"g");ye.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ye.BYTE=new RegExp(vf,"g");ye.NUMERIC=new RegExp(Xo,"g");ye.ALPHANUMERIC=new RegExp(Sf,"g");var _f=new RegExp("^"+Wt+"$"),bf=new RegExp("^"+Xo+"$"),wf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ye.testKanji=function(e){return _f.test(e)};ye.testNumeric=function(e){return bf.test(e)};ye.testAlphanumeric=function(e){return wf.test(e)}});var Ae=S(M=>{var If=is(),as=os();M.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};M.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};M.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};M.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};M.MIXED={bit:-1};M.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!If.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};M.getBestModeForData=function(e){return as.testNumeric(e)?M.NUMERIC:as.testAlphanumeric(e)?M.ALPHANUMERIC:as.testKanji(e)?M.KANJI:M.BYTE};M.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};M.isValid=function(e){return e&&e.bit&&e.ccBits};function Af(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return M.NUMERIC;case"alphanumeric":return M.ALPHANUMERIC;case"kanji":return M.KANJI;case"byte":return M.BYTE;default:throw new Error("Unknown mode: "+t)}}M.from=function(e,n){if(M.isValid(e))return e;try{return Af(e)}catch{return n}}});var na=S(je=>{var qn=we(),xf=ns(),Zo=On(),xe=Ae(),ls=is(),ea=7973,Qo=qn.getBCHDigit(ea);function Tf(t,e,n){for(let r=1;r<=40;r++)if(e<=je.getCapacity(r,n,t))return r}function ta(t,e){return xe.getCharCountIndicator(t,e)+4}function kf(t,e){let n=0;return t.forEach(function(r){let s=ta(r.mode,e);n+=s+r.getBitsLength()}),n}function Ef(t,e){for(let n=1;n<=40;n++)if(kf(t,n)<=je.getCapacity(n,e,xe.MIXED))return n}je.from=function(e,n){return ls.isValid(e)?parseInt(e,10):n};je.getCapacity=function(e,n,r){if(!ls.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=xe.BYTE);let s=qn.getSymbolTotalCodewords(e),i=xf.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===xe.MIXED)return o;let a=o-ta(r,e);switch(r){case xe.NUMERIC:return Math.floor(a/10*3);case xe.ALPHANUMERIC:return Math.floor(a/11*2);case xe.KANJI:return Math.floor(a/13);case xe.BYTE:default:return Math.floor(a/8)}};je.getBestVersionForData=function(e,n){let r,s=Zo.from(n,Zo.M);if(Array.isArray(e)){if(e.length>1)return Ef(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Tf(r.mode,r.getLength(),s)};je.getEncodedBits=function(e){if(!ls.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;qn.getBCHDigit(n)-Qo>=0;)n^=ea<<qn.getBCHDigit(n)-Qo;return e<<12|n}});var oa=S(ia=>{var cs=we(),sa=1335,Cf=21522,ra=cs.getBCHDigit(sa);ia.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;cs.getBCHDigit(s)-ra>=0;)s^=sa<<cs.getBCHDigit(s)-ra;return(r<<10|s)^Cf}});var la=S((zy,aa)=>{var Rf=Ae();function it(t){this.mode=Rf.NUMERIC,this.data=t.toString()}it.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};it.prototype.getLength=function(){return this.data.length};it.prototype.getBitsLength=function(){return it.getBitsLength(this.data.length)};it.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};aa.exports=it});var ua=S((Yy,ca)=>{var Pf=Ae(),us=["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 ot(t){this.mode=Pf.ALPHANUMERIC,this.data=t}ot.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};ot.prototype.getLength=function(){return this.data.length};ot.prototype.getBitsLength=function(){return ot.getBitsLength(this.data.length)};ot.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=us.indexOf(this.data[n])*45;r+=us.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(us.indexOf(this.data[n]),6)};ca.exports=ot});var fa=S((Jy,da)=>{var Lf=Ae();function at(t){this.mode=Lf.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}at.getBitsLength=function(e){return e*8};at.prototype.getLength=function(){return this.data.length};at.prototype.getBitsLength=function(){return at.getBitsLength(this.data.length)};at.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};da.exports=at});var ha=S((Ky,pa)=>{var Mf=Ae(),Nf=we();function lt(t){this.mode=Mf.KANJI,this.data=t}lt.getBitsLength=function(e){return e*13};lt.prototype.getLength=function(){return this.data.length};lt.prototype.getBitsLength=function(){return lt.getBitsLength(this.data.length)};lt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Nf.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)}};pa.exports=lt});var ga=S((Xy,ds)=>{"use strict";var Gt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Gt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,g;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,p=s[l],g=typeof s[l]>"u",(g||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var h=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(h)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Gt.single_source_shortest_paths(t,e,n);return Gt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Gt.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 ds<"u"&&(ds.exports=Gt)});var Ia=S(ct=>{var I=Ae(),Sa=la(),va=ua(),_a=fa(),ba=ha(),Vt=os(),jn=we(),Of=ga();function ma(t){return unescape(encodeURIComponent(t)).length}function $t(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function wa(t){let e=$t(Vt.NUMERIC,I.NUMERIC,t),n=$t(Vt.ALPHANUMERIC,I.ALPHANUMERIC,t),r,s;return jn.isKanjiModeEnabled()?(r=$t(Vt.BYTE,I.BYTE,t),s=$t(Vt.KANJI,I.KANJI,t)):(r=$t(Vt.BYTE_KANJI,I.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function fs(t,e){switch(e){case I.NUMERIC:return Sa.getBitsLength(t);case I.ALPHANUMERIC:return va.getBitsLength(t);case I.KANJI:return ba.getBitsLength(t);case I.BYTE:return _a.getBitsLength(t)}}function Bf(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 Df(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case I.NUMERIC:e.push([r,{data:r.data,mode:I.ALPHANUMERIC,length:r.length},{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.ALPHANUMERIC:e.push([r,{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.KANJI:e.push([r,{data:r.data,mode:I.BYTE,length:ma(r.data)}]);break;case I.BYTE:e.push([{data:r.data,mode:I.BYTE,length:ma(r.data)}])}}return e}function Hf(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=fs(n[f].lastCount+c.length,c.mode)-fs(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=fs(c.length,c.mode)+4+I.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function ya(t,e){let n,r=I.getBestModeForData(t);if(n=I.from(e,r),n!==I.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+I.toString(n)+`.
|
|
10
|
+
Suggested mode is: `+I.toString(r));switch(n===I.KANJI&&!jn.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new Sa(t);case I.ALPHANUMERIC:return new va(t);case I.KANJI:return new ba(t);case I.BYTE:return new _a(t)}}ct.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(ya(r,null)):r.data&&n.push(ya(r.data,r.mode)),n},[])};ct.fromString=function(e,n){let r=wa(e,jn.isKanjiModeEnabled()),s=Df(r),i=Hf(s,n),o=Of.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return ct.fromArray(Bf(a))};ct.rawSplit=function(e){return ct.fromArray(wa(e,jn.isKanjiModeEnabled()))}});var Ss=S(Aa=>{var Gn=we(),ps=On(),Ff=Do(),Uf=Fo(),qf=Uo(),jf=Wo(),ms=Go(),ys=ns(),Wf=Jo(),Wn=na(),Gf=oa(),Vf=Ae(),hs=Ia();function $f(t,e){let n=t.size,r=jf.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function zf(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 Yf(t,e){let n=qf.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function Jf(t,e){let n=t.size,r=Wn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function gs(t,e,n){let r=t.size,s=Gf.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function Kf(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function Xf(t,e,n){let r=new Ff;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Vf.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Gn.getSymbolTotalCodewords(t),i=ys.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Zf(r,t,e)}function Zf(t,e,n){let r=Gn.getSymbolTotalCodewords(e),s=ys.getTotalCodewordsCount(e,n),i=r-s,o=ys.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,p=new Wf(f),g=0,h=new Array(o),y=new Array(o),m=0,E=new Uint8Array(t.buffer);for(let le=0;le<o;le++){let Ke=le<l?u:d;h[le]=E.slice(g,g+Ke),y[le]=p.encode(h[le]),g+=Ke,m=Math.max(m,Ke)}let ae=new Uint8Array(r),C=0,B,K;for(B=0;B<m;B++)for(K=0;K<o;K++)B<h[K].length&&(ae[C++]=h[K][B]);for(B=0;B<f;B++)for(K=0;K<o;K++)ae[C++]=y[K][B];return ae}function Qf(t,e,n,r){let s;if(Array.isArray(t))s=hs.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=hs.rawSplit(t);c=Wn.getBestVersionForData(u,n)}s=hs.fromString(t,c||40)}else throw new Error("Invalid data");let i=Wn.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
|
|
11
11
|
The chosen QR Code version cannot contain this amount of data.
|
|
12
12
|
Minimum version required to store current data is: `+i+`.
|
|
13
|
-
`);let o=Jf(e,n,s),a=Gn.getSymbolSize(e),l=new Hf(a);return Gf(l,e),Vf(l),$f(l,e),ps(l,n,0),e>=7&&zf(l,e),Yf(l,o),isNaN(r)&&(r=hs.getBestMask(l,ps.bind(null,l,n))),hs.applyMask(r,l),ps(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Aa.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ds.M,s,i;return typeof n<"u"&&(r=ds.from(n.errorCorrectionLevel,ds.M),s=Wn.from(n.version),i=hs.from(n.maskPattern),n.toSJISFunc&&Gn.setToSJISFunction(n.toSJISFunc)),Xf(e,s,r,i)}});var ys=S((zy,Ta)=>{"use strict";var Zf=require("util"),xa=require("stream"),re=Ta.exports=function(){xa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Zf.inherits(re,xa);re.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))};re.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};re.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()))};re.prototype.destroySoon=re.prototype.end;re.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};re.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};re.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))};re.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};re.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 vs=S(Ss=>{"use strict";var xe=[{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]}];Ss.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<xe.length;a++){let l=xe[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};Ss.getInterlaceIterator=function(t){return function(e,n,r){let s=e%xe[r].x.length,i=(e-s)/xe[r].x.length*8+xe[r].x[s],o=n%xe[r].y.length,a=(n-o)/xe[r].y.length*8+xe[r].y[o];return i*4+a*t*4}}});var _s=S((Jy,ka)=>{"use strict";ka.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var ws=S((Ky,Ca)=>{"use strict";var Qf=vs(),ep=_s();function Ea(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var lt=Ca.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Qf.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Ea(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Ea(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};lt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};lt.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};lt.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};lt.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};lt.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=ep(c,l,u);e[o]=a+d}};lt.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var La=S((Xy,Pa)=>{"use strict";var tp=require("util"),Ra=ys(),np=ws(),rp=Pa.exports=function(t){Ra.call(this);let e=[],n=this;this._filter=new np(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};tp.inherits(rp,Ra)});var ct=S((Zy,Ma)=>{"use strict";Ma.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var As=S((Qy,Na)=>{"use strict";var bs=[];(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;bs[t]=e}})();var Is=Na.exports=function(){this._crc=-1};Is.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=bs[(this._crc^t[e])&255]^this._crc>>>8;return!0};Is.prototype.crc32=function(){return this._crc^-1};Is.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=bs[(e^t[n])&255]^e>>>8;return e^-1}});var xs=S((eS,Oa)=>{"use strict";var O=ct(),sp=As(),H=Oa.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[O.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[O.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[O.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[O.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[O.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[O.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(){}};H.prototype.start=function(){this.read(O.PNG_SIGNATURE.length,this._parseSignature.bind(this))};H.prototype._parseSignature=function(t){let e=O.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))};H.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==O.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new sp,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};H.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};H.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};H.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))};H.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};H.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in O.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=O.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&O.COLORTYPE_PALETTE),color:!!(s&O.COLORTYPE_COLOR),alpha:!!(s&O.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};H.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};H.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()};H.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};H.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===O.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===O.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===O.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};H.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};H.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/O.GAMMA_DIVISION),this._handleChunkEnd()};H.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};H.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===O.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()};H.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};H.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ts=S(Da=>{"use strict";var Ba=vs(),ip=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],op=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function ap(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,p=i>>4,n.push(p,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,p=i>>6&3,n.push(p,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,p=i>>7&1,n.push(p,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function lp(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);ip[r](e,s,d,i),i+=r}return i}function cp(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);op[r](e,d,f,i)}s.resetAfterLine()}}Da.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=ap(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=Ba.getImagePasses(n,r),f=Ba.getInterlaceIterator(n,r);else{let p=0;f=function(){let g=p;return p+=4,g},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=lp(d[p],l,f,i,t,u):cp(d[p],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var ks=S((nS,Ha)=>{"use strict";function up(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function dp(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function fp(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}Ha.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?up(t,l,r,s,a):(o&&dp(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),fp(t,l,r,s,n))),l}});var qa=S((rS,Ua)=>{"use strict";var pp=require("util"),Es=require("zlib"),Fa=ys(),hp=La(),gp=xs(),mp=Ts(),yp=ks(),ue=Ua.exports=function(t){Fa.call(this),this._parser=new gp(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()};pp.inherits(ue,Fa);ue.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};ue.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Es.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,Es.Z_MIN_CHUNK);this._inflate=Es.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ue.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new hp(this._bitmapInfo)};ue.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ue.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ue.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ue.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ue.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ue.prototype._complete=function(t){if(this.errord)return;let e;try{let n=mp.dataToBitMap(t,this._bitmapInfo);e=yp(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Wa=S((sS,ja)=>{"use strict";var ee=ct();ja.exports=function(t,e,n,r){let s=[ee.COLORTYPE_COLOR_ALPHA,ee.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let h=new ArrayBuffer(2);return new DataView(h).setInt16(0,256,!0),new Int16Array(h)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ee.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=ee.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 p(){let g,h,y,m=o;switch(r.inputColorType){case ee.COLORTYPE_COLOR_ALPHA:m=i[u+3],g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_COLOR:g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_ALPHA:m=i[u+1],g=i[u],h=g,y=g;break;case ee.COLORTYPE_GRAYSCALE:g=i[u],h=g,y=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(m/=o,g=Math.min(Math.max(Math.round((1-m)*f.red+m*g),0),o),h=Math.min(Math.max(Math.round((1-m)*f.green+m*h),0),o),y=Math.min(Math.max(Math.round((1-m)*f.blue+m*y),0),o))),{red:g,green:h,blue:y,alpha:m}}for(let g=0;g<n;g++)for(let h=0;h<e;h++){let y=p(i,u);switch(r.colorType){case ee.COLORTYPE_COLOR_ALPHA:case ee.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,s&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),s&&c.writeUInt16BE(y.alpha,d+6));break;case ee.COLORTYPE_ALPHA:case ee.COLORTYPE_GRAYSCALE:{let m=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=m,s&&(c[d+1]=y.alpha)):(c.writeUInt16BE(m,d),s&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var $a=S((iS,Va)=>{"use strict";var Ga=_s();function Sp(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function vp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function _p(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function wp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function bp(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function Ip(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function Ap(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function xp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Tp(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-Ga(a,l,c);r[s+o]=u}}function kp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-Ga(o,a,l);s+=Math.abs(c)}return s}var Ep={0:Sp,1:_p,2:bp,3:Ap,4:Tp},Cp={0:vp,1:wp,2:Ip,3:xp,4:kp};Va.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let p=0;p<i.length;p++){let g=Cp[i[p]](t,l,o,s);g<f&&(u=i[p],f=g)}}c[a]=u,a++,Ep[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Cs=S((oS,za)=>{"use strict";var q=ct(),Rp=As(),Pp=Wa(),Lp=$a(),Mp=require("zlib"),Te=za.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||Mp.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:q.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:q.COLORTYPE_COLOR_ALPHA,[q.COLORTYPE_GRAYSCALE,q.COLORTYPE_COLOR,q.COLORTYPE_COLOR_ALPHA,q.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([q.COLORTYPE_GRAYSCALE,q.COLORTYPE_COLOR,q.COLORTYPE_COLOR_ALPHA,q.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")};Te.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Te.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Te.prototype.filterData=function(t,e,n){let r=Pp(t,e,n,this._options),s=q.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Lp(r,e,n,this._options,s)};Te.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(Rp.crc32(r.slice(4,r.length-4)),r.length-4),r};Te.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*q.GAMMA_DIVISION),0),this._packChunk(q.TYPE_gAMA,e)};Te.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(q.TYPE_IHDR,n)};Te.prototype.packIDAT=function(t){return this._packChunk(q.TYPE_IDAT,t)};Te.prototype.packIEND=function(){return this._packChunk(q.TYPE_IEND,null)}});var Xa=S((aS,Ka)=>{"use strict";var Np=require("util"),Ya=require("stream"),Op=ct(),Bp=Cs(),Ja=Ka.exports=function(t){Ya.call(this);let e=t||{};this._packer=new Bp(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Np.inherits(Ja,Ya);Ja.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Op.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var rl=S((zt,nl)=>{"use strict";var Za=require("assert").ok,ut=require("zlib"),Dp=require("util"),Qa=require("buffer").kMaxLength;function je(t){if(!(this instanceof je))return new je(t);t&&t.chunkSize<ut.Z_MIN_CHUNK&&(t.chunkSize=ut.Z_MIN_CHUNK),ut.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 Hp(t){return new je(t)}function el(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}je.prototype._processChunk=function(t,e,n){if(typeof n=="function")return ut.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,h){if(r._hadError)return;let y=i-h;if(Za(y>=0,"have should not go down"),y>0){let m=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,m.length>o&&(m=m.slice(0,o)),l.push(m),c+=m.length,o-=m.length,o===0)return!1}return(h===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),h===0?(a+=s-g,s=g,!0):!1}Za(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Qa)throw el(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Qa.toString(16)+" bytes");let p=Buffer.concat(l,c);return el(this),p};Dp.inherits(je,ut.Inflate);function Fp(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=ut.Z_FINISH),t._processChunk(e,n)}function tl(t,e){return Fp(new je(e),t)}nl.exports=zt=tl;zt.Inflate=je;zt.createInflate=Hp;zt.inflateSync=tl});var Rs=S((lS,il)=>{"use strict";var sl=il.exports=function(t){this._buffer=t,this._reads=[]};sl.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};sl.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 al=S(ol=>{"use strict";var Up=Rs(),qp=ws();ol.process=function(t,e){let n=[],r=new Up(t);return new qp(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var dl=S((uS,ul)=>{"use strict";var ll=!0,cl=require("zlib"),jp=rl();cl.deflateSync||(ll=!1);var Wp=Rs(),Gp=al(),Vp=xs(),$p=Ts(),zp=ks();ul.exports=function(t,e){if(!ll)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(C){n=C}let s;function i(C){s=C}function o(C){s.transColor=C}function a(C){s.palette=C}function l(){s.alpha=!0}let c;function u(C){c=C}let d=[];function f(C){d.push(C)}let p=new Wp(t);if(new Vp(e,{read:p.read.bind(p),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let h=Buffer.concat(d);d.length=0;let y;if(s.interlace)y=cl.inflateSync(h);else{let B=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=jp(h,{chunkSize:B,maxLength:B})}if(h=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let m=Gp.process(y,s);h=null;let E=$p.dataToBitMap(m,s);m=null;let ae=zp(E,s);return s.data=ae,s.gamma=c||0,s}});var gl=S((dS,hl)=>{"use strict";var fl=!0,pl=require("zlib");pl.deflateSync||(fl=!1);var Yp=ct(),Jp=Cs();hl.exports=function(t,e){if(!fl)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 Jp(n),s=[];s.push(Buffer.from(Yp.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=pl.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var ml=S(Ps=>{"use strict";var Kp=dl(),Xp=gl();Ps.read=function(t,e){return Kp(t,e||{})};Ps.write=function(t,e){return Xp(t,e)}});var vl=S(Sl=>{"use strict";var Zp=require("util"),yl=require("stream"),Qp=qa(),eh=Xa(),th=ml(),j=Sl.PNG=function(t){yl.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 Qp(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 eh(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"))};Zp.inherits(j,yl);j.sync=th;j.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)};j.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};j.prototype.write=function(t){return this._parser.write(t),!0};j.prototype.end=function(t){this._parser.end(t)};j.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};j.prototype._gamma=function(t){this.gamma=t};j.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};j.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};j.prototype.bitblt=function(t,e,n,r,s,i,o){return j.bitblt(this,t,e,n,r,s,i,o),this};j.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};j.prototype.adjustGamma=function(){j.adjustGamma(this)}});var Yt=S(We=>{function _l(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("")}}We.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:_l(e.color.dark||"#000000ff"),light:_l(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};We.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};We.getImageWidth=function(e,n){let r=We.getScale(e,n);return Math.floor((e+n.margin*2)*r)};We.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=We.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,p=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),h=Math.floor((d-l)/o);p=c[i[g*s+h]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var wl=S(de=>{var nh=require("fs"),rh=vl().PNG,Ls=Yt();de.render=function(e,n){let r=Ls.getOptions(n),s=r.rendererOpts,i=Ls.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new rh(s);return Ls.qrToImageData(o.data,e,r),o};de.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),de.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};de.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=de.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};de.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=nh.createWriteStream(e);a.on("error",o),a.on("close",o),de.renderToFileStream(a,n,r)};de.renderToFileStream=function(e,n,r){de.render(n,r).pack().pipe(e)}});var bl=S(Vn=>{var sh=Yt(),ih={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},oh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function ah(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Vn.render=function(t,e,n){let r=sh.getOptions(e),s=ih;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=oh);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
|
|
14
|
-
`);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],p=o[(u+1)*i+d];a+=
|
|
13
|
+
`);let o=Xf(e,n,s),a=Gn.getSymbolSize(e),l=new Uf(a);return $f(l,e),zf(l),Yf(l,e),gs(l,n,0),e>=7&&Jf(l,e),Kf(l,o),isNaN(r)&&(r=ms.getBestMask(l,gs.bind(null,l,n))),ms.applyMask(r,l),gs(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Aa.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ps.M,s,i;return typeof n<"u"&&(r=ps.from(n.errorCorrectionLevel,ps.M),s=Wn.from(n.version),i=ms.from(n.maskPattern),n.toSJISFunc&&Gn.setToSJISFunction(n.toSJISFunc)),Qf(e,s,r,i)}});var vs=S((eS,Ta)=>{"use strict";var ep=require("util"),xa=require("stream"),re=Ta.exports=function(){xa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ep.inherits(re,xa);re.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))};re.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};re.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()))};re.prototype.destroySoon=re.prototype.end;re.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};re.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};re.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))};re.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};re.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 bs=S(_s=>{"use strict";var Te=[{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]}];_s.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Te.length;a++){let l=Te[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};_s.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Te[r].x.length,i=(e-s)/Te[r].x.length*8+Te[r].x[s],o=n%Te[r].y.length,a=(n-o)/Te[r].y.length*8+Te[r].y[o];return i*4+a*t*4}}});var ws=S((nS,ka)=>{"use strict";ka.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Is=S((rS,Ca)=>{"use strict";var tp=bs(),np=ws();function Ea(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var ut=Ca.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=tp.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Ea(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Ea(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};ut.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ut.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};ut.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};ut.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};ut.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=np(c,l,u);e[o]=a+d}};ut.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var La=S((sS,Pa)=>{"use strict";var rp=require("util"),Ra=vs(),sp=Is(),ip=Pa.exports=function(t){Ra.call(this);let e=[],n=this;this._filter=new sp(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};rp.inherits(ip,Ra)});var dt=S((iS,Ma)=>{"use strict";Ma.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Ts=S((oS,Na)=>{"use strict";var As=[];(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;As[t]=e}})();var xs=Na.exports=function(){this._crc=-1};xs.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=As[(this._crc^t[e])&255]^this._crc>>>8;return!0};xs.prototype.crc32=function(){return this._crc^-1};xs.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=As[(e^t[n])&255]^e>>>8;return e^-1}});var ks=S((aS,Oa)=>{"use strict";var O=dt(),op=Ts(),H=Oa.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[O.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[O.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[O.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[O.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[O.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[O.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(){}};H.prototype.start=function(){this.read(O.PNG_SIGNATURE.length,this._parseSignature.bind(this))};H.prototype._parseSignature=function(t){let e=O.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))};H.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==O.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new op,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};H.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};H.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};H.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))};H.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};H.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in O.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=O.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&O.COLORTYPE_PALETTE),color:!!(s&O.COLORTYPE_COLOR),alpha:!!(s&O.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};H.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};H.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()};H.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};H.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===O.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===O.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===O.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};H.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};H.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/O.GAMMA_DIVISION),this._handleChunkEnd()};H.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};H.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===O.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()};H.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};H.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Es=S(Da=>{"use strict";var Ba=bs(),ap=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],lp=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function cp(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,p=i>>4,n.push(p,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,p=i>>6&3,n.push(p,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,p=i>>7&1,n.push(p,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function up(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);ap[r](e,s,d,i),i+=r}return i}function dp(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);lp[r](e,d,f,i)}s.resetAfterLine()}}Da.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=cp(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=Ba.getImagePasses(n,r),f=Ba.getInterlaceIterator(n,r);else{let p=0;f=function(){let g=p;return p+=4,g},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=up(d[p],l,f,i,t,u):dp(d[p],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Cs=S((cS,Ha)=>{"use strict";function fp(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function pp(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function hp(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}Ha.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?fp(t,l,r,s,a):(o&&pp(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),hp(t,l,r,s,n))),l}});var qa=S((uS,Ua)=>{"use strict";var gp=require("util"),Rs=require("zlib"),Fa=vs(),mp=La(),yp=ks(),Sp=Es(),vp=Cs(),ue=Ua.exports=function(t){Fa.call(this),this._parser=new yp(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()};gp.inherits(ue,Fa);ue.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};ue.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Rs.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,Rs.Z_MIN_CHUNK);this._inflate=Rs.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ue.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new mp(this._bitmapInfo)};ue.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ue.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ue.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ue.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ue.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ue.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Sp.dataToBitMap(t,this._bitmapInfo);e=vp(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Wa=S((dS,ja)=>{"use strict";var ee=dt();ja.exports=function(t,e,n,r){let s=[ee.COLORTYPE_COLOR_ALPHA,ee.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let h=new ArrayBuffer(2);return new DataView(h).setInt16(0,256,!0),new Int16Array(h)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=ee.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=ee.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 p(){let g,h,y,m=o;switch(r.inputColorType){case ee.COLORTYPE_COLOR_ALPHA:m=i[u+3],g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_COLOR:g=i[u],h=i[u+1],y=i[u+2];break;case ee.COLORTYPE_ALPHA:m=i[u+1],g=i[u],h=g,y=g;break;case ee.COLORTYPE_GRAYSCALE:g=i[u],h=g,y=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(m/=o,g=Math.min(Math.max(Math.round((1-m)*f.red+m*g),0),o),h=Math.min(Math.max(Math.round((1-m)*f.green+m*h),0),o),y=Math.min(Math.max(Math.round((1-m)*f.blue+m*y),0),o))),{red:g,green:h,blue:y,alpha:m}}for(let g=0;g<n;g++)for(let h=0;h<e;h++){let y=p(i,u);switch(r.colorType){case ee.COLORTYPE_COLOR_ALPHA:case ee.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,s&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),s&&c.writeUInt16BE(y.alpha,d+6));break;case ee.COLORTYPE_ALPHA:case ee.COLORTYPE_GRAYSCALE:{let m=(y.red+y.green+y.blue)/3;r.bitDepth===8?(c[d]=m,s&&(c[d+1]=y.alpha)):(c.writeUInt16BE(m,d),s&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var $a=S((fS,Va)=>{"use strict";var Ga=ws();function _p(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function bp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function wp(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function Ip(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function Ap(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function xp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function Tp(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function kp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Ep(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-Ga(a,l,c);r[s+o]=u}}function Cp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-Ga(o,a,l);s+=Math.abs(c)}return s}var Rp={0:_p,1:wp,2:Ap,3:Tp,4:Ep},Pp={0:bp,1:Ip,2:xp,3:kp,4:Cp};Va.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let p=0;p<i.length;p++){let g=Pp[i[p]](t,l,o,s);g<f&&(u=i[p],f=g)}}c[a]=u,a++,Rp[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Ps=S((pS,za)=>{"use strict";var F=dt(),Lp=Ts(),Mp=Wa(),Np=$a(),Op=require("zlib"),ke=za.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||Op.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:F.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:F.COLORTYPE_COLOR_ALPHA,[F.COLORTYPE_GRAYSCALE,F.COLORTYPE_COLOR,F.COLORTYPE_COLOR_ALPHA,F.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([F.COLORTYPE_GRAYSCALE,F.COLORTYPE_COLOR,F.COLORTYPE_COLOR_ALPHA,F.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")};ke.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ke.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ke.prototype.filterData=function(t,e,n){let r=Mp(t,e,n,this._options),s=F.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Np(r,e,n,this._options,s)};ke.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(Lp.crc32(r.slice(4,r.length-4)),r.length-4),r};ke.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*F.GAMMA_DIVISION),0),this._packChunk(F.TYPE_gAMA,e)};ke.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(F.TYPE_IHDR,n)};ke.prototype.packIDAT=function(t){return this._packChunk(F.TYPE_IDAT,t)};ke.prototype.packIEND=function(){return this._packChunk(F.TYPE_IEND,null)}});var Xa=S((hS,Ka)=>{"use strict";var Bp=require("util"),Ya=require("stream"),Dp=dt(),Hp=Ps(),Ja=Ka.exports=function(t){Ya.call(this);let e=t||{};this._packer=new Hp(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Bp.inherits(Ja,Ya);Ja.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Dp.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var rl=S((zt,nl)=>{"use strict";var Za=require("assert").ok,ft=require("zlib"),Fp=require("util"),Qa=require("buffer").kMaxLength;function We(t){if(!(this instanceof We))return new We(t);t&&t.chunkSize<ft.Z_MIN_CHUNK&&(t.chunkSize=ft.Z_MIN_CHUNK),ft.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 Up(t){return new We(t)}function el(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}We.prototype._processChunk=function(t,e,n){if(typeof n=="function")return ft.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,h){if(r._hadError)return;let y=i-h;if(Za(y>=0,"have should not go down"),y>0){let m=r._buffer.slice(r._offset,r._offset+y);if(r._offset+=y,m.length>o&&(m=m.slice(0,o)),l.push(m),c+=m.length,o-=m.length,o===0)return!1}return(h===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),h===0?(a+=s-g,s=g,!0):!1}Za(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Qa)throw el(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Qa.toString(16)+" bytes");let p=Buffer.concat(l,c);return el(this),p};Fp.inherits(We,ft.Inflate);function qp(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=ft.Z_FINISH),t._processChunk(e,n)}function tl(t,e){return qp(new We(e),t)}nl.exports=zt=tl;zt.Inflate=We;zt.createInflate=Up;zt.inflateSync=tl});var Ls=S((gS,il)=>{"use strict";var sl=il.exports=function(t){this._buffer=t,this._reads=[]};sl.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};sl.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 al=S(ol=>{"use strict";var jp=Ls(),Wp=Is();ol.process=function(t,e){let n=[],r=new jp(t);return new Wp(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var dl=S((yS,ul)=>{"use strict";var ll=!0,cl=require("zlib"),Gp=rl();cl.deflateSync||(ll=!1);var Vp=Ls(),$p=al(),zp=ks(),Yp=Es(),Jp=Cs();ul.exports=function(t,e){if(!ll)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(C){n=C}let s;function i(C){s=C}function o(C){s.transColor=C}function a(C){s.palette=C}function l(){s.alpha=!0}let c;function u(C){c=C}let d=[];function f(C){d.push(C)}let p=new Vp(t);if(new zp(e,{read:p.read.bind(p),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let h=Buffer.concat(d);d.length=0;let y;if(s.interlace)y=cl.inflateSync(h);else{let B=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=Gp(h,{chunkSize:B,maxLength:B})}if(h=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let m=$p.process(y,s);h=null;let E=Yp.dataToBitMap(m,s);m=null;let ae=Jp(E,s);return s.data=ae,s.gamma=c||0,s}});var gl=S((SS,hl)=>{"use strict";var fl=!0,pl=require("zlib");pl.deflateSync||(fl=!1);var Kp=dt(),Xp=Ps();hl.exports=function(t,e){if(!fl)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 Xp(n),s=[];s.push(Buffer.from(Kp.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=pl.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var ml=S(Ms=>{"use strict";var Zp=dl(),Qp=gl();Ms.read=function(t,e){return Zp(t,e||{})};Ms.write=function(t,e){return Qp(t,e)}});var vl=S(Sl=>{"use strict";var eh=require("util"),yl=require("stream"),th=qa(),nh=Xa(),rh=ml(),j=Sl.PNG=function(t){yl.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 th(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 nh(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"))};eh.inherits(j,yl);j.sync=rh;j.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)};j.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};j.prototype.write=function(t){return this._parser.write(t),!0};j.prototype.end=function(t){this._parser.end(t)};j.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};j.prototype._gamma=function(t){this.gamma=t};j.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};j.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};j.prototype.bitblt=function(t,e,n,r,s,i,o){return j.bitblt(this,t,e,n,r,s,i,o),this};j.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};j.prototype.adjustGamma=function(){j.adjustGamma(this)}});var Yt=S(Ge=>{function _l(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("")}}Ge.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:_l(e.color.dark||"#000000ff"),light:_l(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ge.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Ge.getImageWidth=function(e,n){let r=Ge.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Ge.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=Ge.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,p=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),h=Math.floor((d-l)/o);p=c[i[g*s+h]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var bl=S(de=>{var sh=require("fs"),ih=vl().PNG,Ns=Yt();de.render=function(e,n){let r=Ns.getOptions(n),s=r.rendererOpts,i=Ns.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new ih(s);return Ns.qrToImageData(o.data,e,r),o};de.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),de.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};de.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=de.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};de.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=sh.createWriteStream(e);a.on("error",o),a.on("close",o),de.renderToFileStream(a,n,r)};de.renderToFileStream=function(e,n,r){de.render(n,r).pack().pipe(e)}});var wl=S(Vn=>{var oh=Yt(),ah={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},lh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function ch(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Vn.render=function(t,e,n){let r=oh.getOptions(e),s=ah;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=lh);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
|
|
14
|
+
`);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],p=o[(u+1)*i+d];a+=ch(f,p,s)}a+=c+`
|
|
15
15
|
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Vn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Vn.render(n,r);i.writeFile(e,o,s)}});var Al=S(Il=>{Il.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
|
|
16
16
|
`;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=s[u*r+d]?i:o;a+=c+`
|
|
17
17
|
`}return a+=l+`
|
|
18
|
-
`,typeof n=="function"&&n(null,a),a}});var El=S(kl=>{var
|
|
19
|
-
`+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[Tl(s,r,p,f)];d+=c[Tl(s,r,r,f)]+u}return d+=
|
|
20
|
-
`;return typeof r=="function"&&r(null,f),f}});var Ml=S($n=>{var
|
|
18
|
+
`,typeof n=="function"&&n(null,a),a}});var El=S(kl=>{var uh="\x1B[47m",dh="\x1B[40m",Os="\x1B[37m",Bs="\x1B[30m",Ve="\x1B[0m",fh=uh+Bs,ph=dh+Os,hh=function(t,e,n){return{"00":Ve+" "+t,"01":Ve+e+"\u2584"+t,"02":Ve+n+"\u2584"+t,10:Ve+e+"\u2580"+t,11:" ",12:"\u2584",20:Ve+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},xl=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},Tl=function(t,e,n,r){return xl(t,e,n,r)+xl(t,e,n,r+1)};kl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?ph:fh,c=hh(o,i?Bs:Os,i?Os:Bs),u=Ve+`
|
|
19
|
+
`+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[Tl(s,r,p,f)];d+=c[Tl(s,r,r,f)]+u}return d+=Ve,typeof n=="function"&&n(null,d),d}});var Rl=S(Cl=>{var gh=Al(),mh=El();Cl.render=function(t,e,n){return e&&e.small?mh.render(t,e,n):gh.render(t,e,n)}});var Hs=S(Ll=>{var yh=Yt();function Pl(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Ds(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Sh(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?Ds("M",l+n,.5+c+n):Ds("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=Ds("h",o),o=0)):s++}return r}Ll.render=function(e,n,r){let s=yh.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+Pl(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Pl(s.color.dark,"stroke")+' d="'+Sh(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
|
|
20
|
+
`;return typeof r=="function"&&r(null,f),f}});var Ml=S($n=>{var vh=Hs();$n.render=vh.render;$n.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+$n.render(n,r);i.writeFile(e,a,s)}});var Nl=S(zn=>{var Fs=Yt();function _h(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 bh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}zn.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=bh()),s=Fs.getOptions(s);let o=Fs.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Fs.qrToImageData(l.data,e,s),_h(a,i,o),a.putImageData(l,0,0),i};zn.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=zn.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Bl=S(Jt=>{var wh=Qr(),Us=Ss(),Ol=Nl(),Ih=Hs();function qs(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!wh())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=Us.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Us.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}Jt.create=Us.create;Jt.toCanvas=qs.bind(null,Ol.render);Jt.toDataURL=qs.bind(null,Ol.renderToDataURL);Jt.toString=qs.bind(null,function(t,e,n){return Ih.render(t,n)})});var Ul=S(Ee=>{var Dl=Qr(),js=Ss(),Ah=bl(),Hl=wl(),xh=Rl(),Fl=Ml();function Kt(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(Dl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Th(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Yn(t){switch(t){case"svg":return Fl;case"txt":case"utf8":return Hl;case"png":case"image/png":default:return Ah}}function kh(t){switch(t){case"svg":return Fl;case"terminal":return xh;case"utf8":default:return Hl}}function Xt(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=js.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=js.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Ee.create=js.create;Ee.toCanvas=Bl().toCanvas;Ee.toString=function(e,n,r){let s=Kt(e,n,r),i=s.opts?s.opts.type:void 0,o=kh(i);return Xt(o.render,e,s)};Ee.toDataURL=function(e,n,r){let s=Kt(e,n,r),i=Yn(s.opts.type);return Xt(i.renderToDataURL,e,s)};Ee.toBuffer=function(e,n,r){let s=Kt(e,n,r),i=Yn(s.opts.type);return Xt(i.renderToBuffer,e,s)};Ee.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Dl())throw new Error("Too few arguments provided");let i=Kt(n,r,s),o=i.opts.type||Th(e),l=Yn(o).renderToFile.bind(null,e);return Xt(l,n,i)};Ee.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Kt(n,r,e.emit.bind(e,"error")),o=Yn("png").renderToFileStream.bind(null,e);Xt(o,n,s)}});var jl=S((LS,ql)=>{ql.exports=Ul()});var Cu=require("http");var cf=Xe(Ao(),1),uf=Xe(qr(),1),df=Xe(Gr(),1),ff=Xe(Mn(),1),Zr=Xe(Mo(),1);var oe=require("fs/promises"),Ru=require("crypto"),_n=require("path"),Pu=require("os"),Lu=Xe(jl(),1);var mt=require("child_process"),nc=require("fs"),G=require("path"),en=require("os");var nr=require("fs");var Wl=require("os"),W=require("path"),pt=(0,W.join)((0,Wl.homedir)(),".vibelet"),Jn=(0,W.join)(pt,"logs"),Kn=(0,W.join)(pt,"data"),Eh=(0,W.join)(pt,"runtime"),MS=(0,W.join)(Eh,"current"),Gl=(0,W.join)(pt,"identity.json"),Vl=(0,W.join)(pt,"pairings.json"),$l=(0,W.join)(Kn,"push-subscriptions.json"),Xn=(0,W.join)(Kn,"sessions.json"),ht=(0,W.join)(Kn,"audit.jsonl"),Ws=(0,W.join)(Kn,"uploads"),Zn=(0,W.join)(Jn,"daemon.stdout.log"),Qn=(0,W.join)(Jn,"daemon.stderr.log"),zl=(0,W.join)(pt,"update-check.json");var er={stdout:!1,stderr:!1};function Yl(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Ch(t){return!t.destroyed&&t.writable!==!1}function Jl(t,e){if(er[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Ch(n))return er[t]=!0,!1;try{return n.write(e,r=>{Yl(r)&&(er[t]=!0)}),!0}catch(r){return Yl(r)&&(er[t]=!0),!1}}function Zt(t){return Jl("stdout",t)}function tr(t){return Jl("stderr",t)}var Kl={debug:10,info:20,warn:30,error:40},Rh=process.env.VIBE_LOG_LEVEL||"info";function Ph(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Lh(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var Zl=!Ph()&&!Lh();if(Zl)try{(0,nr.mkdirSync)(Jn,{recursive:!0})}catch{}function Xl(t,e,n){if(Kl[t]<Kl[Rh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?tr(s+`
|
|
21
21
|
`):Zt(s+`
|
|
22
22
|
`),Zl){let i=t==="error"||t==="warn"?Qn:Zn;try{(0,nr.appendFileSync)(i,s+`
|
|
23
|
-
`)}catch{}}}function Ql(t={}){function e(n,r,s){typeof r=="string"?Xl(n,t,r):Xl(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Ql({...t,...n})}}var P=Ql({module:"daemon"});var
|
|
24
|
-
`)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return
|
|
25
|
-
`;tn(
|
|
23
|
+
`)}catch{}}}function Ql(t={}){function e(n,r,s){typeof r=="string"?Xl(n,t,r):Xl(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Ql({...t,...n})}}var P=Ql({module:"daemon"});var Mh=["fnm_multishells"],Nh=6e4,Oh=P.child({module:"config"});function Ce(t){return Mh.some(e=>t.includes(e))}function Vs(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var gt=null;function rc(){if(gt&&!Ce(gt.PATH??""))return gt;for(let t of Vs())try{let e=(0,mt.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
|
|
24
|
+
`)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return Ce(n.PATH??"")?gt=null:gt=n,n}catch{}return gt={},{}}function Bh(t=rc()){let e=(0,en.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,G.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",s=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,G.join)(e,".npm-global","bin"),(0,G.join)(e,".local","bin"),(0,G.join)(e,".claude","bin"),n],i=r.split(G.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(G.delimiter)}function Gs(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 ec(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function rr(){let t=rc(),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=Bh(t),e.HOME||(e.HOME=(0,en.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Qt(t,e=3e3){try{return(0,mt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:rr()}).trim()||null}catch{return null}}function Dh(t){for(let e of Vs())try{let n=(0,mt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function Hh(){let t=(0,en.homedir)();return[(0,G.join)(t,".local","bin","claude"),(0,G.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,G.join)(t,".npm-global","bin","claude")]}function Fh(){for(let t of Hh())if(Qt(t))return t;try{let t=(0,mt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:rr()}).trim();if(t&&!t.includes("cmux")&&Qt(t))return t}catch{}}function Uh(){let t=(0,en.homedir)(),e=[process.env.PNPM_HOME,(0,G.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,G.join)(t,".npm-global","bin","codex"),(0,G.join)(t,".local","bin","codex"),...e.map(n=>(0,G.join)(n,"codex"))]}function qh(){let t;for(let n of Uh())if(Qt(n)){if(!Ce(n))return n;t=n}try{let n=(0,mt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:rr()}).trim();if(n&&Qt(n)){if(!Ce(n))return n;t=t??n}}catch{}let e=Dh("codex");if(e&&Qt(e)){if(!Ce(e))return e;t=t??e}return t}function sc(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();return(!n||i-r>Nh||!(0,nc.existsSync)(n)||Ce(n))&&(n=t()??e,r=i,Oh.info({name:e,path:n,transient:Ce(n)},"binary resolved")),n}}var jh=sc(Fh,"claude"),Wh=sc(qh,"codex");function Gh(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var tc=Gh();function Vh(t,e){return{command:Vs()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var v={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:tc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:tc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:ec("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:ec("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:Gs("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Gs("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Gs("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return jh()},get codexPath(){return Wh()},isTransientPath:Ce,execViaLoginShell:Vh,buildSanitizedEnv:rr};var vi=require("crypto"),au=require("fs/promises");var pc=require("child_process"),hc=require("fs");var sr=require("fs"),ac=require("path");var V=require("fs");function $h(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function tn(t,e){if(!(0,V.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,V.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=$h(r,e.maxBytes,s,e.retainBytes),o=(0,V.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,V.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,V.ftruncateSync)(o,0),a.length>0&&(0,V.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,V.closeSync)(o)}}function ic(t){let e=[tn(t.auditPath,{maxBytes:t.auditMaxBytes}),tn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),tn(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 oc=!1,zh=new Set(["ts","event","source","appEvent","level"]);function Yh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Jh(t={}){let e={};for(let[n,r]of Object.entries(t))zh.has(n)||(e[n]=r);return e}function Kh(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Jh(n)}}function Xh(){oc||((0,sr.mkdirSync)((0,ac.dirname)(ht),{recursive:!0}),oc=!0)}var $s=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(Kh(e,n,r,s))}write(e){if(!Yh()){Xh();try{let n=JSON.stringify(e)+`
|
|
25
|
+
`;tn(ht,{maxBytes:v.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,sr.appendFileSync)(ht,n)}catch{}}}},_=new $s;var Re=require("fs"),lc=require("os"),nn=require("path"),cc=require("crypto"),zs="claude-hook:",rn="x-vibelet-claude-hook-secret",sn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function Zh(t,e){return`#!/usr/bin/env node
|
|
26
26
|
const http = require('http');
|
|
27
27
|
const chunks = [];
|
|
28
28
|
process.stdin.on('data', (chunk) => chunks.push(chunk));
|
|
@@ -43,7 +43,7 @@ process.stdin.on('end', () => {
|
|
|
43
43
|
req.end(body);
|
|
44
44
|
});
|
|
45
45
|
process.stdin.resume();
|
|
46
|
-
`}function
|
|
46
|
+
`}function Qh(t,e){return`#!/usr/bin/env node
|
|
47
47
|
const http = require('http');
|
|
48
48
|
const fallback = ${JSON.stringify(JSON.stringify(sn))};
|
|
49
49
|
const chunks = [];
|
|
@@ -79,44 +79,44 @@ process.stdin.on('end', () => {
|
|
|
79
79
|
req.end(body);
|
|
80
80
|
});
|
|
81
81
|
process.stdin.resume();
|
|
82
|
-
`}function uc(t,e){let n=(0,nn.join)((0,lc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,cc.randomUUID)()}`);(0,
|
|
83
|
-
`)}function
|
|
84
|
-
`):""}function
|
|
82
|
+
`}function uc(t,e){let n=(0,nn.join)((0,lc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,cc.randomUUID)()}`);(0,Re.mkdirSync)(n,{recursive:!0});let r=(0,nn.join)(n,"settings.json"),s=(0,nn.join)(n,"session_hook_forwarder.cjs"),i=(0,nn.join)(n,"permission_hook_forwarder.cjs");return(0,Re.writeFileSync)(s,Zh(t,e),"utf8"),(0,Re.writeFileSync)(i,Qh(t,e),"utf8"),(0,Re.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function ir(t){if(t)try{(0,Re.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var te=P.child({module:"claude"}),gc="claude-permission-denial:",eg=/\u001B\[[0-?]*[ -/]*[@-~]/g;function tg(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Ys(t){tg()&&tr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
|
|
83
|
+
`)}function ng(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(`
|
|
84
|
+
`):""}function rg(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function sg(t){if(typeof t=="string")return t;let e=ng(t);return e||(rg(t)?"":JSON.stringify(t))}function ig(t){return/requested permissions|haven't granted/i.test(t)}function dc(t){return t.replace(eg,"").replace(/\s+/g," ").trim()}function og(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function ag(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 lg(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function fc(t){let e=dc(t.resultText??""),n=(t.stderrLines??[]).map(dc).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&ag(i));if(r)return lg(r);let s=[e,...n].find(i=>!!i&&!og(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function or(t){return t.startsWith(gc)}var on=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=v.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),te.info({sessionId:this.sessionId,cwd:e},"session initialized"),_.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),ir(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=uc(this.hookPort,this.hookSecret),n.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;te.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Ys(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0,this.proc=(0,pc.spawn)(v.claudePath,n,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",s=>{let i=s.message;s.code==="ENOENT"&&this.cwd&&!(0,hc.existsSync)(this.cwd)&&(i=`Working directory does not exist: ${this.cwd}`),te.error({sessionId:this.sessionId,error:i,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:i}),this.handler?.({type:"error",sessionId:this.sessionId,message:i})}),this.buffer="",this.proc.stdout.on("data",s=>{this.buffer+=s.toString();let i=this.buffer.split(`
|
|
85
85
|
`);this.buffer=i.pop();for(let o of i)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{te.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",s=>{let i=s.toString().trim();i&&(te.debug({sessionId:this.sessionId,stderr:i},"stderr"),this.lastStderr.push(i),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(s,i)=>{te.info({sessionId:this.sessionId,exitCode:s,signal:i},"process exited");let o=this.interrupted;this.proc=null,ir(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):s&&s!==0&&!this.sawFinalResult&&(te.error({sessionId:this.sessionId,exitCode:s,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:fc({stderrLines:this.lastStderr,exitCode:s})})),this.exitHandler?.(s)})}respondApproval(e,n){if(te.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return te.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+`
|
|
86
|
-
`),!0}setApprovalMode(e){this.approvalMode=e,te.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),te.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,ir(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(te.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=
|
|
87
|
-
`);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{x.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(x.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=
|
|
88
|
-
`),!0}restorePendingApproval(e){let n=
|
|
86
|
+
`),!0}setApprovalMode(e){this.approvalMode=e,te.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),te.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,ir(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(te.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=sg(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&ig(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(_.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":{this.replayPhase=!1;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.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){Ys("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:fc({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${gc}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;Ys("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var vc=require("child_process"),_c=require("fs");var Js=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();P.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},w=new Js;var mc=require("node:fs"),Ks=require("node:path"),cg="@vibelet/cli";function ug(t){try{let e=JSON.parse((0,mc.readFileSync)(t,"utf8"));if(e.name===cg&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function dg(){return"0.1.21"}var yt=dg();var x=P.child({module:"codex"});function fg(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function pg(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function $(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function k(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var hg=new Set(["aborted","interrupted","cancelled","canceled"]);function gg(t){let e=k(t);return e?e.toLowerCase():null}function mg(t){let e=k(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Xs(t){return t?k(t.itemId)??k(t.id)??k(t.callId)??k(t.call_id):null}function Zs(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function bc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function wc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function yg(t){if(!Array.isArray(t))return null;for(let e of t){let n=$(e);if(!n)continue;let r=k(n.id),s=Array.isArray(n.options)?n.options.map(l=>$(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>k(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>bc(l))??i[0],a=i.find(l=>wc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Sg(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>$(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>$(o)).filter(o=>!!o).map(o=>k(o.label)).filter(o=>!!o)),n=e.some(s=>bc(s)),r=e.some(s=>wc(s));return n&&r}function yc(t){let e=mg(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Zs(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Zs(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=k(t.server),r=k(t.tool)??k(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:$(t.arguments)??$(t.input)??{}}:null}return null}function vg(t){if(!Array.isArray(t))return"";for(let e of t){let n=$(e);if(!n)continue;let r=k(n.question)??k(n.header);if(r)return r}return""}function Sc(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var ar=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=v.codexPath,i,o=this.buildSpawnArgs();if(v.isTransientPath(s)){let c=v.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,x.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,vc.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:v.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,_c.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),x.error({error:u,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
|
|
87
|
+
`);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{x.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(x.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=w.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:yt},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=Sc(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.info({threadId:this.threadId},"thread created"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let n=Sc(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,x.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:n.approvalPolicy,sandboxPolicy:n.sandboxPolicy}).then(r=>{x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(r=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return x.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
|
|
88
|
+
`),!0}restorePendingApproval(e){let n=pg(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,x.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=w.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
|
|
89
89
|
`),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),x.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
|
|
90
90
|
`)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
|
|
91
|
-
`)}resolveToolContext(e){let n=$(e?.item)??e??null,r=
|
|
92
|
-
`)){let n=lr(e);if(n&&!
|
|
93
|
-
`).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function
|
|
94
|
-
`).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
|
|
95
|
-
`).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2],i=Qs(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function Fg(){let e=(await Hg()).filter(n=>Og(n.pid));return Promise.all(e.map(async n=>({pid:n.pid,agent:n.agent,command:n.command,cwd:await Bg(n.pid),sessionFiles:await Dg(n.pid)})))}function Ug(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function qg(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Re.join)((0,Zs.homedir)(),".claude","projects",Ug(e)),l=(await(0,yt.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 p=await(0,yt.stat)((0,Re.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Re.join)(o,c.name),d=St(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Re.join)((0,Zs.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,yt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Re.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,yt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await cn(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(n);let i=r;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function jg(){let t=await Fg(),e=await Promise.all(t.map(async r=>{let s=Lg(r);if(s)return Tc(s);if(Pg(r.agent,r.command))return null;let i=await qg(r.agent,r.cwd);return i?Tc({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=Ng(e.filter(r=>r!==null));return ln={value:n,expiresAt:Date.now()+Tg},n}async function Cc(){return ln&&Date.now()<ln.expiresAt?ln.value:an||(an=jg().finally(()=>{an=null}),an)}var $e=P.child({module:"inventory"}),Wg=6e3,Gg=1e4,Vg={listScannedSessions:pn,scanRunningSessions:Cc,searchSessionContent:Bc},se=$g(),dn=null,dr=0,pr=0,fr=0,ni=0,ri=new Set;function $g(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function zg(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode})}function Yg(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,pid:t.pid,command:t.command,confidence:t.confidence,isResponding:t.isResponding})}function Rc(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(zg).sort(),runningSessions:t.runningSessions.map(Yg).sort()})}function Jg(){for(let t of ri)try{t()}catch(e){$e.warn({error:String(e)},"session inventory backfill listener failed")}}function un(){b.gauge("session.inventory.external_cached_sessions",se.scannedSessions.length),b.gauge("session.inventory.external_running_sessions",se.runningSessions.length),b.gauge("session.inventory.backfill_inflight",dn?1:0)}function Mc(t){return ri.add(t),()=>{ri.delete(t)}}function Nc(){return{cachedSessions:se.scannedSessions.length,runningSessions:se.runningSessions.length,cacheAgeMs:se.refreshedAt?Math.max(0,Date.now()-se.refreshedAt):void 0,backfillInFlight:!!dn,lastBackfillDurationMs:fr||void 0,lastBackfillCompletedAt:pr?new Date(pr).toISOString():void 0,lastBackfillAppliedAt:ni?new Date(ni).toISOString():void 0}}un();var vt={daemonActive:3,externalRunning:2,idle:1},Pc={high:3,medium:2,low:1};function Oc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Kg(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||vt[e.runtime.state]-vt[t.runtime.state]||Oc(t,e)}function Xg(t,e){return vt[e.state]>vt[t.state]?e:vt[e.state]<vt[t.state]?t:Pc[e.confidence]>Pc[t.confidence]?e:t}function Zg(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Qg(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function em(t,e){return e?t?!(mt(e)&&!mt(t)):!0:!1}function si(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function tm(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...si()},managed:t.managed,approvalMode:t.approvalMode}}function nm(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,isResponding:t.isResponding}}}function rm(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function sm(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=em(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=Xg(s.runtime,n.runtime),l=s.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?n.lastActivityAt:Qg(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:Zg(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode})}}function im(...t){let e=new Map;for(let n of t)sm(e,n);return[...e.values()]}function om(t,e,n,r,s){let i=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&$e.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function am(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function Lc(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=im(t.sessionRecords.map(tm),t.scannedSessions,t.runningSessions.map(m=>nm(m,t.scannedAt)),t.activeSessions.map(rm)),c=t.deletedSessionIds?.size?l.filter(m=>!t.deletedSessionIds?.has(m.sessionId)):l,u=om(c,r,s,i,o),d=u.filter(m=>m.runtime.state!=="idle"||m.managed).sort(Kg),f=u.filter(m=>m.runtime.state==="idle"&&!m.managed).sort(Oc),p=am(f,n),g=f.slice(p,p+a),y=p+g.length<f.length&&g.length>0?{lastActivityAt:g[g.length-1].lastActivityAt,sessionId:g[g.length-1].sessionId}:void 0;return{sessions:n?g:[...d,...g],nextCursor:y}}function fn(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;$e.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||$e.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function lm(t=Date.now()){return se.refreshedAt===0||t-se.refreshedAt>=Gg}async function cm(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([fn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),fn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function um(t,e){if(dn)return;let n=dr,r=b.startTimer("session.inventory.backfill_latency_ms");dn=cm(t,e).then(s=>{if(n!==dr)return;let i=Rc(se);se=s;let o=Rc(s),a=r();fr=a,pr=Date.now(),un(),i!==o&&(ni=Date.now(),b.increment("session.inventory.backfill_applied"),$e.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),Jg())}).catch(s=>{n===dr&&(fr=r(),pr=Date.now(),un(),$e.warn({error:String(s),durationMs:fr},"session inventory external backfill failed"))}).finally(()=>{n===dr&&(dn=null,un())}),un()}async function hr(t){let e={...Vg,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??Wg);if(!t.search){let c=b.startTimer("session.inventory.fast_path_latency_ms");lm()&&um(e,n);let u=se,d=Lc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:u.scannedSessions,runningSessions:u.runningSessions,scannedAt:u.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd);return c(),d}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([fn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),fn("process.running_sessions",()=>e.scanRunningSessions(),[],n),fn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);return $e.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Lc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l)}var Pe=P.child({module:"scanner"});function Uc(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 qc=3e4,li=Uc(qc),ci=Uc(qc),ii=new Map,oi=new Map,_t=24;function mr(){li.clear(),ci.clear()}function jc(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function wt(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}function*Wc(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
|
|
96
|
-
`,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var ai=512*1024;async function Gc(t,e){if(e<=ai)return(0,L.readFile)(t,"utf-8");let n=await(0,L.open)(t,"r");try{let r=Buffer.alloc(ai),{bytesRead:s}=await n.read(r,0,ai,0);return r.toString("utf-8",0,s)}finally{await n.close()}}function pi(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 Vc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?pi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function yr(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 dm=["<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 fm(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?dm.some(r=>n.startsWith(r)):!1}function Sr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=yr(t.message.content);return fm(t,e)?"":e}function pm(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function $c(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function gr(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:si()}}function St(t,e){let n=(0,R.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 hm(t,e){let n=await Gc(t,e),r=Wc(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=Ve([u.customTitle,u.summary])),!l){let d=Sr(u),f=Ve([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||St("claude",t)||(0,R.basename)(t,".jsonl"),cwd:s,title:o??l??Ve([],a)}:null}async function gm(t,e){let n=await Gc(t,e),r=Wc(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=Ve([u.payload?.title,u.title])),!l){let d=Vc(u),f=d&&!$c(d)?Ve([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||St("codex",t)||(0,R.basename)(t,".jsonl"),cwd:s,title:o??l??Ve([],a)}:null}async function cn(t,e){let n=await(0,L.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await hm(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await gm(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Dc(t,e){let n=(0,R.join)((0,Se.homedir)(),".claude","projects");try{let r;t?r=[jc(t)]:r=(await(0,L.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,R.join)(n,l),u=await(0,L.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,R.join)(c,d))}let i=await wt(s,_t,async l=>{let c=await(0,L.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await wt(i,_t,async l=>{let c=await cn(l.path,"claude");return c&&e&&e.push(gr(c)),c})).filter(l=>l!==null).map(l=>gr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Pe.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Hc(t,e){let n=(0,R.join)((0,Se.homedir)(),".codex","sessions");try{let r=await(0,L.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,R.join)(n,l),u=await(0,L.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,R.join)(c,d),p=await(0,L.readdir)(f).catch(()=>[]);for(let g of p){let h=(0,R.join)(f,g),y=await(0,L.readdir)(h).catch(()=>[]);for(let m of y)m.endsWith(".jsonl")&&s.push((0,R.join)(h,m))}}}let i=await wt(s,_t,async l=>{let c=await(0,L.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await wt(i,_t,async l=>{let c=await cn(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(gr(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>gr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Pe.warn({error:String(r)},"failed to list codex sessions"),[]}}async function pn(t,e,n){let s=`list:${(0,Se.homedir)()}:${t??"all"}:${e??""}`,i=li.get(s);if(i)return i;let o=ii.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Dc(e,n);else if(t==="codex")l=await Hc(e,n);else{let[c,u]=await Promise.all([Dc(e,n),Hc(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return li.set(s,l),l})();return ii.set(s,a),a.finally(()=>ii.delete(s)),a}async function Bc(t,e){let r=`search:${(0,Se.homedir)()}:${t}:${e??"all"}`,s=ci.get(r);if(s)return s;let i=oi.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,R.join)((0,Se.homedir)(),".claude","projects");try{let f=await(0,L.readdir)(d,{withFileTypes:!0}),p=[];for(let h of f){if(!h.isDirectory())continue;let y=(0,R.join)(d,h.name),m=await(0,L.readdir)(y).catch(()=>[]);for(let E of m)E.endsWith(".jsonl")&&p.push((0,R.join)(y,E))}let g=await wt(p,_t,h=>Fc(h,l,"claude"));for(let h of g)h&&a.add(h)}catch(f){Pe.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,R.join)((0,Se.homedir)(),".codex","sessions");try{let f=[];async function p(h){let y=await(0,L.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let m of y){let E=(0,R.join)(h,m.name);m.isDirectory()?await p(E):m.name.endsWith(".jsonl")&&f.push(E)}}await p(d);let g=await wt(f,_t,h=>Fc(h,l,"codex"));for(let h of g)h&&a.add(h)}catch(f){Pe.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),ci.set(r,a),a})();return oi.set(r,o),o.finally(()=>oi.delete(r)),o}async function Fc(t,e,n){let r=(0,di.createReadStream)(t,{encoding:"utf-8"}),s=(0,fi.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?mm:ym,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||St(n,t):null}function mm(t){return t?.type==="user"&&t.message?.role==="user"?Sr(t):t?.type==="assistant"&&t.message?.role==="assistant"?yr(t.message.content):""}function ym(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return pi(t.payload.content)}let e=Vc(t);return e||""}async function ui(t,e){let n=(0,di.createReadStream)(t,{encoding:"utf-8"}),r=(0,fi.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function zc(t,e){let n=(0,R.join)((0,Se.homedir)(),".claude","projects"),r=e?jc(e):null,s=await(0,L.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,R.join)(n,o,`${t}.jsonl`);if((await(0,L.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Yc(t,e,n){if(e==="claude")return zc(t,n);let r=(0,R.join)((0,Se.homedir)(),".codex","sessions");return Jc(r,t)}function Sm(t){if(t?.type==="user"&&t.message?.role==="user")return pm(t.message.content)?{kind:"toolResult"}:Sr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=yr(t.message.content),n=t.message?.stop_reason;return{kind:"assistant",stopReason:typeof n=="string"?n:n??null,...e?{text:e}:{}}}return null}function vm(t){if(!t)return{};if(t.kind==="assistant"){let e=t.stopReason==null||t.stopReason==="tool_use";return{...e?{isResponding:!0}:{},...e&&t.text?{partialReplyText:t.text}:{}}}return{isResponding:!0}}async function ti(t,e){if(e!=="claude")return{};let n=null;try{await ui(t,r=>{let s=Sm(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Pe.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return vm(n)}async function hi(t,e,n){let r=await Yc(t,e,n);return r?ti(r,e):{}}async function hn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await zc(t,n);i&&await ui(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=Sr(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=yr(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Pe.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await Yc(t,e,n);i&&await ui(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=pi(o.payload.content);l&&(a==="user"&&$c(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Pe.warn({error:String(i)},"failed to read codex session history")}return r}async function Jc(t,e){try{let n=await(0,L.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,R.join)(t,r.name);if(r.isDirectory()){let i=await Jc(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Pe.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var bt=require("fs"),Zc=require("path");var _m=500,Kc=200;function wm(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Kc?e:e.slice(-Kc)}function bm(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function Im(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Xc(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:wm(t.acceptedClientMessageIds),pendingApproval:Im(t.pendingApproval)}}function Am(t){if(Array.isArray(t))return{records:t.map(Xc),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Xc):[],deletedSessionIds:bm(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var vr=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},_m)}loadFromDisk(){try{let e=(0,bt.readFileSync)(Xn,"utf-8");return Am(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,bt.mkdirSync)((0,Zc.dirname)(Xn),{recursive:!0}),(0,bt.writeFileSync)(Xn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var It=require("path"),Qc=require("os");function _r(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,It.join)((0,Qc.homedir)(),t.slice(2)):t}function xm(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function gi(t,e){let n=_r(xm(t));if(!n||(0,It.isAbsolute)(n))return n;let r=_r(e??"");return r?(0,It.resolve)(r,n):n}var eu={approvalRequestV1:"vibelet.approvalRequest.v1"};var At=require("fs"),tu=require("path");function Tm(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function km(t){try{let e=(0,At.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Tm):[]}catch{return[]}}function gn(t,e){(0,At.mkdirSync)((0,tu.dirname)(t),{recursive:!0}),(0,At.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
97
|
-
`,"utf8")}var wr=class{constructor(e=$l){this.pushSubscriptionsPath=e;this.records=km(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],gn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,gn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,gn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&gn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],gn(this.pushSubscriptionsPath,this.records)}};var z=P.child({module:"push"}),Em="https://exp.host/--/api/v2/push/send",Cm="https://exp.host/--/api/v2/push/getReceipts",Rm=[0,1e3,3e3],mn=new wr;function Pm(t){return!!(t&&typeof t=="object"&&typeof t.daemonId=="string"&&typeof t.canonicalHost=="string"&&typeof t.sessionId=="string"&&(t.agent==="claude"||t.agent==="codex")&&(t.eventType==="reply_ready"||t.eventType==="approval_request")&&(typeof t.requestId>"u"||typeof t.requestId=="string"))}function Lm(t){return new Promise(e=>{setTimeout(e,t)})}function nu(t){return t==="DeviceNotRegistered"}function Mm(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function Nm(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function Om(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function Bm(t,e,n,r){let s=new Map(t);for(let i of Rm){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(Cm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){z.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){z.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){z.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=Om(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(z.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),nu(f)){let p=r.unregisterToken(u);z.info({token:u,errorCode:f,removed:p},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&z.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function Dm(t){let e=t?.pushStore??mn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??Lm;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...Pm(a)&&a.eventType==="approval_request"?{categoryId:eu.approvalRequestV1}:{}}));try{let u=await n(Em,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){z.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){z.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:p}=Mm(d,l),g=Nm(d,l);for(let{token:h,ticket:y}of p){let m=y.details?.error;if(z.error({token:h,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),nu(m)){let E=e.unregisterToken(h);z.info({token:h,errorCode:m,removed:E},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await Bm(g,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function mi(t,e){mn.register(t,e),z.info({deviceId:t,token:e,total:mn.count()},"push token registered")}function yi(t,e){let n=mn.unregister(t,e);z.info({deviceId:t,token:e,total:mn.count(),removed:n},"push token unregistered")}var br=Dm();var w=P.child({module:"manager"}),Hm="Done.",Fm="Approval required",ru=180,Ar=200;function yn(...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>Ar&&e.splice(0,e.length-Ar));return e}function Ir(t){return t?.length?{acceptedClientMessageIds:yn(t)}:{}}function fe(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:yn(t.acceptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function su(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&or(e)}function iu(t,e,n){return{sessionId:t,agent:e,...n}}function Um(t){return t.startsWith(Vs)}function ou(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var xr=class{constructor(e=br){this.pushSender=e;this.removeInventoryBackfillListener=Mc(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new vr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){v.idleTimeoutMs<=0&&v.turnStallTimeoutMs<=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=v.idleTimeoutMs,r=v.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(w.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),b.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;w.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),b.increment("driver.stall_timeout",{agent:o.agent}),_.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(w.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),b.increment("driver.idle_timeout",{agent:o.agent}),_.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){e.driver?.onMessage(i=>{if(w.debug({agent:n,context:r,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&"sessionId"in i&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)&&this.remapSessionId(e,i.sessionId,s),(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!su(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(i.requestId,!0)??!1){_.emit("approval.response",{sessionId:e.sessionId,requestId:i.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}w.warn({sessionId:e.sessionId,requestId:i.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description,...i.approvalContext?{approvalContext:i.approvalContext}:{}},this.pushSender(Fm,this.buildPushBody(`${e.title||e.sessionId}: ${i.description||i.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:i.requestId,eventType:"approval_request"})}n==="claude"&&i.type==="approval.request"&&or(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:w.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),(i.type==="approval.request"||i.type==="session.done"||i.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,i),(i.type==="session.done"||i.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),e.driver?.onExit?.(i=>{w.info({agent:n,context:r,exitCode:i,sessionId:e.sessionId},"driver exited"),_.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:i}),b.increment("driver.exit",{agent:n,abnormal:i&&i!==0?"true":"false"});let o=!!(e.pendingApproval&&(e.agent==="codex"||i===0&&su(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){w.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;w.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(fe(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=b.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){w.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,w.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){w.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),w.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r){if(e!=="claude"||!(n instanceof on))return;let s=r??(0,Si.randomUUID)().replace(/-/g,"");return n.configureHookBridge(v.port,s),s}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=sn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&Um(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(w.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return w.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),sn;if(r.approvalMode==="autoApprove")return ou(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return sn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${Vs}${l.trim()||(0,Si.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},_.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),p}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=yn(r?.acceptedClientMessageIds),p=r?.isResponding,g=r?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.pendingApproval??l,c=h.title||c,u=h.createdAt||u,d=h.lastActivityAt||d,f=yn(h.acceptedClientMessageIds,f),g="record";else if(!r){let m=(await pn(n??i)).find(E=>E.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,p=m.runtime.isResponding??p,g="scanner")}if(!i&&n&&(i=n,g=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,source:g,managed:r?.managed??h?.managed,isResponding:p||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(iu(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(iu(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(fe(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=ru?n:`${n.slice(0,Math.max(1,ru-3)).trimEnd()}...`:Hm}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(fe(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;b.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,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return pn(e,n)}async handle(e,n){switch(w.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images);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}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){w.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){hr({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o){s=_r(s),w.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,au.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return w.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,s,i);w.info("continue mode: no previous sessions found, creating new")}catch(a){w.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=this.createDriver(r),l=this.configureDriverBeforeStart(r,a);if(r==="codex"){let p=`pending_${Date.now()}`;w.info({sessionId:p,agent:r,cwd:s},"session created (pending codex startup)"),b.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:p,agent:r,cwd:s,approvalMode:i});let g={sessionId:p,agent:r,cwd:s,approvalMode:i,driver:a,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:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(p,g),this.registerClaudeHookSession(g),this.store.upsert(fe(g)),this.updateGauges(),mr(),ur(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(g,r,"",e),this.reply(e,n,!0,{sessionId:p}),this.startPendingCodexSession(g,e);return}let c=b.startTimer("driver.spawn"),u=await a.start(s,void 0,i),d=c();w.info({sessionId:u,agent:r,spawnMs:d},"session created"),b.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:u,agent:r,cwd:s,approvalMode:i});let f={sessionId:u,agent:r,cwd:s,approvalMode:i,driver:a,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:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(fe(f)),this.updateGauges(),mr(),ur(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){w.error({agent:r,cwd:s,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated");let f=await hn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let g={type:"session.history",sessionId:r,messages:f,...Ir(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:p,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=b.startTimer("driver.spawn"),p=this.createDriver(s),g=this.configureDriverBeforeStart(s,p),h=await p.start(c,r,u),y=f();w.info({sessionId:h,agent:s,spawnMs:y},"session resumed"),b.increment("session.resume",{agent:s}),_.emit("session.resume",{sessionId:h,agent:s,cwd:c});let m={sessionId:h,agent:s,cwd:c,approvalMode:u,driver:p,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:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(h,m),this.registerClaudeHookSession(m),this.store.upsert(fe(m)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(m,s," (resumed)",e),this.restoreDriverPendingApproval(p,m.pendingApproval);let E=await hn(r,s,c);if(E.length>0||m.pendingApproval){w.info({sessionId:r,historyCount:E.length},"sending history messages");let ae={type:"session.history",sessionId:h,messages:E,...Ir(m.acceptedClientMessageIds),approvalMode:u,pendingApproval:m.pendingApproval};e.readyState===1&&e.send(JSON.stringify(ae))}this.reply(e,n,!0,{sessionId:h})}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>Ar&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Ar))}async sendMessage(e,n,r,s,i,o,a){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(r);if(!l||!l.driver){let d=await this.resolveReconnectSession(r,i,l);if(!d){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:d.agent,source:d.source},"auto-reconnecting session"),b.increment("session.reconnect",{agent:d.agent,source:d.source}),_.emit("session.reconnect",{sessionId:r,agent:d.agent,source:d.source});try{let f=this.createDriver(d.agent),p=this.configureDriverBeforeStart(d.agent,f,l?.claudeHookSecret);await f.start(d.cwd,r,d.approvalMode),this.restoreDriverPendingApproval(f,d.pendingApproval),l?(l.approvalMode=d.approvalMode,l.pendingApproval=d.pendingApproval,l.driver=f,l.active=!0,l.clients.add(e),l.lastActivityAt=d.lastActivityAt,l.lastActivityTs=Date.now(),l.isResponding=!1,l.currentReplyText="",l.acceptedClientMessageIds=yn(l.acceptedClientMessageIds,d.acceptedClientMessageIds),l.syntheticApprovalRetries=l.syntheticApprovalRetries??{},l.startupInProgress=!1,l.bufferedPrompts=l.bufferedPrompts??[],l.startupToken=l.startupToken??0,l.claudeHookSecret=p??l.claudeHookSecret,l.pendingClaudeHookApprovals=l.pendingClaudeHookApprovals??new Map):(l={sessionId:r,agent:d.agent,cwd:d.cwd,approvalMode:d.approvalMode,driver:f,clients:new Set([e]),title:d.title,createdAt:d.createdAt,lastActivityAt:d.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:d.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:d.managed,pendingApproval:d.pendingApproval,claudeHookSecret:p,pendingClaudeHookApprovals:new Map},this.sessions.set(r,l)),this.registerClaudeHookSession(l),this.bindDriverLifecycle(l,d.agent," (reconnected)"),this.store.upsert(fe(l)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(f){this.reply(e,n,!1,void 0,`Failed to reconnect: ${f}`);return}}if(l.clients.add(e),l.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(l,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(w.info({sessionId:r,clients:l.clients.size,hasDriver:!!l.driver,active:l.active,imageCount:a?.length??0},"sending message"),_.emit("session.send",{sessionId:r,agent:l.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),mt(l.title)){let d=Xs(s,50);d&&d!==l.title&&(l.title=d),this.store.upsert(fe(l))}o&&this.rememberAcceptedClientMessage(l,o),this.touchSession(l.sessionId);let c=a?.length?a.map(d=>`[Attached image: ${d}]`).join(`
|
|
91
|
+
`)}resolveToolContext(e){let n=$(e?.item)??e??null,r=Xs(n);if(!r)return null;let s=n?yc(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?Zs(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),_.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){x.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:fg(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!Sg(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=yg(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},vg(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},k(r?.reason)??k(r?.description)??"");return}if(e==="item/permissions/requestApproval"){x.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}x.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(x.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=$(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&x.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||x.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=$(r?.item),i=Xs(s),o=s?yc(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=$(r?.item)??r,i=Xs(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=k(r?.reason)??k($(r?.turn)?.reason);x.info({threadId:this.threadId,reason:s},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=$(r?.turn),i=gg(s?.status),o=$(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&hg.has(i)){x.info({threadId:this.threadId,status:i},"turn interrupted"),_.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}x.info({threadId:this.threadId,status:i??"completed"},"turn completed"),_.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var L=require("fs/promises"),fi=require("fs"),pi=require("readline"),R=require("path"),Se=require("os");var _g=new Set(["New session","Resumed session","Untitled session"]),bg=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function wg(t){return t.replace(/\s+/g," ").trim()}function lr(t){return typeof t!="string"?void 0:wg(t)||void 0}function Ic(t){let e=lr(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 St(t){let e=lr(t);return!e||_g.has(e)||Ic(e)}function Ig(t){for(let e of t.replace(/\r/g,"").split(`
|
|
92
|
+
`)){let n=lr(e);if(n&&!Ag(n)&&!xg(n))return n}}function Ag(t){return bg.some(e=>t.startsWith(e))}function xg(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Tg(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 Qs(t,e=80){if(typeof t!="string")return;let n=Ig(t);if(!n)return;let r=Tg(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Ic(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function $e(t,e){for(let n of t){let r=lr(n);if(!(!r||St(r)))return r}return Qs(e)}var kc=require("child_process"),vt=require("fs/promises"),Pe=require("path"),ei=require("os"),Ec=require("util");var kg=(0,Ec.promisify)(kc.execFile),Ac=P.child({module:"process-scanner"}),xc=1500,Eg="(^|[^[:alnum:]_.-])(claude|codex)([^[:alnum:]_.-]|$)",Cg=/(^|[^A-Za-z0-9_.-])(claude|codex)([^A-Za-z0-9_.-]|$)/,Rg=15e3,ln=null,an=null;function ur(){ln=null}function Pg(t){return t.replace(/^['"]|['"]$/g,"")}function Lg(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Pg)}function Mg(t){for(let e=0;e<t.length;e+=1){let n=t[e],r=(0,Pe.basename)(n);if(r==="claude"||r==="codex")return{agent:r,args:t.slice(e+1)};if(/\s/.test(n)){let s=dr(n);if(s)return s}}return null}function dr(t){return Mg(Lg(t))}function Ng(t){return Cg.test(t)}function Og(t,e){let n=dr(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function cr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Bg(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Dg(t,e){let n=dr(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function Hg(t){let e=Og(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(s=>Bg(t.agent,s));if(n.length!==1)return null;let r=_t(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 Fg(t,e){let n=t,r=e;return(cr(e.confidence)>cr(t.confidence)||cr(e.confidence)===cr(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,isResponding:n.isResponding??r.isResponding}}function Ug(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?Fg(s,n):n)}return[...e.values()]}function qg(t){try{return process.kill(t,0),!0}catch{return!1}}async function ti(t,e){try{let{stdout:n}=await kg(t,e,{maxBuffer:8388608,timeout:xc});return n}catch(n){let r=String(n);return r.includes("ESRCH")||r.includes("No such process")?Ac.debug({file:t,args:e,error:r},"process scan command skipped \u2014 process exited"):Ac.warn({file:t,args:e,timeoutMs:xc,error:r},"process scan command failed"),""}}async function Tc(t){if(!t.sessionFilePath)return t;let e=await cn(t.sessionFilePath,t.agent);if(!e)return null;let n=await ni(t.sessionFilePath,t.agent);return{...t,cwd:t.cwd||e.cwd,title:t.title??e.title,isResponding:n.isResponding}}async function jg(t){return(await ti("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
|
|
93
|
+
`).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function Wg(t){let n=(await ti("lsof",["-p",String(t),"-Fn"])).split(`
|
|
94
|
+
`).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 Gg(){return(await ti("pgrep",["-fal",Eg])).split(`
|
|
95
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2];if(!Ng(s))return null;let i=dr(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function Vg(){let e=(await Gg()).filter(n=>qg(n.pid));return Promise.all(e.map(async n=>({pid:n.pid,agent:n.agent,command:n.command,cwd:await jg(n.pid),sessionFiles:await Wg(n.pid)})))}function $g(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function zg(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Pe.join)((0,ei.homedir)(),".claude","projects",$g(e)),l=(await(0,vt.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 p=await(0,vt.stat)((0,Pe.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Pe.join)(o,c.name),d=_t(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Pe.join)((0,ei.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,vt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Pe.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,vt.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await cn(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(n);let i=r;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function Yg(){let t=await Vg(),e=await Promise.all(t.map(async r=>{let s=Hg(r);if(s)return Tc(s);if(Dg(r.agent,r.command))return null;let i=await zg(r.agent,r.cwd);return i?Tc({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=Ug(e.filter(r=>r!==null));return ln={value:n,expiresAt:Date.now()+Rg},n}async function Cc(){return ln&&Date.now()<ln.expiresAt?ln.value:an||(an=Yg().finally(()=>{an=null}),an)}var ze=P.child({module:"inventory"}),Jg=6e3,Kg=1e4,Xg={listScannedSessions:pn,scanRunningSessions:Cc,searchSessionContent:Bc},se=Zg(),dn=null,fr=0,hr=0,pr=0,ri=0,si=new Set;function Zg(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function Qg(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode})}function em(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,pid:t.pid,command:t.command,confidence:t.confidence,isResponding:t.isResponding})}function Rc(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(Qg).sort(),runningSessions:t.runningSessions.map(em).sort()})}function tm(){for(let t of si)try{t()}catch(e){ze.warn({error:String(e)},"session inventory backfill listener failed")}}function un(){w.gauge("session.inventory.external_cached_sessions",se.scannedSessions.length),w.gauge("session.inventory.external_running_sessions",se.runningSessions.length),w.gauge("session.inventory.backfill_inflight",dn?1:0)}function Mc(t){return si.add(t),()=>{si.delete(t)}}function Nc(){return{cachedSessions:se.scannedSessions.length,runningSessions:se.runningSessions.length,cacheAgeMs:se.refreshedAt?Math.max(0,Date.now()-se.refreshedAt):void 0,backfillInFlight:!!dn,lastBackfillDurationMs:pr||void 0,lastBackfillCompletedAt:hr?new Date(hr).toISOString():void 0,lastBackfillAppliedAt:ri?new Date(ri).toISOString():void 0}}un();var bt={daemonActive:3,externalRunning:2,idle:1},Pc={high:3,medium:2,low:1};function Oc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function nm(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||bt[e.runtime.state]-bt[t.runtime.state]||Oc(t,e)}function rm(t,e){return bt[e.state]>bt[t.state]?e:bt[e.state]<bt[t.state]?t:Pc[e.confidence]>Pc[t.confidence]?e:t}function sm(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function im(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function om(t,e){return e?t?!(St(e)&&!St(t)):!0:!1}function ii(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function am(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...ii()},managed:t.managed,approvalMode:t.approvalMode}}function lm(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,isResponding:t.isResponding}}}function cm(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function um(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=om(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=rm(s.runtime,n.runtime),l=s.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?n.lastActivityAt:im(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:sm(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode})}}function dm(...t){let e=new Map;for(let n of t)um(e,n);return[...e.values()]}function fm(t,e,n,r,s){let i=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&ze.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function pm(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function Lc(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=dm(t.sessionRecords.map(am),t.scannedSessions,t.runningSessions.map(m=>lm(m,t.scannedAt)),t.activeSessions.map(cm)),c=t.deletedSessionIds?.size?l.filter(m=>!t.deletedSessionIds?.has(m.sessionId)):l,u=fm(c,r,s,i,o),d=u.filter(m=>m.runtime.state!=="idle"||m.managed).sort(nm),f=u.filter(m=>m.runtime.state==="idle"&&!m.managed).sort(Oc),p=pm(f,n),g=f.slice(p,p+a),y=p+g.length<f.length&&g.length>0?{lastActivityAt:g[g.length-1].lastActivityAt,sessionId:g[g.length-1].sessionId}:void 0;return{sessions:n?g:[...d,...g],nextCursor:y}}function fn(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;ze.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||ze.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function hm(t=Date.now()){return se.refreshedAt===0||t-se.refreshedAt>=Kg}async function gm(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([fn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),fn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function mm(t,e){if(dn)return;let n=fr,r=w.startTimer("session.inventory.backfill_latency_ms");dn=gm(t,e).then(s=>{if(n!==fr)return;let i=Rc(se);se=s;let o=Rc(s),a=r();pr=a,hr=Date.now(),un(),i!==o&&(ri=Date.now(),w.increment("session.inventory.backfill_applied"),ze.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),tm())}).catch(s=>{n===fr&&(pr=r(),hr=Date.now(),un(),ze.warn({error:String(s),durationMs:pr},"session inventory external backfill failed"))}).finally(()=>{n===fr&&(dn=null,un())}),un()}async function gr(t){let e={...Xg,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??Jg);if(!t.search){let c=w.startTimer("session.inventory.fast_path_latency_ms");hm()&&mm(e,n);let u=se,d=Lc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:u.scannedSessions,runningSessions:u.runningSessions,scannedAt:u.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd);return c(),d}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([fn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),fn("process.running_sessions",()=>e.scanRunningSessions(),[],n),fn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);return ze.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),Lc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l)}var Le=P.child({module:"scanner"});function Uc(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 qc=3e4,ci=Uc(qc),ui=Uc(qc),oi=new Map,ai=new Map,wt=24;function yr(){ci.clear(),ui.clear()}function jc(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function It(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}function*Wc(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
|
|
96
|
+
`,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var li=512*1024;async function Gc(t,e){if(e<=li)return(0,L.readFile)(t,"utf-8");let n=await(0,L.open)(t,"r");try{let r=Buffer.alloc(li),{bytesRead:s}=await n.read(r,0,li,0);return r.toString("utf-8",0,s)}finally{await n.close()}}function hi(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 Vc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?hi(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Sr(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 ym=["<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 Sm(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?ym.some(r=>n.startsWith(r)):!1}function vr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Sr(t.message.content);return Sm(t,e)?"":e}function vm(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function $c(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function mr(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:ii()}}function _t(t,e){let n=(0,R.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 _m(t,e){let n=await Gc(t,e),r=Wc(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=$e([u.customTitle,u.summary])),!l){let d=vr(u),f=$e([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||_t("claude",t)||(0,R.basename)(t,".jsonl"),cwd:s,title:o??l??$e([],a)}:null}async function bm(t,e){let n=await Gc(t,e),r=Wc(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=$e([u.payload?.title,u.title])),!l){let d=Vc(u),f=d&&!$c(d)?$e([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||_t("codex",t)||(0,R.basename)(t,".jsonl"),cwd:s,title:o??l??$e([],a)}:null}async function cn(t,e){let n=await(0,L.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await _m(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await bm(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function Dc(t,e){let n=(0,R.join)((0,Se.homedir)(),".claude","projects");try{let r;t?r=[jc(t)]:r=(await(0,L.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,R.join)(n,l),u=await(0,L.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,R.join)(c,d))}let i=await It(s,wt,async l=>{let c=await(0,L.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await It(i,wt,async l=>{let c=await cn(l.path,"claude");return c&&e&&e.push(mr(c)),c})).filter(l=>l!==null).map(l=>mr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Le.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Hc(t,e){let n=(0,R.join)((0,Se.homedir)(),".codex","sessions");try{let r=await(0,L.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,R.join)(n,l),u=await(0,L.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,R.join)(c,d),p=await(0,L.readdir)(f).catch(()=>[]);for(let g of p){let h=(0,R.join)(f,g),y=await(0,L.readdir)(h).catch(()=>[]);for(let m of y)m.endsWith(".jsonl")&&s.push((0,R.join)(h,m))}}}let i=await It(s,wt,async l=>{let c=await(0,L.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await It(i,wt,async l=>{let c=await cn(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(mr(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>mr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Le.warn({error:String(r)},"failed to list codex sessions"),[]}}async function pn(t,e,n){let s=`list:${(0,Se.homedir)()}:${t??"all"}:${e??""}`,i=ci.get(s);if(i)return i;let o=oi.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await Dc(e,n);else if(t==="codex")l=await Hc(e,n);else{let[c,u]=await Promise.all([Dc(e,n),Hc(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return ci.set(s,l),l})();return oi.set(s,a),a.finally(()=>oi.delete(s)),a}async function Bc(t,e){let r=`search:${(0,Se.homedir)()}:${t}:${e??"all"}`,s=ui.get(r);if(s)return s;let i=ai.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,R.join)((0,Se.homedir)(),".claude","projects");try{let f=await(0,L.readdir)(d,{withFileTypes:!0}),p=[];for(let h of f){if(!h.isDirectory())continue;let y=(0,R.join)(d,h.name),m=await(0,L.readdir)(y).catch(()=>[]);for(let E of m)E.endsWith(".jsonl")&&p.push((0,R.join)(y,E))}let g=await It(p,wt,h=>Fc(h,l,"claude"));for(let h of g)h&&a.add(h)}catch(f){Le.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,R.join)((0,Se.homedir)(),".codex","sessions");try{let f=[];async function p(h){let y=await(0,L.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let m of y){let E=(0,R.join)(h,m.name);m.isDirectory()?await p(E):m.name.endsWith(".jsonl")&&f.push(E)}}await p(d);let g=await It(f,wt,h=>Fc(h,l,"codex"));for(let h of g)h&&a.add(h)}catch(f){Le.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),ui.set(r,a),a})();return ai.set(r,o),o.finally(()=>ai.delete(r)),o}async function Fc(t,e,n){let r=(0,fi.createReadStream)(t,{encoding:"utf-8"}),s=(0,pi.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?wm:Im,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||_t(n,t):null}function wm(t){return t?.type==="user"&&t.message?.role==="user"?vr(t):t?.type==="assistant"&&t.message?.role==="assistant"?Sr(t.message.content):""}function Im(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return hi(t.payload.content)}let e=Vc(t);return e||""}async function di(t,e){let n=(0,fi.createReadStream)(t,{encoding:"utf-8"}),r=(0,pi.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function zc(t,e){let n=(0,R.join)((0,Se.homedir)(),".claude","projects"),r=e?jc(e):null,s=await(0,L.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,R.join)(n,o,`${t}.jsonl`);if((await(0,L.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Yc(t,e,n){if(e==="claude")return zc(t,n);let r=(0,R.join)((0,Se.homedir)(),".codex","sessions");return Jc(r,t)}function Am(t){if(t?.type==="user"&&t.message?.role==="user")return vm(t.message.content)?{kind:"toolResult"}:vr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=Sr(t.message.content),n=t.message?.stop_reason;return{kind:"assistant",stopReason:typeof n=="string"?n:n??null,...e?{text:e}:{}}}return null}function xm(t){if(!t)return{};if(t.kind==="assistant"){let e=t.stopReason==null||t.stopReason==="tool_use";return{...e?{isResponding:!0}:{},...e&&t.text?{partialReplyText:t.text}:{}}}return{isResponding:!0}}async function ni(t,e){if(e!=="claude")return{};let n=null;try{await di(t,r=>{let s=Am(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Le.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return xm(n)}async function gi(t,e,n){let r=await Yc(t,e,n);return r?ni(r,e):{}}async function hn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await zc(t,n);i&&await di(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=vr(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=Sr(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Le.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await Yc(t,e,n);i&&await di(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=hi(o.payload.content);l&&(a==="user"&&$c(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Le.warn({error:String(i)},"failed to read codex session history")}return r}async function Jc(t,e){try{let n=await(0,L.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,R.join)(t,r.name);if(r.isDirectory()){let i=await Jc(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Le.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var At=require("fs"),Zc=require("path");var Tm=500,Kc=200;function km(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Kc?e:e.slice(-Kc)}function Em(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function Cm(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Xc(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:km(t.acceptedClientMessageIds),pendingApproval:Cm(t.pendingApproval)}}function Rm(t){if(Array.isArray(t))return{records:t.map(Xc),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Xc):[],deletedSessionIds:Em(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var _r=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},Tm)}loadFromDisk(){try{let e=(0,At.readFileSync)(Xn,"utf-8");return Rm(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,At.mkdirSync)((0,Zc.dirname)(Xn),{recursive:!0}),(0,At.writeFileSync)(Xn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var xt=require("path"),Qc=require("os");function br(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,xt.join)((0,Qc.homedir)(),t.slice(2)):t}function Pm(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function mi(t,e){let n=br(Pm(t));if(!n||(0,xt.isAbsolute)(n))return n;let r=br(e??"");return r?(0,xt.resolve)(r,n):n}var eu={approvalRequestV1:"vibelet.approvalRequest.v1"};var Tt=require("fs"),tu=require("path");function Lm(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function Mm(t){try{let e=(0,Tt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Lm):[]}catch{return[]}}function gn(t,e){(0,Tt.mkdirSync)((0,tu.dirname)(t),{recursive:!0}),(0,Tt.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
97
|
+
`,"utf8")}var wr=class{constructor(e=$l){this.pushSubscriptionsPath=e;this.records=Mm(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],gn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,gn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,gn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&gn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],gn(this.pushSubscriptionsPath,this.records)}};var z=P.child({module:"push"}),Nm="https://exp.host/--/api/v2/push/send",Om="https://exp.host/--/api/v2/push/getReceipts",Bm=[0,1e3,3e3],mn=new wr;function Dm(t){return!!(t&&typeof t=="object"&&typeof t.daemonId=="string"&&typeof t.canonicalHost=="string"&&typeof t.sessionId=="string"&&(t.agent==="claude"||t.agent==="codex")&&(t.eventType==="reply_ready"||t.eventType==="approval_request")&&(typeof t.requestId>"u"||typeof t.requestId=="string"))}function Hm(t){return new Promise(e=>{setTimeout(e,t)})}function nu(t){return t==="DeviceNotRegistered"}function Fm(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function Um(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function qm(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function jm(t,e,n,r){let s=new Map(t);for(let i of Bm){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(Om,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){z.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){z.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){z.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=qm(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(z.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),nu(f)){let p=r.unregisterToken(u);z.info({token:u,errorCode:f,removed:p},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&z.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function Wm(t){let e=t?.pushStore??mn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??Hm;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...Dm(a)&&a.eventType==="approval_request"?{categoryId:eu.approvalRequestV1}:{}}));try{let u=await n(Nm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){z.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){z.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:p}=Fm(d,l),g=Um(d,l);for(let{token:h,ticket:y}of p){let m=y.details?.error;if(z.error({token:h,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),nu(m)){let E=e.unregisterToken(h);z.info({token:h,errorCode:m,removed:E},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await jm(g,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function yi(t,e){mn.register(t,e),z.info({deviceId:t,token:e,total:mn.count()},"push token registered")}function Si(t,e){let n=mn.unregister(t,e);z.info({deviceId:t,token:e,total:mn.count(),removed:n},"push token unregistered")}var Ir=Wm();var b=P.child({module:"manager"}),Gm="Done.",Vm="Approval required",ru=180,xr=200;function yn(...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>xr&&e.splice(0,e.length-xr));return e}function Ar(t){return t?.length?{acceptedClientMessageIds:yn(t)}:{}}function fe(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:yn(t.acceptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function su(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&or(e)}function iu(t,e,n){return{sessionId:t,agent:e,...n}}function $m(t){return t.startsWith(zs)}function ou(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var Tr=class{constructor(e=Ir){this.pushSender=e;this.removeInventoryBackfillListener=Mc(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new _r;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){v.idleTimeoutMs<=0&&v.turnStallTimeoutMs<=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=v.idleTimeoutMs,r=v.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(b.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),w.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;b.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),w.increment("driver.stall_timeout",{agent:o.agent}),_.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(b.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),w.increment("driver.idle_timeout",{agent:o.agent}),_.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){e.driver?.onMessage(i=>{if(b.debug({agent:n,context:r,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&"sessionId"in i&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)&&this.remapSessionId(e,i.sessionId,s),(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!su(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(i.requestId,!0)??!1){_.emit("approval.response",{sessionId:e.sessionId,requestId:i.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}b.warn({sessionId:e.sessionId,requestId:i.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description,...i.approvalContext?{approvalContext:i.approvalContext}:{}},this.pushSender(Vm,this.buildPushBody(`${e.title||e.sessionId}: ${i.description||i.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:i.requestId,eventType:"approval_request"})}n==="claude"&&i.type==="approval.request"&&or(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:b.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),(i.type==="approval.request"||i.type==="session.done"||i.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,i),(i.type==="session.done"||i.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),e.driver?.onExit?.(i=>{b.info({agent:n,context:r,exitCode:i,sessionId:e.sessionId},"driver exited"),_.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:i}),w.increment("driver.exit",{agent:n,abnormal:i&&i!==0?"true":"false"});let o=!!(e.pendingApproval&&(e.agent==="codex"||i===0&&su(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){b.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;b.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(fe(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=w.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){b.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,b.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){b.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r){if(e!=="claude"||!(n instanceof on))return;let s=r??(0,vi.randomUUID)().replace(/-/g,"");return n.configureHookBridge(v.port,s),s}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=sn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&$m(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(b.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return b.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),sn;if(r.approvalMode==="autoApprove")return ou(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return sn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${zs}${l.trim()||(0,vi.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},_.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),p}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=yn(r?.acceptedClientMessageIds),p=r?.isResponding,g=r?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.pendingApproval??l,c=h.title||c,u=h.createdAt||u,d=h.lastActivityAt||d,f=yn(h.acceptedClientMessageIds,f),g="record";else if(!r){let m=(await pn(n??i)).find(E=>E.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,p=m.runtime.isResponding??p,g="scanner")}if(!i&&n&&(i=n,g=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,source:g,managed:r?.managed??h?.managed,isResponding:p||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(iu(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(iu(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(fe(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=ru?n:`${n.slice(0,Math.max(1,ru-3)).trimEnd()}...`:Gm}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(fe(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;w.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,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return pn(e,n)}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,n.images);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}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),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.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){gr({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o){s=br(s),b.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,au.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return b.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,s,i);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=this.createDriver(r),l=this.configureDriverBeforeStart(r,a);if(r==="codex"){let p=`pending_${Date.now()}`;b.info({sessionId:p,agent:r,cwd:s},"session created (pending codex startup)"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:p,agent:r,cwd:s,approvalMode:i});let g={sessionId:p,agent:r,cwd:s,approvalMode:i,driver:a,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:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(p,g),this.registerClaudeHookSession(g),this.store.upsert(fe(g)),this.updateGauges(),yr(),ur(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(g,r,"",e),this.reply(e,n,!0,{sessionId:p}),this.startPendingCodexSession(g,e);return}let c=w.startTimer("driver.spawn"),u=await a.start(s,void 0,i),d=c();b.info({sessionId:u,agent:r,spawnMs:d},"session created"),w.increment("session.create",{agent:r}),_.emit("session.create",{sessionId:u,agent:r,cwd:s,approvalMode:i});let f={sessionId:u,agent:r,cwd:s,approvalMode:i,driver:a,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:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(fe(f)),this.updateGauges(),yr(),ur(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){b.error({agent:r,cwd:s,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated");let f=await hn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let g={type:"session.history",sessionId:r,messages:f,...Ar(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:p,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=w.startTimer("driver.spawn"),p=this.createDriver(s),g=this.configureDriverBeforeStart(s,p),h=await p.start(c,r,u),y=f();b.info({sessionId:h,agent:s,spawnMs:y},"session resumed"),w.increment("session.resume",{agent:s}),_.emit("session.resume",{sessionId:h,agent:s,cwd:c});let m={sessionId:h,agent:s,cwd:c,approvalMode:u,driver:p,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:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(h,m),this.registerClaudeHookSession(m),this.store.upsert(fe(m)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(m,s," (resumed)",e),this.restoreDriverPendingApproval(p,m.pendingApproval);let E=await hn(r,s,c);if(E.length>0||m.pendingApproval){b.info({sessionId:r,historyCount:E.length},"sending history messages");let ae={type:"session.history",sessionId:h,messages:E,...Ar(m.acceptedClientMessageIds),approvalMode:u,pendingApproval:m.pendingApproval};e.readyState===1&&e.send(JSON.stringify(ae))}this.reply(e,n,!0,{sessionId:h})}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>xr&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-xr))}async sendMessage(e,n,r,s,i,o,a){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let l=this.sessions.get(r);if(!l||!l.driver){let d=await this.resolveReconnectSession(r,i,l);if(!d){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:d.agent,source:d.source},"auto-reconnecting session"),w.increment("session.reconnect",{agent:d.agent,source:d.source}),_.emit("session.reconnect",{sessionId:r,agent:d.agent,source:d.source});try{let f=this.createDriver(d.agent),p=this.configureDriverBeforeStart(d.agent,f,l?.claudeHookSecret);await f.start(d.cwd,r,d.approvalMode),this.restoreDriverPendingApproval(f,d.pendingApproval),l?(l.approvalMode=d.approvalMode,l.pendingApproval=d.pendingApproval,l.driver=f,l.active=!0,l.clients.add(e),l.lastActivityAt=d.lastActivityAt,l.lastActivityTs=Date.now(),l.isResponding=!1,l.currentReplyText="",l.acceptedClientMessageIds=yn(l.acceptedClientMessageIds,d.acceptedClientMessageIds),l.syntheticApprovalRetries=l.syntheticApprovalRetries??{},l.startupInProgress=!1,l.bufferedPrompts=l.bufferedPrompts??[],l.startupToken=l.startupToken??0,l.claudeHookSecret=p??l.claudeHookSecret,l.pendingClaudeHookApprovals=l.pendingClaudeHookApprovals??new Map):(l={sessionId:r,agent:d.agent,cwd:d.cwd,approvalMode:d.approvalMode,driver:f,clients:new Set([e]),title:d.title,createdAt:d.createdAt,lastActivityAt:d.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:d.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:d.managed,pendingApproval:d.pendingApproval,claudeHookSecret:p,pendingClaudeHookApprovals:new Map},this.sessions.set(r,l)),this.registerClaudeHookSession(l),this.bindDriverLifecycle(l,d.agent," (reconnected)"),this.store.upsert(fe(l)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(f){this.reply(e,n,!1,void 0,`Failed to reconnect: ${f}`);return}}if(l.clients.add(e),l.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(l,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(b.info({sessionId:r,clients:l.clients.size,hasDriver:!!l.driver,active:l.active,imageCount:a?.length??0},"sending message"),_.emit("session.send",{sessionId:r,agent:l.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),St(l.title)){let d=Qs(s,50);d&&d!==l.title&&(l.title=d),this.store.upsert(fe(l))}o&&this.rememberAcceptedClientMessage(l,o),this.touchSession(l.sessionId);let c=a?.length?a.map(d=>`[Attached image: ${d}]`).join(`
|
|
98
98
|
`):"",u=c?s?`${s}
|
|
99
99
|
|
|
100
|
-
${c}`:c:s;if(l.startupInProgress){l.isResponding=!0,l.currentReplyText="",l.lastUserMessage=s,l.bufferedPrompts.push(u),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(l.isResponding){l.bufferedPrompts.push(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}l.isResponding=!0,l.currentReplyText="",l.lastUserMessage=s,this.noteInventoryChanged("session_updated"),l.driver.sendPrompt(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await
|
|
101
|
-
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function cu(t,e=
|
|
102
|
-
`,"utf8")}function hu(t,e=Gl){try{let r=(0,
|
|
103
|
-
`,"utf8")}var Tr=class{constructor(e=Vl){this.pairingsPath=e;this.records=zm(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_${wi(8)}`,r=wi(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:n,pairNonce:r,expiresAt:s};return this.windows.set(r,i),i}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=wi(32),i={deviceId:e,deviceName:n,tokenHash:bi(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Sn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=bi(n);return gu(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),Sn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=bi(e),s=this.records.find(i=>!i.revokedAt&&gu(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),Sn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Sn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Sn(this.pairingsPath,this.records)}};function Et(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Ym(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function yu(t,e){return Ym(t)??e}function Ii(t,e){return!!(t&&e&&t===e)}function Su(t,e,n,r=!0){return t?Ii(t,e)?!0:!!n(t,r):!1}var _u=require("child_process");function Ai(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function wu(t){if(!Ai(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Jm(t){if(!Ai(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Km(t){if(!Ai(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function xi(t){return!!t&&!Jm(t)&&!Km(t)}function Ct(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function bu(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Xm(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||xi(s.address)&&(wu(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function vu(t){let e=JSON.parse(t),n=Ct(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>Ct(o)).filter(o=>!!o).filter(o=>wu(o)&&xi(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Iu(t=_u.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return vu(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return vu(n)}catch{return{fallbackHosts:[]}}}function Au(t){let e=Ct(t.canonicalHost),n=Ct(t.configuredCanonicalHost)||Ct(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Xm(t.interfaces)].map(s=>Ct(s)).filter(s=>!!s).filter(s=>xi(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function xu(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 U=P.child({module:"daemon"}),vn=P.child({module:"ws"});function Zm(){try{let t=JSON.parse(require("fs").readFileSync(zl,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var F=hu(v.port),J=new xr((t,e,n)=>br(t,e,{daemonId:F.daemonId,canonicalHost:F.canonicalHost,...n??{}})),Me=new Tr,kr=new Set,Le=new WeakMap,Tu=!1,Pu=Date.now(),Rt=null;function Pt(){let t=Iu();return Au({canonicalHost:F.canonicalHost,configuredCanonicalHost:v.canonicalHost,configuredFallbackHosts:bu(v.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Cu.networkInterfaces)()})}async function Ti(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 N(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function Qm(t){let e=(0,_n.extname)(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".md":"text/markdown; charset=utf-8",".markdown":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".js":"text/plain; charset=utf-8",".jsx":"text/plain; charset=utf-8",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".mjs":"text/plain; charset=utf-8",".cjs":"text/plain; charset=utf-8",".css":"text/plain; charset=utf-8",".html":"text/plain; charset=utf-8",".yml":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8"}[e]||"application/octet-stream"}function Lu(){let t=Me.openWindow(),e=Pt(),n=e.canonicalHost,r=F.port,s=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(v.relayUrl)try{let i=new URL(v.relayUrl);n=i.hostname,r=i.port?Number(i.port):i.protocol==="https:"?443:80,s=[e.canonicalHost,...s??[]].filter(Boolean)}catch{U.warn({relayUrl:v.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:F.daemonId,displayName:F.displayName,canonicalHost:n,fallbackHosts:s,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function ey(t,e){let n=gi(t,e),r=await(0,oe.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,oe.stat)((0,_n.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var wn=(0,ku.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${v.port}`);if(n.pathname==="/health"){let s=Pt(),i={status:"ok",version:gt,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Pu)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:Me.pairedCount(),wsClients:ie.clients.size,drivers:J.getDriverCounts(),sessionInventory:Nc(),metrics:b.snapshot()};v.relayUrl&&(i.relayUrl=v.relayUrl);let o=Zm();o&&(i.latestVersion=o),N(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,Lu());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}Me.reset(),N(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,{status:"stopping"}),setTimeout(()=>ze("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!Et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Ti(t),i=t.headers[rn],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),N(e,200,{ok:!0})}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!Et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Ti(t),i=t.headers[rn],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);N(e,200,a)}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await Ti(t);if(s.daemonId!==F.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){N(e,400,{error:"invalid_pair_request"});return}if(!Me.consumeWindow(s.pairNonce)){N(e,401,{error:"pair_window_expired"});return}let o=Me.issuePairToken(s.deviceId,s.deviceName),a=Pt();N(e,200,{daemonId:F.daemonId,displayName:F.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:F.port,deviceId:s.deviceId,pairToken:o})}catch(s){N(e,400,{error:String(s)})}return}let r=yu(t.headers.authorization,n.searchParams.get("token"));if(!Su(r,v.legacyToken,(s,i)=>Me.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){N(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,oe.mkdir)(qs,{recursive:!0});let u=`${Date.now()}_${(0,Eu.randomBytes)(8).toString("hex")}${o}`,d=(0,_n.join)(qs,u);await(0,oe.writeFile)(d,Buffer.concat(l)),U.info({filePath:d,size:c},"file uploaded"),N(e,200,{path:d})}catch(u){U.error({error:String(u)},"upload failed"),N(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=gi(s,i);if(!(await(0,oe.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=Qm(o),c=await(0,oe.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${gt}`)}),ie=new Kr.default({server:wn});wn.on("connection",t=>{kr.add(t),t.on("close",()=>{kr.delete(t)})});ie.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${v.port}`).searchParams.get("token");if(r&&Ii(r,v.legacyToken))Le.set(t,{authMode:"query_token"}),b.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=Me.validateAnyPairToken(r);if(s)Le.set(t,{authMode:"query_token",deviceId:s.deviceId}),b.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else{b.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}vn.info({clients:ie.clients.size},"client connected"),b.increment("ws.connect"),b.gauge("ws.clients",ie.clients.size),_.emit("ws.connect",{clients:ie.clients.size,authMode:Le.get(t)?.authMode??"pending",deviceId:Le.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(xu(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!Le.has(t)){if(o.action==="auth.hello"&&o.daemonId===F.daemonId&&Me.validatePairToken(o.deviceId,o.pairToken)){Le.set(t,{authMode:"auth_hello",deviceId:o.deviceId}),b.increment("ws.auth.success",{mode:"auth_hello"}),J.addGlobalClient(t),J.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:F.daemonId,displayName:F.displayName}}));return}if(o.action==="auth.hello"){b.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}b.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)_.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?U.error:a.level==="warn"?U.warn:U.info).call(U,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await ey(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=Le.get(t);vi(i,{deviceId:a?.deviceId,registerToken:mi,unregisterToken:yi,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Le.get(t);vi(i,{deviceId:a?.deviceId,registerToken:mi,unregisterToken:yi,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){vn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{vn.info({clients:ie.clients.size,code:s},"client disconnected"),b.increment("ws.disconnect"),b.increment("ws.disconnect.code",{code:String(s)}),b.gauge("ws.clients",ie.clients.size),_.emit("ws.disconnect",{clients:ie.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{vn.error({error:s.message},"websocket error")})});function ki(){for(let t of kr)try{t.destroy()}catch{}kr.clear()}function Mu(){let t=ic({auditPath:ft,stdoutLogPath:Zn,stderrLogPath:Qn,auditMaxBytes:v.auditMaxBytes,logMaxBytes:v.daemonLogMaxBytes});t.trimmedFiles>0&&U.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 ty(){Rt||(Rt=setInterval(Mu,v.storageHousekeepingIntervalMs),Rt.unref())}function ny(){Rt&&(clearInterval(Rt),Rt=null)}function ze(t,e=0){if(!Tu){Tu=!0,U.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Pu)/1e3)}),b.stopPeriodicLog(),ny(),J.shutdown();for(let n of ie.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ie.close(n=>{n&&U.error({error:String(n)},"websocket close error")}),wn.close(n=>{if(n){U.error({error:String(n)},"http close error"),ki(),process.exit(1);return}ki(),process.exit(e)}),setTimeout(()=>{U.error("force exiting after shutdown timeout"),ki(),process.exit(e||1)},3e3).unref()}}ie.on("error",t=>{vn.error({error:t.message},"wss error")});wn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=cu(v.port).filter(n=>n.pid!==process.pid);U.error({port:v.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else U.error({error:String(t)},"server error");ze(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ze("SIGINT"));process.once("SIGTERM",()=>ze("SIGTERM"));process.once("SIGHUP",()=>ze("SIGHUP"));process.once("SIGTTIN",()=>ze("SIGTTIN"));process.once("SIGTSTP",()=>ze("SIGTSTP"));process.on("uncaughtException",t=>{U.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{U.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});wn.listen(v.port,async()=>{Mu(),_.emit("daemon.start",{port:v.port}),b.startPeriodicLog(),ty(),U.info({port:v.port,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:Pt().canonicalHost,fallbackHosts:Pt().fallbackHosts,claudePath:v.claudePath,codexPath:v.codexPath,auditMaxBytes:v.auditMaxBytes,daemonLogMaxBytes:v.daemonLogMaxBytes,storageHousekeepingIntervalMs:v.storageHousekeepingIntervalMs,turnStallTimeoutMs:v.turnStallTimeoutMs},"daemon started");let t=Pt(),e=Lu();Zt(`
|
|
100
|
+
${c}`:c:s;if(l.startupInProgress){l.isResponding=!0,l.currentReplyText="",l.lastUserMessage=s,l.bufferedPrompts.push(u),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(l.isResponding){l.bufferedPrompts.push(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}l.isResponding=!0,l.currentReplyText="",l.lastUserMessage=s,this.noteInventoryChanged("session_updated"),l.driver.sendPrompt(u),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await gr({agent:r,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(f){b.warn({error:String(f)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}c={...c,inventoryVersion:this.inventoryVersion};let u;if(o&&!l.has(o)){let f=a??c.sessions.find(h=>h.sessionId===o)?.agent,p=this.sessions.get(o);p&&p.clients.add(e);let g=await this.resolveReconnectSession(o,f,p);if(g){let h=await hn(o,g.agent,p?.cwd??g.cwd),y=p?{}:await gi(o,g.agent,g.cwd);u={sessionId:o,agent:g.agent,messages:h,...Ar(p?.acceptedClientMessageIds??g.acceptedClientMessageIds),isResponding:p?.isResponding??y.isResponding??g.isResponding,partialReplyText:p?this.currentPartialReplyText(p):y.partialReplyText,approvalMode:p?.approvalMode??g.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{}}}}let d=this.collectReconnectPendingApprovals();w.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,inventoryVersion:c.inventoryVersion,...u?{activeSession:u}:{},...d.length>0?{pendingApprovals:d}:{}}})}catch(l){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),l.resolve(ou(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&or(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(fe(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),b.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),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,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):b.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(fe(i)),this.noteInventoryChanged("session_updated"),b.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(_.emit("session.interrupt",{sessionId:r,agent:s.agent}),s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;b.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}b.info({sessionId:r,agent:s.agent},"stopping session"),_.emit("session.stop",{sessionId:r,agent:s.agent}),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.updateGauges(),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(b.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),_.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),yr(),ur(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r);if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let o=i?.cwd??this.store.find(r)?.cwd??"",a=this.store.find(r),l=await hn(r,s,o),c=i?{}:await gi(r,s,o),u=i?.isResponding??c.isResponding,d=i?this.currentPartialReplyText(i):c.partialReplyText;b.info({sessionId:r,historyCount:l.length,isResponding:u,approvalMode:i?.approvalMode??a?.approvalMode},"sending history");let f={type:"session.history",sessionId:r,messages:l,...Ar(i?.acceptedClientMessageIds??a?.acceptedClientMessageIds),isResponding:u,partialReplyText:d,approvalMode:i?.approvalMode??a?.approvalMode,pendingApproval:i?.pendingApproval??a?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(f)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await gr({agent:r,cwd:s,search:i,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...l,inventoryVersion:this.inventoryVersion})}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new on;case"codex":return new ar;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 s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&w.increment("broadcast.fail"),n.type!=="text.delta"&&b.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function _i(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var lu=require("child_process");function zm(t,e){return(0,lu.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function Ym(t){let e=t.split(`
|
|
101
|
+
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function cu(t,e=zm){let n;try{n=Ym(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var kt=require("fs"),bi=require("os"),du=require("crypto"),fu=require("path");function pu(t){return(0,du.randomBytes)(t).toString("base64url")}function Jm(){return`d_${pu(12)}`}function Km(){return(0,bi.hostname)()}function Xm(){let t=(0,bi.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Zm(t){return{daemonId:Jm(),daemonSecret:pu(32),displayName:Km(),canonicalHost:Xm(),port:t,createdAt:new Date().toISOString()}}function uu(t,e){(0,kt.mkdirSync)((0,fu.dirname)(e),{recursive:!0}),(0,kt.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
102
|
+
`,"utf8")}function hu(t,e=Gl){try{let r=(0,kt.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,uu(i,e)),i}}catch{}let n=Zm(t);return uu(n,e),n}var Et=require("crypto"),Ct=require("fs"),mu=require("path");function wi(t){return(0,Et.randomBytes)(t).toString("base64url")}function Ii(t){return(0,Et.createHash)("sha256").update(t).digest("hex")}function gu(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Et.timingSafeEqual)(n,r)}function Qm(t){try{let e=(0,Ct.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 Sn(t,e){(0,Ct.mkdirSync)((0,mu.dirname)(t),{recursive:!0}),(0,Ct.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
103
|
+
`,"utf8")}var kr=class{constructor(e=Vl){this.pairingsPath=e;this.records=Qm(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_${wi(8)}`,r=wi(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:n,pairNonce:r,expiresAt:s};return this.windows.set(r,i),i}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=wi(32),i={deviceId:e,deviceName:n,tokenHash:Ii(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Sn(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=Ii(n);return gu(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),Sn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Ii(e),s=this.records.find(i=>!i.revokedAt&&gu(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),Sn(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Sn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Sn(this.pairingsPath,this.records)}};function Rt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function ey(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function yu(t,e){return ey(t)??e}function Ai(t,e){return!!(t&&e&&t===e)}function Su(t,e,n,r=!0){return t?Ai(t,e)?!0:!!n(t,r):!1}var bu=require("child_process");function xi(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function wu(t){if(!xi(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function ty(t){if(!xi(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function ny(t){if(!xi(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function Er(t){return!!t&&!ty(t)&&!ny(t)}function ve(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function vu(t,e){return(t??[]).map(n=>ve(n)).filter(n=>!!n).filter(n=>Er(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function Iu(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function ry(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||Er(s.address)&&(wu(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function _u(t){let e=JSON.parse(t),n=ve(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>ve(o)).filter(o=>!!o).filter(o=>wu(o)&&Er(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Au(t=bu.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return _u(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return _u(n)}catch{return{fallbackHosts:[]}}}function xu(t){let e=ve(t.canonicalHost)||"localhost",n=vu(t.fallbackHosts,e);if(!t.relayUrl)return{canonicalHost:e,fallbackHosts:n,port:t.port};try{let r=new URL(t.relayUrl),s=ve(r.hostname);if(!s)throw new Error("invalid relay hostname");let i=r.port?Number(r.port):r.protocol==="https:"?443:80;return{canonicalHost:s,fallbackHosts:vu([e,...n],s),port:Number.isFinite(i)&&i>0?Math.floor(i):t.port}}catch{return{canonicalHost:e,fallbackHosts:n,port:t.port}}}function Tu(t){let e=ve(t.canonicalHost),n=ve(t.configuredCanonicalHost)||ve(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...ry(t.interfaces)].map(s=>ve(s)).filter(s=>!!s).filter(s=>Er(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function ku(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 q=P.child({module:"daemon"}),vn=P.child({module:"ws"});function sy(){try{let t=JSON.parse(require("fs").readFileSync(zl,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var U=hu(v.port),J=new Tr((t,e,n)=>Ir(t,e,{daemonId:U.daemonId,canonicalHost:Ye().canonicalHost,...n??{}})),Ne=new kr,Cr=new Set,Me=new WeakMap,Eu=!1,Mu=Date.now(),Pt=null;function iy(){let t=Au();return Tu({canonicalHost:U.canonicalHost,configuredCanonicalHost:v.canonicalHost,configuredFallbackHosts:Iu(v.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Pu.networkInterfaces)()})}function Ye(){let t=iy();return xu({canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,port:U.port,relayUrl:v.relayUrl})}async function Ti(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 N(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function oy(t){let e=(0,_n.extname)(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".md":"text/markdown; charset=utf-8",".markdown":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".js":"text/plain; charset=utf-8",".jsx":"text/plain; charset=utf-8",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".mjs":"text/plain; charset=utf-8",".cjs":"text/plain; charset=utf-8",".css":"text/plain; charset=utf-8",".html":"text/plain; charset=utf-8",".yml":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8"}[e]||"application/octet-stream"}function Nu(){let t=Ne.openWindow(),e=Ye();return{type:"vibelet-pair",daemonId:U.daemonId,displayName:U.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function ay(t,e){let n=mi(t,e),r=await(0,oe.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,oe.stat)((0,_n.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var bn=(0,Cu.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${v.port}`);if(n.pathname==="/health"){let s=Ye(),i={status:"ok",version:yt,daemonId:U.daemonId,displayName:U.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Mu)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:Ne.pairedCount(),wsClients:ie.clients.size,drivers:J.getDriverCounts(),sessionInventory:Nc(),metrics:w.snapshot()};v.relayUrl&&(i.relayUrl=v.relayUrl);let o=sy();o&&(i.latestVersion=o),N(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,Nu());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}Ne.reset(),N(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,{status:"stopping"}),setTimeout(()=>Je("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!Rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Ti(t),i=t.headers[rn],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),N(e,200,{ok:!0})}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!Rt(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Ti(t),i=t.headers[rn],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);N(e,200,a)}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await Ti(t);if(s.daemonId!==U.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){N(e,400,{error:"invalid_pair_request"});return}if(!Ne.consumeWindow(s.pairNonce)){N(e,401,{error:"pair_window_expired"});return}let o=Ne.issuePairToken(s.deviceId,s.deviceName),a=Ye();N(e,200,{daemonId:U.daemonId,displayName:U.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,deviceId:s.deviceId,pairToken:o})}catch(s){N(e,400,{error:String(s)})}return}let r=yu(t.headers.authorization,n.searchParams.get("token"));if(!Su(r,v.legacyToken,(s,i)=>Ne.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){N(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,oe.mkdir)(Ws,{recursive:!0});let u=`${Date.now()}_${(0,Ru.randomBytes)(8).toString("hex")}${o}`,d=(0,_n.join)(Ws,u);await(0,oe.writeFile)(d,Buffer.concat(l)),q.info({filePath:d,size:c},"file uploaded"),N(e,200,{path:d})}catch(u){q.error({error:String(u)},"upload failed"),N(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=mi(s,i);if(!(await(0,oe.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=oy(o),c=await(0,oe.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${yt}`)}),ie=new Zr.default({server:bn});bn.on("connection",t=>{Cr.add(t),t.on("close",()=>{Cr.delete(t)})});ie.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${v.port}`).searchParams.get("token");if(r&&Ai(r,v.legacyToken))Me.set(t,{authMode:"query_token"}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=Ne.validateAnyPairToken(r);if(s)Me.set(t,{authMode:"query_token",deviceId:s.deviceId}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else{w.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}vn.info({clients:ie.clients.size},"client connected"),w.increment("ws.connect"),w.gauge("ws.clients",ie.clients.size),_.emit("ws.connect",{clients:ie.clients.size,authMode:Me.get(t)?.authMode??"pending",deviceId:Me.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(ku(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!Me.has(t)){if(o.action==="auth.hello"&&o.daemonId===U.daemonId&&Ne.validatePairToken(o.deviceId,o.pairToken)){Me.set(t,{authMode:"auth_hello",deviceId:o.deviceId}),w.increment("ws.auth.success",{mode:"auth_hello"}),J.addGlobalClient(t),J.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:U.daemonId,displayName:U.displayName}}));return}if(o.action==="auth.hello"){w.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}w.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)_.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?q.error:a.level==="warn"?q.warn:q.info).call(q,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await ay(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=Me.get(t);_i(i,{deviceId:a?.deviceId,registerToken:yi,unregisterToken:Si,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Me.get(t);_i(i,{deviceId:a?.deviceId,registerToken:yi,unregisterToken:Si,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){vn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{vn.info({clients:ie.clients.size,code:s},"client disconnected"),w.increment("ws.disconnect"),w.increment("ws.disconnect.code",{code:String(s)}),w.gauge("ws.clients",ie.clients.size),_.emit("ws.disconnect",{clients:ie.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{vn.error({error:s.message},"websocket error")})});function ki(){for(let t of Cr)try{t.destroy()}catch{}Cr.clear()}function Ou(){let t=ic({auditPath:ht,stdoutLogPath:Zn,stderrLogPath:Qn,auditMaxBytes:v.auditMaxBytes,logMaxBytes:v.daemonLogMaxBytes});t.trimmedFiles>0&&q.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 ly(){Pt||(Pt=setInterval(Ou,v.storageHousekeepingIntervalMs),Pt.unref())}function cy(){Pt&&(clearInterval(Pt),Pt=null)}function Je(t,e=0){if(!Eu){Eu=!0,q.info({reason:t,exitCode:e},"shutting down"),_.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Mu)/1e3)}),w.stopPeriodicLog(),cy(),J.shutdown();for(let n of ie.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}ie.close(n=>{n&&q.error({error:String(n)},"websocket close error")}),bn.close(n=>{if(n){q.error({error:String(n)},"http close error"),ki(),process.exit(1);return}ki(),process.exit(e)}),setTimeout(()=>{q.error("force exiting after shutdown timeout"),ki(),process.exit(e||1)},3e3).unref()}}ie.on("error",t=>{vn.error({error:t.message},"wss error")});bn.on("error",t=>{if(t.code==="EADDRINUSE"){let e=cu(v.port).filter(n=>n.pid!==process.pid);q.error({port:v.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else q.error({error:String(t)},"server error");Je(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>Je("SIGINT"));process.once("SIGTERM",()=>Je("SIGTERM"));process.once("SIGHUP",()=>Je("SIGHUP"));process.once("SIGTTIN",()=>Je("SIGTTIN"));process.once("SIGTSTP",()=>Je("SIGTSTP"));process.on("uncaughtException",t=>{q.error({error:String(t),stack:t.stack},"uncaughtException"),_.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{q.error({reason:String(t)},"unhandledRejection"),_.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});bn.listen(v.port,async()=>{Ou(),_.emit("daemon.start",{port:v.port}),w.startPeriodicLog(),ly(),q.info({port:v.port,pairingPort:Ye().port,daemonId:U.daemonId,displayName:U.displayName,canonicalHost:Ye().canonicalHost,fallbackHosts:Ye().fallbackHosts,claudePath:v.claudePath,codexPath:v.codexPath,auditMaxBytes:v.auditMaxBytes,daemonLogMaxBytes:v.daemonLogMaxBytes,storageHousekeepingIntervalMs:v.storageHousekeepingIntervalMs,turnStallTimeoutMs:v.turnStallTimeoutMs},"daemon started");let t=Nu();Zt(`
|
|
104
104
|
\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
|
|
105
|
-
\u2551 Vibelet Daemon v${
|
|
105
|
+
\u2551 Vibelet Daemon v${yt} \u2551
|
|
106
106
|
\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
|
|
107
|
-
\u2551 Port: ${String(
|
|
108
|
-
\u2551 ID: ${
|
|
107
|
+
\u2551 Port: ${String(t.port).padEnd(28)}\u2551
|
|
108
|
+
\u2551 ID: ${U.daemonId.slice(0,28).padEnd(28)}\u2551
|
|
109
109
|
\u2551 Host: ${t.canonicalHost.slice(0,28).padEnd(28)}\u2551
|
|
110
110
|
\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
|
|
111
111
|
|
|
112
112
|
Pair with: npx @vibelet/cli or npx vibelet
|
|
113
113
|
Host: ${t.canonicalHost}
|
|
114
|
-
Fallbacks: ${t.fallbackHosts
|
|
114
|
+
Fallbacks: ${t.fallbackHosts?.join(", ")||"(none)"}
|
|
115
115
|
|
|
116
116
|
Claude: ${v.claudePath}
|
|
117
117
|
Codex: ${v.codexPath}
|
|
118
|
-
`);try{let
|
|
118
|
+
`);try{let e=await Lu.default.toString(JSON.stringify(t),{type:"terminal",small:!0});Zt(`
|
|
119
119
|
Scan this QR code with Vibelet app:
|
|
120
120
|
|
|
121
|
-
${
|
|
121
|
+
${e}
|
|
122
122
|
`)}catch{}});
|