UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

12 lines 78.5 kB
import{a as e,i as t,n,t as r}from"../_chunks/node/virtual-loader-Cwgujv7l.js";import{createRequire as i}from"node:module";import{isAbsolute as a}from"node:path";import{pathToFileURL as o}from"node:url";import{existsSync as s,readFileSync as c}from"node:fs";import{Readable as l}from"node:stream";import u from"node:http";import d from"node:https";import f from"node:http2";import{parentPort as p,workerData as m}from"node:worker_threads";import{pipeline as h}from"node:stream/promises";async function g(e){if(!e||Object.keys(e).length===0)return C;let{registerHooks:t,stripTypeScriptTypes:n}=await import(`node:module`);if(typeof t==`function`){let i=`Deno`in globalThis,a;if(i){a=(e,t)=>S(e,t,n);let t={};for(let[n,r]of Object.entries(e))t[n]=a(n,r);e=t}let o={virtual:e,versions:new Map,transformSource:a},s=t(r(e,o.versions,void 0,i));return y.unshift(o),w(()=>{let e=y.indexOf(o);e!==-1&&y.splice(e,1),s.deregister()})}return typeof globalThis.Bun?.plugin==`function`?(b=e,x(Object.keys(e)),w(()=>{b===e&&(b=void 0)})):(console.warn("[env-runner] virtual modules require `module.registerHooks` (Node.js >= 22.15 / Deno >= 2.x) or `Bun.plugin`; skipping registration."),C)}function _(e){return b?.[e]!==void 0&&(x([e]),!0)}function v(e,t){for(let r of y){if(!Object.hasOwn(r.virtual,e))continue;let{virtual:i,versions:a,transformSource:o}=r;t!==void 0&&(i[e]=o?o(e,t):t);for(let t of n(i,e))a.set(t,(a.get(t)??0)+1);return!0}return b&&Object.hasOwn(b,e)?(t!==void 0&&(b[e]=t),x(n(b,e)),!0):!1}function ee(e,t){let n=v(e.specifier,e.source);t({event:`module-invalidated`,specifier:e.specifier,error:n?void 0:`Cannot invalidate "${e.specifier}" (not a registered virtual module)`})}const y=[];let b;function x(t){globalThis.Bun.plugin({name:`env-runner-virtual`,setup(n){for(let r of t)n.module(r,()=>{let t=b?.[r];if(t===void 0)throw Error(`Cannot find virtual module "${r}" (unregistered)`);let n=e(r);return n===`json`?{exports:{default:JSON.parse(t)},loader:`object`}:{contents:t,loader:n===`module-typescript`?`ts`:`js`}})}})}function S(n,r,i){let a=e(n);return a===`module-typescript`?t(n,r,i,{requirement:`(custom load hooks bypass Deno's native type stripping)`,remedy:`upgrade Deno`}):a===`json`?`export default JSON.parse(${JSON.stringify(r)});`:r}const C=()=>{};function w(e){let t=!1;return()=>{t||(t=!0,e())}}function te(e,t){return!!(e&&t&&Object.hasOwn(t,e))}async function ne(e,t){let n=await(t?import(e):import(ae(e))),r=n.default||n;if(typeof r.fetch!=`function`)throw Error(`[env-runner] Entry module "${e}" must export a \`fetch\` handler (export default { fetch(req) { ... } }).`);return r}function re(e){let t=new URL(e.url);return{host:t.hostname,port:Number(t.port)}}async function ie(e,t,n,r){await t.ipc?.onClose?.();let i=await E(e,r);return await i.ipc?.onOpen?.({sendMessage:n}),i}function ae(e){let t=e.indexOf(`?`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t);return a(n)?o(n).href+r:e}let T=0;async function E(e,t){let n=e.indexOf(`?`),r=n===-1?e:e.slice(0,n),i;if(!t&&s(r)){let e=c(r,`utf8`);i=await import(`data:text/javascript;base64,`+Buffer.from(e).toString(`base64`))}else i=t&&_(r)?await import(r):await import(e+(n===-1?`?`:`&`)+`__envRunnerReload=`+T++);let a=i.default||i;if(typeof a.fetch!=`function`)throw Error(`[env-runner] Entry module "${e}" must export a \`fetch\` handler (export default { fetch(req) { ... } }).`);return a}function D(e,t,n){for(let r of[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)]){if(r===`constructor`)continue;let i=Object.getOwnPropertyDescriptor(e,r),a=Object.getOwnPropertyDescriptor(t,r),o=!1;a.get&&=(o=!0,i?.get||function(){return this[n][r]}),a.set&&=(o=!0,i?.set||function(e){this[n][r]=e}),!i?.value&&typeof a.value==`function`&&(o=!0,a.value=function(...e){return this[n][r](...e)}),o&&Object.defineProperty(e,r,a)}}const O=/(?:(?:^|\/)(?:\.|\.\.|%2e|%2e\.|\.%2e|%2e%2e)(?:\/|$))|[\\^#"<>{}`\x80-\uffff]/i,k=/[#"'<>]/,A=(()=>{let e=globalThis.URL,t=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(t){if(typeof t==`string`){let n=t[0]===`/`;n&&!k.test(t)?this.#t=t:this.#e=new e(n?`http://localhost${t}`:t)}else O.test(t.pathname)||t.search&&k.test(t.search)?this.#e=new e(`${t.protocol||`http:`}//${t.host||`localhost`}${t.pathname}${t.search||``}`):(this.#n=t.protocol,this.#r=t.host,this.#i=t.pathname,this.#a=t.search)}static[Symbol.hasInstance](t){return t instanceof e}get _url(){return this.#e?this.#e:(this.#e=new e(this.href),this.#t=void 0,this.#n=void 0,this.#r=void 0,this.#i=void 0,this.#a=void 0,this.#o=void 0,this.#s=void 0,this.#e)}get href(){return this.#e?this.#e.href:(this.#t||=`${this.#n||`http:`}//${this.#r||`localhost`}${this.#i||`/`}${this.#a||``}`,this.#t)}#c(){if(!this.#s){let e=this.href,t=e.indexOf(`://`),n=t===-1?-1:e.indexOf(`/`,t+4),r=n===-1?-1:e.indexOf(`?`,n);this.#s=[t,n,r]}return this.#s}get pathname(){if(this.#e)return this.#e.pathname;if(this.#i===void 0){let[,e,t]=this.#c();if(e===-1)return this._url.pathname;this.#i=this.href.slice(e,t===-1?void 0:t)}return this.#i}get search(){if(this.#e)return this.#e.search;if(this.#a===void 0){let[,e,t]=this.#c();if(e===-1)return this._url.search;let n=this.href;this.#a=t===-1||t===n.length-1?``:n.slice(t)}return this.#a}get searchParams(){return this.#e?this.#e.searchParams:(this.#o||=new URLSearchParams(this.search),this.#o)}get protocol(){if(this.#e)return this.#e.protocol;if(this.#n===void 0){let[e]=this.#c();if(e===-1)return this._url.protocol;let t=this.href;this.#n=t.slice(0,e+1)}return this.#n}toString(){return this.href}toJSON(){return this.href}};return D(t.prototype,e.prototype,`_url`),Object.setPrototypeOf(t.prototype,e.prototype),Object.setPrototypeOf(t,e),t})();function oe(e){let t=e.port??globalThis.process?.env.PORT??3e3,n=typeof t==`number`?t:Number.parseInt(t,10);if(n<0||n>65535)throw RangeError(`Port must be between 0 and 65535 (got "${n}").`);return{port:n,hostname:e.hostname??globalThis.process?.env.HOST}}function se(e,t,n){if(e&&t)return e.includes(`:`)&&(e=`[${e}]`),`http${n?`s`:``}://${e}:${t}/`}function j(e,t){if(!t||(e.silent??globalThis.process?.env?.TEST))return;let n=``;try{let e=new URL(t);(e.hostname===`[::]`||e.hostname===`0.0.0.0`)&&(e.hostname=`localhost`,t=e.href,n=` (all interfaces)`)}catch{}let r=`➜ Listening on:`;globalThis.process.stdout?.isTTY&&(r=`\u001B[32m${r}\u001B[0m`,t=`\u001B[36m${t}\u001B[0m`,n=`\u001B[2m${n}\u001B[0m`),console.log(`${r} ${t}${n}`)}function M(e){if(!e.tls||e.protocol===`http`)return;let t=N(e.tls.cert),n=N(e.tls.key);if(!t&&!n){if(e.protocol===`https`)throw TypeError("TLS `cert` and `key` must be provided for `https` protocol.");return}if(!t||!n)throw TypeError("TLS `cert` and `key` must be provided together.");return{cert:t,key:n,passphrase:e.tls.passphrase}}function N(e){if(!e)return;if(typeof e!=`string`)throw TypeError(`TLS certificate and key must be strings in PEM format or file paths.`);if(e.startsWith(`-----BEGIN `))return e;let{readFileSync:t}=process.getBuiltinModule(`node:fs`);return t(e,`utf8`)}function ce(){let e=new Set;return{waitUntil:t=>{typeof t?.then==`function`&&e.add(Promise.resolve(t).catch(console.error).finally(()=>{e.delete(t)}))},wait:()=>Promise.all(e)}}const le=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`})(),P=(e,t=39)=>n=>le?n:`\u001B[${e}m${n}\u001B[${t}m`,ue=P(1,22),de=P(31),fe=P(32),F=P(90);function pe(e){let t=e.options.fetch,n=e.options.middleware||[];return n.length===0?t:e=>I(e,t,n,0)}function I(e,t,n,r){return r===n.length?t(e):n[r](e,()=>I(e,t,n,r+1))}const L=e=>{let t=e.options.error;t&&e.options.middleware.unshift((e,n)=>{try{let e=n();return e instanceof Promise?e.catch(e=>t(e)):e}catch(e){return t(e)}})},R=e=>{let t=e.options?.gracefulShutdown;if(!globalThis.process?.on||t===!1||t===void 0&&(process.env.CI||process.env.TEST))return;let n=t===!0||!t?.gracefulTimeout?Number.parseInt(process.env.SERVER_SHUTDOWN_TIMEOUT||``)||5:t.gracefulTimeout,r=!1,i=!1,a=e.options.silent?()=>{}:process.stderr.write.bind(process.stderr),o=async()=>{i||(a(de(`\x1B[2K\rForcibly closing connections...
`)),i=!0,await e.close(!0))},s=async()=>{if(r||i)return;setTimeout(()=>{globalThis.process.once(`SIGINT`,o)},100),r=!0;let t=e.close();for(let e=n;e>0;e--)if(a(F(`\rStopping server gracefully (${e}s)... Press ${ue(`Ctrl+C`)} again to force close.`)),await Promise.race([t.then(()=>!0),new Promise(e=>setTimeout(()=>e(!1),1e3))])){a(`\x1B[2K\r`+fe(`Server closed successfully.
`)),i=!0;return}a(`\x1B[2K\rGraceful shutdown timed out.
`),await o()};for(let e of[`SIGINT`,`SIGTERM`])globalThis.process.on(e,s)};function z(e,t){if(e===void 0||e===!1)return!1;if(e===!0)return!0;if(e===`loopback`)return me(t);if(t===void 0)return!1;if(e.includes(t))return!0;let n=B(t);return n!==void 0&&e.includes(n)}function B(e){return e.startsWith(`::ffff:`)&&e.includes(`.`)?e.slice(7):void 0}function me(e){return!!e&&(e===`::1`||e.startsWith(`127.`)||e.startsWith(`::ffff:127.`))}const he=/^(\[(?:[A-Fa-f0-9:.]+)\]|(?:[A-Za-z0-9_-]+\.)*[A-Za-z0-9_-]+|(?:\d{1,3}\.){3}\d{1,3})(:\d{1,5})?$/;function V(e){if(e)return(Array.isArray(e)?e[0]:e).split(`,`)[0].trim()||void 0}function ge(e){return Object.assign(Error(`Request body exceeds the maximum allowed size of ${e} bytes.`),{code:`ERR_BODY_TOO_LARGE`,statusCode:413,status:413})}function _e(e,t){let n=e.getReader(),r=0;return new ReadableStream({async pull(e){let{done:i,value:a}=await n.read();if(i){e.close();return}if(r+=a.byteLength,r>t){let r=ge(t);n.cancel(r).catch(()=>{}),e.error(r);return}e.enqueue(a)},cancel(e){return n.cancel(e)}})}function ve(e,t){try{return be(e,t,!0)}catch(t){ye(e,t)}}function ye(e,t){e.headersSent?e.destroy():(e.statusCode=500,e.end())}function be(e,t,n){if(!t)return e.statusCode=500,U(e,n);if(t._toNodeResponse){let r=t._toNodeResponse();if(r.body){if(r.body instanceof ReadableStream)return H(e,r.status,r.statusText,r.headers),Se(r.body,e);if(typeof r.body?.pipe==`function`)return xe(r.body,e,r.status,r.statusText,r.headers);H(e,r.status,r.statusText,r.headers),e.write(r.body)}else H(e,r.status,r.statusText,r.headers);return U(e,n)}let r=[];for(let[e,n]of t.headers)r.push(e,n);return H(e,t.status,t.statusText,r),t.body?Se(t.body,e):U(e,n)}function H(e,t,n,r){e.headersSent||(e.req?.httpVersion===`2.0`?e.writeHead(t,r):e.writeHead(t,n,r))}function U(e,t){if(t){e.end();return}return new Promise(t=>e.end(t))}function xe(e,t,n,r,i){if(t.destroyed){e.destroy?.();return}return typeof e.on!=`function`||typeof e.destroy!=`function`?(H(t,n,r,i),e.pipe(t),new Promise(e=>t.on(`close`,e))):e.destroyed?(H(t,500,`Internal Server Error`,[]),U(t)):new Promise(a=>{function o(){e.off(`readable`,s),e.destroy(),H(t,500,`Internal Server Error`,[]),U(t).then(a)}function s(){if(e.off(`error`,o),t.destroyed)return e.destroy(),a();H(t,n,r,i),h(e,t).catch(()=>{}).then(()=>a())}e.once(`error`,o),e.once(`readable`,s)})}function Se(e,t){if(t.destroyed){e.cancel();return}let n=e.getReader();function r(e){n.cancel(e).catch(()=>{}),e&&t.destroy(e)}function i({done:e,value:a}){try{e?t.end():t.write(a)?n.read().then(i,r):t.once(`drain`,()=>n.read().then(i,r))}catch(e){r(e instanceof Error?e:void 0)}}return t.on(`close`,r),t.on(`error`,r),n.read().then(i,r),n.closed.catch(r).finally(()=>{t.off(`close`,r),t.off(`error`,r)})}var Ce=class extends A{constructor({req:e,trusted:t=!1}){let n=e.url||`/`,r=t?V(e.headers[`x-forwarded-host`]):void 0,i=(r&&he.test(r)?r:void 0)||e.headers.host||e.headers[`:authority`];i&&!he.test(i)?i=`_invalid_`:i||=e.socket?`${e.socket.localFamily===`IPv6`?`[`+e.socket.localAddress+`]`:e.socket.localAddress}:${e.socket?.localPort||`80`}`:`localhost`;let a=t?V(e.headers[`x-forwarded-proto`]):void 0,o=e.socket?.encrypted||a===`https`||t&&e.headers[`:scheme`]===`https`?`https:`:`http:`;if(n[0]===`/`){let e=n.indexOf(`?`);super({protocol:o,host:i,pathname:e===-1?n:n.slice(0,e)||`/`,search:e===-1?``:n.slice(e)||``})}else super(n===`*`?{protocol:o,host:i,pathname:`/*`,search:``}:n)}};const we=new Set([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`server`,`user-agent`]),Te=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;function Ee(e,t){let n=!1;for(let r=0;r<e.length;r+=2){let i=e[r];if(i.length===t.length&&i.toLowerCase()===t){if(n)return!0;n=!0}}return!1}const De=(()=>{let e=globalThis.Headers;class t{#e;#t;constructor(e){this.#e=e}static[Symbol.hasInstance](t){return t instanceof e}get _headers(){if(!this.#t){let t=new e,n=this.#e.rawHeaders,r=n.length;for(let e=0;e<r;e+=2){let r=n[e];if(r.charCodeAt(0)===58)continue;let i=n[e+1];t.append(r,i)}this.#t=t}return this.#t}get(e){if(this.#t)return this.#t.get(e);let t=e.toLowerCase();if(t.charCodeAt(0)===58)return this._headers.get(e);let n=this.#e.headers[t];return typeof n==`string`?we.has(t)&&Ee(this.#e.rawHeaders,t)?this._headers.get(e):n:Array.isArray(n)?n.join(`, `):t!==`__proto__`&&Te.test(e)?null:this._headers.get(e)}has(e){if(this.#t)return this.#t.has(e);let t=e.toLowerCase();return t.charCodeAt(0)===58?this._headers.has(e):Object.hasOwn(this.#e.headers,t)?!0:t!==`__proto__`&&Te.test(e)?!1:this._headers.has(e)}getSetCookie(){if(this.#t)return this.#t.getSetCookie();let e=this.#e.headers[`set-cookie`];return Array.isArray(e)?e.slice():e?[e]:[]}entries(){return this._headers.entries()}[Symbol.iterator](){return this.entries()}}return D(t.prototype,e.prototype,`_headers`),Object.setPrototypeOf(t,e),Object.setPrototypeOf(t.prototype,e.prototype),t})(),Oe=Symbol.for(`srvx.nativeRequest`),ke=(()=>{let e=je();class t{runtime;waitUntil;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=!1;#u;#d;constructor(e){this.#e=e.req,this.#o=e.maxRequestBodySize,this.#s=e.trustProxy,this.runtime={name:`node`,node:e}}static[Symbol.hasInstance](t){return t instanceof e}#f(){return this.#d===void 0&&(this.#u=this.#e.socket?.remoteAddress,this.#d=z(this.#s,this.#u)),this.#d}get ip(){if(this.#l)return this.#c;if(this.#l=!0,this.#f()){let e=V(this.#e.headers[`x-forwarded-for`]);if(e)return this.#c=e}return this.#c=this.#u}get method(){return this.#r?this.#r.method:this.#e.method||`GET`}get _url(){return this.#t||=new Ce({req:this.#e,trusted:this.#f()})}set _url(e){this.#t=e}get url(){return this.#r?this.#r.url:this._url.href}get headers(){return this.#r?this.#r.headers:this.#i||=new De(this.#e)}get _abortController(){if(!this.#a){this.#a=new AbortController;let{req:e,res:t}=this.runtime.node,n=this.#a,r=e=>n.abort?.(e);t?t.once(`close`,()=>{let n=e.errored;n?r(n):t.writableEnded||r()}):e.once(`close`,()=>{e.complete||r()})}return this.#a}get signal(){return this.#r?this.#r.signal:this._abortController.signal}get body(){if(this.#r)return this.#r.body;if(this.#n===void 0){let e=this.method,t=e!==`GET`&&e!==`HEAD`?l.toWeb(this.#e):null;t&&this.#o!==void 0&&(t=_e(t,this.#o)),this.#n=t}return this.#n}#p(){return Ae(this.#e,this.#o)}text(){return this.#r?this.#r.text():this.#n===void 0?this.#p().then(e=>e.toString()):this.#n?new Response(this.#n).text():Promise.resolve(``)}json(){return this.#r?this.#r.json():this.#n===void 0?this.#p().then(e=>JSON.parse(e.toString())):this.text().then(e=>JSON.parse(e))}get _request(){if(!this.#r){let t=this.body;this.#r=new e(this.url,{method:this.method,headers:this.headers,signal:this._abortController.signal,body:t,duplex:t?`half`:void 0}),this.#i=void 0,this.#n=void 0}return this.#r}}return D(t.prototype,e.prototype,`_request`),Object.setPrototypeOf(t.prototype,e.prototype),t})();function Ae(e,t){return`rawBody`in e&&Buffer.isBuffer(e.rawBody)?t!==void 0&&e.rawBody.length>t?Promise.reject(ge(t)):Promise.resolve(e.rawBody):new Promise((n,r)=>{let i=[],a=0,o=()=>{e.off(`data`,s),e.off(`end`,l),e.off(`error`,c)},s=n=>{if(t!==void 0&&(a+=n.length,a>t)){o(),e.pause?.(),r(ge(t));return}i.push(n)},c=e=>{o(),r(e)},l=()=>{o(),n(i.length===1?i[0]:Buffer.concat(i))};e.on(`data`,s).once(`end`,l).once(`error`,c)})}function je(){let e=globalThis[Oe]||globalThis.Request;for(;e?._srvx;)e=Object.getPrototypeOf(e);return globalThis[Oe]??=e}function Me(e){return new Ne(e)}var Ne=class{runtime=`node`;options;node;serveOptions;fetch;waitUntil;#e;#t;#n;#r;constructor(e){this.options={...e,middleware:[...e.middleware||[]]};for(let t of e.plugins||[])t(this);L(this);let t=this.fetch=pe(this),n=(e,n)=>{let r=e.url;if(r&&r[0]!==`/`&&r!==`*`&&!URL.canParse(r)){n.statusCode=400,n.end();return}let i=new ke({req:e,res:n,maxRequestBodySize:this.options.maxRequestBodySize,trustProxy:this.options.trustProxy});i.waitUntil=this.#r?.waitUntil;let a=t(i);return a instanceof Promise?a.then(e=>ve(n,e)):ve(n,a)};this.node={handler:n,server:void 0};let r=globalThis.__srvxLoader__;if(r){r({server:this});return}R(this),this.#r=ce(),this.waitUntil=this.#r.waitUntil;let i=M(this.options),{port:a,hostname:o}=oe(this.options);this.serveOptions={port:a,host:o,exclusive:!this.options.reusePort,...i,...this.options.node};let s;if(this.#e=!!this.serveOptions.cert&&this.options.protocol!==`http`,this.options.node?.http2??this.#e){if(this.#e)s=f.createSecureServer({allowHTTP1:!0,...this.serveOptions},n);else throw Error(`node.http2 option requires tls certificate!`)}else s=this.#e?d.createServer(this.serveOptions,n):u.createServer(this.serveOptions,n);this.node.server=s,e.manual||this.serve().catch(()=>{})}serve(){if(this.#t)return this.#t.then(()=>this);let e=this.node?.server;return e?(this.#n=void 0,this.#t=new Promise((t,n)=>{let r=t=>{e.off(`listening`,i),this.#n=t,this.#t=void 0,n(t)},i=()=>{e.off(`error`,r),j(this.options,this.url),t()};e.once(`error`,r),e.once(`listening`,i),e.listen(this.serveOptions)}),this.#t.then(()=>this)):Promise.reject(Error(`Server not initialized`))}get url(){let e=this.node?.server?.address();if(e)return typeof e==`string`?e:se(e.address,e.port,this.#e)}ready(){return this.#n?Promise.reject(this.#n):Promise.resolve(this.#t).then(()=>this)}async close(e){await Promise.all([this.#r?.wait(),new Promise((t,n)=>{let r=this.node?.server;if(r&&e&&`closeAllConnections`in r&&r.closeAllConnections(),!r||!r.listening)return t();r.close(e=>e?n(e):t())})])}},Pe=Object.create,Fe=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,Le=Object.getOwnPropertyNames,Re=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty,W=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Be=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Le(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ze.call(e,s)&&s!==n&&Fe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ie(t,s))||r.enumerable});return e},Ve=(e,t,n)=>(n=e==null?{}:Pe(Re(e)),Be(t||!e||!e.__esModule||!ze.call(e,`default`)?Fe(n,`default`,{value:e,enumerable:!0}):n,e)),G=i(import.meta.url),K=W(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),q=W(((e,t)=>{let{EMPTY_BUFFER:n}=K(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=G(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),He=W(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),J=W(((e,t)=>{let n=G(`zlib`),r=q(),i=He(),{kStatusCode:a}=K(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&(typeof e.client_max_window_bits==`number`?t.clientMaxWindowBits>e.client_max_window_bits:!e.client_max_window_bits)));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Y=W(((e,t)=>{let{isUtf8:n}=G(`buffer`),{hasBlob:r}=K(),i=[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 a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=G(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Ue=W(((e,t)=>{let{Writable:n}=G(`stream`),r=J(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=K(),{concat:c,toArrayBuffer:l,unmask:u}=q(),{isValidStatusCode:d,isValidUTF8:f}=Y(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0||e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=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._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._state=this._masked?3:4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`));return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),We=W(((e,t)=>{let{Duplex:n}=G(`stream`),{randomFillSync:r}=G(`crypto`),{types:{isUint8Array:i}}=G(`util`),a=J(),{EMPTY_BUFFER:o,kWebSocket:s,NOOP:c}=K(),{isBlob:l,isValidStatusCode:u}=Y(),{mask:d,toBuffer:f}=q(),p=Symbol(`kByteLength`),m=Buffer.alloc(4),h=8192,g,_=h;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[s]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||m,t.generateMask?t.generateMask(n):(_===h&&(g===void 0&&(g=Buffer.alloc(h)),r(g,0,h),_=0),n[0]=g[_++],n[1]=g[_++],n[2]=g[_++],n[3]=g[_++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[p]!==void 0?s=t[p]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(d(e,n,l,a,s),[l]):(d(e,n,e,0,s),[l,e])}close(t,n,r,a){let s;if(t===void 0)s=o;else if(typeof t!=`number`||!u(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),typeof n==`string`)s.write(n,2);else if(i(n))s.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[p]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(s,c),a):this.enqueue([this.dispatch,s,!1,c,a])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[a.extensionName],i=t.binary?2:1,o=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):l(e)?(s=e.size,c=!1):(e=f(e),s=e.length,c=f.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let u={[p]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};l(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[p],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(v,this,e,i);return}this._bufferedBytes-=r[p];let a=f(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(ee,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[a.extensionName];this._bufferedBytes+=r[p],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);v(this,e,i);return}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function v(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function ee(e,t,n){v(e,t,n),e.onerror(t)}})),Ge=W(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=K(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean!==void 0&&t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,"code",{enumerable:!0}),Object.defineProperty(p.prototype,"reason",{enumerable:!0}),Object.defineProperty(p.prototype,"wasClean",{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Ke=W(((e,t)=>{let{tokenChars:n}=Y();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`)}else if(l===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s){if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),qe=W(((e,t)=>{let n=G(`events`),r=G(`https`),i=G(`http`),a=G(`net`),o=G(`tls`),{randomBytes:s,createHash:c}=G(`crypto`),{Duplex:l,Readable:u}=G(`stream`),{URL:d}=G(`url`),f=J(),p=Ue(),m=We(),{isBlob:h}=Y(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:ee,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=K(),{EventTarget:{addEventListener:w,removeEventListener:te}}=Ge(),{format:ne,parse:re}=Ke(),{toBuffer:ie}=q(),ae=Symbol(`kAborted`),T=[8,13],E=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],D=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var O=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,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._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),k(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,N),i.on(`drain`,ce),i.on(`error`,le),i.on(`message`,ue),i.on(`ping`,de),i.on(`pong`,fe),a.onerror=pe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,L),t.on(`data`,R),t.on(`end`,z),t.on(`error`,B),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[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(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,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),I(this)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){M(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){M(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){M(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(O,"CONNECTING",{enumerable:!0,value:E.indexOf(`CONNECTING`)}),Object.defineProperty(O.prototype,"CONNECTING",{enumerable:!0,value:E.indexOf(`CONNECTING`)}),Object.defineProperty(O,"OPEN",{enumerable:!0,value:E.indexOf(`OPEN`)}),Object.defineProperty(O.prototype,"OPEN",{enumerable:!0,value:E.indexOf(`OPEN`)}),Object.defineProperty(O,"CLOSING",{enumerable:!0,value:E.indexOf(`CLOSING`)}),Object.defineProperty(O.prototype,"CLOSING",{enumerable:!0,value:E.indexOf(`CLOSING`)}),Object.defineProperty(O,"CLOSED",{enumerable:!0,value:E.indexOf(`CLOSED`)}),Object.defineProperty(O.prototype,"CLOSED",{enumerable:!0,value:E.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(O.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(O.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),O.prototype.addEventListener=w,O.prototype.removeEventListener=te,t.exports=O;function k(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:T[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,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=o.autoPong,e._closeTimeout=o.closeTimeout,!T.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${T.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;A(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?se:oe),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=ne({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!D.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:!e._originalIpc&&l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=v(o);o.timeout&&x.on(`timeout`,()=>{j(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[ae]||(x=e._req=null,A(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){j(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{A(e,SyntaxError(`Invalid URL: ${i}`));return}k(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||j(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==O.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){j(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+ee).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){j(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){j(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){j(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=re(u)}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){j(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function A(e,t){e._readyState=O.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function oe(e){return e.path=e.socketPath,a.connect(e)}function se(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function j(e,t,n){e._readyState=O.CLOSING;let r=Error(n);Error.captureStackTrace(r,j),t.setHeader?(t[ae]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(A,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function M(e,t,n){if(t){let n=h(t)?t.size:ie(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${E[e.readyState]})`);process.nextTick(n,t)}}function N(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,R),process.nextTick(F,n._socket),e===1005?n.close():n.close(e,t))}function ce(){let e=this[S];e.isPaused||e._socket.resume()}function le(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,R),process.nextTick(F,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function P(){this[S].emitClose()}function ue(e,t){this[S].emit(`message`,e,t)}function de(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function fe(e){this[S].emit(`pong`,e)}function F(e){e.resume()}function pe(e){let t=this[S];t.readyState!==O.CLOSED&&(t.readyState===O.OPEN&&(t._readyState=O.CLOSING,I(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function I(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function L(){let e=this[S];if(this.removeListener(`close`,L),this.removeListener(`data`,R),this.removeListener(`end`,z),e._readyState=O.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[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,P),e._receiver.on(`finish`,P))}function R(e){this[S]._receiver.write(e)||this.pause()}function z(){let e=this[S];e._readyState=O.CLOSING,e._receiver.end(),this.end()}function B(){let e=this[S];this.removeListener(`error`,B),this.on(`error`,C),e&&(e._readyState=O.CLOSING,this.destroy())}})),Je=W(((e,t)=>{qe();let{Duplex:n}=G(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Ye=W(((e,t)=>{let{tokenChars:n}=Y();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Xe=W(((e,t)=>{let n=G(`events`),r=G(`http`),{Duplex:i}=G(`stream`),{createHash:a}=G(`crypto`),o=Ke(),s=J(),c=Ye(),l=qe(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=K(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1){if(this._state=1,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(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
`).join(`\r
`)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
`)+`\r
\r
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));Je(),Ke(),J(),Ue(),We(),Ye(),Ve(qe(),1);var Ze=Ve(Xe(),1),Qe=class{options;#e=new WeakMap;constructor(e){this.options=e||{}}callHook(e,t,n,r){let i=this.options.hooks?.[e],a=i?.(t,n),o=this.options.resolve;if(!o)return a;let s=t.request||t,c=r||t.context||s,l;if(this.#e.has(c))l=this.#e.get(c);else{try{l=o(s)}catch(e){l=Promise.reject(e)}this.#e.set(c,l),l instanceof Promise&&l.catch(()=>{this.#e.get(c)===l&&this.#e.delete(c)})}if(!l)return a;let u=l instanceof Promise?l.then(t=>t?.[e]):l?.[e];return Promise.all([a,u]).then(([e,r])=>{let i=r?.(t,n);return i instanceof Promise?i.then(t=>t||e):i||e})}async upgrade(e){let t=this.options.getNamespace?.(e)??new URL(e.url).pathname,n=e.context||{},r,i;try{let a=await this.callHook(`upgrade`,e,void 0,n);if(a){if(a.namespace&&(t=a.namespace),a.context&&Object.assign(n,a.context),a instanceof Response)return{context:n,namespace:t,endResponse:a};if(a.handled)return{context:n,namespace:t,handled:!0};r=a.headers,i=a.protocol}}catch(e){let r=e.response||e;if(r instanceof Response)return{context:n,namespace:t,endResponse:r};throw e}let a=await this._resolveProtocol(e,r,i);if(a){let e=new Headers(r);e.set(`sec-websocket-protocol`,a),r=e}return{context:n,namespace:t,upgradeHeaders:r}}async _resolveProtocol(e,t,n){if(n)return n;if(t){let e=(t instanceof Headers?t:new Headers(t)).get(`sec-websocket-protocol`);if(e)return e}let r=this.options.handleProtocols;if(r){let t=$e(e.headers.get(`sec-websocket-protocol`));if(t.size>0){let n=await r(t,e);if(n)return n}}}};function $e(e){let t=new Set;if(!e)return t;for(let n of e.split(`,`)){let e=n.trim();e&&t.add(e)}return t}const et=Symbol.for(`crossws.hooks`);function tt(e){return e[et]??e.context?.[et]}const nt=Symbol.for(`nodejs.util.inspect.custom`);function rt(e){if(e==null)return``;let t=typeof e;return t===`string`?e:t===`number`||t===`boolean`||t===`bigint`?e.toString():t===`function`||t===`symbol`?`{}`:e instanceof Uint8Array||e instanceof ArrayBuffer?e:at(e)?JSON.stringify(e):e}function it(e){let t=rt(e);return typeof t==`string`||t instanceof Uint8Array?t:new Uint8Array(t)}function at(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}let ot;function st(e){ot??=new Set,!ot.has(e)&&(ot.add(e),console.warn(e))}function ct(e,t,n){let r=(t,r,i)=>{for(let a of i?.namespace?[e.get(i.namespace)||[]]:e.values()){let e;for(let n of a)if(n.topics.has(t)){e=n;break}if(e&&(e.send(r,i),e._publish(t,r,i),n?.nativePubSub&&!i?.namespace))break}},i;if(t?.sync){let e=(e,n)=>{t.onError?t.onError(n,{stage:e}):console.error(`[crossws] sync ${e} failed:`,n)},n=t.sync({id:crypto.randomUUID()}),a=t=>{try{r(t.topic,t.data,{namespace:t.namespace||void 0})}catch(t){e(`delivery`,t)}};try{Promise.resolve(n.subscribe(a)).catch(t=>e(`subscribe`,t))}catch(t){e(`subscribe`,t)}i={subscribe:e=>n.subscribe(e),publish:t=>{try{return Promise.resolve(n.publish(t)).catch(t=>e(`publish`,t))}catch(t){e(`publish`,t)}},close:n.close?()=>n.close():void 0}}return{peers:e,sync:i,publish(e,t,n){r(e,t,n),i?.publish({namespace:n?.namespace||``,topic:e,data:it(t)})},async close(t,n){for(let r of e.values())for(let e of r)e.close(t,n);await i?.close?.()}}}function lt(e,t){if(!t)throw Error(`Websocket publish namespace missing.`);let n=e.get(t);return n||(n=new Set,e.set(t,n)),n}var ut=class{event;peer;rawData;#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.rawData=e||``,this.peer=t,this.event=n}get id(){return this.#e||=crypto.randomUUID(),this.#e}uint8Array(){let e=this.#t;if(e)return e;let t=this.rawData;if(t instanceof Uint8Array)return this.#t=t;if(t instanceof ArrayBuffer||t instanceof SharedArrayBuffer)return this.#n=t,this.#t=new Uint8Array(t);if(typeof t==`string`)return this.#i=t,this.#t=new TextEncoder().encode(this.#i);if(Symbol.iterator in t||typeof t?.length==`number`)return this.#t=new Uint8Array(t);if(t instanceof DataView)return this.#t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw TypeError(`Unsupported message type: ${Object.prototype.toString.call(t)}`)}arrayBuffer(){let e=this.#n;if(e)return e;let t=this.rawData;return this.#n=t instanceof ArrayBuffer||t instanceof SharedArrayBuffer?t:this.uint8Array().buffer}blob(){let e=this.#r;if(e)return e;let t=this.rawData;return this.#r=t instanceof Blob?t:new Blob([this.uint8Array()])}text(){let e=this.#i;if(e)return e;let t=this.rawData;return this.#i=typeof t==`string`?t:new TextDecoder().decode(this.uint8Array())}json(){return this.#a||=JSON.parse(this.text())}get data(){switch(this.peer?.websocket?.binaryType){case`arraybuffer`:return this.arrayBuffer();case`blob`:return this.blob();case`nodebuffer`:{let e=globalThis.Buffer;return e?e.from(this.uint8Array()):this.uint8Array()}case`uint8array`:return this.uint8Array();case`text`:return this.text();default:return this.rawData}}toString(){return this.text()}[Symbol.toPrimitive](){return this.text()}[nt](){return{message:{id:this.id,peer:this.peer,text:this.text()}}}},dt=class{_internal;_topics;_id;#e;#t=!1;constructor(e){this._topics=new Set,this._internal=e}get context(){return this._internal.context??={}}get namespace(){return this._internal.namespace}get id(){return this._id||=crypto.randomUUID(),this._id}get remoteAddress(){}get request(){return this._internal.request}get websocket(){if(!this.#e){let e=this._internal.ws,t=this._internal.request;this.#e=t?ft(e,t):e}return this.#e}get peers(){return this._internal.peers||new Set}get topics(){return this._topics}get bufferedAmount(){return this._internal.ws?.bufferedAmount??0}waitForDrain(e={}){let t=e.threshold??0;if(this.bufferedAmount<=t)return Promise.resolve();let n=e.signal;return n?.aborted?Promise.reject(n.reason):new Promise((r,i)=>{let a=()=>{(this.bufferedAmount<=t||(this.websocket.readyState??1)>1)&&(c(),r())},o=()=>{c(),i(n.reason)},s=setInterval(a,e.pollInterval??100);s.unref?.();let c=()=>{clearInterval(s),n?.removeEventListener(`abort`,o)};n?.addEventListener(`abort`,o,{once:!0})})}terminate(){this.close()}ping(e){this.#t||(this.#t=!0,console.warn("[crossws] `peer.ping()` is not supported by this adapter."))}subscribe(e){this._topics.add(e)}unsubscribe(e){this._topics.delete(e)}publish(e,t,n){this._publish(e,t,n),this._internal.sync?.publish({namespace:this.namespace,topic:e,data:it(t)})}toString(){return this.id}[Symbol.toPrimitive](){return this.id}[Symbol.toStringTag](){return`WebSocket`}[nt](){return{peer:{id:this.id,ip:this.remoteAddress}}}};function ft(e,t){return new Proxy(e,{get:(e,n)=>{let r=Reflect.get(e,n);if(!r)switch(n){case`protocol`:return t?.headers?.get(`sec-websocket-protocol`)||``;case`extensions`:return t?.headers?.get(`sec-websocket-extensions`)||``;case`url`:return t?.url?.replace(/^http/,`ws`)||void 0}return r}})}var pt=class extends Error{constructor(...e){super(...e),this.name=`WSError`}};const mt=(()=>{class e{url;_abortController;_headers;_init;constructor(e,t={}){this.url=e,this._init=t}get headers(){return this._headers||=new Headers(this._init?.headers),this._headers}clone(){return new e(this.url,this._init)}get method(){return`GET`}get signal(){return this._abortController||=new AbortController,this._abortController.signal}get cache(){return`default`}get credentials(){return`same-origin`}get destination(){return``}get integrity(){return``}get keepalive(){return!1}get redirect(){return`follow`}get mode(){return`cors`}get referrer(){return`about:client`}get referrerPolicy(){return``}get body(){return null}get bodyUsed(){return!1}arrayBuffer(){return Promise.resolve(new ArrayBuffer(0))}blob(){return Promise.resolve(new Blob)}bytes(){return Promise.resolve(new Uint8Array)}formData(){return Promise.resolve(new FormData)}json(){return Promise.resolve(JSON.parse(``))}text(){return Promise.resolve(``)}}return Object.setPrototypeOf(e.prototype,globalThis.Request.prototype),e})(),ht=Buffer.from(`crossws-ping`),gt=(e={})=>{if(`Deno`in globalThis||`Bun`in globalThis)throw Error(`[crossws] Using Node.js adapter in an incompatible environment.`);let t=new Qe(e),n=new Map,r=ct(n,e),i=e.wss||new Ze.default({noServer:!0,handleProtocols:()=>!1,...e.serverOptions}),a=new Set,o=(e.idleTimeout??30)*1e3,s=Math.max(1,Math.floor(o));i.on(`connection`,(e,i)=>{let s=new vt(i),c=lt(n,i._namespace),l=new _t({ws:e,request:s,peers:c,nodeReq:i,namespace:i._namespace,sync:r.sync,hooks:t});if(c.add(l),a.add(e),o>0){e._isAlive=!0;let t=()=>{e._isAlive=!0};e.on(`pong`,t),e.on(`ping`,t),e.on(`message`,t)}t.callHook(`open`,l),e.on(`message`,(e,n)=>{let r=Array.isArray(e)?Buffer.concat(e):e,i=!n&&!(r instanceof ArrayBuffer)?r.toString(`utf8`):r;t.callHook(`message`,l,new ut(i,l))}),e.on(`ping`,e=>{t.callHook(`ping`,l,e)}),e.on(`pong`,e=>{e.equals(ht)||t.callHook(`pong`,l,e)}),e.on(`error`,e=>{c.delete(l),t.callHook(`error`,l,new pt(e))});let u=e._socket,d=()=>t.callHook(`drain`,l);u?.on(`drain`,d),e.on(`close`,(n,r)=>{c.delete(l),a.delete(e),u?.off(`drain`,d),t.callHook(`close`,l,{code:n,reason:r?.toString()})})});let c,l=()=>{c&&=(clearInterval(c),void 0)};return o>0&&(c=setInterval(()=>{for(let e of a){if(e._isAlive===!1){e.terminate();continue}e._isAlive=!1;try{e.ping(ht)}catch{}}},s),c.unref?.(),i.on(`close`,l)),i.on(`headers`,(e,t)=>{let n=t._upgradeHeaders;if(n)for(let[t,r]of new Headers(n))e.push(`${t}: ${r}`)}),{...r,close:async(e,t)=>{l(),await r.close(e,t)},handleUpgrade:async(e,n,r,a)=>{let o=a||new vt(e),s;try{s=await t.upgrade(o)}catch{return yt(n,new Response(`Internal Server Error`,{status:500}))}let{upgradeHeaders:c,endResponse:l,handled:u,context:d,namespace:f}=s;if(l)return yt(n,l);u||(e._request=o,e._upgradeHeaders=c,e._context=d,e._namespace=f,i.handleUpgrade(e,n,r,t=>{i.emit(`connection`,t,e)}))},closeAll:(e,t,n)=>{for(let r of a)n?r.terminate():r.close(e,t)}}};var _t=class extends dt{get remoteAddress(){return this._internal.nodeReq.socket?.remoteAddress}get context(){return this._internal.nodeReq._context}send(e,t){let n=rt(e),r=typeof n!=`string`;return this._internal.ws.send(n,{compress:t?.compress,binary:r,...t}),this._internal.ws.bufferedAmount}_publish(e,t,n){let r=rt(t),i=typeof r!=`string`,a={compress:n?.compress,binary:i,...n};for(let t of this._internal.peers)t!==this&&t._topics.has(e)&&t._internal.ws.send(r,a)}close(e,t){this._internal.ws.close(e,t)}terminate(){this._internal.ws.terminate()}ping(e){try{this._internal.ws.ping(e)}catch(e){this._internal.hooks.callHook(`error`,this,new pt(e))}}},vt=class extends mt{constructor(e){let t=e.headers.host||`localhost`,n=`${e.socket?.encrypted??e.headers[`x-forwarded-proto`]===`https`?`https`:`http`}://${t}${e.url}`;super(n,{headers:e.headers})}};async function yt(e,t){let n=[`HTTP/1.1 ${t.status||200} ${t.statusText||``}`,...[...t.headers.entries()].map(([e,t])=>`${e}: ${t}`)];if(e.write(n.join(`\r
`)+`\r
\r
`),t.body)for await(let n of t.body)e.write(n);return new Promise(t=>{e.end(()=>{e.destroy(),t()})})}const bt=[`upgrade`,`message`,`open`,`close`,`drain`,`error`,`ping`,`pong`];function xt(e,t){if(t.resolve)return t.resolve;if(bt.some(e=>typeof t[e]==`function`))return;let n=e.options.fetch;if(typeof n!=`function`)throw Error(`[crossws] server has no fetch handler to resolve WebSocket hooks from`);return e=>Promise.resolve(n(e)).then(t=>St(t,tt(e)))}function St(e,t){let n=e?.crossws;if(e instanceof Response)return n?(e.body?.cancel().catch(()=>{}),n):!e.ok&&e.status!==101&&!(e.status===426&&t)?(e.status===426&&st("[crossws] Received a 426 response with no WebSocket hooks attached. The app routed to a WebSocket handler but its hooks were lost in transit (a middleware likely rebuilt the response). Attach them to the request with `setWebSocketHooks(request, hooks)` instead, or upgrade the framework to a version that does."),{upgrade:()=>e}):(e.body?.cancel().catch(()=>{}),t);let r=e?.headers;if(!r)return n??t;let i=n??t,a=i?.upgrade;return{...i,async upgrade(e){let t=await a?.(e);return t instanceof Response?t:{...t,headers:Ct(r,t?.headers)}}}}function Ct(e,t){if(!t)return e;let n=new Headers(e);for(let[e,r]of new Headers(t))n.set(e,r);return n}function wt(e){return t=>{let n=gt({hooks:e,resolve:xt(t,e),...e.options?.node}),r=t.serve;t.serve=()=>(t.node?.server.on(`upgrade`,(e,t,r)=>{n.handleUpgrade(e,t,r,new ke({req:e,upgrade:{socket:t,head:r}}))}),r.call(t))}}const X=m||{},Z=e=>p?.postMessage(e),Tt=te(X.entry,X.virtual);let Et,Q;try{Et=await g(X.virtual),Q=await ne(X.entry,Tt)}catch(e){let t=e?.message||String(e);Z({event:`init-error`,error:t}),console.error(`[env-runner] worker init failed: ${t}`),process.exit(1)}const $=Me({port:0,hostname:`127.0.0.1`,silent:!0,fetch:e=>Q.fetch(e),middleware:Q.middleware,plugins:[...Q.plugins||[],...Q.websocket?[wt(Q.websocket)]:[]],gracefulShutdown:!1});await $.ready(),Q.upgrade&&$.node?.server?.on(`upgrade`,(e,t,n)=>{Q.upgrade({node:{req:e,socket:t,head:n}})}),Q.ipc&&await Q.ipc.onOpen?.({sendMessage:Z}),p?.postMessage({address:re($)}),p?.on(`message`,async e=>{if(e?.event===`shutdown`){Promise.resolve($.close(!0)).then(()=>Q.ipc?.onClose?.()).then(()=>{Et(),p?.postMessage({event:`exit`}),p?.close()});return}if(e?.event===`reload-module`){try{Q=await ie(X.entry,Q,Z,Tt),p?.postMessage({event:`module-reloaded`})}catch(e){p?.postMessage({event:`module-reloaded`,error:e?.message||String(e)})}return}if(e?.event===`invalidate-module`){ee(e,Z);return}if(e?.type===`ping`){p?.postMessage({type:`pong`,data:e.data});return}Q.ipc?.onMessage?.(e)});export{};