@jagreehal/workflow 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/visualize.cjs +27 -27
- package/dist/visualize.cjs.map +1 -1
- package/dist/visualize.d.cts +105 -2
- package/dist/visualize.d.ts +105 -2
- package/dist/visualize.js +26 -26
- package/dist/visualize.js.map +1 -1
- package/docs/pino-logging-example.md +106 -3
- package/package.json +2 -1
package/dist/visualize.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var mn=Object.create;var st=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var vn=Object.getOwnPropertyNames;var yn=Object.getPrototypeOf,wn=Object.prototype.hasOwnProperty;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var bn=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Sn=(e,t)=>{for(var r in t)st(e,r,{get:t[r],enumerable:!0})},_n=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vn(t))!wn.call(e,n)&&n!==r&&st(e,n,{get:()=>t[n],enumerable:!(o=gn(t,n))||o.enumerable});return e};var Ie=(e,t,r)=>(r=e!=null?mn(yn(e)):{},_n(t||!e||!e.__esModule?st(r,"default",{value:e,enumerable:!0}):r,e));var Q=V((hi,ir)=>{"use strict";var or=["nodebuffer","arraybuffer","fragments"],sr=typeof Blob<"u";sr&&or.push("blob");ir.exports={BINARY_TYPES:or,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:sr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Oe=V((mi,qe)=>{"use strict";var{EMPTY_BUFFER:lo}=Q(),bt=Buffer[Symbol.species];function uo(e,t){if(e.length===0)return lo;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),o=0;for(let n=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return o<t?new bt(r.buffer,r.byteOffset,o):r}function ar(e,t,r,o,n){for(let s=0;s<n;s++)r[o+s]=e[s]^t[s&3]}function cr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function fo(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function St(e){if(St.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new bt(e):ArrayBuffer.isView(e)?t=new bt(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),St.readOnly=!1),t}qe.exports={concat:uo,mask:ar,toArrayBuffer:fo,toBuffer:St,unmask:cr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=A("bufferutil");qe.exports.mask=function(t,r,o,n,s){s<48?ar(t,r,o,n,s):e.mask(t,r,o,n,s)},qe.exports.unmask=function(t,r){t.length<32?cr(t,r):e.unmask(t,r)}}catch{}});var ur=V((gi,dr)=>{"use strict";var lr=Symbol("kDone"),_t=Symbol("kRun"),xt=class{constructor(t){this[lr]=()=>{this.pending--,this[_t]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[_t]()}[_t](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[lr])}}};dr.exports=xt});var Le=V((vi,mr)=>{"use strict";var Ce=A("zlib"),fr=Oe(),po=ur(),{kStatusCode:pr}=Q(),ho=Buffer[Symbol.species],mo=Buffer.from([0,0,255,255]),Ke=Symbol("permessage-deflate"),ee=Symbol("total-length"),Se=Symbol("callback"),ie=Symbol("buffers"),_e=Symbol("error"),Ge,kt=class{constructor(t,r,o){if(this._maxPayload=o|0,this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Ge){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ge=new po(n)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Se];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,o=t.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!o)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(o.server_no_context_takeover=!0),r.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(o.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?o.client_max_window_bits=r.clientMaxWindowBits:(o.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(o=>{let n=r[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=s}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);r[o]=n})}),t}decompress(t,r,o){Ge.add(n=>{this._decompress(t,r,(s,i)=>{n(),o(s,i)})})}compress(t,r,o){Ge.add(n=>{this._compress(t,r,(s,i)=>{n(),o(s,i)})})}_decompress(t,r,o){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,i=typeof this.params[s]!="number"?Ce.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ce.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Ke]=this,this._inflate[ee]=0,this._inflate[ie]=[],this._inflate.on("error",vo),this._inflate.on("data",hr)}this._inflate[Se]=o,this._inflate.write(t),r&&this._inflate.write(mo),this._inflate.flush(()=>{let s=this._inflate[_e];if(s){this._inflate.close(),this._inflate=null,o(s);return}let i=fr.concat(this._inflate[ie],this._inflate[ee]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ee]=0,this._inflate[ie]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(t,r,o){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,i=typeof this.params[s]!="number"?Ce.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ce.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[ee]=0,this._deflate[ie]=[],this._deflate.on("data",go)}this._deflate[Se]=o,this._deflate.write(t),this._deflate.flush(Ce.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=fr.concat(this._deflate[ie],this._deflate[ee]);r&&(s=new ho(s.buffer,s.byteOffset,s.length-4)),this._deflate[Se]=null,this._deflate[ee]=0,this._deflate[ie]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,s)})}};mr.exports=kt;function go(e){this[ie].push(e),this[ee]+=e.length}function hr(e){if(this[ee]+=e.length,this[Ke]._maxPayload<1||this[ee]<=this[Ke]._maxPayload){this[ie].push(e);return}this[_e]=new RangeError("Max payload size exceeded"),this[_e].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[_e][pr]=1009,this.removeListener("data",hr),this.reset()}function vo(e){if(this[Ke]._inflate=null,this[_e]){this[Se](this[_e]);return}e[pr]=1007,this[Se](e)}});var xe=V((yi,Ye)=>{"use strict";var{isUtf8:gr}=A("buffer"),{hasBlob:yo}=Q(),wo=[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 bo(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Et(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function So(e){return yo&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Ye.exports={isBlob:So,isValidStatusCode:bo,isValidUTF8:Et,tokenChars:wo};if(gr)Ye.exports.isValidUTF8=function(e){return e.length<24?Et(e):gr(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=A("utf-8-validate");Ye.exports.isValidUTF8=function(t){return t.length<32?Et(t):e(t)}}catch{}});var Nt=V((wi,xr)=>{"use strict";var{Writable:_o}=A("stream"),vr=Le(),{BINARY_TYPES:xo,EMPTY_BUFFER:yr,kStatusCode:ko,kWebSocket:Eo}=Q(),{concat:Tt,toArrayBuffer:To,unmask:Ro}=Oe(),{isValidStatusCode:Io,isValidUTF8:wr}=xe(),Je=Buffer[Symbol.species],G=0,br=1,Sr=2,_r=3,Rt=4,It=5,Xe=6,$t=class extends _o{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||xo[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[Eo]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=G}_write(t,r,o){if(this._opcode===8&&this._state==G)return o();this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(o)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new Je(o.buffer,o.byteOffset+t,o.length-t),new Je(o.buffer,o.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let o=this._buffers[0],n=r.length-t;t>=o.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(o.buffer,o.byteOffset,t),n),this._buffers[0]=new Je(o.buffer,o.byteOffset+t,o.length-t)),t-=o.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case G:this.getInfo(t);break;case br:this.getPayloadLength16(t);break;case Sr:this.getPayloadLength64(t);break;case _r:this.getMask();break;case Rt:this.getData(t);break;case It:case Xe:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(n);return}let o=(r[0]&64)===64;if(o&&!this._extensions[vr.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(n);return}this._payloadLength===126?this._state=br:this._payloadLength===127?this._state=Sr:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),o=r.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(n);return}this._payloadLength=o*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=_r:this._state=Rt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Rt}getData(t){let r=yr;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Ro(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._compressed){this._state=It,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[vr.extensionName].decompress(t,this._fin,(n,s)=>{if(n)return r(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===G&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=G;return}let r=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Tt(o,r):this._binaryType==="arraybuffer"?n=To(Tt(o,r)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=G):(this._state=Xe,setImmediate(()=>{this.emit("message",n,!0),this._state=G,this.startLoop(t)}))}else{let n=Tt(o,r);if(!this._skipUTF8Validation&&!wr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._state===It||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=G):(this._state=Xe,setImmediate(()=>{this.emit("message",n,!1),this._state=G,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,yr),this.end();else{let o=t.readUInt16BE(0);if(!Io(o)){let s=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new Je(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!wr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=G):(this._state=Xe,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=G,this.startLoop(r)}))}createError(t,r,o,n,s){this._loop=!1,this._errored=!0;let i=new t(o?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[ko]=n,i}};xr.exports=$t});var Ct=V((Si,Tr)=>{"use strict";var{Duplex:bi}=A("stream"),{randomFillSync:$o}=A("crypto"),kr=Le(),{EMPTY_BUFFER:No,kWebSocket:Do,NOOP:Oo}=Q(),{isBlob:ke,isValidStatusCode:Co}=xe(),{mask:Er,toBuffer:ue}=Oe(),K=Symbol("kByteLength"),Lo=Buffer.alloc(4),Ze=8*1024,fe,Ee=Ze,J=0,Mo=1,Bo=2,Dt=class e{constructor(t,r,o){this._extensions=r||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=J,this.onerror=Oo,this[Do]=void 0}static frame(t,r){let o,n=!1,s=2,i=!1;r.mask&&(o=r.maskBuffer||Lo,r.generateMask?r.generateMask(o):(Ee===Ze&&(fe===void 0&&(fe=Buffer.alloc(Ze)),$o(fe,0,Ze),Ee=0),o[0]=fe[Ee++],o[1]=fe[Ee++],o[2]=fe[Ee++],o[3]=fe[Ee++]),i=(o[0]|o[1]|o[2]|o[3])===0,s=6);let l;typeof t=="string"?(!r.mask||i)&&r[K]!==void 0?l=r[K]:(t=Buffer.from(t),l=t.length):(l=t.length,n=r.mask&&r.readOnly&&!i);let d=l;l>=65536?(s+=8,d=127):l>125&&(s+=2,d=126);let a=Buffer.allocUnsafe(n?l+s:s);return a[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(a[0]|=64),a[1]=d,d===126?a.writeUInt16BE(l,2):d===127&&(a[2]=a[3]=0,a.writeUIntBE(l,4,6)),r.mask?(a[1]|=128,a[s-4]=o[0],a[s-3]=o[1],a[s-2]=o[2],a[s-1]=o[3],i?[a,t]:n?(Er(t,o,a,s,l),[a]):(Er(t,o,t,0,l),[a,t])):[a,t]}close(t,r,o,n){let s;if(t===void 0)s=No;else{if(typeof t!="number"||!Co(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let l=Buffer.byteLength(r);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+l),s.writeUInt16BE(t,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[K]:s.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==J?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(e.frame(s,i),n)}ping(t,r,o){let n,s;if(typeof t=="string"?(n=Buffer.byteLength(t),s=!1):ke(t)?(n=t.size,s=!1):(t=ue(t),n=t.length,s=ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ke(t)?this._state!==J?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==J?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}pong(t,r,o){let n,s;if(typeof t=="string"?(n=Buffer.byteLength(t),s=!1):ke(t)?(n=t.size,s=!1):(t=ue(t),n=t.length,s=ue.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ke(t)?this._state!==J?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==J?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}send(t,r,o){let n=this._extensions[kr.extensionName],s=r.binary?2:1,i=r.compress,l,d;typeof t=="string"?(l=Buffer.byteLength(t),d=!1):ke(t)?(l=t.size,d=!1):(t=ue(t),l=t.length,d=ue.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=l>=n._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let a={[K]:l,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};ke(t)?this._state!==J?this.enqueue([this.getBlobData,t,this._compress,a,o]):this.getBlobData(t,this._compress,a,o):this._state!==J?this.enqueue([this.dispatch,t,this._compress,a,o]):this.dispatch(t,this._compress,a,o)}getBlobData(t,r,o,n){this._bufferedBytes+=o[K],this._state=Bo,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Ot,this,l,n);return}this._bufferedBytes-=o[K];let i=ue(s);r?this.dispatch(i,r,o,n):(this._state=J,this.sendFrame(e.frame(i,o),n),this.dequeue())}).catch(s=>{process.nextTick(Po,this,s,n)})}dispatch(t,r,o,n){if(!r){this.sendFrame(e.frame(t,o),n);return}let s=this._extensions[kr.extensionName];this._bufferedBytes+=o[K],this._state=Mo,s.compress(t,o.fin,(i,l)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");Ot(this,d,n);return}this._bufferedBytes-=o[K],this._state=J,o.readOnly=!1,this.sendFrame(e.frame(l,o),n),this.dequeue()})}dequeue(){for(;this._state===J&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][K],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][K],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};Tr.exports=Dt;function Ot(e,t,r){typeof r=="function"&&r(t);for(let o=0;o<e._queue.length;o++){let n=e._queue[o],s=n[n.length-1];typeof s=="function"&&s(t)}}function Po(e,t,r){Ot(e,t,r),e.onerror(t)}});var Mr=V((_i,Lr)=>{"use strict";var{kForOnEventAttribute:Me,kListener:Lt}=Q(),Rr=Symbol("kCode"),Ir=Symbol("kData"),$r=Symbol("kError"),Nr=Symbol("kMessage"),Dr=Symbol("kReason"),Te=Symbol("kTarget"),Or=Symbol("kType"),Cr=Symbol("kWasClean"),te=class{constructor(t){this[Te]=null,this[Or]=t}get target(){return this[Te]}get type(){return this[Or]}};Object.defineProperty(te.prototype,"target",{enumerable:!0});Object.defineProperty(te.prototype,"type",{enumerable:!0});var pe=class extends te{constructor(t,r={}){super(t),this[Rr]=r.code===void 0?0:r.code,this[Dr]=r.reason===void 0?"":r.reason,this[Cr]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Rr]}get reason(){return this[Dr]}get wasClean(){return this[Cr]}};Object.defineProperty(pe.prototype,"code",{enumerable:!0});Object.defineProperty(pe.prototype,"reason",{enumerable:!0});Object.defineProperty(pe.prototype,"wasClean",{enumerable:!0});var Re=class extends te{constructor(t,r={}){super(t),this[$r]=r.error===void 0?null:r.error,this[Nr]=r.message===void 0?"":r.message}get error(){return this[$r]}get message(){return this[Nr]}};Object.defineProperty(Re.prototype,"error",{enumerable:!0});Object.defineProperty(Re.prototype,"message",{enumerable:!0});var Be=class extends te{constructor(t,r={}){super(t),this[Ir]=r.data===void 0?null:r.data}get data(){return this[Ir]}};Object.defineProperty(Be.prototype,"data",{enumerable:!0});var Wo={addEventListener(e,t,r={}){for(let n of this.listeners(e))if(!r[Me]&&n[Lt]===t&&!n[Me])return;let o;if(e==="message")o=function(s,i){let l=new Be("message",{data:i?s:s.toString()});l[Te]=this,Qe(t,this,l)};else if(e==="close")o=function(s,i){let l=new pe("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Te]=this,Qe(t,this,l)};else if(e==="error")o=function(s){let i=new Re("error",{error:s,message:s.message});i[Te]=this,Qe(t,this,i)};else if(e==="open")o=function(){let s=new te("open");s[Te]=this,Qe(t,this,s)};else return;o[Me]=!!r[Me],o[Lt]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[Lt]===t&&!r[Me]){this.removeListener(e,r);break}}};Lr.exports={CloseEvent:pe,ErrorEvent:Re,Event:te,EventTarget:Wo,MessageEvent:Be};function Qe(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var Mt=V((xi,Br)=>{"use strict";var{tokenChars:Pe}=xe();function X(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function Ao(e){let t=Object.create(null),r=Object.create(null),o=!1,n=!1,s=!1,i,l,d=-1,a=-1,c=-1,u=0;for(;u<e.length;u++)if(a=e.charCodeAt(u),i===void 0)if(c===-1&&Pe[a]===1)d===-1&&(d=u);else if(u!==0&&(a===32||a===9))c===-1&&d!==-1&&(c=u);else if(a===59||a===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1&&(c=u);let m=e.slice(d,c);a===44?(X(t,m,r),r=Object.create(null)):i=m,d=c=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===void 0)if(c===-1&&Pe[a]===1)d===-1&&(d=u);else if(a===32||a===9)c===-1&&d!==-1&&(c=u);else if(a===59||a===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1&&(c=u),X(r,e.slice(d,c),!0),a===44&&(X(t,i,r),r=Object.create(null),i=void 0),d=c=-1}else if(a===61&&d!==-1&&c===-1)l=e.slice(d,u),d=c=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(n){if(Pe[a]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1?d=u:o||(o=!0),n=!1}else if(s)if(Pe[a]===1)d===-1&&(d=u);else if(a===34&&d!==-1)s=!1,c=u;else if(a===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===34&&e.charCodeAt(u-1)===61)s=!0;else if(c===-1&&Pe[a]===1)d===-1&&(d=u);else if(d!==-1&&(a===32||a===9))c===-1&&(c=u);else if(a===59||a===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1&&(c=u);let m=e.slice(d,c);o&&(m=m.replace(/\\/g,""),o=!1),X(r,l,m),a===44&&(X(t,i,r),r=Object.create(null),i=void 0),l=void 0,d=c=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(d===-1||s||a===32||a===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=u);let p=e.slice(d,c);return i===void 0?X(t,p,r):(l===void 0?X(r,p,!0):o?X(r,l,p.replace(/\\/g,"")):X(r,l,p),X(t,i,r)),t}function Uo(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(o=>[t].concat(Object.keys(o).map(n=>{let s=o[n];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Br.exports={format:Uo,parse:Ao}});var nt=V((Ti,Kr)=>{"use strict";var Fo=A("events"),Ho=A("https"),zo=A("http"),Ar=A("net"),Vo=A("tls"),{randomBytes:jo,createHash:qo}=A("crypto"),{Duplex:ki,Readable:Ei}=A("stream"),{URL:Bt}=A("url"),ae=Le(),Go=Nt(),Ko=Ct(),{isBlob:Yo}=xe(),{BINARY_TYPES:Pr,CLOSE_TIMEOUT:Jo,EMPTY_BUFFER:et,GUID:Xo,kForOnEventAttribute:Pt,kListener:Zo,kStatusCode:Qo,kWebSocket:U,NOOP:Ur}=Q(),{EventTarget:{addEventListener:es,removeEventListener:ts}}=Mr(),{format:rs,parse:ns}=Mt(),{toBuffer:os}=Oe(),Fr=Symbol("kAborted"),Wt=[8,13],re=["CONNECTING","OPEN","CLOSING","CLOSED"],ss=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,W=class e extends Fo{constructor(t,r,o){super(),this._binaryType=Pr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=et,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(o=r,r=[]):r=[r]),Hr(this,t,r,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Pr.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}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(t,r,o){let n=new Go({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),s=new Ko(t,this._extensions,o.generateMask);this._receiver=n,this._sender=s,this._socket=t,n[U]=this,s[U]=this,t[U]=this,n.on("conclude",cs),n.on("drain",ls),n.on("error",ds),n.on("message",us),n.on("ping",fs),n.on("pong",ps),s.onerror=hs,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",jr),t.on("data",rt),t.on("end",qr),t.on("error",Gr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ae.extensionName]&&this._extensions[ae.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Vr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(o=t,t=r=void 0):typeof r=="function"&&(o=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){At(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||et,r,o)}pong(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(o=t,t=r=void 0):typeof r=="function"&&(o=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){At(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||et,r,o)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(o=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){At(this,t,o);return}let n={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ae.extensionName]||(n.compress=!1),this._sender.send(t||et,n,o)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(W,"CONNECTING",{enumerable:!0,value:re.indexOf("CONNECTING")});Object.defineProperty(W.prototype,"CONNECTING",{enumerable:!0,value:re.indexOf("CONNECTING")});Object.defineProperty(W,"OPEN",{enumerable:!0,value:re.indexOf("OPEN")});Object.defineProperty(W.prototype,"OPEN",{enumerable:!0,value:re.indexOf("OPEN")});Object.defineProperty(W,"CLOSING",{enumerable:!0,value:re.indexOf("CLOSING")});Object.defineProperty(W.prototype,"CLOSING",{enumerable:!0,value:re.indexOf("CLOSING")});Object.defineProperty(W,"CLOSED",{enumerable:!0,value:re.indexOf("CLOSED")});Object.defineProperty(W.prototype,"CLOSED",{enumerable:!0,value:re.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(W.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(W.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Pt])return t[Zo];return null},set(t){for(let r of this.listeners(e))if(r[Pt]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[Pt]:!0})}})});W.prototype.addEventListener=es;W.prototype.removeEventListener=ts;Kr.exports=W;function Hr(e,t,r,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Jo,protocolVersion:Wt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=n.autoPong,e._closeTimeout=n.closeTimeout,!Wt.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Wt.join(", ")})`);let s;if(t instanceof Bt)s=t;else try{s=new Bt(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",l=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!l?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let g=new SyntaxError(d);if(e._redirects===0)throw g;tt(e,g);return}let a=i?443:80,c=jo(16).toString("base64"),u=i?Ho.request:zo.request,p=new Set,m;if(n.createConnection=n.createConnection||(i?as:is),n.defaultPort=n.defaultPort||a,n.port=s.port||a,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(m=new ae(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=rs({[ae.extensionName]:m.offer()})),r.length){for(let g of r){if(typeof g!="string"||!ss.test(g)||p.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(g)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),l){let g=n.path.split(":");n.socketPath=g[0],n.path=g[1]}let v;if(n.followRedirects){if(e._redirects===0){e._originalIpc=l,e._originalSecure=i,e._originalHostOrSocketPath=l?n.socketPath:s.host;let g=o&&o.headers;if(o={...o,headers:{}},g)for(let[w,$]of Object.entries(g))o.headers[w.toLowerCase()]=$}else if(e.listenerCount("redirect")===0){let g=l?e._originalIpc?n.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!g||e._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,g||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),v=e._req=u(n),e._redirects&&e.emit("redirect",e.url,v)}else v=e._req=u(n);n.timeout&&v.on("timeout",()=>{q(e,v,"Opening handshake has timed out")}),v.on("error",g=>{v===null||v[Fr]||(v=e._req=null,tt(e,g))}),v.on("response",g=>{let w=g.headers.location,$=g.statusCode;if(w&&n.followRedirects&&$>=300&&$<400){if(++e._redirects>n.maxRedirects){q(e,v,"Maximum redirects exceeded");return}v.abort();let O;try{O=new Bt(w,t)}catch{let h=new SyntaxError(`Invalid URL: ${w}`);tt(e,h);return}Hr(e,O,r,o)}else e.emit("unexpected-response",v,g)||q(e,v,`Unexpected server response: ${g.statusCode}`)}),v.on("upgrade",(g,w,$)=>{if(e.emit("upgrade",g),e.readyState!==W.CONNECTING)return;v=e._req=null;let O=g.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){q(e,w,"Invalid Upgrade header");return}let D=qo("sha1").update(c+Xo).digest("base64");if(g.headers["sec-websocket-accept"]!==D){q(e,w,"Invalid Sec-WebSocket-Accept header");return}let h=g.headers["sec-websocket-protocol"],x;if(h!==void 0?p.size?p.has(h)||(x="Server sent an invalid subprotocol"):x="Server sent a subprotocol but none was requested":p.size&&(x="Server sent no subprotocol"),x){q(e,w,x);return}h&&(e._protocol=h);let b=g.headers["sec-websocket-extensions"];if(b!==void 0){if(!m){q(e,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=ns(b)}catch{q(e,w,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(k);if(B.length!==1||B[0]!==ae.extensionName){q(e,w,"Server indicated an extension that was not requested");return}try{m.accept(k[ae.extensionName])}catch{q(e,w,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ae.extensionName]=m}e.setSocket(w,$,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(v,e):v.end()}function tt(e,t){e._readyState=W.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function is(e){return e.path=e.socketPath,Ar.connect(e)}function as(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Ar.isIP(e.host)?"":e.host),Vo.connect(e)}function q(e,t,r){e._readyState=W.CLOSING;let o=new Error(r);Error.captureStackTrace(o,q),t.setHeader?(t[Fr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(tt,e,o)):(t.destroy(o),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function At(e,t,r){if(t){let o=Yo(t)?t.size:os(t).length;e._socket?e._sender._bufferedBytes+=o:e._bufferedAmount+=o}if(r){let o=new Error(`WebSocket is not open: readyState ${e.readyState} (${re[e.readyState]})`);process.nextTick(r,o)}}function cs(e,t){let r=this[U];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[U]!==void 0&&(r._socket.removeListener("data",rt),process.nextTick(zr,r._socket),e===1005?r.close():r.close(e,t))}function ls(){let e=this[U];e.isPaused||e._socket.resume()}function ds(e){let t=this[U];t._socket[U]!==void 0&&(t._socket.removeListener("data",rt),process.nextTick(zr,t._socket),t.close(e[Qo])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Wr(){this[U].emitClose()}function us(e,t){this[U].emit("message",e,t)}function fs(e){let t=this[U];t._autoPong&&t.pong(e,!this._isServer,Ur),t.emit("ping",e)}function ps(e){this[U].emit("pong",e)}function zr(e){e.resume()}function hs(e){let t=this[U];t.readyState!==W.CLOSED&&(t.readyState===W.OPEN&&(t._readyState=W.CLOSING,Vr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Vr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function jr(){let e=this[U];if(this.removeListener("close",jr),this.removeListener("data",rt),this.removeListener("end",qr),e._readyState=W.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[U]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Wr),e._receiver.on("finish",Wr))}function rt(e){this[U]._receiver.write(e)||this.pause()}function qr(){let e=this[U];e._readyState=W.CLOSING,e._receiver.end(),this.end()}function Gr(){let e=this[U];this.removeListener("error",Gr),this.on("error",Ur),e&&(e._readyState=W.CLOSING,this.destroy())}});var Zr=V((Ii,Xr)=>{"use strict";var Ri=nt(),{Duplex:ms}=A("stream");function Yr(e){e.emit("close")}function gs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Jr(e){this.removeListener("error",Jr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function vs(e,t){let r=!0,o=new ms({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let l=!i&&o._readableState.objectMode?s.toString():s;o.push(l)||e.pause()}),e.once("error",function(s){o.destroyed||(r=!1,o.destroy(s))}),e.once("close",function(){o.destroyed||o.push(null)}),o._destroy=function(n,s){if(e.readyState===e.CLOSED){s(n),process.nextTick(Yr,o);return}let i=!1;e.once("error",function(d){i=!0,s(d)}),e.once("close",function(){i||s(n),process.nextTick(Yr,o)}),r&&e.terminate()},o._final=function(n){if(e.readyState===e.CONNECTING){e.once("open",function(){o._final(n)});return}e._socket!==null&&(e._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(e._socket.once("finish",function(){n()}),e.close()))},o._read=function(){e.isPaused&&e.resume()},o._write=function(n,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){o._write(n,s,i)});return}e.send(n,i)},o.on("end",gs),o.on("error",Jr),o}Xr.exports=vs});var en=V(($i,Qr)=>{"use strict";var{tokenChars:ys}=xe();function ws(e){let t=new Set,r=-1,o=-1,n=0;for(n;n<e.length;n++){let i=e.charCodeAt(n);if(o===-1&&ys[i]===1)r===-1&&(r=n);else if(n!==0&&(i===32||i===9))o===-1&&r!==-1&&(o=n);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let l=e.slice(r,o);if(t.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);t.add(l),r=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,n);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}Qr.exports={parse:ws}});var cn=V((Di,an)=>{"use strict";var bs=A("events"),ot=A("http"),{Duplex:Ni}=A("stream"),{createHash:Ss}=A("crypto"),tn=Mt(),he=Le(),_s=en(),xs=nt(),{CLOSE_TIMEOUT:ks,GUID:Es,kWebSocket:Ts}=Q(),Rs=/^[+/0-9A-Za-z]{22}==$/,rn=0,nn=1,sn=2,Ut=class extends bs{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ks,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:xs,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=ot.createServer((o,n)=>{let s=ot.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=Is(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,i)=>{this.handleUpgrade(n,s,i,o)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=rn}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===sn){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(We,this);return}if(t&&this.once("close",t),this._state!==nn)if(this._state=nn,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(We,this):process.nextTick(We,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{We(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,o,n){r.on("error",on);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,l=+t.headers["sec-websocket-version"];if(t.method!=="GET"){me(this,t,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){me(this,t,r,400,"Invalid Upgrade header");return}if(s===void 0||!Rs.test(s)){me(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){me(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Ae(r,400);return}let d=t.headers["sec-websocket-protocol"],a=new Set;if(d!==void 0)try{a=_s.parse(d)}catch{me(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let c=t.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&c!==void 0){let p=new he(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let m=tn.parse(c);m[he.extensionName]&&(p.accept(m[he.extensionName]),u[he.extensionName]=p)}catch{me(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:t.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(m,v,g,w)=>{if(!m)return Ae(r,v||401,g,w);this.completeUpgrade(u,s,a,t,r,o,n)});return}if(!this.options.verifyClient(p))return Ae(r,401)}this.completeUpgrade(u,s,a,t,r,o,n)}completeUpgrade(t,r,o,n,s,i,l){if(!s.readable||!s.writable)return s.destroy();if(s[Ts])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>rn)return Ae(s,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ss("sha1").update(r+Es).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(o.size){let u=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;u&&(a.push(`Sec-WebSocket-Protocol: ${u}`),c._protocol=u)}if(t[he.extensionName]){let u=t[he.extensionName].params,p=tn.format({[he.extensionName]:[u]});a.push(`Sec-WebSocket-Extensions: ${p}`),c._extensions=t}this.emit("headers",a,n),s.write(a.concat(`\r
|
|
1
|
+
var yn=Object.create;var it=Object.defineProperty;var vn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xn=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_n=(e,t)=>{for(var r in t)it(e,r,{get:t[r],enumerable:!0})},kn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of wn(t))!Sn.call(e,n)&&n!==r&&it(e,n,{get:()=>t[n],enumerable:!(o=vn(t,n))||o.enumerable});return e};var Ie=(e,t,r)=>(r=e!=null?yn(bn(e)):{},kn(t||!e||!e.__esModule?it(r,"default",{value:e,enumerable:!0}):r,e));var ee=V((Ei,cr)=>{"use strict";var ir=["nodebuffer","arraybuffer","fragments"],ar=typeof Blob<"u";ar&&ir.push("blob");cr.exports={BINARY_TYPES:ir,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ar,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Oe=V((Ri,Ge)=>{"use strict";var{EMPTY_BUFFER:vo}=ee(),St=Buffer[Symbol.species];function wo(e,t){if(e.length===0)return vo;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),o=0;for(let n=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return o<t?new St(r.buffer,r.byteOffset,o):r}function lr(e,t,r,o,n){for(let s=0;s<n;s++)r[o+s]=e[s]^t[s&3]}function dr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function bo(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function xt(e){if(xt.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new St(e):ArrayBuffer.isView(e)?t=new St(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),xt.readOnly=!1),t}Ge.exports={concat:wo,mask:lr,toArrayBuffer:bo,toBuffer:xt,unmask:dr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=A("bufferutil");Ge.exports.mask=function(t,r,o,n,s){s<48?lr(t,r,o,n,s):e.mask(t,r,o,n,s)},Ge.exports.unmask=function(t,r){t.length<32?dr(t,r):e.unmask(t,r)}}catch{}});var pr=V((Ti,fr)=>{"use strict";var ur=Symbol("kDone"),_t=Symbol("kRun"),kt=class{constructor(t){this[ur]=()=>{this.pending--,this[_t]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[_t]()}[_t](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[ur])}}};fr.exports=kt});var Le=V((Ii,yr)=>{"use strict";var Ce=A("zlib"),hr=Oe(),So=pr(),{kStatusCode:mr}=ee(),xo=Buffer[Symbol.species],_o=Buffer.from([0,0,255,255]),Ye=Symbol("permessage-deflate"),te=Symbol("total-length"),Se=Symbol("callback"),de=Symbol("buffers"),xe=Symbol("error"),Ke,Et=class{constructor(t,r,o){if(this._maxPayload=o|0,this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Ke){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ke=new So(n)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Se];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,o=t.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!o)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(o.server_no_context_takeover=!0),r.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(o.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?o.client_max_window_bits=r.clientMaxWindowBits:(o.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(o=>{let n=r[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=s}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);r[o]=n})}),t}decompress(t,r,o){Ke.add(n=>{this._decompress(t,r,(s,i)=>{n(),o(s,i)})})}compress(t,r,o){Ke.add(n=>{this._compress(t,r,(s,i)=>{n(),o(s,i)})})}_decompress(t,r,o){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,i=typeof this.params[s]!="number"?Ce.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ce.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Ye]=this,this._inflate[te]=0,this._inflate[de]=[],this._inflate.on("error",Eo),this._inflate.on("data",gr)}this._inflate[Se]=o,this._inflate.write(t),r&&this._inflate.write(_o),this._inflate.flush(()=>{let s=this._inflate[xe];if(s){this._inflate.close(),this._inflate=null,o(s);return}let i=hr.concat(this._inflate[de],this._inflate[te]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[te]=0,this._inflate[de]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(t,r,o){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,i=typeof this.params[s]!="number"?Ce.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ce.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[te]=0,this._deflate[de]=[],this._deflate.on("data",ko)}this._deflate[Se]=o,this._deflate.write(t),this._deflate.flush(Ce.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=hr.concat(this._deflate[de],this._deflate[te]);r&&(s=new xo(s.buffer,s.byteOffset,s.length-4)),this._deflate[Se]=null,this._deflate[te]=0,this._deflate[de]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,s)})}};yr.exports=Et;function ko(e){this[de].push(e),this[te]+=e.length}function gr(e){if(this[te]+=e.length,this[Ye]._maxPayload<1||this[te]<=this[Ye]._maxPayload){this[de].push(e);return}this[xe]=new RangeError("Max payload size exceeded"),this[xe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xe][mr]=1009,this.removeListener("data",gr),this.reset()}function Eo(e){if(this[Ye]._inflate=null,this[xe]){this[Se](this[xe]);return}e[mr]=1007,this[Se](e)}});var _e=V(($i,Je)=>{"use strict";var{isUtf8:vr}=A("buffer"),{hasBlob:Ro}=ee(),To=[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 Io(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Rt(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function $o(e){return Ro&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Je.exports={isBlob:$o,isValidStatusCode:Io,isValidUTF8:Rt,tokenChars:To};if(vr)Je.exports.isValidUTF8=function(e){return e.length<24?Rt(e):vr(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=A("utf-8-validate");Je.exports.isValidUTF8=function(t){return t.length<32?Rt(t):e(t)}}catch{}});var Dt=V((Ni,Er)=>{"use strict";var{Writable:No}=A("stream"),wr=Le(),{BINARY_TYPES:Do,EMPTY_BUFFER:br,kStatusCode:Oo,kWebSocket:Co}=ee(),{concat:Tt,toArrayBuffer:Lo,unmask:Mo}=Oe(),{isValidStatusCode:Bo,isValidUTF8:Sr}=_e(),Xe=Buffer[Symbol.species],G=0,xr=1,_r=2,kr=3,It=4,$t=5,Ze=6,Nt=class extends No{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||Do[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[Co]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=G}_write(t,r,o){if(this._opcode===8&&this._state==G)return o();this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(o)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new Xe(o.buffer,o.byteOffset+t,o.length-t),new Xe(o.buffer,o.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let o=this._buffers[0],n=r.length-t;t>=o.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(o.buffer,o.byteOffset,t),n),this._buffers[0]=new Xe(o.buffer,o.byteOffset+t,o.length-t)),t-=o.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case G:this.getInfo(t);break;case xr:this.getPayloadLength16(t);break;case _r:this.getPayloadLength64(t);break;case kr:this.getMask();break;case It:this.getData(t);break;case $t:case Ze:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(n);return}let o=(r[0]&64)===64;if(o&&!this._extensions[wr.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(n);return}this._payloadLength===126?this._state=xr:this._payloadLength===127?this._state=_r:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),o=r.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(n);return}this._payloadLength=o*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=kr:this._state=It}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=It}getData(t){let r=br;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Mo(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._compressed){this._state=$t,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[wr.extensionName].decompress(t,this._fin,(n,s)=>{if(n)return r(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===G&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=G;return}let r=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Tt(o,r):this._binaryType==="arraybuffer"?n=Lo(Tt(o,r)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=G):(this._state=Ze,setImmediate(()=>{this.emit("message",n,!0),this._state=G,this.startLoop(t)}))}else{let n=Tt(o,r);if(!this._skipUTF8Validation&&!Sr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._state===$t||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=G):(this._state=Ze,setImmediate(()=>{this.emit("message",n,!1),this._state=G,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,br),this.end();else{let o=t.readUInt16BE(0);if(!Bo(o)){let s=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new Xe(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Sr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=G):(this._state=Ze,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=G,this.startLoop(r)}))}createError(t,r,o,n,s){this._loop=!1,this._errored=!0;let i=new t(o?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[Oo]=n,i}};Er.exports=Nt});var Lt=V((Oi,Ir)=>{"use strict";var{Duplex:Di}=A("stream"),{randomFillSync:Wo}=A("crypto"),Rr=Le(),{EMPTY_BUFFER:Po,kWebSocket:Ao,NOOP:Fo}=ee(),{isBlob:ke,isValidStatusCode:Ho}=_e(),{mask:Tr,toBuffer:he}=Oe(),K=Symbol("kByteLength"),Uo=Buffer.alloc(4),Qe=8*1024,me,Ee=Qe,X=0,zo=1,Vo=2,Ot=class e{constructor(t,r,o){this._extensions=r||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=X,this.onerror=Fo,this[Ao]=void 0}static frame(t,r){let o,n=!1,s=2,i=!1;r.mask&&(o=r.maskBuffer||Uo,r.generateMask?r.generateMask(o):(Ee===Qe&&(me===void 0&&(me=Buffer.alloc(Qe)),Wo(me,0,Qe),Ee=0),o[0]=me[Ee++],o[1]=me[Ee++],o[2]=me[Ee++],o[3]=me[Ee++]),i=(o[0]|o[1]|o[2]|o[3])===0,s=6);let a;typeof t=="string"?(!r.mask||i)&&r[K]!==void 0?a=r[K]:(t=Buffer.from(t),a=t.length):(a=t.length,n=r.mask&&r.readOnly&&!i);let l=a;a>=65536?(s+=8,l=127):a>125&&(s+=2,l=126);let c=Buffer.allocUnsafe(n?a+s:s);return c[0]=r.fin?r.opcode|128:r.opcode,r.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)),r.mask?(c[1]|=128,c[s-4]=o[0],c[s-3]=o[1],c[s-2]=o[2],c[s-1]=o[3],i?[c,t]:n?(Tr(t,o,c,s,a),[c]):(Tr(t,o,t,0,a),[c,t])):[c,t]}close(t,r,o,n){let s;if(t===void 0)s=Po;else{if(typeof t!="number"||!Ho(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(t,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[K]:s.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==X?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(e.frame(s,i),n)}ping(t,r,o){let n,s;if(typeof t=="string"?(n=Buffer.byteLength(t),s=!1):ke(t)?(n=t.size,s=!1):(t=he(t),n=t.length,s=he.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ke(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==X?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}pong(t,r,o){let n,s;if(typeof t=="string"?(n=Buffer.byteLength(t),s=!1):ke(t)?(n=t.size,s=!1):(t=he(t),n=t.length,s=he.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ke(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==X?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}send(t,r,o){let n=this._extensions[Rr.extensionName],s=r.binary?2:1,i=r.compress,a,l;typeof t=="string"?(a=Buffer.byteLength(t),l=!1):ke(t)?(a=t.size,l=!1):(t=he(t),a=t.length,l=he.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=n._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let c={[K]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:i};ke(t)?this._state!==X?this.enqueue([this.getBlobData,t,this._compress,c,o]):this.getBlobData(t,this._compress,c,o):this._state!==X?this.enqueue([this.dispatch,t,this._compress,c,o]):this.dispatch(t,this._compress,c,o)}getBlobData(t,r,o,n){this._bufferedBytes+=o[K],this._state=Vo,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ct,this,a,n);return}this._bufferedBytes-=o[K];let i=he(s);r?this.dispatch(i,r,o,n):(this._state=X,this.sendFrame(e.frame(i,o),n),this.dequeue())}).catch(s=>{process.nextTick(jo,this,s,n)})}dispatch(t,r,o,n){if(!r){this.sendFrame(e.frame(t,o),n);return}let s=this._extensions[Rr.extensionName];this._bufferedBytes+=o[K],this._state=zo,s.compress(t,o.fin,(i,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ct(this,l,n);return}this._bufferedBytes-=o[K],this._state=X,o.readOnly=!1,this.sendFrame(e.frame(a,o),n),this.dequeue()})}dequeue(){for(;this._state===X&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][K],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][K],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};Ir.exports=Ot;function Ct(e,t,r){typeof r=="function"&&r(t);for(let o=0;o<e._queue.length;o++){let n=e._queue[o],s=n[n.length-1];typeof s=="function"&&s(t)}}function jo(e,t,r){Ct(e,t,r),e.onerror(t)}});var Wr=V((Ci,Br)=>{"use strict";var{kForOnEventAttribute:Me,kListener:Mt}=ee(),$r=Symbol("kCode"),Nr=Symbol("kData"),Dr=Symbol("kError"),Or=Symbol("kMessage"),Cr=Symbol("kReason"),Re=Symbol("kTarget"),Lr=Symbol("kType"),Mr=Symbol("kWasClean"),re=class{constructor(t){this[Re]=null,this[Lr]=t}get target(){return this[Re]}get type(){return this[Lr]}};Object.defineProperty(re.prototype,"target",{enumerable:!0});Object.defineProperty(re.prototype,"type",{enumerable:!0});var ge=class extends re{constructor(t,r={}){super(t),this[$r]=r.code===void 0?0:r.code,this[Cr]=r.reason===void 0?"":r.reason,this[Mr]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[$r]}get reason(){return this[Cr]}get wasClean(){return this[Mr]}};Object.defineProperty(ge.prototype,"code",{enumerable:!0});Object.defineProperty(ge.prototype,"reason",{enumerable:!0});Object.defineProperty(ge.prototype,"wasClean",{enumerable:!0});var Te=class extends re{constructor(t,r={}){super(t),this[Dr]=r.error===void 0?null:r.error,this[Or]=r.message===void 0?"":r.message}get error(){return this[Dr]}get message(){return this[Or]}};Object.defineProperty(Te.prototype,"error",{enumerable:!0});Object.defineProperty(Te.prototype,"message",{enumerable:!0});var Be=class extends re{constructor(t,r={}){super(t),this[Nr]=r.data===void 0?null:r.data}get data(){return this[Nr]}};Object.defineProperty(Be.prototype,"data",{enumerable:!0});var qo={addEventListener(e,t,r={}){for(let n of this.listeners(e))if(!r[Me]&&n[Mt]===t&&!n[Me])return;let o;if(e==="message")o=function(s,i){let a=new Be("message",{data:i?s:s.toString()});a[Re]=this,et(t,this,a)};else if(e==="close")o=function(s,i){let a=new ge("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Re]=this,et(t,this,a)};else if(e==="error")o=function(s){let i=new Te("error",{error:s,message:s.message});i[Re]=this,et(t,this,i)};else if(e==="open")o=function(){let s=new re("open");s[Re]=this,et(t,this,s)};else return;o[Me]=!!r[Me],o[Mt]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[Mt]===t&&!r[Me]){this.removeListener(e,r);break}}};Br.exports={CloseEvent:ge,ErrorEvent:Te,Event:re,EventTarget:qo,MessageEvent:Be};function et(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var Bt=V((Li,Pr)=>{"use strict";var{tokenChars:We}=_e();function Z(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function Go(e){let t=Object.create(null),r=Object.create(null),o=!1,n=!1,s=!1,i,a,l=-1,c=-1,d=-1,u=0;for(;u<e.length;u++)if(c=e.charCodeAt(u),i===void 0)if(d===-1&&We[c]===1)l===-1&&(l=u);else if(u!==0&&(c===32||c===9))d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let h=e.slice(l,d);c===44?(Z(t,h,r),r=Object.create(null)):i=h,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&We[c]===1)l===-1&&(l=u);else if(c===32||c===9)d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),Z(r,e.slice(l,d),!0),c===44&&(Z(t,i,r),r=Object.create(null),i=void 0),l=d=-1}else if(c===61&&l!==-1&&d===-1)a=e.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(n){if(We[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:o||(o=!0),n=!1}else if(s)if(We[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)s=!1,d=u;else if(c===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&e.charCodeAt(u-1)===61)s=!0;else if(d===-1&&We[c]===1)l===-1&&(l=u);else if(l!==-1&&(c===32||c===9))d===-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let h=e.slice(l,d);o&&(h=h.replace(/\\/g,""),o=!1),Z(r,a,h),c===44&&(Z(t,i,r),r=Object.create(null),i=void 0),a=void 0,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(l===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let p=e.slice(l,d);return i===void 0?Z(t,p,r):(a===void 0?Z(r,p,!0):o?Z(r,a,p.replace(/\\/g,"")):Z(r,a,p),Z(t,i,r)),t}function Ko(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(o=>[t].concat(Object.keys(o).map(n=>{let s=o[n];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pr.exports={format:Ko,parse:Go}});var ot=V((Wi,Jr)=>{"use strict";var Yo=A("events"),Jo=A("https"),Xo=A("http"),Hr=A("net"),Zo=A("tls"),{randomBytes:Qo,createHash:es}=A("crypto"),{Duplex:Mi,Readable:Bi}=A("stream"),{URL:Wt}=A("url"),ue=Le(),ts=Dt(),rs=Lt(),{isBlob:ns}=_e(),{BINARY_TYPES:Ar,CLOSE_TIMEOUT:os,EMPTY_BUFFER:tt,GUID:ss,kForOnEventAttribute:Pt,kListener:is,kStatusCode:as,kWebSocket:F,NOOP:Ur}=ee(),{EventTarget:{addEventListener:cs,removeEventListener:ls}}=Wr(),{format:ds,parse:us}=Bt(),{toBuffer:fs}=Oe(),zr=Symbol("kAborted"),At=[8,13],ne=["CONNECTING","OPEN","CLOSING","CLOSED"],ps=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class e extends Yo{constructor(t,r,o){super(),this._binaryType=Ar[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=tt,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(o=r,r=[]):r=[r]),Vr(this,t,r,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Ar.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}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(t,r,o){let n=new ts({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),s=new rs(t,this._extensions,o.generateMask);this._receiver=n,this._sender=s,this._socket=t,n[F]=this,s[F]=this,t[F]=this,n.on("conclude",gs),n.on("drain",ys),n.on("error",vs),n.on("message",ws),n.on("ping",bs),n.on("pong",Ss),s.onerror=xs,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Gr),t.on("data",nt),t.on("end",Kr),t.on("error",Yr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ue.extensionName]&&this._extensions[ue.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),qr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(o=t,t=r=void 0):typeof r=="function"&&(o=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Ft(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||tt,r,o)}pong(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(o=t,t=r=void 0):typeof r=="function"&&(o=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Ft(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||tt,r,o)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(o=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Ft(this,t,o);return}let n={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ue.extensionName]||(n.compress=!1),this._sender.send(t||tt,n,o)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:ne.indexOf("CONNECTING")});Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:ne.indexOf("CONNECTING")});Object.defineProperty(P,"OPEN",{enumerable:!0,value:ne.indexOf("OPEN")});Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:ne.indexOf("OPEN")});Object.defineProperty(P,"CLOSING",{enumerable:!0,value:ne.indexOf("CLOSING")});Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:ne.indexOf("CLOSING")});Object.defineProperty(P,"CLOSED",{enumerable:!0,value:ne.indexOf("CLOSED")});Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:ne.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Pt])return t[is];return null},set(t){for(let r of this.listeners(e))if(r[Pt]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[Pt]:!0})}})});P.prototype.addEventListener=cs;P.prototype.removeEventListener=ls;Jr.exports=P;function Vr(e,t,r,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:os,protocolVersion:At[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=n.autoPong,e._closeTimeout=n.closeTimeout,!At.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${At.join(", ")})`);let s;if(t instanceof Wt)s=t;else try{s=new Wt(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!i&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let m=new SyntaxError(l);if(e._redirects===0)throw m;rt(e,m);return}let c=i?443:80,d=Qo(16).toString("base64"),u=i?Jo.request:Xo.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?ms:hs),n.defaultPort=n.defaultPort||c,n.port=s.port||c,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(h=new ue(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=ds({[ue.extensionName]:h.offer()})),r.length){for(let m of r){if(typeof m!="string"||!ps.test(m)||p.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(m)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),a){let m=n.path.split(":");n.socketPath=m[0],n.path=m[1]}let g;if(n.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?n.socketPath:s.host;let m=o&&o.headers;if(o={...o,headers:{}},m)for(let[S,$]of Object.entries(m))o.headers[S.toLowerCase()]=$}else if(e.listenerCount("redirect")===0){let m=a?e._originalIpc?n.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!m||e._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,m||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=e._req=u(n),e._redirects&&e.emit("redirect",e.url,g)}else g=e._req=u(n);n.timeout&&g.on("timeout",()=>{q(e,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[zr]||(g=e._req=null,rt(e,m))}),g.on("response",m=>{let S=m.headers.location,$=m.statusCode;if(S&&n.followRedirects&&$>=300&&$<400){if(++e._redirects>n.maxRedirects){q(e,g,"Maximum redirects exceeded");return}g.abort();let O;try{O=new Wt(S,t)}catch{let v=new SyntaxError(`Invalid URL: ${S}`);rt(e,v);return}Vr(e,O,r,o)}else e.emit("unexpected-response",g,m)||q(e,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,S,$)=>{if(e.emit("upgrade",m),e.readyState!==P.CONNECTING)return;g=e._req=null;let O=m.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){q(e,S,"Invalid Upgrade header");return}let D=es("sha1").update(d+ss).digest("base64");if(m.headers["sec-websocket-accept"]!==D){q(e,S,"Invalid Sec-WebSocket-Accept header");return}let v=m.headers["sec-websocket-protocol"],w;if(v!==void 0?p.size?p.has(v)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":p.size&&(w="Server sent no subprotocol"),w){q(e,S,w);return}v&&(e._protocol=v);let b=m.headers["sec-websocket-extensions"];if(b!==void 0){if(!h){q(e,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=us(b)}catch{q(e,S,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(k);if(B.length!==1||B[0]!==ue.extensionName){q(e,S,"Server indicated an extension that was not requested");return}try{h.accept(k[ue.extensionName])}catch{q(e,S,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ue.extensionName]=h}e.setSocket(S,$,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,e):g.end()}function rt(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function hs(e){return e.path=e.socketPath,Hr.connect(e)}function ms(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Hr.isIP(e.host)?"":e.host),Zo.connect(e)}function q(e,t,r){e._readyState=P.CLOSING;let o=new Error(r);Error.captureStackTrace(o,q),t.setHeader?(t[zr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(rt,e,o)):(t.destroy(o),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Ft(e,t,r){if(t){let o=ns(t)?t.size:fs(t).length;e._socket?e._sender._bufferedBytes+=o:e._bufferedAmount+=o}if(r){let o=new Error(`WebSocket is not open: readyState ${e.readyState} (${ne[e.readyState]})`);process.nextTick(r,o)}}function gs(e,t){let r=this[F];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[F]!==void 0&&(r._socket.removeListener("data",nt),process.nextTick(jr,r._socket),e===1005?r.close():r.close(e,t))}function ys(){let e=this[F];e.isPaused||e._socket.resume()}function vs(e){let t=this[F];t._socket[F]!==void 0&&(t._socket.removeListener("data",nt),process.nextTick(jr,t._socket),t.close(e[as])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Fr(){this[F].emitClose()}function ws(e,t){this[F].emit("message",e,t)}function bs(e){let t=this[F];t._autoPong&&t.pong(e,!this._isServer,Ur),t.emit("ping",e)}function Ss(e){this[F].emit("pong",e)}function jr(e){e.resume()}function xs(e){let t=this[F];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,qr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function qr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Gr(){let e=this[F];if(this.removeListener("close",Gr),this.removeListener("data",nt),this.removeListener("end",Kr),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[F]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Fr),e._receiver.on("finish",Fr))}function nt(e){this[F]._receiver.write(e)||this.pause()}function Kr(){let e=this[F];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Yr(){let e=this[F];this.removeListener("error",Yr),this.on("error",Ur),e&&(e._readyState=P.CLOSING,this.destroy())}});var en=V((Ai,Qr)=>{"use strict";var Pi=ot(),{Duplex:_s}=A("stream");function Xr(e){e.emit("close")}function ks(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zr(e){this.removeListener("error",Zr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Es(e,t){let r=!0,o=new _s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&o._readableState.objectMode?s.toString():s;o.push(a)||e.pause()}),e.once("error",function(s){o.destroyed||(r=!1,o.destroy(s))}),e.once("close",function(){o.destroyed||o.push(null)}),o._destroy=function(n,s){if(e.readyState===e.CLOSED){s(n),process.nextTick(Xr,o);return}let i=!1;e.once("error",function(l){i=!0,s(l)}),e.once("close",function(){i||s(n),process.nextTick(Xr,o)}),r&&e.terminate()},o._final=function(n){if(e.readyState===e.CONNECTING){e.once("open",function(){o._final(n)});return}e._socket!==null&&(e._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(e._socket.once("finish",function(){n()}),e.close()))},o._read=function(){e.isPaused&&e.resume()},o._write=function(n,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){o._write(n,s,i)});return}e.send(n,i)},o.on("end",ks),o.on("error",Zr),o}Qr.exports=Es});var rn=V((Fi,tn)=>{"use strict";var{tokenChars:Rs}=_e();function Ts(e){let t=new Set,r=-1,o=-1,n=0;for(n;n<e.length;n++){let i=e.charCodeAt(n);if(o===-1&&Rs[i]===1)r===-1&&(r=n);else if(n!==0&&(i===32||i===9))o===-1&&r!==-1&&(o=n);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let a=e.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);t.add(a),r=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,n);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}tn.exports={parse:Ts}});var dn=V((Ui,ln)=>{"use strict";var Is=A("events"),st=A("http"),{Duplex:Hi}=A("stream"),{createHash:$s}=A("crypto"),nn=Bt(),ye=Le(),Ns=rn(),Ds=ot(),{CLOSE_TIMEOUT:Os,GUID:Cs,kWebSocket:Ls}=ee(),Ms=/^[+/0-9A-Za-z]{22}==$/,on=0,sn=1,cn=2,Ht=class extends Is{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Os,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ds,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=st.createServer((o,n)=>{let s=st.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=Bs(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,i)=>{this.handleUpgrade(n,s,i,o)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=on}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===cn){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Pe,this);return}if(t&&this.once("close",t),this._state!==sn)if(this._state=sn,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(Pe,this):process.nextTick(Pe,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Pe(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,o,n){r.on("error",an);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,a=+t.headers["sec-websocket-version"];if(t.method!=="GET"){ve(this,t,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){ve(this,t,r,400,"Invalid Upgrade header");return}if(s===void 0||!Ms.test(s)){ve(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ve(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Ae(r,400);return}let l=t.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Ns.parse(l)}catch{ve(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=t.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let p=new ye(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=nn.parse(d);h[ye.extensionName]&&(p.accept(h[ye.extensionName]),u[ye.extensionName]=p)}catch{ve(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:t.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,g,m,S)=>{if(!h)return Ae(r,g||401,m,S);this.completeUpgrade(u,s,c,t,r,o,n)});return}if(!this.options.verifyClient(p))return Ae(r,401)}this.completeUpgrade(u,s,c,t,r,o,n)}completeUpgrade(t,r,o,n,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[Ls])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>on)return Ae(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$s("sha1").update(r+Cs).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(o.size){let u=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(t[ye.extensionName]){let u=t[ye.extensionName].params,p=nn.format({[ye.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${p}`),d._extensions=t}this.emit("headers",c,n),s.write(c.concat(`\r
|
|
2
2
|
`).join(`\r
|
|
3
|
-
`)),s.removeListener("error",
|
|
3
|
+
`)),s.removeListener("error",an),d.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Pe,this)})),a(d,n)}};ln.exports=Ht;function Bs(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let o of Object.keys(t))e.removeListener(o,t[o])}}function Pe(e){e._state=cn,e.emit("close")}function an(){this.destroy()}function Ae(e,t,r,o){r=r||st.STATUS_CODES[t],o={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...o},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${st.STATUS_CODES[t]}\r
|
|
4
4
|
`+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
|
|
5
5
|
`)+`\r
|
|
6
6
|
\r
|
|
7
|
-
`+r)}function me(e,t,r,o,n,s){if(e.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,me),e.emit("wsClientError",i,r,t)}else Ae(r,o,n,s)}});var pn={};Sn(pn,{Receiver:()=>dn.default,Sender:()=>un.default,WebSocket:()=>Ft.default,WebSocketServer:()=>fn.default,createWebSocketStream:()=>ln.default,default:()=>$s});var ln,dn,un,Ft,fn,$s,hn=bn(()=>{"use strict";ln=Ie(Zr(),1),dn=Ie(Nt(),1),un=Ie(Ct(),1),Ft=Ie(nt(),1),fn=Ie(cn(),1),$s=Ft.default});function F(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;let t=Math.floor(e/6e4),r=Math.round(e%6e4/1e3);return r===0?`${t}m`:`${t}m ${r}s`}function it(){return`node_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function xn(e){for(let t of e)if((t.type==="parallel"||t.type==="race"||t.type==="sequence")&&!t.id.startsWith("detected_")||"decisionId"in t)return!0;return!1}function Ue(e,t={}){if(xn(e))return e;let{minOverlapMs:r=0,maxGapMs:o=5}=t,n=[],s=[];for(let a=0;a<e.length;a++){let c=e[a];c.type==="step"&&c.startTs!==void 0?n.push({node:c,startTs:c.startTs,endTs:c.endTs??c.startTs+(c.durationMs??0),originalIndex:a}):s.push({node:c,originalIndex:a})}if(n.length<=1)return e;n.sort((a,c)=>a.startTs-c.startTs);let i=[],l=[n[0]];for(let a=1;a<n.length;a++){let c=n[a],u=Math.min(...l.map(w=>w.startTs)),p=Math.max(...l.map(w=>w.endTs)),m=c.startTs<=u+o,v=c.startTs<p;if(!m&&!v){i.push(l),l=[c];continue}let g=v?Math.min(c.endTs,p)-c.startTs:0;m||g>=r?l.push(c):(i.push(l),l=[c])}i.push(l);let d=[];for(let a of i){let c=Math.min(...a.map(u=>u.originalIndex));if(a.length===1)d.push({node:a[0].node,position:c});else{let u=a.map(g=>g.node),p=Math.min(...a.map(g=>g.startTs)),m=Math.max(...a.map(g=>g.endTs)),v={type:"parallel",id:`detected_parallel_${p}`,name:`${u.length} parallel steps`,state:kn(u),mode:"all",children:u,startTs:p,endTs:m,durationMs:m-p};d.push({node:v,position:c})}}for(let{node:a,originalIndex:c}of s)d.push({node:a,position:c});return d.sort((a,c)=>a.position-c.position),d.map(a=>a.node)}function kn(e){return e.some(s=>s.state==="error")?"error":e.some(s=>s.state==="running")?"running":e.some(s=>s.state==="pending")?"pending":(e.every(s=>s.state==="success"||s.state==="cached"),"success")}function En(e={}){return{detect:t=>Ue(t,e)}}function le(e={}){let{detectParallel:t=!0,parallelDetection:r,enableSnapshots:o=!1,maxSnapshots:n=1e3}=e,s,i,l="pending",d,a,c=new Map,u=[],p=[],m=[],v=Date.now(),g=v,w={onAfterStep:new Map},$=[],O=0;function D(f){return f.stepId??f.stepKey??f.name??it()}function h(f){if(p.length>0){let y=p[p.length-1];for(let H of y.branches.values())if(H.taken){H.children.push(f),g=Date.now();return}let S=Array.from(y.branches.values())[0];if(S){S.children.push(f),g=Date.now();return}}u.length>0?u[u.length-1].children.push(f):m.push(f),g=Date.now()}function x(f){if(!o)return;let y=L(),S=new Map;for(let[Y,ce]of c)S.set(Y,{id:ce.id,name:ce.name,key:ce.key,startTs:ce.startTs,retryCount:ce.retryCount,timedOut:ce.timedOut,timeoutMs:ce.timeoutMs});let H={id:`snapshot_${O}`,eventIndex:O,event:structuredClone(f),ir:structuredClone(y),timestamp:Date.now(),activeSteps:S};$.push(H),$.length>n&&$.shift(),O++}function b(f){switch(f.type){case"workflow_start":s=f.workflowId,i=f.ts,l="running",v=Date.now(),g=v,w.onAfterStep=new Map;break;case"workflow_success":l="success",a=f.durationMs,g=Date.now();break;case"workflow_error":l="error",d=f.error,a=f.durationMs,g=Date.now();break;case"step_start":{let y=D(f);c.set(y,{id:y,name:f.name,key:f.stepKey,startTs:f.ts,retryCount:0,timedOut:!1}),g=Date.now();break}case"step_success":{let y=D(f),S=c.get(y);if(S){let H={type:"step",id:S.id,name:S.name,key:S.key,state:"success",startTs:S.startTs,endTs:f.ts,durationMs:f.durationMs,...S.retryCount>0&&{retryCount:S.retryCount},...S.timedOut&&{timedOut:!0,timeoutMs:S.timeoutMs}};h(H),c.delete(y)}break}case"step_error":{let y=D(f),S=c.get(y);if(S){let H={type:"step",id:S.id,name:S.name,key:S.key,state:"error",startTs:S.startTs,endTs:f.ts,durationMs:f.durationMs,error:f.error,...S.retryCount>0&&{retryCount:S.retryCount},...S.timedOut&&{timedOut:!0,timeoutMs:S.timeoutMs}};h(H),c.delete(y)}break}case"step_aborted":{let y=D(f),S=c.get(y);if(S){let H={type:"step",id:S.id,name:S.name,key:S.key,state:"aborted",startTs:S.startTs,endTs:f.ts,durationMs:f.durationMs,...S.retryCount>0&&{retryCount:S.retryCount},...S.timedOut&&{timedOut:!0,timeoutMs:S.timeoutMs}};h(H),c.delete(y)}break}case"step_cache_hit":{let S={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"cached",startTs:f.ts,endTs:f.ts,durationMs:0};h(S);break}case"step_cache_miss":break;case"step_complete":break;case"step_timeout":{let y=D(f),S=c.get(y);S&&(S.timedOut=!0,S.timeoutMs=f.timeoutMs),g=Date.now();break}case"step_retry":{let y=D(f),S=c.get(y);S&&(S.retryCount=(f.attempt??1)-1),g=Date.now();break}case"step_retries_exhausted":g=Date.now();break;case"step_skipped":{let S={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"skipped",startTs:f.ts,endTs:f.ts,durationMs:0};h(S);break}case"hook_should_run":{let y={type:"shouldRun",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};w.shouldRun=y,g=Date.now();break}case"hook_should_run_error":{let y={type:"shouldRun",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};w.shouldRun=y,g=Date.now();break}case"hook_before_start":{let y={type:"onBeforeStart",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};w.onBeforeStart=y,g=Date.now();break}case"hook_before_start_error":{let y={type:"onBeforeStart",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};w.onBeforeStart=y,g=Date.now();break}case"hook_after_step":{let y={type:"onAfterStep",state:"success",ts:f.ts,durationMs:f.durationMs,context:{stepKey:f.stepKey}};w.onAfterStep.set(f.stepKey,y),g=Date.now();break}case"hook_after_step_error":{let y={type:"onAfterStep",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error,context:{stepKey:f.stepKey}};w.onAfterStep.set(f.stepKey,y),g=Date.now();break}}x(f)}function k(f){if(f.type==="scope_start")u.push({id:f.scopeId,name:f.name,type:f.scopeType,startTs:f.ts,children:[]}),g=Date.now();else if(f.type==="scope_end"){let y=u.pop();if(y){let S=y.type==="race"?{type:"race",id:y.id,name:y.name,state:C(y.children),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,children:y.children,winnerId:f.winnerId}:{type:"parallel",id:y.id,name:y.name,state:C(y.children),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,children:y.children,mode:y.type==="allSettled"?"allSettled":"all"};h(S)}}}function B(f){if(f.type==="decision_start")p.push({id:f.decisionId,name:f.name,condition:f.condition,decisionValue:f.decisionValue,startTs:f.ts,branches:new Map}),g=Date.now();else if(f.type==="decision_branch"){let y=p[p.length-1];if(y&&y.id===f.decisionId){let S=f.branchLabel,H=y.branches.get(S);H?H.taken=f.taken:y.branches.set(S,{label:f.branchLabel,condition:f.condition,taken:f.taken,children:[]}),g=Date.now()}}else if(f.type==="decision_end"){let y=p.pop();if(y&&y.id===f.decisionId){let S=Array.from(y.branches.values()),H={type:"decision",id:y.id,name:y.name,state:C(S.flatMap(Y=>Y.taken?Y.children:[])),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,condition:y.condition,decisionValue:y.decisionValue,branchTaken:f.branchTaken??y.branchTaken,branches:S};h(H)}}}function C(f){return f.length===0?"success":f.some(Y=>Y.state==="error")?"error":f.every(Y=>Y.state==="success"||Y.state==="cached")?"success":f.some(Y=>Y.state==="running")?"running":"pending"}function I(){let f=[...m];for(let[,y]of c)f.push({type:"step",id:y.id,name:y.name,key:y.key,state:"running",startTs:y.startTs,...y.retryCount>0&&{retryCount:y.retryCount},...y.timedOut&&{timedOut:!0,timeoutMs:y.timeoutMs}});return f}function L(){let f=I();t&&(f=Ue(f,r));let y={type:"workflow",id:s??it(),workflowId:s??"unknown",state:l,startTs:i,durationMs:a,children:f,error:d},S=w.shouldRun!==void 0||w.onBeforeStart!==void 0||w.onAfterStep.size>0;return{root:y,metadata:{createdAt:v,lastUpdatedAt:g},...S&&{hooks:w}}}function N(){s=void 0,i=void 0,l="pending",d=void 0,a=void 0,c.clear(),u.length=0,p.length=0,m=[],v=Date.now(),g=v,w={onAfterStep:new Map},$.length=0,O=0}function E(){return[...$]}function T(f){return $[f]}function R(f){return $[f]?.ir}function P(){$.length=0,O=0}return{handleEvent:b,handleScopeEvent:k,handleDecisionEvent:B,getIR:L,reset:N,getSnapshots:E,getSnapshotAt:T,getIRAt:R,clearSnapshots:P,get hasActiveSteps(){return c.size>0},get state(){return l},get snapshotCount(){return $.length},get snapshotsEnabled(){return o}}}function Z(e){return e.type==="step"}function Ws(e){return e.type==="sequence"}function de(e){return e.type==="parallel"}function ge(e){return e.type==="race"}function ve(e){return e.type==="decision"}function As(e){return"children"in e||e.type==="decision"&&"branches"in e}var at="\x1B[0m",Tn="\x1B[1m",jt="\x1B[2m",Rn="\x1B[31m",In="\x1B[32m",$n="\x1B[33m",Nn="\x1B[34m",Vt="\x1B[90m",Dn="\x1B[37m";function ne(e,t){return t?`${t}${e}${at}`:e}function $e(e){return`${Tn}${e}${at}`}function M(e){return`${jt}${e}${at}`}var oe={pending:Dn,running:$n,success:In,error:Rn,aborted:Vt,cached:Nn,skipped:jt+Vt};function On(e){switch(e){case"pending":return"\u25CB";case"running":return"\u27F3";case"success":return"\u2713";case"error":return"\u2717";case"aborted":return"\u2298";case"cached":return"\u21BA";case"skipped":return"\u2298"}}function Ne(e,t){let r=On(e);return ne(r,t[e])}function ct(e,t,r){return ne(e,r[t])}function qt(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}var _={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",teeRight:"\u251C",teeLeft:"\u2524",teeDown:"\u252C",teeUp:"\u2534",cross:"\u253C"},ye={cold:"\x1B[34m",cool:"\x1B[36m",neutral:"",warm:"\x1B[33m",hot:"\x1B[31m",critical:"\x1B[41m"},Cn="\x1B[0m";function Ln(e){return e<.2?ye.cold:e<.4?ye.cool:e<.6?ye.neutral:e<.8?ye.warm:e<.95?ye.hot:ye.critical}function Gt(e,t){let r=Ln(t);return r?`${r}${e}${Cn}`:e}var Kt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Mn(e,t=10){if(e.length===0)return"";let r=e.slice(-t),o=Math.min(...r),s=Math.max(...r)-o||1;return r.map(i=>{let l=(i-o)/s,d=Math.floor(l*(Kt.length-1));return Kt[d]}).join("")}function lt(e,t){let r=qt(e).length,o=Math.max(0,t-r);return e+" ".repeat(o)}function Bn(e,t){if(!t)return _.horizontal.repeat(e);let r=` ${t} `,o=e-r.length;if(o<4)return _.horizontal.repeat(e);let n=2,s=o-n;return _.horizontal.repeat(n)+r+_.horizontal.repeat(s)}function Yt(e,t,r){let o=e.state==="success"?ne("\u2699",r.success):ne("\u26A0",r.error),n=e.durationMs!==void 0?M(` [${F(e.durationMs)}]`):"",s="";e.type==="shouldRun"&&e.context?.skipped?s=M(" \u2192 workflow skipped"):e.type==="shouldRun"&&e.context?.result===!0?s=M(" \u2192 proceed"):e.type==="onBeforeStart"&&e.context?.skipped?s=M(" \u2192 workflow skipped"):e.type==="onAfterStep"&&e.context?.stepKey&&(s=M(` (${e.context.stepKey})`));let i=e.state==="error"&&e.error?M(` error: ${String(e.error)}`):"";return`${o} ${M(t)}${s}${n}${i}`}function Pn(e,t){let r=[];return e.shouldRun&&r.push(Yt(e.shouldRun,"shouldRun",t)),e.onBeforeStart&&r.push(Yt(e.onBeforeStart,"onBeforeStart",t)),r.length>0&&r.push(M("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),r}function we(){return{name:"ascii",supportsLive:!0,render(e,t){let r={...oe,...t.colors},o=t.terminalWidth??60,n=o-4,s=[],i=e.root.name??"workflow",l=$e(i);if(s.push(`${_.topLeft}${Bn(o-2,l)}${_.topRight}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.hooks){let a=Pn(e.hooks,r);for(let c of a)s.push(`${_.vertical} ${lt(c,n)}${_.vertical}`)}let d=Fe(e.root.children,t,r,0,e.hooks);for(let a of d)s.push(`${_.vertical} ${lt(a,n)}${_.vertical}`);if(s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.root.durationMs!==void 0&&t.showTimings){let a=e.root.state==="success"?"Completed":"Failed",u=`${ct(a,e.root.state,r)} in ${F(e.root.durationMs)}`;s.push(`${_.vertical} ${lt(u,n)}${_.vertical}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`)}return s.push(`${_.bottomLeft}${_.horizontal.repeat(o-2)}${_.bottomRight}`),s.join(`
|
|
8
|
-
`)}}}function Fe(e,t,r,o,n){let s=[];for(let i of e)Z(i)?s.push(dt(i,t,r,n)):de(i)?s.push(...Wn(i,t,r,o,n)):ge(i)?s.push(...An(i,t,r,o,n)):ve(i)&&s.push(...Un(i,t,r,o,n));return s}function dt(e,t,r,o){let n=Ne(e.state,r),s=e.name??e.key??"step",i=t,l=e.name??e.id,d=i.showHeatmap&&i.heatmapData?i.heatmapData.heat.get(e.id)??i.heatmapData.heat.get(l):void 0,a;d!==void 0?a=Gt(s,d):a=ct(s,e.state,r);let c=`${n} ${a}`;if(t.showKeys&&e.key&&(c+=M(` [key: ${e.key}]`)),e.input!==void 0){let u=typeof e.input=="string"?e.input:JSON.stringify(e.input).slice(0,30);c+=M(` [in: ${u}${u.length>=30?"...":""}]`)}if(e.output!==void 0&&e.state==="success"){let u=typeof e.output=="string"?e.output:JSON.stringify(e.output).slice(0,30);c+=M(` [out: ${u}${u.length>=30?"...":""}]`)}if(t.showTimings&&e.durationMs!==void 0){let u=F(e.durationMs),p=d!==void 0?Gt(`[${u}]`,d):M(`[${u}]`);c+=` ${p}`}if(i.showSparklines&&i.timingHistory){let u=i.timingHistory.get(l);u&&u.length>1&&(c+=` ${M(Mn(u))}`)}if(e.retryCount!==void 0&&e.retryCount>0&&(c+=M(` [${e.retryCount} ${e.retryCount===1?"retry":"retries"}]`)),e.timedOut){let u=e.timeoutMs!==void 0?` ${e.timeoutMs}ms`:"";c+=M(` [timeout${u}]`)}if(o&&e.key&&o.onAfterStep.has(e.key)){let u=o.onAfterStep.get(e.key),p=u.state==="success"?ne("\u2699",r.success):ne("\u26A0",r.error),m=u.durationMs!==void 0?M(` ${F(u.durationMs)}`):"";c+=` ${p}${m}`}return c}function Wn(e,t,r,o,n){let s=[],i=" ".repeat(o),l=Ne(e.state,r),d=e.name??"parallel",a=e.mode==="allSettled"?" (allSettled)":"";if(s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${l} ${$e(d)}${a}`),e.children.length===0)s.push(`${i}${_.vertical} ${M("(operations not individually tracked)")}`),s.push(`${i}${_.vertical} ${M("(wrap each operation with step() to see individual steps)")}`);else for(let c=0;c<e.children.length;c++){let u=e.children[c],m=c===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`;if(Z(u))s.push(`${m} ${dt(u,t,r,n)}`);else{let v=Fe([u],t,r,o+1,n);for(let g of v)s.push(`${i}${_.vertical} ${g}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${F(e.durationMs)}]`)}`),s}function An(e,t,r,o,n){let s=[],i=" ".repeat(o),l=Ne(e.state,r),d=e.name??"race";if(s.push(`${i}${_.teeRight}\u26A1 ${l} ${$e(d)}`),e.children.length===0)s.push(`${i}${_.vertical} ${M("(operations not individually tracked)")}`),s.push(`${i}${_.vertical} ${M("(wrap each operation with step() to see individual steps)")}`);else for(let a=0;a<e.children.length;a++){let c=e.children[a],p=a===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,v=e.winnerId&&c.id===e.winnerId?M(" (winner)"):"";if(Z(c))s.push(`${p} ${dt(c,t,r,n)}${v}`);else{let g=Fe([c],t,r,o+1,n);for(let w of g)s.push(`${i}${_.vertical} ${w}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${F(e.durationMs)}]`)}`),s}function Un(e,t,r,o,n){let s=[],i=" ".repeat(o),l=Ne(e.state,r),d=e.name??"decision",a=e.condition?M(` (${e.condition})`):"",c=e.decisionValue!==void 0?M(` = ${String(e.decisionValue)}`):"",u=e.branchTaken!==void 0?M(` \u2192 ${String(e.branchTaken)}`):"";s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${l} ${$e(d)}${a}${c}${u}`);for(let p=0;p<e.branches.length;p++){let m=e.branches[p],g=p===e.branches.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,w=m.taken?"\u2713":"\u2298",$=m.taken?r.success:r.skipped,O=ne(`${w} ${m.label}`,$),D=m.condition?M(` (${m.condition})`):"";if(s.push(`${g} ${O}${D}`),m.children.length>0){let h=Fe(m.children,t,r,o+1,n);for(let x of h)s.push(`${i}${_.vertical} ${x}`)}else m.taken||s.push(`${i}${_.vertical} ${M("(skipped)")}`)}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${F(e.durationMs)}]`)}`),s}function ut(e){let t=[];for(let r of e)if(t.push(r),"children"in r&&Array.isArray(r.children)&&t.push(...ut(r.children)),"branches"in r)for(let o of r.branches)t.push(...ut(o.children));return t}function He(e,t){if(e.length===0)return 0;let r=Math.floor(e.length*t);return e[Math.min(r,e.length-1)]}function ft(e){return e<.2?"cold":e<.4?"cool":e<.6?"neutral":e<.8?"warm":e<.95?"hot":"critical"}function pt(){let e=new Map,t=new Map,r=new Map,o=new Map,n=[];function s(h){return h.name??h.stepKey??h.stepId??"unknown"}function i(h){let x=new Map;for(let b of h)switch(b.type){case"step_start":{let k=s(b);x.set(k,{retried:!1,timedOut:!1});break}case"step_retry":{let k=s(b),B=x.get(k);B&&(B.retried=!0);break}case"step_timeout":{let k=s(b),B=x.get(k);B&&(B.timedOut=!0);let C=o.get(k)??{timedOut:0,total:0};C.timedOut++,C.total++,o.set(k,C);break}case"step_success":{let k=s(b),B=x.get(k),C=e.get(k)??[];C.push(b.durationMs),e.set(k,C);let I=t.get(k)??{retried:0,total:0};I.total++,B?.retried&&I.retried++,t.set(k,I);let L=r.get(k)??{errors:0,total:0};L.total++,r.set(k,L),x.delete(k);break}case"step_error":{let k=s(b),B=x.get(k),C=e.get(k)??[];C.push(b.durationMs),e.set(k,C);let I=t.get(k)??{retried:0,total:0};I.total++,B?.retried&&I.retried++,t.set(k,I);let L=r.get(k)??{errors:0,total:0};L.total++,L.errors++,r.set(k,L),x.delete(k);break}}}function l(h){i(h.events)}function d(h){n.push(h)}function a(h){n.length>0&&(i(n),n=[])}function c(h){let x=e.get(h);if(!x||x.length===0)return;let b=[...x].sort((E,T)=>E-T),B=b.reduce((E,T)=>E+T,0)/b.length,C=b.reduce((E,T)=>E+(T-B)**2,0)/b.length,I=t.get(h)??{retried:0,total:1},L=r.get(h)??{errors:0,total:1},N=o.get(h)??{timedOut:0,total:1};return{nodeId:h,avgDurationMs:B,minDurationMs:b[0],maxDurationMs:b[b.length-1],stdDevMs:Math.sqrt(C),samples:b.length,retryRate:I.total>0?I.retried/I.total:0,timeoutRate:N.total>0?N.timedOut/N.total:0,errorRate:L.total>0?L.errors/L.total:0,percentiles:{p50:He(b,.5),p90:He(b,.9),p95:He(b,.95),p99:He(b,.99)}}}function u(h){return c(h)}function p(h,x="duration"){let b=new Map,k=ut(h.root.children),B=[];for(let T of k){let R=T.name??T.id,P=c(R);if(P){let f;switch(x){case"duration":f=P.avgDurationMs;break;case"retryRate":f=P.retryRate;break;case"errorRate":f=P.errorRate;break}B.push({id:T.id,value:f})}}if(B.length===0)return{heat:b,metric:x,stats:{min:0,max:0,mean:0,threshold:0}};let C=B.map(T=>T.value),I=Math.min(...C),L=Math.max(...C),N=C.reduce((T,R)=>T+R,0)/C.length,E=L-I||1;for(let{id:T,value:R}of B)b.set(T,(R-I)/E);return{heat:b,metric:x,stats:{min:I,max:L,mean:N,threshold:N+(L-N)*.5}}}function m(){let h=new Map;for(let x of e.keys()){let b=c(x);b&&h.set(x,b)}return h}function v(h=10){return[...m().values()].sort((b,k)=>k.avgDurationMs-b.avgDurationMs).slice(0,h)}function g(h=10){return[...m().values()].filter(b=>b.errorRate>0).sort((b,k)=>k.errorRate-b.errorRate).slice(0,h)}function w(h=10){return[...m().values()].filter(b=>b.retryRate>0).sort((b,k)=>k.retryRate-b.retryRate).slice(0,h)}function $(){return JSON.stringify({timingData:Object.fromEntries(e),retryData:Object.fromEntries(t),errorData:Object.fromEntries(r),timeoutData:Object.fromEntries(o)})}function O(h){let x=JSON.parse(h);e.clear(),t.clear(),r.clear(),o.clear();for(let[b,k]of Object.entries(x.timingData??{}))e.set(b,k);for(let[b,k]of Object.entries(x.retryData??{}))t.set(b,k);for(let[b,k]of Object.entries(x.errorData??{}))r.set(b,k);for(let[b,k]of Object.entries(x.timeoutData??{}))o.set(b,k)}function D(){e.clear(),t.clear(),r.clear(),o.clear(),n=[]}return{addRun:l,addEvent:d,finalizeRun:a,getNodePerformance:u,getHeatmap:p,getSlowestNodes:v,getErrorProneNodes:g,getRetryProneNodes:w,getAllPerformance:m,exportData:$,importData:O,clear:D}}function Fn(){return[" classDef pending fill:#f3f4f6,stroke:#9ca3af,stroke-width:2px,color:#374151"," classDef running fill:#fef3c7,stroke:#f59e0b,stroke-width:3px,color:#92400e"," classDef success fill:#d1fae5,stroke:#10b981,stroke-width:3px,color:#065f46"," classDef error fill:#fee2e2,stroke:#ef4444,stroke-width:3px,color:#991b1b"," classDef aborted fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#4b5563,stroke-dasharray: 5 5"," classDef cached fill:#dbeafe,stroke:#3b82f6,stroke-width:3px,color:#1e40af"," classDef skipped fill:#f9fafb,stroke:#d1d5db,stroke-width:2px,color:#6b7280,stroke-dasharray: 5 5"]}function Hn(){return[" classDef heat_cold fill:#dbeafe,stroke:#3b82f6,stroke-width:2px,color:#1e40af"," classDef heat_cool fill:#ccfbf1,stroke:#14b8a6,stroke-width:2px,color:#0f766e"," classDef heat_neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#374151"," classDef heat_warm fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#92400e"," classDef heat_hot fill:#fed7aa,stroke:#f97316,stroke-width:3px,color:#c2410c"," classDef heat_critical fill:#fecaca,stroke:#ef4444,stroke-width:3px,color:#b91c1c"]}function zn(e){return`heat_${e}`}function Vn(){return[" classDef hook_success fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e"," classDef hook_error fill:#fef2f2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d"]}function jn(e,t,r){let o;if(e.shouldRun){let n="hook_shouldRun",s=e.shouldRun.state==="success"?"hook_success":"hook_error",i=e.shouldRun.state==="success"?"\u2699":"\u26A0",l=r.showTimings&&e.shouldRun.durationMs!==void 0?` ${F(e.shouldRun.durationMs)}`:"",d=e.shouldRun.context?.skipped?"\\nskipped workflow":e.shouldRun.context?.result===!0?"\\nproceed":"";t.push(` ${n}[["${i} shouldRun${d}${l}"]]:::${s}`),o=n}if(e.onBeforeStart){let n="hook_beforeStart",s=e.onBeforeStart.state==="success"?"hook_success":"hook_error",i=e.onBeforeStart.state==="success"?"\u2699":"\u26A0",l=r.showTimings&&e.onBeforeStart.durationMs!==void 0?` ${F(e.onBeforeStart.durationMs)}`:"",d=e.onBeforeStart.context?.skipped?"\\nskipped workflow":"";t.push(` ${n}[["${i} onBeforeStart${d}${l}"]]:::${s}`),o&&t.push(` ${o} --> ${n}`),o=n}return{lastHookId:o}}var Jt=0;function De(e="node"){return`${e}_${++Jt}`}function qn(){Jt=0}function j(e){return e.replace(/[{}[\]()]/g,"").replace(/[<>]/g,"").replace(/"/g,"'").trim()}function Xt(e){return j(e).replace(/[[\]]/g,"")}function ze(){return{name:"mermaid",supportsLive:!1,render(e,t){qn();let r=[],o=t;r.push("flowchart TD");let n;e.hooks&&(n=jn(e.hooks,r,t).lastHookId);let s="start";r.push(` ${s}(("\u25B6 Start"))`),n&&r.push(` ${n} --> ${s}`);let i=s;for(let l of e.root.children){let d=Ve(l,t,r,o,e.hooks);r.push(` ${i} --> ${d.entryId}`),i=d.exitId}if(e.root.state==="success"||e.root.state==="error"){let l="finish",d=e.root.state==="success"?"\u2713":"\u2717",a=e.root.state==="success"?"Done":"Failed",c=`(("${d} ${a}"))`,u=e.root.state==="success"?":::success":":::error";r.push(` ${l}${c}${u}`),r.push(` ${i} --> ${l}`)}return r.push(""),r.push(...Fn()),o.showHeatmap&&r.push(...Hn()),e.hooks&&r.push(...Vn()),r.join(`
|
|
9
|
-
`)}}}function Ve(e,t,r,o,n){if(
|
|
7
|
+
`+r)}function ve(e,t,r,o,n,s){if(e.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,ve),e.emit("wsClientError",i,r,t)}else Ae(r,o,n,s)}});var mn={};_n(mn,{Receiver:()=>fn.default,Sender:()=>pn.default,WebSocket:()=>Ut.default,WebSocketServer:()=>hn.default,createWebSocketStream:()=>un.default,default:()=>Ws});var un,fn,pn,Ut,hn,Ws,gn=xn(()=>{"use strict";un=Ie(en(),1),fn=Ie(Dt(),1),pn=Ie(Lt(),1),Ut=Ie(ot(),1),hn=Ie(dn(),1),Ws=Ut.default});function H(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;let t=Math.floor(e/6e4),r=Math.round(e%6e4/1e3);return r===0?`${t}m`:`${t}m ${r}s`}function at(){return`node_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function En(e){for(let t of e)if((t.type==="parallel"||t.type==="race"||t.type==="sequence")&&!t.id.startsWith("detected_")||"decisionId"in t)return!0;return!1}function Fe(e,t={}){if(En(e))return e;let{minOverlapMs:r=0,maxGapMs:o=5}=t,n=[],s=[];for(let c=0;c<e.length;c++){let d=e[c];d.type==="step"&&d.startTs!==void 0?n.push({node:d,startTs:d.startTs,endTs:d.endTs??d.startTs+(d.durationMs??0),originalIndex:c}):s.push({node:d,originalIndex:c})}if(n.length<=1)return e;n.sort((c,d)=>c.startTs-d.startTs);let i=[],a=[n[0]];for(let c=1;c<n.length;c++){let d=n[c],u=Math.min(...a.map(S=>S.startTs)),p=Math.max(...a.map(S=>S.endTs)),h=d.startTs<=u+o,g=d.startTs<p;if(!h&&!g){i.push(a),a=[d];continue}let m=g?Math.min(d.endTs,p)-d.startTs:0;h||m>=r?a.push(d):(i.push(a),a=[d])}i.push(a);let l=[];for(let c of i){let d=Math.min(...c.map(u=>u.originalIndex));if(c.length===1)l.push({node:c[0].node,position:d});else{let u=c.map(m=>m.node),p=Math.min(...c.map(m=>m.startTs)),h=Math.max(...c.map(m=>m.endTs)),g={type:"parallel",id:`detected_parallel_${p}`,name:`${u.length} parallel steps`,state:Rn(u),mode:"all",children:u,startTs:p,endTs:h,durationMs:h-p};l.push({node:g,position:d})}}for(let{node:c,originalIndex:d}of s)l.push({node:c,position:d});return l.sort((c,d)=>c.position-d.position),l.map(c=>c.node)}function Rn(e){return e.some(s=>s.state==="error")?"error":e.some(s=>s.state==="running")?"running":e.some(s=>s.state==="pending")?"pending":(e.every(s=>s.state==="success"||s.state==="cached"),"success")}function Tn(e={}){return{detect:t=>Fe(t,e)}}function pe(e={}){let{detectParallel:t=!0,parallelDetection:r,enableSnapshots:o=!1,maxSnapshots:n=1e3}=e,s,i,a="pending",l,c,d=new Map,u=[],p=[],h=[],g=Date.now(),m=g,S={onAfterStep:new Map},$=[],O=0;function D(f){return f.stepId??f.stepKey??f.name??at()}function v(f){if(p.length>0){let y=p[p.length-1];for(let U of y.branches.values())if(U.taken){U.children.push(f),m=Date.now();return}let x=Array.from(y.branches.values())[0];if(x){x.children.push(f),m=Date.now();return}}u.length>0?u[u.length-1].children.push(f):h.push(f),m=Date.now()}function w(f){if(!o)return;let y=L(),x=new Map;for(let[Y,fe]of d)x.set(Y,{id:fe.id,name:fe.name,key:fe.key,startTs:fe.startTs,retryCount:fe.retryCount,timedOut:fe.timedOut,timeoutMs:fe.timeoutMs});let U={id:`snapshot_${O}`,eventIndex:O,event:structuredClone(f),ir:structuredClone(y),timestamp:Date.now(),activeSteps:x};$.push(U),$.length>n&&$.shift(),O++}function b(f){switch(f.type){case"workflow_start":s=f.workflowId,i=f.ts,a="running",g=Date.now(),m=g,S.onAfterStep=new Map;break;case"workflow_success":a="success",c=f.durationMs,m=Date.now();break;case"workflow_error":a="error",l=f.error,c=f.durationMs,m=Date.now();break;case"step_start":{let y=D(f);d.set(y,{id:y,name:f.name,key:f.stepKey,startTs:f.ts,retryCount:0,timedOut:!1}),m=Date.now();break}case"step_success":{let y=D(f),x=d.get(y);if(x){let U={type:"step",id:x.id,name:x.name,key:x.key,state:"success",startTs:x.startTs,endTs:f.ts,durationMs:f.durationMs,...x.retryCount>0&&{retryCount:x.retryCount},...x.timedOut&&{timedOut:!0,timeoutMs:x.timeoutMs}};v(U),d.delete(y)}break}case"step_error":{let y=D(f),x=d.get(y);if(x){let U={type:"step",id:x.id,name:x.name,key:x.key,state:"error",startTs:x.startTs,endTs:f.ts,durationMs:f.durationMs,error:f.error,...x.retryCount>0&&{retryCount:x.retryCount},...x.timedOut&&{timedOut:!0,timeoutMs:x.timeoutMs}};v(U),d.delete(y)}break}case"step_aborted":{let y=D(f),x=d.get(y);if(x){let U={type:"step",id:x.id,name:x.name,key:x.key,state:"aborted",startTs:x.startTs,endTs:f.ts,durationMs:f.durationMs,...x.retryCount>0&&{retryCount:x.retryCount},...x.timedOut&&{timedOut:!0,timeoutMs:x.timeoutMs}};v(U),d.delete(y)}break}case"step_cache_hit":{let x={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"cached",startTs:f.ts,endTs:f.ts,durationMs:0};v(x);break}case"step_cache_miss":break;case"step_complete":break;case"step_timeout":{let y=D(f),x=d.get(y);x&&(x.timedOut=!0,x.timeoutMs=f.timeoutMs),m=Date.now();break}case"step_retry":{let y=D(f),x=d.get(y);x&&(x.retryCount=(f.attempt??1)-1),m=Date.now();break}case"step_retries_exhausted":m=Date.now();break;case"step_skipped":{let x={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"skipped",startTs:f.ts,endTs:f.ts,durationMs:0};v(x);break}case"hook_should_run":{let y={type:"shouldRun",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};S.shouldRun=y,m=Date.now();break}case"hook_should_run_error":{let y={type:"shouldRun",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};S.shouldRun=y,m=Date.now();break}case"hook_before_start":{let y={type:"onBeforeStart",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};S.onBeforeStart=y,m=Date.now();break}case"hook_before_start_error":{let y={type:"onBeforeStart",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};S.onBeforeStart=y,m=Date.now();break}case"hook_after_step":{let y={type:"onAfterStep",state:"success",ts:f.ts,durationMs:f.durationMs,context:{stepKey:f.stepKey}};S.onAfterStep.set(f.stepKey,y),m=Date.now();break}case"hook_after_step_error":{let y={type:"onAfterStep",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error,context:{stepKey:f.stepKey}};S.onAfterStep.set(f.stepKey,y),m=Date.now();break}}w(f)}function k(f){if(f.type==="scope_start")u.push({id:f.scopeId,name:f.name,type:f.scopeType,startTs:f.ts,children:[]}),m=Date.now();else if(f.type==="scope_end"){let y=u.pop();if(y){let x=y.type==="race"?{type:"race",id:y.id,name:y.name,state:C(y.children),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,children:y.children,winnerId:f.winnerId}:{type:"parallel",id:y.id,name:y.name,state:C(y.children),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,children:y.children,mode:y.type==="allSettled"?"allSettled":"all"};v(x)}}}function B(f){if(f.type==="decision_start")p.push({id:f.decisionId,name:f.name,condition:f.condition,decisionValue:f.decisionValue,startTs:f.ts,branches:new Map}),m=Date.now();else if(f.type==="decision_branch"){let y=p[p.length-1];if(y&&y.id===f.decisionId){let x=f.branchLabel,U=y.branches.get(x);U?U.taken=f.taken:y.branches.set(x,{label:f.branchLabel,condition:f.condition,taken:f.taken,children:[]}),m=Date.now()}}else if(f.type==="decision_end"){let y=p.pop();if(y&&y.id===f.decisionId){let x=Array.from(y.branches.values()),U={type:"decision",id:y.id,name:y.name,state:C(x.flatMap(Y=>Y.taken?Y.children:[])),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,condition:y.condition,decisionValue:y.decisionValue,branchTaken:f.branchTaken??y.branchTaken,branches:x};v(U)}}}function C(f){return f.length===0?"success":f.some(Y=>Y.state==="error")?"error":f.every(Y=>Y.state==="success"||Y.state==="cached")?"success":f.some(Y=>Y.state==="running")?"running":"pending"}function I(){let f=[...h];for(let[,y]of d)f.push({type:"step",id:y.id,name:y.name,key:y.key,state:"running",startTs:y.startTs,...y.retryCount>0&&{retryCount:y.retryCount},...y.timedOut&&{timedOut:!0,timeoutMs:y.timeoutMs}});return f}function L(){let f=I();t&&(f=Fe(f,r));let y={type:"workflow",id:s??at(),workflowId:s??"unknown",state:a,startTs:i,durationMs:c,children:f,error:l},x=S.shouldRun!==void 0||S.onBeforeStart!==void 0||S.onAfterStep.size>0;return{root:y,metadata:{createdAt:g,lastUpdatedAt:m},...x&&{hooks:S}}}function N(){s=void 0,i=void 0,a="pending",l=void 0,c=void 0,d.clear(),u.length=0,p.length=0,h=[],g=Date.now(),m=g,S={onAfterStep:new Map},$.length=0,O=0}function E(){return[...$]}function R(f){return $[f]}function T(f){return $[f]?.ir}function W(){$.length=0,O=0}return{handleEvent:b,handleScopeEvent:k,handleDecisionEvent:B,getIR:L,reset:N,getSnapshots:E,getSnapshotAt:R,getIRAt:T,clearSnapshots:W,get hasActiveSteps(){return d.size>0},get state(){return a},get snapshotCount(){return $.length},get snapshotsEnabled(){return o}}}function J(e){return e.type==="step"}function jt(e){return e.type==="sequence"}function Q(e){return e.type==="parallel"}function oe(e){return e.type==="race"}function se(e){return e.type==="decision"}function qs(e){return"children"in e||e.type==="decision"&&"branches"in e}var ct="\x1B[0m",In="\x1B[1m",Gt="\x1B[2m",$n="\x1B[31m",Nn="\x1B[32m",Dn="\x1B[33m",On="\x1B[34m",qt="\x1B[90m",Cn="\x1B[37m";function ie(e,t){return t?`${t}${e}${ct}`:e}function $e(e){return`${In}${e}${ct}`}function M(e){return`${Gt}${e}${ct}`}var ae={pending:Cn,running:Dn,success:Nn,error:$n,aborted:qt,cached:On,skipped:Gt+qt};function Ln(e){switch(e){case"pending":return"\u25CB";case"running":return"\u27F3";case"success":return"\u2713";case"error":return"\u2717";case"aborted":return"\u2298";case"cached":return"\u21BA";case"skipped":return"\u2298"}}function Ne(e,t){let r=Ln(e);return ie(r,t[e])}function lt(e,t,r){return ie(e,r[t])}function Kt(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}var _={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",teeRight:"\u251C",teeLeft:"\u2524",teeDown:"\u252C",teeUp:"\u2534",cross:"\u253C"},we={cold:"\x1B[34m",cool:"\x1B[36m",neutral:"",warm:"\x1B[33m",hot:"\x1B[31m",critical:"\x1B[41m"},Mn="\x1B[0m";function Bn(e){return e<.2?we.cold:e<.4?we.cool:e<.6?we.neutral:e<.8?we.warm:e<.95?we.hot:we.critical}function Yt(e,t){let r=Bn(t);return r?`${r}${e}${Mn}`:e}var Jt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Wn(e,t=10){if(e.length===0)return"";let r=e.slice(-t),o=Math.min(...r),s=Math.max(...r)-o||1;return r.map(i=>{let a=(i-o)/s,l=Math.floor(a*(Jt.length-1));return Jt[l]}).join("")}function dt(e,t){let r=Kt(e).length,o=Math.max(0,t-r);return e+" ".repeat(o)}function Pn(e,t){if(!t)return _.horizontal.repeat(e);let r=` ${t} `,o=e-r.length;if(o<4)return _.horizontal.repeat(e);let n=2,s=o-n;return _.horizontal.repeat(n)+r+_.horizontal.repeat(s)}function Xt(e,t,r){let o=e.state==="success"?ie("\u2699",r.success):ie("\u26A0",r.error),n=e.durationMs!==void 0?M(` [${H(e.durationMs)}]`):"",s="";e.type==="shouldRun"&&e.context?.skipped?s=M(" \u2192 workflow skipped"):e.type==="shouldRun"&&e.context?.result===!0?s=M(" \u2192 proceed"):e.type==="onBeforeStart"&&e.context?.skipped?s=M(" \u2192 workflow skipped"):e.type==="onAfterStep"&&e.context?.stepKey&&(s=M(` (${e.context.stepKey})`));let i=e.state==="error"&&e.error?M(` error: ${String(e.error)}`):"";return`${o} ${M(t)}${s}${n}${i}`}function An(e,t){let r=[];return e.shouldRun&&r.push(Xt(e.shouldRun,"shouldRun",t)),e.onBeforeStart&&r.push(Xt(e.onBeforeStart,"onBeforeStart",t)),r.length>0&&r.push(M("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),r}function ce(){return{name:"ascii",supportsLive:!0,render(e,t){let r={...ae,...t.colors},o=t.terminalWidth??60,n=o-4,s=[],i=e.root.name??"workflow",a=$e(i);if(s.push(`${_.topLeft}${Pn(o-2,a)}${_.topRight}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.hooks){let c=An(e.hooks,r);for(let d of c)s.push(`${_.vertical} ${dt(d,n)}${_.vertical}`)}let l=He(e.root.children,t,r,0,e.hooks);for(let c of l)s.push(`${_.vertical} ${dt(c,n)}${_.vertical}`);if(s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.root.durationMs!==void 0&&t.showTimings){let c=e.root.state==="success"?"Completed":"Failed",u=`${lt(c,e.root.state,r)} in ${H(e.root.durationMs)}`;s.push(`${_.vertical} ${dt(u,n)}${_.vertical}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`)}return s.push(`${_.bottomLeft}${_.horizontal.repeat(o-2)}${_.bottomRight}`),s.join(`
|
|
8
|
+
`)}}}function He(e,t,r,o,n){let s=[];for(let i of e)J(i)?s.push(ut(i,t,r,n)):Q(i)?s.push(...Fn(i,t,r,o,n)):oe(i)?s.push(...Hn(i,t,r,o,n)):se(i)&&s.push(...Un(i,t,r,o,n));return s}function ut(e,t,r,o){let n=Ne(e.state,r),s=e.name??e.key??"step",i=t,a=e.name??e.id,l=i.showHeatmap&&i.heatmapData?i.heatmapData.heat.get(e.id)??i.heatmapData.heat.get(a):void 0,c;l!==void 0?c=Yt(s,l):c=lt(s,e.state,r);let d=`${n} ${c}`;if(t.showKeys&&e.key&&(d+=M(` [key: ${e.key}]`)),e.input!==void 0){let u=typeof e.input=="string"?e.input:JSON.stringify(e.input).slice(0,30);d+=M(` [in: ${u}${u.length>=30?"...":""}]`)}if(e.output!==void 0&&e.state==="success"){let u=typeof e.output=="string"?e.output:JSON.stringify(e.output).slice(0,30);d+=M(` [out: ${u}${u.length>=30?"...":""}]`)}if(t.showTimings&&e.durationMs!==void 0){let u=H(e.durationMs),p=l!==void 0?Yt(`[${u}]`,l):M(`[${u}]`);d+=` ${p}`}if(i.showSparklines&&i.timingHistory){let u=i.timingHistory.get(a);u&&u.length>1&&(d+=` ${M(Wn(u))}`)}if(e.retryCount!==void 0&&e.retryCount>0&&(d+=M(` [${e.retryCount} ${e.retryCount===1?"retry":"retries"}]`)),e.timedOut){let u=e.timeoutMs!==void 0?` ${e.timeoutMs}ms`:"";d+=M(` [timeout${u}]`)}if(o&&e.key&&o.onAfterStep.has(e.key)){let u=o.onAfterStep.get(e.key),p=u.state==="success"?ie("\u2699",r.success):ie("\u26A0",r.error),h=u.durationMs!==void 0?M(` ${H(u.durationMs)}`):"";d+=` ${p}${h}`}return d}function Fn(e,t,r,o,n){let s=[],i=" ".repeat(o),a=Ne(e.state,r),l=e.name??"parallel",c=e.mode==="allSettled"?" (allSettled)":"";if(s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${a} ${$e(l)}${c}`),e.children.length===0)s.push(`${i}${_.vertical} ${M("(operations not individually tracked)")}`),s.push(`${i}${_.vertical} ${M("(wrap each operation with step() to see individual steps)")}`);else for(let d=0;d<e.children.length;d++){let u=e.children[d],h=d===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`;if(J(u))s.push(`${h} ${ut(u,t,r,n)}`);else{let g=He([u],t,r,o+1,n);for(let m of g)s.push(`${i}${_.vertical} ${m}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${H(e.durationMs)}]`)}`),s}function Hn(e,t,r,o,n){let s=[],i=" ".repeat(o),a=Ne(e.state,r),l=e.name??"race";if(s.push(`${i}${_.teeRight}\u26A1 ${a} ${$e(l)}`),e.children.length===0)s.push(`${i}${_.vertical} ${M("(operations not individually tracked)")}`),s.push(`${i}${_.vertical} ${M("(wrap each operation with step() to see individual steps)")}`);else for(let c=0;c<e.children.length;c++){let d=e.children[c],p=c===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,g=e.winnerId&&d.id===e.winnerId?M(" (winner)"):"";if(J(d))s.push(`${p} ${ut(d,t,r,n)}${g}`);else{let m=He([d],t,r,o+1,n);for(let S of m)s.push(`${i}${_.vertical} ${S}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${H(e.durationMs)}]`)}`),s}function Un(e,t,r,o,n){let s=[],i=" ".repeat(o),a=Ne(e.state,r),l=e.name??"decision",c=e.condition?M(` (${e.condition})`):"",d=e.decisionValue!==void 0?M(` = ${String(e.decisionValue)}`):"",u=e.branchTaken!==void 0?M(` \u2192 ${String(e.branchTaken)}`):"";s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${a} ${$e(l)}${c}${d}${u}`);for(let p=0;p<e.branches.length;p++){let h=e.branches[p],m=p===e.branches.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,S=h.taken?"\u2713":"\u2298",$=h.taken?r.success:r.skipped,O=ie(`${S} ${h.label}`,$),D=h.condition?M(` (${h.condition})`):"";if(s.push(`${m} ${O}${D}`),h.children.length>0){let v=He(h.children,t,r,o+1,n);for(let w of v)s.push(`${i}${_.vertical} ${w}`)}else h.taken||s.push(`${i}${_.vertical} ${M("(skipped)")}`)}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${H(e.durationMs)}]`)}`),s}function ft(e){let t=[];for(let r of e)if(t.push(r),"children"in r&&Array.isArray(r.children)&&t.push(...ft(r.children)),"branches"in r)for(let o of r.branches)t.push(...ft(o.children));return t}function Ue(e,t){if(e.length===0)return 0;let r=Math.floor(e.length*t);return e[Math.min(r,e.length-1)]}function pt(e){return e<.2?"cold":e<.4?"cool":e<.6?"neutral":e<.8?"warm":e<.95?"hot":"critical"}function ht(){let e=new Map,t=new Map,r=new Map,o=new Map,n=[];function s(v){return v.name??v.stepKey??v.stepId??"unknown"}function i(v){let w=new Map;for(let b of v)switch(b.type){case"step_start":{let k=s(b);w.set(k,{retried:!1,timedOut:!1});break}case"step_retry":{let k=s(b),B=w.get(k);B&&(B.retried=!0);break}case"step_timeout":{let k=s(b),B=w.get(k);B&&(B.timedOut=!0);let C=o.get(k)??{timedOut:0,total:0};C.timedOut++,C.total++,o.set(k,C);break}case"step_success":{let k=s(b),B=w.get(k),C=e.get(k)??[];C.push(b.durationMs),e.set(k,C);let I=t.get(k)??{retried:0,total:0};I.total++,B?.retried&&I.retried++,t.set(k,I);let L=r.get(k)??{errors:0,total:0};L.total++,r.set(k,L),w.delete(k);break}case"step_error":{let k=s(b),B=w.get(k),C=e.get(k)??[];C.push(b.durationMs),e.set(k,C);let I=t.get(k)??{retried:0,total:0};I.total++,B?.retried&&I.retried++,t.set(k,I);let L=r.get(k)??{errors:0,total:0};L.total++,L.errors++,r.set(k,L),w.delete(k);break}}}function a(v){i(v.events)}function l(v){n.push(v)}function c(v){n.length>0&&(i(n),n=[])}function d(v){let w=e.get(v);if(!w||w.length===0)return;let b=[...w].sort((E,R)=>E-R),B=b.reduce((E,R)=>E+R,0)/b.length,C=b.reduce((E,R)=>E+(R-B)**2,0)/b.length,I=t.get(v)??{retried:0,total:1},L=r.get(v)??{errors:0,total:1},N=o.get(v)??{timedOut:0,total:1};return{nodeId:v,avgDurationMs:B,minDurationMs:b[0],maxDurationMs:b[b.length-1],stdDevMs:Math.sqrt(C),samples:b.length,retryRate:I.total>0?I.retried/I.total:0,timeoutRate:N.total>0?N.timedOut/N.total:0,errorRate:L.total>0?L.errors/L.total:0,percentiles:{p50:Ue(b,.5),p90:Ue(b,.9),p95:Ue(b,.95),p99:Ue(b,.99)}}}function u(v){return d(v)}function p(v,w="duration"){let b=new Map,k=ft(v.root.children),B=[];for(let R of k){let T=R.name??R.id,W=d(T);if(W){let f;switch(w){case"duration":f=W.avgDurationMs;break;case"retryRate":f=W.retryRate;break;case"errorRate":f=W.errorRate;break}B.push({id:R.id,value:f})}}if(B.length===0)return{heat:b,metric:w,stats:{min:0,max:0,mean:0,threshold:0}};let C=B.map(R=>R.value),I=Math.min(...C),L=Math.max(...C),N=C.reduce((R,T)=>R+T,0)/C.length,E=L-I||1;for(let{id:R,value:T}of B)b.set(R,(T-I)/E);return{heat:b,metric:w,stats:{min:I,max:L,mean:N,threshold:N+(L-N)*.5}}}function h(){let v=new Map;for(let w of e.keys()){let b=d(w);b&&v.set(w,b)}return v}function g(v=10){return[...h().values()].sort((b,k)=>k.avgDurationMs-b.avgDurationMs).slice(0,v)}function m(v=10){return[...h().values()].filter(b=>b.errorRate>0).sort((b,k)=>k.errorRate-b.errorRate).slice(0,v)}function S(v=10){return[...h().values()].filter(b=>b.retryRate>0).sort((b,k)=>k.retryRate-b.retryRate).slice(0,v)}function $(){return JSON.stringify({timingData:Object.fromEntries(e),retryData:Object.fromEntries(t),errorData:Object.fromEntries(r),timeoutData:Object.fromEntries(o)})}function O(v){let w=JSON.parse(v);e.clear(),t.clear(),r.clear(),o.clear();for(let[b,k]of Object.entries(w.timingData??{}))e.set(b,k);for(let[b,k]of Object.entries(w.retryData??{}))t.set(b,k);for(let[b,k]of Object.entries(w.errorData??{}))r.set(b,k);for(let[b,k]of Object.entries(w.timeoutData??{}))o.set(b,k)}function D(){e.clear(),t.clear(),r.clear(),o.clear(),n=[]}return{addRun:a,addEvent:l,finalizeRun:c,getNodePerformance:u,getHeatmap:p,getSlowestNodes:g,getErrorProneNodes:m,getRetryProneNodes:S,getAllPerformance:h,exportData:$,importData:O,clear:D}}function zn(){return[" classDef pending fill:#f3f4f6,stroke:#9ca3af,stroke-width:2px,color:#374151"," classDef running fill:#fef3c7,stroke:#f59e0b,stroke-width:3px,color:#92400e"," classDef success fill:#d1fae5,stroke:#10b981,stroke-width:3px,color:#065f46"," classDef error fill:#fee2e2,stroke:#ef4444,stroke-width:3px,color:#991b1b"," classDef aborted fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#4b5563,stroke-dasharray: 5 5"," classDef cached fill:#dbeafe,stroke:#3b82f6,stroke-width:3px,color:#1e40af"," classDef skipped fill:#f9fafb,stroke:#d1d5db,stroke-width:2px,color:#6b7280,stroke-dasharray: 5 5"]}function Vn(){return[" classDef heat_cold fill:#dbeafe,stroke:#3b82f6,stroke-width:2px,color:#1e40af"," classDef heat_cool fill:#ccfbf1,stroke:#14b8a6,stroke-width:2px,color:#0f766e"," classDef heat_neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#374151"," classDef heat_warm fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#92400e"," classDef heat_hot fill:#fed7aa,stroke:#f97316,stroke-width:3px,color:#c2410c"," classDef heat_critical fill:#fecaca,stroke:#ef4444,stroke-width:3px,color:#b91c1c"]}function jn(e){return`heat_${e}`}function qn(){return[" classDef hook_success fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e"," classDef hook_error fill:#fef2f2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d"]}function Gn(e,t,r){let o;if(e.shouldRun){let n="hook_shouldRun",s=e.shouldRun.state==="success"?"hook_success":"hook_error",i=e.shouldRun.state==="success"?"\u2699":"\u26A0",a=r.showTimings&&e.shouldRun.durationMs!==void 0?` ${H(e.shouldRun.durationMs)}`:"",l=e.shouldRun.context?.skipped?"\\nskipped workflow":e.shouldRun.context?.result===!0?"\\nproceed":"";t.push(` ${n}[["${i} shouldRun${l}${a}"]]:::${s}`),o=n}if(e.onBeforeStart){let n="hook_beforeStart",s=e.onBeforeStart.state==="success"?"hook_success":"hook_error",i=e.onBeforeStart.state==="success"?"\u2699":"\u26A0",a=r.showTimings&&e.onBeforeStart.durationMs!==void 0?` ${H(e.onBeforeStart.durationMs)}`:"",l=e.onBeforeStart.context?.skipped?"\\nskipped workflow":"";t.push(` ${n}[["${i} onBeforeStart${l}${a}"]]:::${s}`),o&&t.push(` ${o} --> ${n}`),o=n}return{lastHookId:o}}var Zt=0;function De(e="node"){return`${e}_${++Zt}`}function Kn(){Zt=0}function j(e){return e.replace(/[{}[\]()]/g,"").replace(/[<>]/g,"").replace(/"/g,"'").trim()}function Qt(e){return j(e).replace(/[[\]]/g,"")}function ze(){return{name:"mermaid",supportsLive:!1,render(e,t){Kn();let r=[],o=t;r.push("flowchart TD");let n;e.hooks&&(n=Gn(e.hooks,r,t).lastHookId);let s="start";r.push(` ${s}(("\u25B6 Start"))`),n&&r.push(` ${n} --> ${s}`);let i=s;for(let a of e.root.children){let l=Ve(a,t,r,o,e.hooks);r.push(` ${i} --> ${l.entryId}`),i=l.exitId}if(e.root.state==="success"||e.root.state==="error"){let a="finish",l=e.root.state==="success"?"\u2713":"\u2717",c=e.root.state==="success"?"Done":"Failed",d=`(("${l} ${c}"))`,u=e.root.state==="success"?":::success":":::error";r.push(` ${a}${d}${u}`),r.push(` ${i} --> ${a}`)}return r.push(""),r.push(...zn()),o.showHeatmap&&r.push(...Vn()),e.hooks&&r.push(...qn()),r.join(`
|
|
9
|
+
`)}}}function Ve(e,t,r,o,n){if(J(e))return Yn(e,t,r,o,n);if(Q(e))return Jn(e,t,r,o,n);if(oe(e))return Xn(e,t,r,o,n);if(se(e))return Zn(e,t,r,o,n);let s=De("unknown");return r.push(` ${s}[Unknown Node]`),{entryId:s,exitId:s}}function Yn(e,t,r,o,n){let s=t,i=s.showRetryEdges??!0,a=s.showErrorEdges??!0,l=s.showTimeoutEdges??!0,c=e.key?`step_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:De("step"),d=j(e.name??e.key??"Step"),u=t.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"",p="";switch(e.state){case"success":p="\u2713 ";break;case"error":p="\u2717 ";break;case"cached":p="\u{1F4BE} ";break;case"running":p="\u23F3 ";break;case"skipped":p="\u2298 ";break}let h="";if(e.input!==void 0){let v=typeof e.input=="string"?j(e.input):j(JSON.stringify(e.input).slice(0,20));h+=`\\nin: ${v}`}if(e.output!==void 0&&e.state==="success"){let v=typeof e.output=="string"?j(e.output):j(JSON.stringify(e.output).slice(0,20));h+=`\\nout: ${v}`}let g="";if(n&&e.key&&n.onAfterStep.has(e.key)){let v=n.onAfterStep.get(e.key),w=v.state==="success"?"\u2699":"\u26A0",b=t.showTimings&&v.durationMs!==void 0?` ${H(v.durationMs)}`:"";g=`\\n${w} hook${b}`}let m=(p+d+h+g+u).trim(),S,$=e.name??e.id,O=o?.showHeatmap&&o.heatmapData?o.heatmapData.heat.get(e.id)??o.heatmapData.heat.get($):void 0;if(O!==void 0){let v=pt(O);S=jn(v)}else S=e.state;let D;switch(e.state){case"error":D=`{{${m}}}`;break;case"cached":D=`[(${m})]`;break;case"skipped":D=`[${m}]:::skipped`;break;default:D=`[${m}]`}if(r.push(` ${c}${D}:::${S}`),i&&e.retryCount!==void 0&&e.retryCount>0){let v=`\u21BB ${e.retryCount} retr${e.retryCount===1?"y":"ies"}`;r.push(` ${c} -.->|"${v}"| ${c}`)}if(a&&e.state==="error"&&e.error!==void 0){let v=`ERR_${c}`,w=j(String(e.error)).slice(0,30);r.push(` ${v}{{${w}}}`),r.push(` ${c} -->|error| ${v}`),r.push(` style ${v} fill:#fee2e2,stroke:#dc2626`)}if(l&&e.timedOut){let v=`TO_${c}`,w=e.timeoutMs!==void 0?`${e.timeoutMs}ms`:"";r.push(` ${v}{{\u23F1 Timeout ${w}}}`),r.push(` ${c} -.->|timeout| ${v}`),r.push(` style ${v} fill:#fef3c7,stroke:#f59e0b`)}return{entryId:c,exitId:c}}function Jn(e,t,r,o,n){let s=De("parallel"),i=`${s}_fork`,a=`${s}_join`,l=Qt(e.name??"Parallel"),c=e.mode==="allSettled"?" (allSettled)":"";if(e.children.length===0){let p=s,h=j(`${l}${c}`),g="operations not individually tracked",m=t.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"";return r.push(` ${p}[${h}${m}\\n${g}]:::${e.state}`),{entryId:p,exitId:p}}r.push(` subgraph ${s}["${l}${c}"]`),r.push(" direction TB"),r.push(` ${i}{"\u26A1 Fork"}`);let d=[];for(let p of e.children){let h=Ve(p,t,r,o,n);r.push(` ${i} --> ${h.entryId}`),d.push(h.exitId)}r.push(` ${a}{"\u2713 Join"}`);for(let p of d)r.push(` ${p} --> ${a}`);r.push(" end");let u=e.state;return r.push(` class ${s} ${u}`),{entryId:i,exitId:a}}function Xn(e,t,r,o,n){let s=De("race"),i=`${s}_start`,a=`${s}_end`,l=Qt(e.name??"Race");if(e.children.length===0){let p=s,h=j(l),g="operations not individually tracked",m=t.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"";return r.push(` ${p}[\u26A1 ${h}${m}\\n${g}]:::${e.state}`),{entryId:p,exitId:p}}r.push(` subgraph ${s}["\u26A1 ${l}"]`),r.push(" direction TB"),r.push(` ${i}(("\u{1F3C1} Start"))`);let c=[],d;for(let p of e.children){let h=Ve(p,t,r,o,n),g=J(p)&&e.winnerId===p.id;r.push(` ${i} --> ${h.entryId}`),g&&(d=h.exitId),c.push({exitId:h.exitId,isWinner:g})}r.push(` ${a}(("\u2713 First"))`);for(let{exitId:p,isWinner:h}of c)h&&d?r.push(` ${p} ==>|\u{1F3C6} Winner| ${a}`):e.winnerId?r.push(` ${p} -. cancelled .-> ${a}`):r.push(` ${p} --> ${a}`);r.push(" end");let u=e.state;return r.push(` class ${s} ${u}`),{entryId:i,exitId:a}}function Zn(e,t,r,o,n){let s=e.key?`decision_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:De("decision"),i=j(e.condition??"condition"),a=e.decisionValue!==void 0?` = ${j(String(e.decisionValue)).slice(0,30)}`:"",l=`${i}${a}`.trim();r.push(` ${s}{${l}}`);let c=[],d;for(let u of e.branches){let p=`${s}_${u.label.replace(/[^a-zA-Z0-9]/g,"_")}`,h=j(u.label),g=u.taken?`${h} \u2713`:`${h} skipped`,m=u.taken?":::success":":::skipped";r.push(` ${p}[${g}]${m}`);let S=u.condition?`|${j(u.condition).replace(/\|/g,"")}|`:"";if(r.push(` ${s} -->${S} ${p}`),u.children.length>0){let $=p;for(let O of u.children){let D=Ve(O,t,r,o,n);r.push(` ${$} --> ${D.entryId}`),$=D.exitId}c.push($),u.taken&&(d=$)}else c.push(p),u.taken&&(d=p)}return d?{entryId:s,exitId:d}:{entryId:s,exitId:s}}function Qn(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function eo(e){let t=[];function r(o){for(let n of o)if(J(n))t.push(n);else if(jt(n))r(n.children);else if(Q(n)||oe(n))r(n.children);else if(se(n))for(let s of n.branches)r(s.children)}return r(e),t}function to(e){let t={id:e.id,name:e.name??e.key??e.id,state:e.state};return e.key&&(t.key=e.key),e.durationMs!==void 0&&(t.durationMs=e.durationMs),e.startTs!==void 0&&(t.startTs=e.startTs),e.endTs!==void 0&&(t.endTs=e.endTs),e.retryCount!==void 0&&e.retryCount>0&&(t.retryCount=e.retryCount),e.timedOut&&(t.timedOut=!0,e.timeoutMs!==void 0&&(t.timeoutMs=e.timeoutMs)),e.error!==void 0&&(t.error=typeof e.error=="string"?e.error:String(e.error)),t}function ro(e){let t=0,r=0,o=0,n=0,s=0,i;for(let a of e)a.state==="success"&&t++,a.state==="error"&&r++,a.state==="cached"&&o++,a.state==="skipped"&&n++,a.retryCount!==void 0&&(s+=a.retryCount),a.durationMs!==void 0&&(!i||a.durationMs>i.durationMs)&&(i={name:a.name??a.key??a.id,durationMs:a.durationMs});return{totalSteps:e.length,successCount:t,errorCount:r,cacheHits:o,skippedCount:n,totalRetries:s,slowestStep:i}}function no(e){let t={};if(e.shouldRun&&(t.shouldRun={result:e.shouldRun.context?.result,durationMs:e.shouldRun.durationMs},e.shouldRun.error&&(t.shouldRun.error=String(e.shouldRun.error))),e.onBeforeStart&&(t.onBeforeStart={durationMs:e.onBeforeStart.durationMs},e.onBeforeStart.error&&(t.onBeforeStart.error=String(e.onBeforeStart.error))),e.onAfterStep.size>0){t.onAfterStep=[];for(let[r,o]of e.onAfterStep){let n={stepKey:r};o.durationMs!==void 0&&(n.durationMs=o.durationMs),o.error&&(n.error=String(o.error)),t.onAfterStep.push(n)}}return t}function oo(e,t){let r=e.root,o=eo(r.children),n=t.includeDiagram??!0,s=t.stripAnsiColors??!0,i={workflow:{id:r.workflowId,name:r.name,state:r.state,durationMs:r.durationMs,startedAt:r.startTs,completedAt:r.endTs},steps:o.map(to),summary:ro(o)};if(e.hooks){let a=no(e.hooks);Object.keys(a).length>0&&(i.hooks=a)}if(n){let l=ce().render(e,t);s&&(l=Qn(l)),i.diagram=l}return i}function je(){return{name:"logger",supportsLive:!1,render(e,t){let o=oo(e,t);return JSON.stringify(o)}}}function er(e){let t={bg:"#ffffff",bgSecondary:"#f8f9fa",text:"#212529",textMuted:"#6c757d",border:"#dee2e6",primary:"#0d6efd",success:"#198754",error:"#dc3545",warning:"#ffc107",info:"#0dcaf0",muted:"#6c757d",nodePending:"#e9ecef",nodeRunning:"#fff3cd",nodeSuccess:"#d1e7dd",nodeError:"#f8d7da",nodeAborted:"#e9ecef",nodeCached:"#cfe2ff",nodeSkipped:"#f8f9fa",heatCold:"#0d6efd",heatCool:"#0dcaf0",heatNeutral:"#6c757d",heatWarm:"#ffc107",heatHot:"#fd7e14",heatCritical:"#dc3545"},r={bg:"#212529",bgSecondary:"#343a40",text:"#f8f9fa",textMuted:"#adb5bd",border:"#495057",primary:"#0d6efd",success:"#198754",error:"#dc3545",warning:"#ffc107",info:"#0dcaf0",muted:"#6c757d",nodePending:"#495057",nodeRunning:"#664d03",nodeSuccess:"#0f5132",nodeError:"#842029",nodeAborted:"#495057",nodeCached:"#084298",nodeSkipped:"#343a40",heatCold:"#0d6efd",heatCool:"#0dcaf0",heatNeutral:"#6c757d",heatWarm:"#ffc107",heatHot:"#fd7e14",heatCritical:"#dc3545"},o=s=>`
|
|
10
10
|
--bg: ${s.bg};
|
|
11
11
|
--bg-secondary: ${s.bgSecondary};
|
|
12
12
|
--text: ${s.text};
|
|
@@ -505,7 +505,7 @@ body {
|
|
|
505
505
|
height: auto;
|
|
506
506
|
}
|
|
507
507
|
}
|
|
508
|
-
`}function
|
|
508
|
+
`}function tr(e){return`
|
|
509
509
|
(function() {
|
|
510
510
|
'use strict';
|
|
511
511
|
|
|
@@ -1087,38 +1087,38 @@ body {
|
|
|
1087
1087
|
return (ms / 60000).toFixed(1) + 'm';
|
|
1088
1088
|
}
|
|
1089
1089
|
})();
|
|
1090
|
-
`}var be=160,
|
|
1091
|
-
<g class="wv-node wv-node--${e.state}" data-node-id="${
|
|
1090
|
+
`}var be=160,qe=50,mt=40,so=30,z=20;function io(e,t="TB"){let r=t==="TB"||t==="BT",o=[],n=z,s=z,i=0,a=0;for(let l of e){let c=gt(l,n,s,r);o.push(c.node),r?(s+=c.height+so,i=Math.max(i,c.width),a=s):(n+=c.width+mt,a=Math.max(a,c.height),i=n)}return{nodes:o,width:i+z,height:a+z}}function gt(e,t,r,o){if(J(e))return{node:{id:e.id,name:e.name??e.key??"step",type:"step",state:e.state,x:t,y:r,width:be,height:qe,durationMs:e.durationMs},width:be,height:qe};if(Q(e)||oe(e)){let n=Q(e)?"parallel":"race",s=e.name??n,i=[],a=t+z,l=r+z+20,c=0,d=0;for(let h of e.children){let g=gt(h,a,l,!0);i.push(g.node),a+=g.width+mt,d=Math.max(d,g.height)}c=a-t-z;let u=Math.max(c+z,be+z*2),p=d+z*2+20;return{node:{id:e.id,name:s,type:n,state:e.state,x:t,y:r,width:u,height:p,durationMs:e.durationMs,children:i,containerType:n,containerLabel:n==="parallel"?"PARALLEL":"RACE"},width:u,height:p}}if(se(e)){let n=e.name??"decision",s=[],i=t+z,a=r+z+20,l=0;for(let u of e.branches)for(let p of u.children){let h=gt(p,i,a,!0);s.push(h.node),i+=h.width+mt,l=Math.max(l,h.height)}let c=Math.max(i-t,be+z*2),d=l+z*2+20;return{node:{id:e.id,name:n,type:"decision",state:e.state,x:t,y:r,width:c,height:d,durationMs:e.durationMs,children:s,containerType:"decision",containerLabel:"DECISION"},width:c,height:d}}return{node:{id:e.id,name:e.name??"unknown",type:e.type,state:e.state,x:t,y:r,width:be,height:qe},width:be,height:qe}}function rr(e,t){return e.containerType?co(e,t):ao(e,t)}function ao(e,t){let o=t&&e.durationMs!==void 0?H(e.durationMs):"";return`
|
|
1091
|
+
<g class="wv-node wv-node--${e.state}" data-node-id="${or(e.id)}" transform="translate(${e.x}, ${e.y})">
|
|
1092
1092
|
<rect width="${e.width}" height="${e.height}" rx="8" ry="8" />
|
|
1093
|
-
<text x="${e.width/2}" y="${e.height/2-(o?4:0)}">${
|
|
1093
|
+
<text x="${e.width/2}" y="${e.height/2-(o?4:0)}">${yt(po(e.name,20))}</text>
|
|
1094
1094
|
${o?`<text class="wv-node-timing" x="${e.width/2}" y="${e.height/2+12}">${o}</text>`:""}
|
|
1095
1095
|
</g>
|
|
1096
|
-
`}function
|
|
1096
|
+
`}function co(e,t){let o=e.children?.map(n=>rr(n,t)).join(`
|
|
1097
1097
|
`)??"";return`
|
|
1098
|
-
<g class="wv-container wv-container--${e.containerType}" data-node-id="${
|
|
1098
|
+
<g class="wv-container wv-container--${e.containerType}" data-node-id="${or(e.id)}" transform="translate(${e.x}, ${e.y})">
|
|
1099
1099
|
<rect width="${e.width}" height="${e.height}" rx="12" ry="12" />
|
|
1100
1100
|
<text class="wv-container-label" x="${z}" y="16">${e.containerLabel}</text>
|
|
1101
1101
|
<g transform="translate(${-e.x}, ${-e.y})">
|
|
1102
1102
|
${o}
|
|
1103
1103
|
</g>
|
|
1104
1104
|
</g>
|
|
1105
|
-
`}function
|
|
1106
|
-
<path class="wv-edge" d="M ${s} ${i} L ${
|
|
1107
|
-
<polygon class="wv-edge-arrow" points="${
|
|
1105
|
+
`}function lo(e){let t=[];for(let r=0;r<e.length-1;r++){let o=e[r],n=e[r+1],s=o.x+o.width/2,i=o.y+o.height,a=n.x+n.width/2,l=n.y;t.push(`
|
|
1106
|
+
<path class="wv-edge" d="M ${s} ${i} L ${a} ${l-8}" />
|
|
1107
|
+
<polygon class="wv-edge-arrow" points="${a-4},${l-8} ${a+4},${l-8} ${a},${l}" />
|
|
1108
1108
|
`)}return t.join(`
|
|
1109
|
-
`)}function
|
|
1110
|
-
`),i=
|
|
1109
|
+
`)}function nr(e,t){let r=io(e.root.children,t.layout),o=Math.max(r.width,400),n=Math.max(r.height,300),s=r.nodes.map(d=>rr(d,t.showTimings)).join(`
|
|
1110
|
+
`),i=lo(r.nodes),a=e.root.name??"Workflow",l=er(t.theme),c=tr({wsUrl:t.wsUrl,interactive:t.interactive,timeTravel:t.timeTravel,heatmap:t.heatmap});return`<!DOCTYPE html>
|
|
1111
1111
|
<html lang="en">
|
|
1112
1112
|
<head>
|
|
1113
1113
|
<meta charset="UTF-8">
|
|
1114
1114
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1115
|
-
<title>${
|
|
1116
|
-
<style>${
|
|
1115
|
+
<title>${yt(a)} - Workflow Visualizer</title>
|
|
1116
|
+
<style>${l}</style>
|
|
1117
1117
|
</head>
|
|
1118
1118
|
<body>
|
|
1119
1119
|
<div class="workflow-visualizer">
|
|
1120
1120
|
<header class="wv-header">
|
|
1121
|
-
<h1>${
|
|
1121
|
+
<h1>${yt(a)}</h1>
|
|
1122
1122
|
<div class="wv-controls">
|
|
1123
1123
|
${t.wsUrl?'<div id="live-indicator" class="wv-live" style="display:none"><span class="wv-live-dot"></span>LIVE</div>':""}
|
|
1124
1124
|
${t.heatmap?`
|
|
@@ -1183,13 +1183,13 @@ body {
|
|
|
1183
1183
|
</div>
|
|
1184
1184
|
|
|
1185
1185
|
<script>
|
|
1186
|
-
window.__WORKFLOW_DATA__ = ${
|
|
1186
|
+
window.__WORKFLOW_DATA__ = ${fo(e)};
|
|
1187
1187
|
</script>
|
|
1188
|
-
<script>${
|
|
1188
|
+
<script>${c}</script>
|
|
1189
1189
|
</body>
|
|
1190
|
-
</html>`}function
|
|
1191
|
-
`),p=E,
|
|
1192
|
-
`).length)}function O(){u&&(
|
|
1193
|
-
`),
|
|
1194
|
-
Install with: npm install ws`),null}}function D(E){let
|
|
1190
|
+
</html>`}function uo(e){let t={};function r(o){for(let n of o)if(t[n.id]={id:n.id,name:n.name,type:n.type,state:n.state,key:n.key,durationMs:n.durationMs,startTs:n.startTs,error:n.error?String(n.error):void 0,retryCount:n.retryCount},"children"in n&&Array.isArray(n.children)&&r(n.children),"branches"in n)for(let s of n.branches)r(s.children)}return r(e.root.children),{nodes:t}}function fo(e){return JSON.stringify(uo(e)).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function yt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function or(e){return e.replace(/"/g,""").replace(/'/g,"'")}function po(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}var sr={interactive:!0,timeTravel:!0,heatmap:!0,animationDuration:200,theme:"auto",layout:"TB"};function ho(){return{name:"html",supportsLive:!0,render(e,t){let r={...t,...sr,...t};return nr(e,r)}}}function vt(e,t={}){let r={showTimings:!0,showKeys:!1,colors:{pending:"#6c757d",running:"#ffc107",success:"#198754",error:"#dc3545",aborted:"#6c757d",cached:"#0dcaf0",skipped:"#adb5bd"},...sr,...t};return nr(e,r)}var le={clearToEnd:"\x1B[J",cursorUp:e=>`\x1B[${e}A`,cursorToStart:"\x1B[G",hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",saveCursor:"\x1B[s",restoreCursor:"\x1B[u"};function mo(e={}){let{workflowName:t,detectParallel:r=!0,showTimings:o=!0,showKeys:n=!1,colors:s,stream:i=process.stdout,updateInterval:a=100}=e,l=pe({detectParallel:r}),c=ce(),d={showTimings:o,showKeys:n,terminalWidth:i.columns??80,colors:{...ae,...s}},u=!1,p="",h=0,g=null,m=!1;function S(N){i.writable&&i.write(N)}function $(){if(!u)return;let N=b(),E=c.render(N,d);E!==p&&(h>0&&(S(le.cursorUp(h)),S(le.cursorToStart),S(le.clearToEnd)),S(E),S(`
|
|
1191
|
+
`),p=E,h=E.split(`
|
|
1192
|
+
`).length)}function O(){u&&(m=!0,g===null&&(g=setTimeout(()=>{g=null,m&&(m=!1,$())},a)))}function D(N){if(N.type==="scope_start"||N.type==="scope_end"){v(N);return}l.handleEvent(N),u&&(N.type==="workflow_start"||N.type==="workflow_success"||N.type==="workflow_error"?$():O())}function v(N){l.handleScopeEvent(N),u&&O()}function w(N){l.handleDecisionEvent(N),u&&O()}function b(){let N=l.getIR();return t&&!N.root.name&&(N.root.name=t),N}function k(){return c.render(b(),d)}function B(){u||(u=!0,p="",h=0,S(le.hideCursor),$())}function C(){if(!u)return;u=!1,g!==null&&(clearTimeout(g),g=null);let N=b(),E=c.render(N,d);h>0&&(S(le.cursorUp(h)),S(le.cursorToStart),S(le.clearToEnd)),S(E),S(`
|
|
1193
|
+
`),S(le.showCursor)}function I(){g!==null&&(clearTimeout(g),g=null),m=!1,$()}function L(){l.reset(),p="",h=0}return{handleEvent:D,handleScopeEvent:v,handleDecisionEvent:w,getIR:b,render:k,start:B,stop:C,refresh:I,reset:L}}function wt(e,t={}){let{condition:r,value:o,name:n,workflowId:s=crypto.randomUUID(),emit:i}=t,a=Date.now(),l,c=[];function d(p,h,g){c.push({label:p,condition:g,taken:h}),h&&(l=p),i?.({type:"decision_branch",workflowId:s,decisionId:e,branchLabel:p,condition:g,taken:h,ts:Date.now()})}function u(){let p=Date.now()-a;i?.({type:"decision_end",workflowId:s,decisionId:e,branchTaken:l,ts:Date.now(),durationMs:p})}return i?.({type:"decision_start",workflowId:s,decisionId:e,condition:r,decisionValue:o,name:n,ts:a}),{takeBranch:d,end:u,getBranchTaken:()=>l,getBranches:()=>[...c]}}function go(e,t,r={}){let o=wt(e,{...r,condition:r.condition??String(t),value:r.value??t});return{...o,condition:t,then:()=>{o.takeBranch("if",!0)},else:()=>{o.takeBranch("else",!0)}}}function yo(e,t,r={}){let o=wt(e,{...r,condition:r.condition??`switch(${String(t)})`,value:t});return{...o,value:t,case:(n,s)=>{o.takeBranch(`case '${n}'`,s,`value === '${n}'`)},default:n=>{o.takeBranch("default",n)}}}function bt(e={}){let{maxSnapshots:t=1e3,autoRecord:r=!0,builderOptions:o={}}=e,n=pe({...o,enableSnapshots:!0,maxSnapshots:t}),s={snapshots:[],currentIndex:-1,isPlaying:!1,playbackSpeed:1,isRecording:r},i=new Set,a=null;function l(){let I=v();for(let L of i)L(I)}function c(){s.snapshots=n.getSnapshots(),s.isRecording&&s.snapshots.length>0&&(s.currentIndex=s.snapshots.length-1)}function d(I){n.handleEvent(I),s.isRecording&&(c(),l())}function u(I){let L=n.getSnapshots();if(!(I<0||I>=L.length))return s.currentIndex=I,s.snapshots=L,l(),L[I].ir}function p(){return u(s.currentIndex+1)}function h(){return u(s.currentIndex-1)}function g(I=1){s.playbackSpeed=I,s.isPlaying=!0,l();let L=()=>{if(!s.isPlaying)return;let N=n.getSnapshots();if(s.currentIndex<N.length-1){let E=N[s.currentIndex],W=(N[s.currentIndex+1].timestamp-E.timestamp)/s.playbackSpeed;a=setTimeout(()=>{p(),L()},Math.max(16,W))}else m()};L()}function m(){s.isPlaying=!1,a&&(clearTimeout(a),a=null),l()}function S(){let I=n.getSnapshots();return s.currentIndex>=0&&s.currentIndex<I.length?I[s.currentIndex].ir:n.getIR()}function $(I){return n.getIRAt(I)}function O(){return n.getSnapshots()}function D(I){return n.getSnapshotAt(I)}function v(){return{snapshots:n.getSnapshots(),currentIndex:s.currentIndex,isPlaying:s.isPlaying,playbackSpeed:s.playbackSpeed,isRecording:s.isRecording}}function w(I){return i.add(I),()=>i.delete(I)}function b(){s.isRecording=!0,l()}function k(){s.isRecording=!1,l()}function B(){m(),n.reset(),s={snapshots:[],currentIndex:-1,isPlaying:!1,playbackSpeed:1,isRecording:r},l()}function C(){return n}return{handleEvent:d,seek:u,stepForward:p,stepBackward:h,play:g,pause:m,getCurrentIR:S,getIRAt:$,getSnapshots:O,getSnapshotAt:D,getState:v,onStateChange:w,startRecording:b,stopRecording:k,reset:B,getBuilder:C}}import{createServer as Ps}from"http";import{execFile as zt}from"child_process";async function As(e={}){let{port:t=3377,host:r="localhost",autoOpen:o=!0,workflowName:n="Workflow",timeTravel:s=!0,heatmap:i=!0,maxSnapshots:a=1e3}=e,l=bt({maxSnapshots:a}),c=ht(),d=null,u=null,p=t,h=!1;function g(E){if(!u)return;let R=JSON.stringify(E);for(let T of u.clients)T.readyState===T.OPEN&&T.send(R)}function m(E,R){try{let T=JSON.parse(typeof R=="string"?R:R.toString());switch(T.type){case"time_travel_seek":{let W=T.payload,f=l.seek(W.index);f&&E.send(JSON.stringify({type:"ir_update",payload:f}));break}case"time_travel_play":{let W=T.payload;l.play(W?.speed);break}case"time_travel_pause":l.pause();break;case"time_travel_step_forward":{let W=l.stepForward();W&&E.send(JSON.stringify({type:"ir_update",payload:W}));break}case"time_travel_step_backward":{let W=l.stepBackward();W&&E.send(JSON.stringify({type:"ir_update",payload:W}));break}case"request_snapshots":{let W=l.getSnapshots().map(f=>({id:f.id,eventIndex:f.eventIndex,timestamp:f.timestamp}));E.send(JSON.stringify({type:"snapshots_list",payload:W}));break}case"toggle_heatmap":case"set_heatmap_metric":break}}catch(T){console.error("[DevServer] Failed to handle message:",T)}}function S(){let E=l.getCurrentIR(),R=`ws://${r}:${p}`;return vt(E,{interactive:!0,timeTravel:s,heatmap:i,theme:"auto",layout:"TB",wsUrl:R})}function $(E,R){let T=E.url??"/";if(T==="/"||T==="/index.html"){R.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),R.end(S());return}if(T==="/api/snapshots"){let W=l.getSnapshots().map(f=>({id:f.id,eventIndex:f.eventIndex,timestamp:f.timestamp}));R.writeHead(200,{"Content-Type":"application/json"}),R.end(JSON.stringify(W));return}if(T==="/api/performance"){R.writeHead(200,{"Content-Type":"application/json"}),R.end(c.exportData());return}if(T==="/api/ir"){R.writeHead(200,{"Content-Type":"application/json"}),R.end(JSON.stringify(l.getCurrentIR()));return}R.writeHead(404,{"Content-Type":"text/plain"}),R.end("Not Found")}async function O(){try{let R=await Promise.resolve().then(()=>(gn(),mn)),T=R.WebSocketServer??R.default?.WebSocketServer;return T?new T({noServer:!0}):(console.warn("[DevServer] WebSocket server class not found in ws module"),null)}catch{return console.warn(`[DevServer] ws package not installed. Live updates disabled.
|
|
1194
|
+
Install with: npm install ws`),null}}function D(E){let R=process.platform;if(!E.startsWith("http://localhost:")&&!E.startsWith("http://127.0.0.1:")){console.warn("[DevServer] Refusing to open non-localhost URL");return}R==="darwin"?zt("open",[E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)}):R==="win32"?zt("cmd.exe",["/c","start","",E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)}):zt("xdg-open",[E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)})}async function v(){return h?{port:p,url:`http://${r}:${p}`}:(d=Ps($),u=await O(),u&&(d.on("upgrade",(E,R,T)=>{if(!u)return;u.handleUpgrade(E,R,T,f=>{f.send(JSON.stringify({type:"ir_update",payload:l.getCurrentIR()})),f.on("message",y=>m(f,y)),f.on("error",y=>console.error("[DevServer] WS error:",y))})}),l.onStateChange(E=>{g({type:"time_travel_state",payload:E})})),new Promise((E,R)=>{if(!d){R(new Error("HTTP server not initialized"));return}d.on("error",T=>{T.code==="EADDRINUSE"?(p++,d?.listen(p,r)):R(T)}),d.on("listening",()=>{h=!0;let T=`http://${r}:${p}`;console.log(`[DevServer] Visualizer running at ${T}`),o&&D(T),E({port:p,url:T})}),d.listen(p,r)}))}async function w(){if(h)return new Promise(E=>{u&&(u.close(),u=null),d?d.close(()=>{d=null,h=!1,E()}):E()})}function b(E){l.handleEvent(E),c.addEvent(E),g({type:"ir_update",payload:l.getCurrentIR()})}function k(E){g({type:"ir_update",payload:E})}function B(E){let R={};for(let[T,W]of E.heat)R[T]=W;g({type:"performance_data",payload:{...E,heat:R}})}function C(){c.finalizeRun("current"),g({type:"workflow_complete",payload:null})}function I(){return l}function L(){return c}function N(){return l.getCurrentIR()}return{start:v,stop:w,handleEvent:b,pushUpdate:k,pushHeatmap:B,complete:C,getTimeTravel:I,getAnalyzer:L,getCurrentIR:N}}function Vt(e={}){let{workflowName:t,detectParallel:r=!0,showTimings:o=!0,showKeys:n=!1,colors:s}=e,i=pe({detectParallel:r}),a=new Set,l=ce(),c=ze(),d=je(),u={showTimings:o,showKeys:n,terminalWidth:process.stdout?.columns??80,colors:{...ae,...s}};function p(){if(a.size>0){let w=i.getIR();for(let b of a)b(w)}}function h(w){if(w.type==="scope_start"||w.type==="scope_end"){g(w);return}i.handleEvent(w),w.type,p()}function g(w){i.handleScopeEvent(w),p()}function m(w){i.handleDecisionEvent(w),p()}function S(){let w=i.getIR();return t&&!w.root.name&&(w.root.name=t),w}function $(){let w=S();return l.render(w,u)}function O(w){let b=S();switch(w){case"ascii":return l.render(b,u);case"mermaid":return c.render(b,u);case"json":return JSON.stringify(b,null,2);case"logger":return d.render(b,u);default:throw new Error(`Unknown format: ${w}`)}}function D(){i.reset(),p()}function v(w){return a.add(w),()=>a.delete(w)}return{handleEvent:h,handleScopeEvent:g,handleDecisionEvent:m,getIR:S,render:$,renderAs:O,reset:D,onUpdate:v}}function Xi(e,t={}){let r=Vt(t);for(let o of e)o.type.startsWith("decision_")?r.handleDecisionEvent(o):r.handleEvent(o);return r.render()}function Zi(e={}){let t=[];return{handleEvent:r=>{t.push(r)},handleDecisionEvent:r=>{t.push(r)},getEvents:()=>[...t],getWorkflowEvents:()=>t.filter(r=>!r.type.startsWith("decision_")),getDecisionEvents:()=>t.filter(r=>r.type.startsWith("decision_")),clear:()=>{t.length=0},visualize:()=>{let r=Vt(e);for(let o of t)o.type.startsWith("decision_")?r.handleDecisionEvent(o):r.handleEvent(o);return r.render()},visualizeAs:r=>{let o=Vt(e);for(let n of t)n.type.startsWith("decision_")?o.handleDecisionEvent(n):o.handleEvent(n);return o.renderAs(r)}}}export{ce as asciiRenderer,As as createDevServer,Zi as createEventCollector,pe as createIRBuilder,mo as createLiveVisualizer,Tn as createParallelDetector,ht as createPerformanceAnalyzer,bt as createTimeTravelController,Vt as createVisualizer,ae as defaultColorScheme,Fe as detectParallelGroups,pt as getHeatLevel,qs as hasChildren,ho as htmlRenderer,se as isDecisionNode,Q as isParallelNode,oe as isRaceNode,jt as isSequenceNode,J as isStepNode,je as loggerRenderer,ze as mermaidRenderer,vt as renderToHTML,wt as trackDecision,go as trackIf,yo as trackSwitch,Xi as visualizeEvents};
|
|
1195
1195
|
//# sourceMappingURL=visualize.js.map
|