agent-device
Version:
Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.
27 lines • 103 kB
JavaScript
import{a as e,i as t,t as n}from"./rolldown-runtime.js";import{t as r}from"./undici.js";import i from"net";import a from"tls";import{domainToASCII as o}from"url";import s from"crypto";import c from"dns";var l=n(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),u=n(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=l(),n.destroy=u,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),d=n(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=u()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),f=n(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),p=n(((e,n)=>{let r=t(`os`),i=t(`tty`),a=f(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION);if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){return c(l(e,e&&e.isTTY))}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),m=n(((e,n)=>{let r=t(`tty`),i=t(`util`);e.init=f,e.log=c,e.formatArgs=o,e.save=l,e.load=d,e.useColors=a,e.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=p();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function a(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
`).join(`
`+a),e.push(i+`m+`+n.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+t+` `+e[0]}function s(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function c(...t){return process.stderr.write(i.formatWithOptions(e.inspectOpts,...t)+`
`)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function d(){return process.env.DEBUG}function f(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}n.exports=u()(e);let{formatters:m}=n.exports;m.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
`).map(e=>e.trim()).join(` `)},m.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),h=n(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?d():m()})),g=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(e,"__esModule",{value:!0}),e.req=e.json=e.toBuffer=void 0;let a=i(t(`http`)),o=i(t(`https`));async function s(e){let t=0,n=[];for await(let r of e)t+=r.length,n.push(r);return Buffer.concat(n,t)}e.toBuffer=s;async function c(e){let t=(await s(e)).toString(`utf8`);try{return JSON.parse(t)}catch(e){let n=e;throw n.message+=` (input: ${t})`,n}}e.json=c;function l(e,t={}){let n=((typeof e==`string`?e:e.href).startsWith(`https:`)?o:a).request(e,t),r=new Promise((e,t)=>{n.once(`response`,e).once(`error`,t).end()});return n.then=r.then.bind(r),n}e.req=l})),_=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=e&&e.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Agent=void 0;let o=i(t(`net`)),s=i(t(`http`)),c=t(`https`);a(g(),e);let l=Symbol(`AgentBaseInternalState`);e.Agent=class extends s.Agent{constructor(e){super(e),this[l]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==`boolean`)return e.secureEndpoint;if(typeof e.protocol==`string`)return e.protocol===`https:`}let{stack:t}=Error();return typeof t==`string`&&t.split(`
`).some(e=>e.indexOf(`(https.js:`)!==-1||e.indexOf(`node:https:`)!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new o.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],r=n.indexOf(t);r!==-1&&(n.splice(r,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?c.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let r={...t,secureEndpoint:this.isSecureEndpoint(t)},i=this.getName(r),a=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,r)).then(o=>{if(this.decrementSockets(i,a),o instanceof s.Agent)try{return o.addRequest(e,r)}catch(e){return n(e)}this[l].currentSocket=o,super.createSocket(e,t,n)},e=>{this.decrementSockets(i,a),n(e)})}createConnection(){let e=this[l].currentSocket;if(this[l].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[l].defaultPort??(this.protocol===`https:`?443:80)}set defaultPort(e){this[l]&&(this[l].defaultPort=e)}get protocol(){return this[l].protocol??(this.isSecureEndpoint()?`https:`:`http:`)}set protocol(e){this[l]&&(this[l].protocol=e)}}})),v=n((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.parseProxyResponse=void 0;let n=(0,t(h()).default)(`https-proxy-agent:parse-proxy-response`);function r(e){return new Promise((t,r)=>{let i=0,a=[];function o(){let t=e.read();t?u(t):e.once(`readable`,o)}function s(){e.removeListener(`end`,c),e.removeListener(`error`,l),e.removeListener(`readable`,o)}function c(){s(),n(`onend`),r(Error(`Proxy connection ended before receiving CONNECT response`))}function l(e){s(),n(`onerror %o`,e),r(e)}function u(c){a.push(c),i+=c.length;let l=Buffer.concat(a,i),u=l.indexOf(`\r
\r
`);if(u===-1){n(`have not received end of HTTP headers yet...`),o();return}let d=l.slice(0,u).toString(`ascii`).split(`\r
`),f=d.shift();if(!f)return e.destroy(),r(Error(`No header received from proxy CONNECT response`));let p=f.split(` `),m=+p[1],h=p.slice(2).join(` `),g={};for(let t of d){if(!t)continue;let n=t.indexOf(`:`);if(n===-1)return e.destroy(),r(Error(`Invalid header from proxy CONNECT response: "${t}"`));let i=t.slice(0,n).toLowerCase(),a=t.slice(n+1).trimStart(),o=g[i];typeof o==`string`?g[i]=[o,a]:Array.isArray(o)?o.push(a):g[i]=a}n(`got proxy server response: %o %o`,f,g),s(),t({connect:{statusCode:m,statusText:h,headers:g},buffered:l})}e.on(`error`,l),e.on(`end`,c),o()})}e.parseProxyResponse=r})),y=n((e=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.HttpsProxyAgent=void 0;let o=i(t(`net`)),s=i(t(`tls`)),c=a(t(`assert`)),l=a(h()),u=_(),d=t(`url`),f=v(),p=(0,l.default)(`https-proxy-agent`),m=e=>e.servername===void 0&&e.host&&!o.isIP(e.host)?{...e,servername:e.host}:e;var g=class extends u.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e==`string`?new d.URL(e):e,this.proxyHeaders=t?.headers??{},p(`Creating new HttpsProxyAgent instance: %o`,this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,``),r=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol===`https:`?443:80;this.connectOpts={ALPNProtocols:[`http/1.1`],...t?b(t,`headers`):null,host:n,port:r}}async connect(e,t){let{proxy:n}=this;if(!t.host)throw TypeError(`No "host" provided`);let r;n.protocol===`https:`?(p("Creating `tls.Socket`: %o",this.connectOpts),r=s.connect(m(this.connectOpts))):(p("Creating `net.Socket`: %o",this.connectOpts),r=o.connect(this.connectOpts));let i=typeof this.proxyHeaders==`function`?this.proxyHeaders():{...this.proxyHeaders},a=o.isIPv6(t.host)?`[${t.host}]`:t.host,l=`CONNECT ${a}:${t.port} HTTP/1.1\r\n`;if(n.username||n.password){let e=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;i[`Proxy-Authorization`]=`Basic ${Buffer.from(e).toString(`base64`)}`}i.Host=`${a}:${t.port}`,i[`Proxy-Connection`]||=this.keepAlive?`Keep-Alive`:`close`;for(let e of Object.keys(i))l+=`${e}: ${i[e]}\r\n`;let u=(0,f.parseProxyResponse)(r);r.write(`${l}\r\n`);let{connect:d,buffered:h}=await u;if(e.emit(`proxyConnect`,d),this.emit(`proxyConnect`,d,e),d.statusCode===200)return e.once(`socket`,y),t.secureEndpoint?(p(`Upgrading socket connection to TLS`),s.connect({...b(m(t),`host`,`path`,`port`),socket:r})):r;r.destroy();let g=new o.Socket({writable:!1});return g.readable=!0,e.once(`socket`,e=>{p(`Replaying proxy buffer for failed request`),(0,c.default)(e.listenerCount(`data`)>0),e.push(h),e.push(null)}),g}};g.protocols=[`http`,`https`],e.HttpsProxyAgent=g;function y(e){e.resume()}function b(e,...t){let n={},r;for(r in e)t.includes(r)||(n[r]=e[r]);return n}}))(),b={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function x(e){try{return new URL(e)}catch{return null}}function S(e){var t=(typeof e==`string`?x(e):e)||{},n=t.protocol,r=t.host,i=t.port;if(typeof r!=`string`||!r||typeof n!=`string`||(n=n.split(`:`,1)[0],r=r.replace(/:\d*$/,``),i=parseInt(i)||b[n]||0,!C(r,i)))return``;var a=w(n+`_proxy`)||w(`all_proxy`);return a&&a.indexOf(`://`)===-1&&(a=n+`://`+a),a}function C(e,t){var n=w(`no_proxy`).toLowerCase();return!n||n!==`*`&&n.split(/[,\s]/).every(function(n){if(!n)return!0;var r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?parseInt(r[2]):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.charAt(0)===`*`&&(i=i.slice(1)),!e.endsWith(i)):e!==i})}function w(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||``}var T=r();const ee={headersTimeout:36e5,bodyTimeout:36e5},E=65536,D=new class{constructor(){this.websocketAgents=new Map,this.fetch=async(e,t)=>this.hasProxyEnv()?fetch(e,{...t??{},dispatcher:this.getEnvHttpProxyAgent()}):fetch(e,t),this.fetchLongRequest=async(e,t)=>(this.longRequestDispatcher??=new T.EnvHttpProxyAgent(ee),fetch(e,{...t??{},dispatcher:this.longRequestDispatcher}))}getWebSocketAgent(e){if(!this.hasProxyEnv())return;let t=S(this.getWebSocketProxyLookupUrl(e));if(!t)return;let n=this.websocketAgents.get(t);if(!n){let e=new y.HttpsProxyAgent(t);this.websocketAgents.set(t,e),n=e}return n}connectTcp(e){let t=e.proxyLookupHost??e.host,n=S(`${e.proxyLookupProtocol}//${A(t,e.port)}`);return n?k(n,e):O(e)}getEnvHttpProxyAgent(){return this.envHttpProxyAgent??=new T.EnvHttpProxyAgent,this.envHttpProxyAgent}hasProxyEnv(){if(typeof process>`u`||!process.versions?.node)return!1;let e=process.env;return!!(e.http_proxy||e.HTTP_PROXY||e.https_proxy||e.HTTPS_PROXY)}getWebSocketProxyLookupUrl(e){let t=new URL(e);return t.protocol===`ws:`?t.protocol=`http:`:t.protocol===`wss:`&&(t.protocol=`https:`),t.toString()}};function O(e){let t=Date.now();return new Promise((n,r)=>{let a=!1,o=i.createConnection({host:e.host,port:e.port,allowHalfOpen:!0}),s=setTimeout(()=>{l(N(`connection to ${A(e.host,e.port)} timed out`,`ETIMEDOUT`))},e.timeoutMs);s.unref();let c=()=>{clearTimeout(s),o.removeListener(`connect`,d),o.removeListener(`error`,l),e.signal?.removeEventListener(`abort`,u)},l=e=>{a||(a=!0,c(),o.destroy(),r(e))},u=()=>l(N(`TCP connection cancelled`,`ECANCELED`)),d=()=>{a||(a=!0,o.pause(),c(),n({socket:o,connectMs:Date.now()-t,...o.remoteAddress===void 0?{}:{remoteAddress:o.remoteAddress}}))};o.once(`connect`,d),o.once(`error`,l),e.signal?.aborted?u():e.signal?.addEventListener(`abort`,u,{once:!0})})}function k(e,t){let n=Date.now();return new Promise((r,o)=>{let s=!1,c=Buffer.alloc(0),l;try{l=new URL(e)}catch{o(N(`invalid proxy URL: ${e}`,`EPROXY`));return}if(l.protocol!==`http:`&&l.protocol!==`https:`){o(N(`unsupported proxy protocol ${l.protocol}`,`EPROXY`));return}let u=l.port?Number(l.port):l.protocol===`https:`?443:80,d=j(l.hostname),f=l.protocol===`https:`?a.connect({host:d,port:u,rejectUnauthorized:!0,...i.isIP(d)?{}:{servername:d},ALPNProtocols:[`http/1.1`]}):i.createConnection({host:d,port:u,allowHalfOpen:!0});f.allowHalfOpen=!0;let p=l.protocol===`https:`?`secureConnect`:`connect`,m=setTimeout(()=>{g(N(`proxy connection to ${A(t.host,t.port)} timed out`,`ETIMEDOUT`))},t.timeoutMs);m.unref();let h=()=>{clearTimeout(m),f.removeListener(p,y),f.removeListener(`data`,b),f.removeListener(`end`,v),f.removeListener(`close`,v),f.removeListener(`error`,g),t.signal?.removeEventListener(`abort`,_)},g=e=>{s||(s=!0,h(),f.destroy(),o(e))},_=()=>g(N(`proxy connection cancelled`,`ECANCELED`)),v=()=>g(N(`proxy closed before completing CONNECT`,`ECONNRESET`)),y=()=>{let e=A(t.host,t.port),n=[`CONNECT ${e} HTTP/1.1`,`Host: ${e}`,`Proxy-Connection: Keep-Alive`];if(l.username||l.password){let e=M(l.username),t=M(l.password);n.push(`Proxy-Authorization: Basic ${Buffer.from(`${e}:${t}`,`utf8`).toString(`base64`)}`)}f.write(`${n.join(`\r
`)}\r\n\r\n`)},b=e=>{c=Buffer.concat([c,e]);let i=c.indexOf(`\r
\r
`);if(i<0){c.length>E&&g(N(`proxy CONNECT response headers exceeded 65536 bytes`,`EPROXY`));return}if(i+4>E){g(N(`proxy CONNECT response headers exceeded 65536 bytes`,`EPROXY`));return}let a=c.indexOf(`\r
`),o=c.subarray(0,a<0?i:a).toString(`latin1`),l=/^HTTP\/1\.[01] ([0-9]{3})(?: |$)/.exec(o);if(!l){g(N(`invalid proxy CONNECT response: ${o}`,`EPROXY`));return}let u=Number(l[1]);if(u<200||u>=300){g(N(`proxy CONNECT failed with status ${u}`,u===407?`EPROXYAUTH`:`EPROXYCONNECT`));return}s=!0,f.pause(),h();let d=c.subarray(i+4);d.length>0&&f.unshift(d),r({socket:f,connectMs:Date.now()-n,remoteAddress:t.host})};f.once(p,y),f.on(`data`,b),f.once(`end`,v),f.once(`close`,v),f.once(`error`,g),t.signal?.aborted?_():t.signal?.addEventListener(`abort`,_,{once:!0})})}function A(e,t){return`${i.isIP(e)===6?`[${e}]`:e}:${t}`}function j(e){return e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function M(e){try{return decodeURIComponent(e)}catch{return e}}function N(e,t){return Object.assign(Error(e),{code:t})}var P=n((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function n(e){}function r(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:r=n,onError:o=n,onRetry:s=n,onComment:c,maxBufferSize:l}=e,u=[],d=0,f=!0,p,m=``,h=0,g,_=!1;function v(e){if(_)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(f&&(f=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),u.length===0){let t=b(e);t!==``&&(u.push(t),d=t.length),y();return}if(e.indexOf(`
`)===-1&&e.indexOf(`\r`)===-1){u.push(e),d+=e.length,y();return}u.push(e);let t=u.join(``);u.length=0,d=0;let n=b(t);n!==``&&(u.push(n),d=n.length),y()}function y(){l!==void 0&&(d+m.length<=l||(_=!0,u.length=0,d=0,p=void 0,m=``,h=0,g=void 0,o(new t(`Buffered data exceeded max buffer size of ${l} characters`,{type:`max-buffer-size-exceeded`}))))}function b(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
`,t);for(;n!==-1;){if(t===n){h>0&&r({id:p,event:g,data:m}),p=void 0,m=``,h=0,g=void 0,t=n+1,n=e.indexOf(`
`,t);continue}let o=e.charCodeAt(t);if(i(e,t,o)){let i=e.charCodeAt(t+5)===32?t+6:t+5,a=e.slice(i,n);if(h===0&&e.charCodeAt(n+1)===10){r({id:p,event:g,data:a}),p=void 0,m=``,g=void 0,t=n+2,n=e.indexOf(`
`,t);continue}m=h===0?a:`${m}
${a}`,h++}else a(e,t,o)?g=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0:x(e,t,n);t=n+1,n=e.indexOf(`
`,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
`,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;x(e,t,i),t=i+1,e.charCodeAt(t-1)===13&&e.charCodeAt(t)===10&&t++}return e.slice(t)}function x(e,t,n){if(t===n){C();return}let r=e.charCodeAt(t);if(i(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);m=h===0?i:`${m}
${i}`,h++;return}if(a(e,t,r)){g=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);r.includes(`\0`)||(p=r);return}if(r===58){if(c){let r=e.slice(t,n);c(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let o=e.slice(t,n),s=o.indexOf(`:`);if(s===-1){S(o,``,o);return}let l=o.slice(0,s),u=o.charCodeAt(s+1)===32?2:1;S(l,o.slice(s+u),o)}function S(e,n,r){switch(e){case`event`:g=n||void 0;break;case`data`:m=h===0?n:`${m}
${n}`,h++;break;case`id`:n.includes(`\0`)||(p=n);break;case`retry`:/^\d+$/.test(n)?s(parseInt(n,10)):o(new t(`Invalid \`retry\` value: "${n}"`,{type:`invalid-retry`,value:n,line:r}));break;default:o(new t(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:n,line:r}))}}function C(){h>0&&r({id:p,event:g,data:m}),p=void 0,m=``,h=0,g=void 0}function w(e={}){if(e.consume&&u.length>0){let e=u.join(``);x(e,0,e.length)}f=!0,p=void 0,m=``,h=0,g=void 0,u.length=0,d=0,_=!1}return{feed:v,reset:w}}function i(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function a(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}e.ParseError=t,e.createParser=r}));const F=e(n((e=>{Object.defineProperty(e,"__esModule",{value:!0});var n=t(`node:stream`),r=P();let i=`connecting`,a=`open`,o=`closed`,s=()=>{};function c(e,{getStream:t}){let n=typeof e==`string`||e instanceof URL?{url:e}:e,{onMessage:c,onComment:u=s,onConnect:d=s,onDisconnect:f=s,onScheduleReconnect:p=s}=n,{fetch:m,url:h,initialLastEventId:g}=l(n),_={...n.headers},v=[],y=c?[c]:[],b=e=>y.forEach(t=>t(e)),x=r.createParser({onEvent:N,onRetry:P,onComment:u}),S,C=h.toString(),w=new AbortController,T=g,ee=2e3,E,D=o;return O(),{close:k,connect:O,[Symbol.iterator]:()=>{throw Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:A,get lastEventId(){return T},get url(){return C},get readyState(){return D}};function O(){S||=(D=i,w=new AbortController,m(h,F()).then(M).catch(e=>{S=null,!(e.name===`AbortError`||e.type===`aborted`||w.signal.aborted)&&j()}))}function k(){D=o,w.abort(),x.reset(),clearTimeout(E),v.forEach(e=>e())}function A(){let e=[],t=[];function n(){return new Promise(n=>{let r=t.shift();r?n({value:r,done:!1}):e.push(n)})}let r=function(n){let r=e.shift();r?r({value:n,done:!1}):t.push(n)};function i(){for(y.splice(y.indexOf(r),1);e.shift(););for(;t.shift(););}function a(){let t=e.shift();t&&(t({done:!0,value:void 0}),i())}return v.push(a),y.push(r),{next(){return D===o?this.return():n()},return(){return i(),Promise.resolve({done:!0,value:void 0})},throw(e){return i(),Promise.reject(e)},[Symbol.asyncIterator](){return this}}}function j(){p({delay:ee}),!w.signal.aborted&&(D=i,E=setTimeout(O,ee))}async function M(e){d(),x.reset();let{body:n,redirected:r,status:i}=e;if(i===204){f(),k();return}if(!n)throw Error(`Missing response body`);r&&(C=e.url);let o=t(n),s=new TextDecoder,c=o.getReader(),l=!0;D=a;do{let{done:e,value:t}=await c.read();t&&x.feed(s.decode(t,{stream:!e})),e&&(l=!1,S=null,x.reset(),j(),f())}while(l)}function N(e){typeof e.id==`string`&&(T=e.id),b(e)}function P(e){ee=e}function F(){let{mode:e,credentials:t,body:r,method:i,redirect:a,referrer:o,referrerPolicy:s}=n;return{mode:e,credentials:t,body:r,method:i,redirect:a,referrer:o,referrerPolicy:s,headers:{Accept:`text/event-stream`,..._,...T?{"Last-Event-ID":T}:void 0},cache:`no-store`,signal:w.signal}}}function l(e){let t=e.fetch||globalThis.fetch;if(!u(t))throw Error(`No fetch implementation provided, and one was not found on the global object.`);if(typeof AbortController!=`function`)throw Error(`Missing AbortController implementation`);let{url:n,initialLastEventId:r}=e;if(typeof n!=`string`&&!(n instanceof URL))throw Error(`Invalid URL provided - must be string or URL instance`);if(typeof r!=`string`&&r!==void 0)throw Error(`Invalid initialLastEventId provided - must be string or undefined`);return{fetch:t,url:n,initialLastEventId:r}}function u(e){return typeof e==`function`}let d={getStream:p};function f(e){return c(e,d)}function p(e){if(`getReader`in e)return e;if(typeof e.pipe!=`function`||typeof e.on!=`function`)throw Error(`Invalid response body, expected a web or node.js stream`);if(typeof n.Readable.toWeb!=`function`)throw Error("Node.js 18 or higher required (`Readable.toWeb()` not defined)");return n.Readable.toWeb(n.Readable.from(e))}e.CLOSED=o,e.CONNECTING=i,e.OPEN=a,e.createEventSource=f}))(),1).createEventSource;var I=n(((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:()=>{}}})),te=n(((e,n)=>{let{EMPTY_BUFFER:r}=I(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(n.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=t(`bufferutil`);n.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},n.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),ne=n(((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])}}}})),re=n(((e,n)=>{let r=t(`zlib`),i=te(),a=ne(),{kStatusCode:o}=I(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;n.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,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(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[d];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){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),L=n(((e,n)=>{let{isUtf8:r}=t(`buffer`),{hasBlob:i}=I(),a=[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 o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(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 c(e){return i&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(n.exports={isBlob:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)n.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=t(`utf-8-validate`);n.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),R=n(((e,n)=>{let{Writable:r}=t(`stream`),i=re(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=I(),{concat:l,toArrayBuffer:u,unmask:d}=te(),{isValidStatusCode:f,isValidUTF8:p}=L(),m=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0||e.allowSynchronousEvents,this._binaryType=e.binaryType||a[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[c]=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 m(t.buffer,t.byteOffset+e,t.length-e),new m(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 m(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[i.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=o;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&&d(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[i.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`?l(n,t):this._binaryType===`arraybuffer`?u(l(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=l(n,t);if(!this._skipUTF8Validation&&!p(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,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(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[s]=r,a}}})),ie=n(((e,n)=>{let{Duplex:r}=t(`stream`),{randomFillSync:i}=t(`crypto`),{types:{isUint8Array:a}}=t(`util`),o=re(),{EMPTY_BUFFER:s,kWebSocket:c,NOOP:l}=I(),{isBlob:u,isValidStatusCode:d}=L(),{mask:f,toBuffer:p}=te(),m=Symbol(`kByteLength`),h=Buffer.alloc(4),g=8192,_,v=g;n.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=l,this[c]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||h,t.generateMask?t.generateMask(n):(v===g&&(_===void 0&&(_=Buffer.alloc(g)),i(_,0,g),v=0),n[0]=_[v++],n[1]=_[v++],n[2]=_[v++],n[3]=_[v++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[m]!==void 0?s=t[m]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?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]:r?(f(e,n,l,a,s),[l]):(f(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=s;else if(typeof t!=`number`||!d(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`)o.write(n,2);else if(a(n))o.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[m]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,c),i):this.enqueue([this.dispatch,o,!1,c,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};u(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):u(t)?(i=t.size,a=!1):(t=p(t),i=t.length,a=p.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[m]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};u(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[o.extensionName],i=t.binary?2:1,a=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):u(e)?(s=e.size,c=!1):(e=p(e),s=e.length,c=p.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=s>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[m]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:a};u(e)?this._state===0?this.getBlobData(e,this._compress,l,n):this.enqueue([this.getBlobData,e,this._compress,l,n]):this._state===0?this.dispatch(e,this._compress,l,n):this.enqueue([this.dispatch,e,this._compress,l,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[m],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(y,this,e,i);return}this._bufferedBytes-=r[m];let a=p(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[o.extensionName];this._bufferedBytes+=r[m],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=Error(`The socket was closed while data was being compressed`);y(this,e,i);return}this._bufferedBytes-=r[m],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][m],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][m],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 y(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 b(e,t,n){y(e,t,n),e.onerror(t)}})),ae=n(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=I(),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)}})),z=n(((e,t)=>{let{tokenChars:n}=L();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}})),oe=n(((e,n)=>{let r=t(`events`),i=t(`https`),a=t(`http`),o=t(`net`),s=t(`tls`),{randomBytes:c,createHash:l}=t(`crypto`),{Duplex:u,Readable:d}=t(`stream`),{URL:f}=t(`url`),p=re(),m=R(),h=ie(),{isBlob:g}=L(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:x,kListener:S,kStatusCode:C,kWebSocket:w,NOOP:T}=I(),{EventTarget:{addEventListener:ee,removeEventListener:E}}=ae(),{format:D,parse:O}=z(),{toBuffer:k}=te(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,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]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.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 m({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 h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[w]=this,a[w]=this,t[w]=this,i.on(`conclude`,V),i.on(`drain`,H),i.on(`error`,U),i.on(`message`,G),i.on(`ping`,le),i.on(`pong`,K),a.onerror=J,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,Y),t.on(`data`,X),t.on(`end`,de),t.on(`error`,fe),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[p.extensionName]&&this._extensions[p.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){B(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())}),ue(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){ce(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||y,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){ce(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||y,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){ce(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){B(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:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,"OPEN",{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,"CLOSING",{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,"CLOSED",{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:M.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[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),P.prototype.addEventListener=ee,P.prototype.removeEventListener=E,n.exports=P;function F(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:j[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ne(e,t);return}let h=u?443:80,g=c(16).toString(`base64`),_=u?i.request:a.request,y=new Set,x;if(o.createConnection=o.createConnection||(u?se:oe),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new p({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers[`Sec-WebSocket-Extensions`]=D({[p.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.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),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:!e._originalIpc&&s.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&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=_(o);o.timeout&&S.on(`timeout`,()=>{B(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,ne(e,t))}),S.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){B(e,S,`Maximum redirects exceeded`);return}S.abort();let i;try{i=new f(a,t)}catch{ne(e,SyntaxError(`Invalid URL: ${a}`));return}F(e,i,n,r)}else e.emit(`unexpected-response`,S,i)||B(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){B(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(g+b).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){B(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?y.size&&(c=`Server sent no subprotocol`):y.size?y.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){B(e,n,c);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){B(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{B(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){B(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[p.extensionName])}catch{B(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=x}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(S,e):S.end()}function ne(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function oe(e){return e.path=e.socketPath,o.connect(e)}function se(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function B(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,B),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ce(e,t,n){if(t){let n=g(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function V(e,t){let n=this[w];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[w]!==void 0&&(n._socket.removeListener(`data`,X),process.nextTick(q,n._socket),e===1005?n.close():n.close(e,t))}function H(){let e=this[w];e.isPaused||e._socket.resume()}function U(e){let t=this[w];t._socket[w]!==void 0&&(t._socket.removeListener(`data`,X),process.nextTick(q,t._socket),t.close(e[C])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function W(){this[w].emitClose()}function G(e,t){this[w].emit(`message`,e,t)}function le(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,T),t.emit(`ping`,e)}function K(e){this[w].emit(`pong`,e)}function q(e){e.resume()}function J(e){let t=this[w];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,ue(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ue(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Y(){let e=this[w];if(this.removeListener(`close`,Y),this.removeListener(`data`,X),this.removeListener(`end`,de),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[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,W),e._receiver.on(`finish`,W))}function X(e){this[w]._receiver.write(e)||this.pause()}function de(){let e=this[w];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function fe(){let e=this[w];this.removeListener(`error`,fe),this.on(`error`,T),e&&(e._readyState=P.CLOSING,this.destroy())}})),se=n(((e,n)=>{oe();let{Duplex:r}=t(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...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||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&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`,a),s.on(`error`,o),s}n.exports=s})),B=n(((e,t)=>{let{tokenChars:n}=L();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}})),ce=n(((e,n)=>{let r=t(`events`),i=t(`http`),{Duplex:a}=t(`stream`),{createHash:o}=t(`crypto`),s=z(),c=re(),l=B(),u=oe(),{CLOSE_TIMEOUT:d,GUID:f,kWebSocket:p}=I(),m=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{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:d,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...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=i.createServer((e,t)=>{let n=i.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=h(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(g,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(g,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{g(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`,_);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){y(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){y(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!m.test(i)){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){y(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){v(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{y(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),p[c.extensionName]=n)}catch{y(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===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 v(t,o||401,s,c);this.completeUpgrade(p,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return v(t,401)}this.completeUpgrade(p,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[p])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return v(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+f).digest(`base64`)}`],d=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}`),d._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
`).join(`\r
`)),i.removeListener(`error`,_),d.setSocket(i,a,{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(d),d.on(`close`,()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(g,this)})),l(d,r)}};function h(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 g(e){e._state=2,e.emit(`close`)}function _(){this.destroy()}function v(e,t,n,r){n||=i.STATUS_CODES[t],r={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...r},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join(`\r
`)+`\r
\r
`+n)}function y(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,y),e.emit(`wsClientError`,r,n,t)}else v(n,r,i,a)}}));se(),z(),re(),R(),ie(),B();var V=e(oe(),1);ce();var H=class extends Error{constructor(e){super(e),this.name=`DestinationTunnelProtocolError`}};function U(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new H(`${t} must be an object`);return e}function W(e,t){let n=e[t];if(!Array.isArray(n))throw new H(`${t} must be an array`);return n}function G(e,t){let n=e[t];if(typeof n!=`string`)throw new H(`${t} must be a string`);return n}function le(e,t){let n=G(e,t);if(n.length===0)throw new H(`${t} must not be empty`);return n}function K(e,t){let n=e[t];if(typeof n!=`boolean`)throw new H(`${t} must be a boolean`);return n}function q(e,t){let n=e[t];if(!Number.isInteger(n))throw new H(`${t} must be an integer`);return n}function J(e,t){let n=e[t];if(typeof n!=`number`||!Number.isFinite(n))throw new H(`${t} must be a finite number`);return n}function ue(e,t){if(!Number.isSafeInteger(e)||e<0)throw new H(`${t} must be a safe non-negative integer`);return e}function Y(e,t){return e[t]===void 0?{}:{[t]:G(e,t)}}function X(e,t){return e[t]===void 0?{}:{[t]:K(e,t)}}function de(e,t){let n=e[t];if(n===void 0)return{};if(!Number.isInteger(n)||n<0)throw new H(`${t} must be a non-negative integer`);return{[t]:n}}function fe(e){if(Buffer.isBuffer(e))return e;if(Array.isArray(e))return Buffer.concat(e);if(e instanceof ArrayBuffer)return Buffer.from(e);throw new H(`unsupported WebSocket payload type`)}function pe(e,t){let n=new URL(e);if(n.protocol!==`https:`&&n.protocol!==`http:`&&n.protocol!==`wss:`&&n.protocol!==`ws:`)throw Error(`Unsupported apiUrl protocol: ${n.protocol}`);return n.pathname=`${be(n.pathname)}/${t}`,n.search=``,n.hash=``,n}function me(e,t){let n=pe(e,t);return n.protocol=n.protocol===`wss:`?`https:`:n.protocol===`ws:`?`http:`:n.protocol,n}function he(e){return ge(pe(e,`tunnel`))}function ge(e){return e.protocol=e.protocol===`https:`||e.protocol===`wss:`?`wss:`:`ws:`,e.toString()}function _e(e){return me(e,`tunnel/status`)}function ve(e,t){return me(e,`tunnel/${encodeURIComponent(t)}`)}function ye(e,t,n=0,r){let i=typeof n==`number`?n:0,a=typeof n==`string`?n:r;if(!Number.isSafeInteger(i)||i<0)throw Error(`afterSequence must be a safe non-negative integer`);let o=new URL(e);return o.protocol=o.protocol===`wss:`?`https:`:o.protocol===`ws:`?`http:`:o.protocol,o.pathname=`${be(o.pathname)}/${encodeURIComponent(t)}/inspection/events`,o.search=``,i>0&&o.searchParams.set(`after-sequence`,String(i)),a!==void 0&&o.searchParams.set(`token`,a),o.hash=``,o.toString()}function be(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function xe(e,t,n,r={}){let i=!0,a=0,o=e=>{je(r.onError,e)},s=(e,t)=>{je(r.onEvent,{type:`gap`,sequence:t,data:{fromSequence:e,toSequence:t,message:`Inspection stream gap: missing sequences ${e}-${t}`}},o)},c=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new H(`inspection sequence must be a safe non-negative integer`);if(e<=a)throw new H(`inspection sequence ${e} is not newer than ${a}`);if(t){if(t.fromSequence!==a+1||t.toSequence!==e||t.fromSequence>t.toSequence)throw new H(`invalid inspection gap range`);s(t.fromSequence,t.toSequence)}else e>a+1&&s(a+1,e-1);a=e},l=ye(e,t,a,n),u=F({url:l,fetch:D.fetch.bind(D),onMessage:e=>{if(i)try{let t=Se(e.id,e.data);t.type===`gap`?c(t.sequence,t.data):(c(t.sequence),je(r.onEvent,t,o))}catch(e){o(e instanceof Error?e:Error(String(e)))}},onDisconnect:()=>{i&&o(Error(`Inspection SSE disconnected; reconnecting`))}});return{close:()=>{i&&(i=!1,u.close())}}}function Se(e,t){if(e===void 0||!/^(0|[1-9]\d*)$/.test(e))throw new H(`inspection SSE event ID must be an unsigned integer`);let n=Number(e);if(!Number.isSafeInteger(n))throw new H(`inspection sequence must be a safe non-negative integer`);let r;try{r=JSON.parse(t)}catch{throw new H(`inspection SSE data must be valid JSON`)}let i=U(r,`inspection event`);if(i.sequence!==void 0&&ue(i.sequence,`inspection sequence`)!==n)throw new H(`inspection SSE event ID does not match envelope sequence`);if(G(i,`type`)!==`body`)return Ce(i,n);let a=ke(i),o=U(i.data,`inspection body data`),s=G(o,`direction`);if(s!==`request`&&s!==`response`)throw new H(`invalid inspection body direction`);if(G(o,`encoding`)!==`base64`)throw new H(`inspection body encoding must be base64`);return{type:`body`,sequence:n,requestId:a,direction:s,body:Me(G(o,`chunk`))}}function Ce(e,t){let n=G(e,`type`),r=U(e.data,`inspection metadata data`);switch(n){case`complete`:return{type:n,sequence:t,requestId:ke(e),data:we(r)};case`gap`:{let e=ue(r.fromSequence,`inspection sequence`),i=ue(r.toSequence,`inspection sequence`);return{type:n,sequence:t,data:{fromSequence:e,toSequence:i,message:`Inspection stream gap: missing sequences ${e}-${i}`}}}case`inspection_error`:return{type:n,sequence:t,...e.requestId===void 0?{}:{requestId:ke(e)},data:{...r,message:G(r,`message`)}};default:throw new H(`unknown inspection metadata type ${n}`)}}function we(e){return Ae(e,`startedDateTime`),J(e,`time`),Ee(U(e.request,`inspection request`)),De(U(e.response,`inspection response`)),Te(U(e._limrun,`inspection extension`)),e}function Te(e){if(G(e,`tunnelId`),G(e,`selectorId`),Y(e,`error`),X(e,`requestBodyTruncated`),X(e,`responseBodyTruncated`),e.responseTrailers!==void 0&&Oe(e.responseTrailers,`response trailers`),e.responseCookieSameSite!==void 0)for(let t of W(e,`responseCookieSameSite`)){let e=U(t,`response cookie same-site metadata`);ue(e.index,`response cookie same-site index`),G(e,`value`)}}function Ee(e){G(e,`method`),G(e,`url`),G(e,`httpVersion`),Oe(e.headers,`request headers`),Oe(e.queryString,`request query string`),Oe(e.cookies,`request cookies`),J(e,`headersSize`),J(e,`bodySize`),e.postData!==void 0&&U(e.postData,`request post data`)}function De(e){J(e,`status`),G(e,`statusText`),G(e,`httpVersion`),Oe(e.headers,`response headers`),Oe(e.cookies,`response cookies`);let t=U(e.content,`response content`);J(t,`size`),G(t,`mimeType`),G(e,`redirectURL`),J(e,`headersSize`),J(e,`bodySize`)}function Oe(e,t){if(!Array.isArray(e))throw new H(`${t} must be an array`);for(let n of e){let e=U(n,t);G(e,`name`),G(e,`value`)}}function ke(e){let t=G(e,`requestId`);if(!t)throw new H(`inspection request ID must not be empty`);return t}function Ae(e,t){let n=G(e,t);if(!Number.isFinite(Date.parse(n)))throw new H(`${t} must be an ISO date-time`);return n}function je(e,t,n){if(e)try{e(t)}catch(e){n?.(e instanceof Error?e:Error(String(e)))}}function Me(e){try{if(e.length%4!=0)throw Error(`invalid base64 length`);let t=atob(e);if(btoa(t)!==e)throw Error(`non-canonical base64`);return Uint8Array.from(t,e=>e.charCodeAt(0))}catch{throw new H(`inspection body chunk must be valid base64`)}}const Ne=10485760;var Z=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`DestinationTunnelSelectorError`}};function Pe(e,t){if(it(e),t.length===0)throw new H(`tunnel data frame must include a payload`);let n=Buffer.allocUnsafe(4+t.length);return n.writeUInt32BE(e,0),t.copy(n,4),n}function Fe(e){if(e.length<=4)throw new H(`tunnel data frame must include a payload`);return{connId:e.readUInt32BE(0),payload:e.subarray(4)}}function Ie(e,t={}){if(!Array.isArray(e))throw new Z(`invalid_host`,`tunnel selectors must be an array`);if(e.length===0)throw new Z(`empty`,`at least one tunnel selector is required`);let n=[],r=new Set,i=0,a=0;for(let o of e){let e=Ke(o,t.minRoutePort);if(e.route?i++:a++,i>10)throw new Z(`too_many`,`at most 10 exact tunnel selectors are allowed`);if(a>64)throw new Z(`too_many`,`at most 64 domain tunnel selectors are allowed`);if(r.has(e.value))throw new Z(`duplicate`,`duplicate tunnel selector ${e.value}`);r.add(e.value),n.push(e.value)}return n}function Le(e,t={}){let n=Ie(e,t),r=[],i=[];for(let e of n){let n=Ke(e,t.minRoutePort);n.route?r.push(n.route):i.push(n.domain)}return{...r.length>0?{routes:r}:{},...i.length>0?{domains:i}:{}}}function Re(e,t=Be()){let n=Ie(e),r=ze(t),i=[`"version":1`,`"selectors":[${n.map(e=>JSON.stringify(e)).join(`,`)}]`];return i.push(`"inspection":{"enabled":${r.enabled},"captureBodies":${r.captureBodies},"maxBodyBytes":${r.maxBodyBytes},"persist":${r.persist},"ttlSeconds":${r.ttlSeconds}}`),s.createHash(`sha256`).update(`{${i.join(`,`)}}`,`utf8`).digest(`hex`)}function ze(e){let t=e.enabled??!1,n=e.captureBodies??!1,r=e.maxBodyBytes??10485760,i=e.persist??!1,a=e.ttlSeconds??259200;if(n&&!t)throw new H(`captureBodies requires inspection to be enabled`);if(i&&!t)throw new H(`persist requires inspection to be enabled`);if(!Number.isInteger(r)||r<1||r>67108864)throw new H(`maxBodyBytes must be an integer between 1 and 67108864`);if(!Number.isInteger(a)||a<1||a>2592e3)throw new H(`ttlSeconds must be an integer between 1 and 2592000`);return{enabled:t,captureBodies:n,maxBodyBytes:r,persist:i,ttlSeconds:a}}function Be(){return ze({enabled:!1,captureBodies:!1})}function Ve(e,t){let n=t.toLowerCase();if(e.startsWith(`*.`)){let t=e.slice(2);return n.length>t.length+1&&n.endsWith(`.${t}`)}return n===e}function He(e,t){let n=Ie(t),r=/^selector-([1-9]\d*)$/.exec(e.selectorId),i=r?.[1]?Number(r[1])-1:-1,a=()=>{throw new H(`server requested undeclared selector ${e.selectorId} ${e.host}:${e.port}`)};i<0&&a(),e.port===53&&a();let o=n[i];if(o===void 0)return a();let s=Ke(o);return s.route?((e.host!==s.route.host||e.port!==s.route.port)&&a(),`route`):(Ve(s.domain,e.host)||a(),`domain`)}function Ue(e){if(e.version!==1)throw new H(`unsupported tunnel version ${e.version}`)}function We(e){let t=U(e,`tunnel control message`),n=G(t,`type`);switch(n){case`start`:{let e=q(t,`version`);if(e!==1)throw new H(`unsupported tunnel version ${e}`);let r=Ie(W(t,`selectors`).map(e=>{if(typeof e!=`string`)throw new H(`tunnel selector must be a string`);return e})),i=Qe(t),{resetsInactivityTimeout:a}=X(t,`resetsInactivityTimeout`);return JSON.stringify({type:n,version:e,selectors:r,inspection:i,window:nt(t),...Y(t,`name`),...a===!1?{resetsInactivityTimeout:a}:{}})}case`openOk`:return JSON.stringify({type:n,connId:Q(t),transport:et(t),window:nt(t)});case`fin`:return JSON.stringify({type:n,connId:Q(t)});case`openFail`:case`reset`:return JSON.stringify({type:n,connId:Q(t),reason:G(t,`reason`),...Y(t,`osCode`)});case`windowUpdate`:return JSON.stringify({type:n,connId:Q(t),increment:rt(t)});default:throw new H(`unknown tunnel control message type ${n}`)}}function Ge(e){let t=U(e,`tunnel control message`),n=G(t,`type`);switch(n){case`ready`:return{type:n,version:q(t,`version`),tunnelId:G(t,`tunnelId`),selectors:W(t,`selectors`).map((e,t)=>Xe(e,`selector-${t+1}`)),configHash:G(t,`configHash`),...Y(t,`name`)};case`open`:return{type:n,connId:Q(t),selectorId:G(t,`selectorId`),host:G(t,`host`),port:tt(t,`port`),transport:$e(t),window:nt(t)};case`fin`:return{type:n,connId:Q(t)};case`reset`:return{type:n,connId:Q(t),reason:G(t,`reason`),...Y(t,`osCode`)};case`windowUpdate`:return{type:n,connId:Q(t),increment:rt(t)};case`error`:return{type:n,code:G(t,`code`)};default:throw new H(`unknown tunnel control message type ${n}`)}}function Ke(e,t=1){if(typeof e!=`string`||e.length===0)throw new Z(`empty`,`tunnel selector must not be empty`);if(!e.startsWith(`[`)&&!e.includes(`:`)){let t=Je(e);return{value:t,domain:t}}let n,r;if(e.startsWith(`[`)){let t=/^\[([^\]]+)\]:(\d+)$/.exec(e);if(!t?.[1]||!t[2])throw new Z(`invalid_host`,`invalid tunnel selector ${e}`);n=t[1],r=t[2]}else{let t=e.lastIndexOf(`:`);if(t<=0||e.indexOf(`:`)!==t)throw new Z(`invalid_host`,`invalid tunnel selector ${e}`);n=e.slice(0,t),r=e.slice(t+1)}if(!/^\d+$/.test(r))throw new Z(`invalid_port`,`invalid tunnel selector port ${r}`);let i=qe({host:n,port:Number(r)},t);return{value:`${i.host.includes(`:`)?`[${i.host}]`:i.host}:${i.port}`,route:i}}function qe(e,t=1){if(!Number.isInteger(e.port)||e.port<t||e.port>65535||e.port===53)throw new Z(`invalid_port`,`invalid tunnel route port ${e.port}`);if(Buffer.byteLength(e.host,`utf8`)===e.host.length&&e.host.toLowerCase()===`localhost`)return{host:`localhost`,port:e.port};let n=i.isIP(e.host);if(n===4)return{host:e.host,port:e.port};if(n===6){let t=new URL(`http://[${e.host}]/`).hostname.slice(1,-1);if(t!==`::1`&&/^::(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4}$/.test(t))throw new Z(`invalid_host`,`invalid tunnel route host ${e.host}`);return{host:Ye(t),port:e.port}}throw new Z(`invalid_host`,`invalid tunnel route host ${e.host}`)}function Je(e){let t=()=>{throw new Z(`invalid_domain`,`invalid tunnel domain ${e}`)};(typeof e!=`string`||e.length===0||e.length>260)&&t(),Buffer.byteLength(e,`utf8`)!==e.length&&t();let n=e.toLowerCase(),r=n.startsWith(`*.`),a=r?n.slice(2):n;(a.length===0||a.length>253)&&t(),a.includes(`*`)&&t(),(a.endsWith(`.`)||a.startsWith(`.`))&&t(),i.isIP(a)!==0&&t(),a===`localhost`&&t(),o(a)!==a&&t();let s=a.split(`.`);for(let e of s)(e.length===0||e.length>63)&&t(),/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)||t();let c=s[s.length-1];return c!==void 0&&/^\d+$/.test(c)&&t(),r?`*.${a}`:a}function Ye(e){let t=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(e);if(!t?.[1]||!t[2])return e;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);return`${n>>8}.${n&255}.${r>>8}.${r&255}`}function Xe(e,t){let n=U(e,`tunnel selector`),r=G(n,`id`);if(r!==t)throw new H(`invalid tunnel selector id ${r}`);let i=G(n,`kind`);if(i!==`route`&&i!==`domain`)throw new H(`invalid tunnel selector kind ${i}`);let a={id:r,kind:i,value:G(n,`value`)};return n.binds!==void 0&&(a.binds=W(n,`binds`).map(Ze)),a}function Ze(e){let t=U(e,`tunnel bind report`),n=G(t,`status`);if(n!==`ok`&&n!==`conflict`&&n!==`error`)throw new H(`invalid tunnel bind status ${n}`);return{address:G(t,`address`),status:n,...Y(t,`osCode`)}}function Qe(e){let t=U(e.inspection,`inspection`);return ze({enabled:K(t,`enabled`),captureBodies:K(t,`captureBodies`),maxBodyBytes:q(t,`maxBodyBytes`),persist:K(t,`persist`),ttlSeconds:q(t,`ttlSeconds`)})}function $e(e){let t=U(e.transport,`transport`),n=G(t,`type`);if(n===`tcp`)return{type:n};if(n===`tls`){let e=G(t,`serverName`);if(e.length===0)throw new H(`TLS transport requires serverName`);return{type:n,serverName:e,alpnProtocols:W(t,`alpnProtocols`).map(e=>{if(typeof e!=`string`||e.length===0)throw new H(`alpnProtocols must contain non-empty strings`);return e})}}throw new H(`unsupported tunnel transport ${n}`)}function et(e){let t=U(e.transport,`transport`),n=G(t,`type`);if(n!==`tcp`&&n!==`tls`)throw new H(`unsupported tunnel transport ${n}`);return{type:n,...Y(t,`alpnProtocol`),...Y(t,`remoteAddress`),...de(t,`dnsMs`),...de(t,`connectMs`),...de(t,`tlsMs`)}}function tt(e,t){let n=q(e,t);if(n<1||n>65535)throw new H(`${t} must be between 1 and 65535`);return n}function nt(e){let t=q(e,`window`);if(t<1||t>67108864)throw new H(`window must be an integer between 1 and 67108864`);return t}function rt(e){let t=q(e,`increment`);if(t<1||t>2147483647)throw new H(`increment must be an integer between 1 and 2147483647`);return t}function Q(e){let t=q(e,`connId`);return it(t),t}function it(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new H(`connId must be an unsigned 32-bit integer`)}const $=new i.BlockList;$.addSubnet(`0.0.0.0`,8,`ipv4`),$.addSubnet(`127.0.0.0`,8,`ipv4`),$.addSubnet(`169.254.0.0`,16,`ipv4`),$.addSubnet(`224.0.0.0`,3,`ipv4`),$.addSubnet(`::`,96,`ipv6`),$.addSubnet(`fe80::`,10,`ipv6`),$.addSubnet(`ff00::`,8,`ipv6`),$.addSubnet(`::ffff:0.0.0.0`,104,`ipv6`),$.addSubnet(`::ffff:127.0.0.0`,104,`ipv6`),$.addSubnet(`::ffff:169.254.0.0`,112,`ipv6`),$.addSubnet(`::ffff:224.0.0.0`,99,`ipv6`);function at(e){return{enabled:!0,captureBodies:!1,...e??{}}}function ot(e,t){return{selectors:e.selectors,inspection:at(e.inspection),...e.onInspectionEvent?{onInspectionEvent:e.onInspectionEvent}:{},...e.onInspectionError?{onInspectionError:e.onInspectionError}:{},...e.window===void 0?{}:{window:e.window},...e.resetsInactivityTimeout===void 0?{}:{resetsInactivityTimeout:e.resetsInactivityTimeout},logLevel:e.logLevel??t}}var st=class extends Error{constructor(e){super(`destination tunnel failed: ${e}`),this.code=e}};async function ct(e,t,n){let r=Ie(n.selectors),i=Le(r).routes??[],o=ze(n.inspection??Be()),s=n.logLevel??`info`,l=dt(n.window??1048576,`window`),u=dt(n.maxConnections??64,`maxConnections`),d=dt(n.maxPendingBytesPerConnection??16777216,`maxPendingBytesPerConnection`),f=dt(n.maxTotalPendingBytes??16777216,`maxTotalPendingBytes`),p=dt(n.maxBufferedBytes??4194304,`maxBufferedBytes`),m=dt(n.connectTimeoutMs??1e4,`connectTimeoutMs`),h=dt(n.handshakeTimeoutMs??15e3,`handshakeTimeoutMs`),g=dt(n.livenessTimeoutMs??9e4,`livenessTimeoutMs`),_=Math.min(3e4,Math.max(1,Math.floor(g/3))),v=p/4,y=p+Math.max(65536,Math.floor(p/4)),b={debug:(...e)=>{s===`debug`&&console.log(`[DestinationTunnel]`,...e)},info:(...e)=>{(s===`info`||s===`debug`)&&console.log(`[DestinationTunnel]`,...e)},warn:(...e)=>{(s===`warn`||s===`info`||s===`debug`)&&console.warn(`[DestinationTunnel]`,...e)},error:(...e)=>{s!==`none`&&console.error(`[DestinationTunnel]`,...e)}};return new Promise((s,x)=>{let S=new Map,C=new Map,w=new Set,T=new URL(e),ee=D.getWebSocketAgent(T.toString()),E=new V.default(T.toString(),{headers:{Authorization:`Bearer ${t}`},...ee?{agent:ee}:{},perMessageDeflate:!1}),O=`connecting`,k,A,j,M=!1,N=!1,P,F=!1,I=0,te=e=>{if(O!==e){O=e;for(let t of w)try{t(e)}catch(e){b.error(`Connection state callback failed:`,e)}}},ne=()=>O,re=e=>(w.add(e),()=>w.delete(e)),L=e=>{let t=C.get(e);t&&clearTimeout(t);let n=setTimeout(()=>C.delete(e),3e4);n.unref(),C.set(e,n)},R=(e,t)=>{let n=S.get(e);n&&(S.delete(e),n.abortController.abort(),clearTimeout(n.connectTimer),L(e),t&&n.socket&&!n.socket.destroyed&&n.socket.destroy())},ie=()=>{for(let e of Array.from(S.keys()))R(e,!0);for(let e of C.values())clearTimeout(e);C.clear(),F=!1},ae=()=>{N||(N=!0,k&&=(clearInterval(k),void 0),A&&=(clearTimeout(A),void 0),j&&=(clearTimeout(j),void 0),ie(),P?.close(),P=void 0,E.removeAllListeners(`open`),E.removeAllListeners(`message`),E.removeAllListeners(`ping`),E.removeAllListeners(`pong`),(E.readyState===V.default.OPEN||E.readyState===V.default.CONNECTING)&&E.close(1e3,`close`),te(`disconnected`))},z=e=>{N||(b.error(e.message),ae(),M||x(e))},oe=e=>!F&&e.creditQueueBytes===0,se=()=>{if(!F){F=!0;for(let e of S.values())e.socket&&!e.socket.destroyed&&e.socket.pause()}},B=()=>{if(!(!F||E.bufferedAmount>=v)){F=!1;for(let e of S.values())e.socket&&!e.socket.destroyed&&oe(e)&&e.socket.resume()}},ce=()=>{E.bufferedAmount>y?z(Error(`destination tunnel WebSocket send buffer exceeded its hard limit`)):!F&&E.bufferedAmount>p&&se()},U=e=>{e?z(e):B()},W=e=>{if(N||E.readyState!==V.default.OPEN){z(Error(`destination tunnel WebSocket is not open`));return}E.send(We(e),U),ce()},G=(e,t)=>{if(N||E.readyState!==V.default.OPEN){z(Error(`destination tunnel WebSocket closed while sending data`));return}E.send(Pe(e,t),{binary:!0},U),ce()},le=(e,t,n)=>{W({type:`openFail`,connId:e,reason:t,...n?{osCode:n}:{}}),L(e)},K=(e,t,n)=>{W({type:`reset`,connId:e,reason:t,...n?{osCode:n}:{}})},q=(e,t,n)=>{for(n&&n.length>0&&(t.creditQueue.push(n),t.creditQueueBytes+=n.length);t.creditQueue.length>0&&t.sendCredit>0;){let n=t.creditQueue[0];if(n.length<=t.sendCredit)t.creditQueue.shift(),t.creditQueueBytes-=n.length,t.sendCredit-=n.length,G(e,n);else{let r=n.subarray(0,t.sendCredit);t.creditQueue[0]=n.subarray(t.sendCredit),t.creditQueueBytes-=r.length,t.sendCredit=0,G(e,r)}if(N)return}t.creditQueue.length===0&&t.finPending&&(t.finPending=!1,t.localInputEnded=!0,W({type:`fin`,connId:e})),!(!t.socket||t.socket.destroyed)&&(t.creditQueueBytes>0?t.socket.pause():F||t.socket.resume())},J=async e=>{let t=Date.now(),n=await c.promises.lookup(e.host,{all:!0,verbatim:!0}),r=Date.now()-t;for(let t of n)if(lt(t.address,e.port,i))return{host:t.address,dnsMs:r};let a=Error(`all resolved addresses for ${e.host} are blocked`);throw a.code=`EBLOCKED`,a},ue=(e,t,n)=>new Promise((r,i)=>{let o=a.connect({socket:e,rejectUnauthorized:!0,servername:t.serverName,ALPNProtocols:t.alpnProtocols});o.allowHalfOpen=!0;let s=()=>{o.removeListener(`secureConnect`,c),o.removeListener(`error`,l),n.signal.removeEventListener(`abort`,u)},c=()=>{s(),o.pause(),r(o)},l=e=>{s(),i(e)},u=()=>{s(),o.destroy(),i(Object.assign(Error(`TLS connection cancelled`),{code:`ECANCELED`}))};o.once(`secureConnect`,c),o.once(`error`,l),n.signal.aborted?u():n.signal.addEventListener(`abort`,u,{once:!0})}),Y=e=>{let t;try{t=He(e,r)}catch{le(e.connId,`selector_not_allowed`);return}if(S.has(e.connId)||C.has(e.connId))throw new H(`server reused connection ID ${e.connId}`);if(S.size>=u){le(e.connId,`resource_exhausted`);return}let n=new AbortController,i=setTimeout(()=>{S.get(e.connId)?.phase===`connecting`&&(b.warn(`Failed to connect to ${e.host}:${e.port}: timed out`),le(e.connId,`connection_timed_out`,`ETIMEDOUT`),R(e.connId,!0))},m);i.unref();let o={phase:`connecting`,abortController:n,connectTimer:i,localInputEnded:!1,remoteInputEnded:!1,pendingWriteBytes:0,sendCredit:e.window,creditQueue:[],creditQueueBytes:0,finPending:!1,deliveredSinceUpdate:0};S.set(e.connId,o),(async()=>{let r=e.host;if(t===`domain`){let t=await J(e);r=t.host,o.dnsMs=t.dnsMs}if(S.get(e.connId)!==o||N)return;let s=await D.connectTcp({host:r,port:e.port,proxyLookupHost:e.host,proxyLookupProtocol:e.transport.type===`tls`?`https:`:`http:`,timeoutMs:m,signal:n.signal});if(S.get(e.connId)!==o||N){s.socket.destroy();return}o.socket=s.socket;let c=s.socket,u;if(e.transport.type===`tls`){let t=Date.now();if(c=await ue(s.socket,e.transport,n),u=Date.now()-t,S.get(e.connId)!==o||N){c.destroy();return}o.socket=c}clearTimeout(i),c.on(`data`,t=>{S.get(e.connId)===o&&o.phase===`open`&&q(e.connId,o,t)}),c.once(`end`,()=>{if(S.get(e.connId)===o&&o.phase===`open`){if(o.creditQueueBytes>0){o.finPending=!0;return}o.localInputEnded=!0,W({type:`fin`,connId:e.connId})}}),c.once(`error`,t=>{S.get(e.connId)===o&&(K(e.connId,`connection_error`,t.code),R(e.connId,!0))}),c.once(`close`,()=>{S.get(e.connId)===o&&((!o.localInputEnded||!o.remoteInputEnded)&&K(e.connId,`connection_error`),R(e.connId,!1))}),o.phase=`open`,W({type:`openOk`,connId:e.connId,transport:{type:e.transport.type,...s.remoteAddress===void 0?{}:{remoteAddress:s.remoteAddress},...o.dnsMs===void 0?{}:{dnsMs:o.dnsMs},connectMs:s.connectMs,...u===void 0?{}:{tlsMs:u},...c instanceof a.TLSSocket&&c.alpnProtocol?{alpnProtocol:c.alpnProtocol}:{}},window:l}),b.debug(`Forwarding connection ${e.connId} to ${e.host}:${e.port}`),!F&&o.creditQueueBytes===0&&c.resume()})().catch(t=>{if(S.get(e.connId)!==o)return;b.warn(`Failed to connect to ${e.host}:${e.port}: ${t.code??t.message}`);let n=t.code===`EBLOCKED`?`selector_not_allowed`:ut(t);le(e.connId,n,t.code===`EBLOCKED`?void 0:t.code),R(e.connId,!0)})},X=e=>{let t=S.get(e);if(t?.phase===`open`&&t.socket)return t;t?(K(e,`protocol_error`),R(e,!0)):C.has(e)||(K(e,`protocol_error`),L(e))},de=e=>{let t=X(e);if(t){if(t.remoteInputEnded){K(e,`protocol_error`),R(e,!0);return}t.remoteInputEnded=!0,t.socket.end()}},pe=e=>{S.has(e)&&R(e,!0)},me=(e,t)=>{let n=S.get(e);!n||n.phase!==`open`||(n.sendCredit+=t,q(e,n))},he=e=>{if(!M)throw new H(`received tunnel data before READY`);let{connId:t,payload:n}=Fe(e),r=X(t);if(!r)return;if(r.remoteInputEnded){K(t,`protocol_error`),R(t,!0);return}let i=r.pendingWriteBytes+n.length,a=I+n.length;if(i>d||a>f){K(t,`resource_exhausted`),R(t,!0);return}r.pendingWriteBytes=i,I=a,r.socket.write(n,e=>{if(r.pendingWriteBytes-=n.length,I-=n.length,e&&S.get(t)===r){let n=e.code;K(t,`connection_error`,n),R(t,!0);return}if(S.get(t)===r&&(r.deliveredSinceUpdate+=n.length,r.deliveredSinceUpdate>=Math.ceil(l/2))){let e=r.deliveredSinceUpdate;r.deliveredSinceUpdate=0,!N&&E.readyState===V.default.OPEN&&W({type:`windowUpdate`,connId:t,increment:e})}})},ge=i=>{switch(i.type){case`ready`:{if(M)throw new H(`received duplicate READY`);Ue(i);let a=Re(r,o);if(i.configHash!==a)throw new H(`server acknowledged config ${i.configHash} but ${a} was negotiated`);if(M=!0,A&&=(clearTimeout(A),void 0),_e(),te(`connected`),b.info(`Destination tunnel ready with ${r.length} selector(s); relaunch apps that connected before it`),o.enabled&&(n.onInspectionEvent||n.onInspectionError))try{P=xe(e,i.tunnelId,t,{...n.onInspectionEvent?{onEvent:n.onInspectionEvent}:{},...n.onInspectionError?{onError:n.onInspectionError}:{}})}catch(e){try{n.onInspectionError?.(e instanceof Error?e:Error(String(e)))}catch{}}s({tunnelId:i.tunnelId,selectors:i.selectors,configHash:i.configHash,inspection:o,...P?{inspectionStream:P}:{},close:ae,getConnectionState:ne,onConnectionStateChange:re});return}case`error`:throw new st(i.code);case`open`:if(!M)throw new H(`received OPEN before READY`);Y(i);return;case`fin`:if(!M)throw new H(`received FIN before READY`);de(i.connId);return;case`windowUpdate`:if(!M)throw new H(`received windowUpdate before READY`);me(i.connId,i.increment);return;case`reset`:if(!M)throw new H(`received RESET before READY`);pe(i.connId)}},_e=()=>{!M||N||(j&&clearTimeout(j),j=setTimeout(()=>{z(Error(`destination tunnel received no frames for ${g}ms`))},g),j.unref())};A=setTimeout(()=>{z(Error(`destination tunnel was not ready within ${h}ms`))},h),A.unref(),E.on(`open`,()=>{W({type:`start`,version:1,selectors:r,inspection:o,window:l,...n.name===void 0?{}:{name:n.name},resetsInactivityTimeout:n.resetsInactivityTimeout??!0}),k=setInterval(()=>{E.readyState===V.default.OPEN&&(E.ping(void 0,!0,U),ce())},_),k.unref()}),E.on(`message`,(e,t)=>{try{_e(),t?he(fe(e)):ge(Ge(JSON.parse(fe(e).toString(`utf8`))))}catch(e){z(e instanceof Error?e:Error(String(e)))}}),E.on(`ping`,_e),E.on(`pong`,_e),E.once(`error`,e=>{z(e)}),E.once(`close`,(e,t)=>{if(N){E.removeAllListeners();return}z(Error(`destination tunnel WebSocket closed: ${e}${t.length?` ${t.toString()}`:``}`)),E.removeAllListeners()})})}function lt(e,t,n){for(let r of n)if(r.port===t&&(r.host===e||r.host===`localhost`&&(e===`127.0.0.1`||e===`::1`)))return!0;let r=i.isIP(e);return r===4?!$.check(e,`ipv4`):r===6&&!$.check(e,`ipv6`)}function ut(e){switch(e.code){case`ENOTFOUND`:return`dns_not_found`;case`EAI_AGAIN`:return`dns_temporary_failure`;case`ECONNREFUSED`:return`connection_refused`;case`ECONNRESET`:return`connection_reset`;case`ETIMEDOUT`:return`connection_timed_out`;case`ENETUNREACH`:case`EHOSTUNREACH`:return`unreachable`;case`EACCES`:case`EPERM`:case`EPROXYAUTH`:return`permission_denied`;case`EMFILE`:case`ENFILE`:case`ENOBUFS`:case`ENOMEM`:return`resource_exhausted`;case`ECANCELED`:return`cancelled`;case`CERT_HAS_EXPIRED`:case`CERT_NOT_YET_VALID`:case`CERT_REJECTED`:case`CERT_REVOKED`:case`CERT_SIGNATURE_FAILURE`:case`CERT_UNTRUSTED`:case`DEPTH_ZERO_SELF_SIGNED_CERT`:case`ERR_TLS_CERT_ALTNAME_FORMAT`:case`SELF_SIGNED_CERT_IN_CHAIN`:case`HOSTNAME_MISMATCH`:case`INVALID_CA`:case`INVALID_PURPOSE`:case`PATH_LENGTH_EXCEEDED`:case`UNABLE_TO_GET_ISSUER_CERT`:case`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`:case`UNABLE_TO_VERIFY_LEAF_SIGNATURE`:case`ERR_TLS_CERT_ALTNAME_INVALID`:return`tls_validation_failed`;case`EPROTO`:return`tls_protocol_error`;default:return e.code?.startsWith(`ERR_SSL_`)||e.code?.startsWith(`ERR_TLS_`)?`tls_handshake_failed`:`internal`}}function dt(e,t){if(!Number.isInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}export{F as _,ze as a,_e as c,W as d,le as f,V as g,G as h,Ne as i,ve as l,U as m,ot as n,Ie as o,Y as p,ct as r,me as s,st as t,he as u,D as v};