@frp-bridge/core 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,258 @@
1
+ import{createRequire as e}from"node:module";import{appendFileSync as t,chmodSync as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,renameSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"node:fs";import{cp as f,readFile as p,readdir as m,rm as h,unlink as g,writeFile as _}from"node:fs/promises";import{exec as v,spawn as ee}from"node:child_process";import{get as y}from"node:http";import{get as b}from"node:https";import x from"node:process";import{promisify as S}from"node:util";import{cpus as te,homedir as ne,hostname as re,platform as ie,release as ae,totalmem as oe}from"node:os";import{join as se}from"node:path";import{randomUUID as C}from"node:crypto";import{EventEmitter as w}from"node:events";import{Buffer as T}from"node:buffer";var E=Object.create,ce=Object.defineProperty,D=Object.getOwnPropertyDescriptor,le=Object.getOwnPropertyNames,ue=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty,k=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),de=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=le(t),a=0,o=i.length,s;a<o;a++)s=i[a],!O.call(e,s)&&s!==n&&ce(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=D(t,s))||r.enumerable});return e},fe=(e,t,n)=>(n=e==null?{}:E(ue(e)),de(t||!e||!e.__esModule?ce(n,`default`,{value:e,enumerable:!0}):n,e)),A=e(import.meta.url);const pe=/^[A-Za-z]:\//;function me(e=``){return e&&e.replace(/\\/g,`/`).replace(pe,e=>e.toUpperCase())}const he=/^[/\\]{2}/,ge=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,_e=/^[A-Za-z]:$/,ve=function(e){if(e.length===0)return`.`;e=me(e);let t=e.match(he),n=be(e),r=e[e.length-1]===`/`;return e=ye(e,!n),e.length===0?n?`/`:r?`./`:`.`:(r&&(e+=`/`),_e.test(e)&&(e+=`/`),t?n?`//${e}`:`//./${e}`:n&&!be(e)?`/${e}`:e)},j=function(...e){let t=``;for(let n of e)if(n)if(t.length>0){let e=t[t.length-1]===`/`,r=n[0]===`/`;e&&r?t+=n.slice(1):t+=e||r?n:`/${n}`}else t+=n;return ve(t)};function ye(e,t){let n=``,r=0,i=-1,a=0,o=null;for(let s=0;s<=e.length;++s){if(s<e.length)o=e[s];else if(o===`/`)break;else o=`/`;if(o===`/`){if(!(i===s-1||a===1))if(a===2){if(n.length<2||r!==2||n[n.length-1]!==`.`||n[n.length-2]!==`.`){if(n.length>2){let e=n.lastIndexOf(`/`);e===-1?(n=``,r=0):(n=n.slice(0,e),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}else if(n.length>0){n=``,r=0,i=s,a=0;continue}}t&&(n+=n.length>0?`/..`:`..`,r=2)}else n.length>0?n+=`/${e.slice(i+1,s)}`:n=e.slice(i+1,s),r=s-i-1;i=s,a=0}else o===`.`&&a!==-1?++a:a=-1}return n}const be=function(e){return ge.test(e)},M=1e3;var xe=class{storage;commandHandlers=new Map;queryHandlers=new Map;eventBuffer=[];commandQueue=Promise.resolve();state={status:`idle`,version:0};constructor(e,t={}){this.context=e,this.storage=t.storage,Object.entries(t.commands??{}).forEach(([e,t])=>{this.commandHandlers.set(e,t)}),Object.entries(t.queries??{}).forEach(([e,t])=>{this.queryHandlers.set(e,t)})}registerCommand(e,t){this.commandHandlers.set(e,t)}registerQuery(e,t){this.queryHandlers.set(e,t)}execute(e){let t=this.commandQueue.then(()=>this.runCommand(e));return this.commandQueue=t.then(()=>void 0,()=>void 0),t}async query(e){let t=this.queryHandlers.get(e.name);if(!t)throw this.buildError(`VALIDATION_ERROR`,`Unknown query: ${e.name}`);return t(e,this.context)}snapshot(){return{...this.state}}drainEvents(){let e=this.eventBuffer;return this.eventBuffer=[],e}async runCommand(e){let t=this.commandHandlers.get(e.name);if(!t)return{status:`failed`,error:this.buildError(`VALIDATION_ERROR`,`Unknown command: ${e.name}`)};let n={...this.state},r={bumped:!1},i={context:this.context,state:n,emit:e=>this.pushEvents(e),requestVersionBump:()=>this.bumpVersion(e.metadata?.author,r)};this.state.status=`running`;try{let n=await t(e,i);return n.events&&this.pushEvents(n.events),n.snapshot&&await this.persistSnapshot(n.snapshot,e.metadata?.author),n.error?(this.state.lastError=n.error,this.state.status=`error`):n.status===`success`&&(this.state.lastError=void 0,this.state.status=`running`),{...n,version:n.version??this.state.version}}catch(e){let t=this.normalizeError(e);return this.state.lastError=t,this.state.status=`error`,{status:`failed`,error:t,version:this.state.version}}}pushEvents(e){let t=this.now();e.forEach(e=>{this.eventBuffer.push({...e,timestamp:e.timestamp??t,version:e.version??this.state.version})}),this.eventBuffer.length>M&&(this.eventBuffer=this.eventBuffer.slice(-M))}bumpVersion(e,t){return t.bumped?this.state.version:(t.bumped=!0,this.state.version+=1,this.state.lastAppliedAt=this.now(),e&&this.pushEvents([{type:`config:version-bumped`,timestamp:this.now(),version:this.state.version,payload:{author:e}}]),this.state.version)}async persistSnapshot(e,t){!this.storage||!e||await this.storage.save({...e,version:e.version??this.state.version,appliedAt:e.appliedAt??this.now(),author:e.author??t})}normalizeError(e){return e&&typeof e==`object`&&`code`in e&&`message`in e?e:{code:`SYSTEM_ERROR`,message:e instanceof Error?e.message:`Unknown error`}}buildError(e,t,n){return{code:e,message:t,details:n}}now(){return this.context.clock?this.context.clock():Date.now()}};const N=`fatedier`,Se=`frp`,P={client:x.platform===`win32`?`frpc.exe`:`frpc`,server:x.platform===`win32`?`frps.exe`:`frps`},Ce={x64:`amd64`,arm64:`arm64`,arm:`arm`,ia32:`386`},we={win32:`windows`,darwin:`darwin`,linux:`linux`,freebsd:`freebsd`};var F=class extends Error{statusCode;details;constructor(e,t){super(e),this.name=this.constructor.name,this.details=t}toJSON(){return{code:this.code,message:this.message,statusCode:this.statusCode,details:this.details}}},Te=class extends F{code;constructor(e,t,n){super(e,n),this.code=t}},I=class extends F{code=`CONFIG_NOT_FOUND`;statusCode=400},L=class extends F{code=`CONFIG_INVALID`;statusCode=400},Ee=class extends F{code=`PROCESS_NOT_RUNNING`;statusCode=409},De=class extends F{code=`PROCESS_ALREADY_RUNNING`;statusCode=409},Oe=class extends F{code=`PROCESS_START_FAILED`;statusCode=500},ke=class extends F{code=`BINARY_NOT_FOUND`;statusCode=500},Ae=class extends F{code=`DOWNLOAD_FAILED`;statusCode=500},je=class extends F{code=`EXTRACTION_FAILED`;statusCode=500},Me=class extends F{code=`VERSION_FETCH_FAILED`;statusCode=503},R=class extends F{code=`VALIDATION_ERROR`;statusCode=400},z=class extends F{code=`MODE_ERROR`;statusCode=409},B=class extends F{code=`NOT_FOUND`;statusCode=404},Ne=class extends F{code=`UNSUPPORTED_PLATFORM`;statusCode=500};let V=function(e){return e.TCP=`tcp`,e.UDP=`udp`,e.HTTP=`http`,e.HTTPS=`https`,e.TCPMUX=`tcpmux`,e.STCP=`stcp`,e.XTCP=`xtcp`,e.SUDP=`sudp`,e}({});function H(e){return[V.TCP,V.UDP,V.STCP,V.XTCP,V.SUDP,V.TCPMUX].includes(e)}const Pe=/^v/,Fe=S(v);async function Ie(){let e=`https://api.github.com/repos/${N}/frp/releases/latest`;return new Promise((t,n)=>{b(e,{headers:{"User-Agent":`frp-bridge`}},e=>{if(e.statusCode!==200){n(Error(`Failed to fetch latest version: ${e.statusCode}`));return}let r=``;e.on(`data`,e=>r+=e),e.on(`end`,()=>{try{t(JSON.parse(r).tag_name?.replace(Pe,``)||`0.65.0`)}catch(e){n(e)}})}).on(`error`,n)})}function Le(){let e=we[x.platform],t=Ce[x.arch];if(!e||!t)throw new Ne(`Unsupported platform: ${x.platform}-${x.arch}`);return`${e}_${t}`}function Re(e,t){return`https://github.com/${N}/frp/releases/download/v${e}/frp_${e}_${t}.${t.startsWith(`windows_`)?`zip`:`tar.gz`}`}async function ze(e,t,n=5){return n<=0?Promise.reject(Error(`Maximum redirect limit reached`)):new Promise((i,a)=>{let o=r(t);(e.startsWith(`https`)?b:y)(e,e=>{if(e.statusCode===302||e.statusCode===301){let r=e.headers.location;if(r){o.close(),ze(r,t,n-1).then(i).catch(a);return}}if(e.statusCode!==200){a(Error(`Failed to download: ${e.statusCode}`)),o.close();return}e.pipe(o),o.on(`finish`,()=>{o.close(),i()})}).on(`error`,e=>{o.close(),a(e)})})}async function Be(e){return Fe(e)}async function Ve(e){try{return x.platform===`win32`?await Fe(`where ${e}`):await Fe(`which ${e}`),!0}catch{return!1}}function U(e){i(e)||a(e,{recursive:!0})}function He(e){let t=`${e}/bin`;if(!i(t))return null;try{let e=s(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);return e.length>0?e[0]:null}catch{return null}}function Ue(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function We(e){return!!e&&typeof e==`object`&&`version`in e}var Ge=class{constructor(e){this.directory=e,U(e)}async save(e){if(typeof e.version!=`number`)throw TypeError(`Snapshot version must be a number when using FileSnapshotStorage`);U(this.directory);let t=JSON.stringify(e,null,2);await _(this.buildPath(e.version),t,`utf-8`)}async load(e){let t=this.buildPath(e);if(!i(t))return;let n=await p(t,`utf-8`),r=JSON.parse(n);if(!We(r))throw TypeError(`Invalid snapshot schema at version ${e}`);return r}async list(){U(this.directory);let e=await m(this.directory),t=[];for(let n of e){if(!n.endsWith(`.json`))continue;let e=await p(j(this.directory,n),`utf-8`),r=JSON.parse(e);We(r)&&t.push(r)}return t.sort((e,t)=>e.version-t.version)}buildPath(e){return j(this.directory,`${e}.json`)}};
2
+ /*!
3
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice, this
10
+ * list of conditions and the following disclaimer.
11
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ * this list of conditions and the following disclaimer in the
13
+ * documentation and/or other materials provided with the distribution.
14
+ * 3. Neither the name of the copyright holder nor the names of its contributors
15
+ * may be used to endorse or promote products derived from this software without
16
+ * specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ */
29
+ function Ke(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function qe(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
30
+ `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
31
+ `))}return i}var W=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Ke(t.toml,t.ptr),i=qe(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};
32
+ /*!
33
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
34
+ * SPDX-License-Identifier: BSD-3-Clause
35
+ *
36
+ * Redistribution and use in source and binary forms, with or without
37
+ * modification, are permitted provided that the following conditions are met:
38
+ *
39
+ * 1. Redistributions of source code must retain the above copyright notice, this
40
+ * list of conditions and the following disclaimer.
41
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
42
+ * this list of conditions and the following disclaimer in the
43
+ * documentation and/or other materials provided with the distribution.
44
+ * 3. Neither the name of the copyright holder nor the names of its contributors
45
+ * may be used to endorse or promote products derived from this software without
46
+ * specific prior written permission.
47
+ *
48
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
49
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
50
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
51
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
52
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
54
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
55
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58
+ */
59
+ function Je(e,t){let n=0;for(;e[t-++n]===`\\`;);return--n&&n%2}function Ye(e,t=0,n=e.length){let r=e.indexOf(`
60
+ `,t);return e[r-1]===`\r`&&r--,r<=n?r:-1}function Xe(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
61
+ `)return n;if(r===`\r`&&e[n+1]===`
62
+ `)return n+1;if(r<` `&&r!==` `||r===``)throw new W(`control characters are not allowed in comments`,{toml:e,ptr:t})}return e.length}function G(e,t,n,r){let i;for(;(i=e[t])===` `||i===` `||!n&&(i===`
63
+ `||i===`\r`&&e[t+1]===`
64
+ `);)t++;return r||i!==`#`?t:G(e,Xe(e,t),n)}function Ze(e,t,n,r,i=!1){if(!r)return t=Ye(e,t),t<0?e.length:t;for(let a=t;a<e.length;a++){let t=e[a];if(t===`#`)a=Ye(e,a);else if(t===n)return a+1;else if(t===r||i&&(t===`
65
+ `||t===`\r`&&e[a+1]===`
66
+ `))return a}throw new W(`cannot find end of structure`,{toml:e,ptr:t})}function Qe(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!==`'`&&Je(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}
67
+ /*!
68
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
69
+ * SPDX-License-Identifier: BSD-3-Clause
70
+ *
71
+ * Redistribution and use in source and binary forms, with or without
72
+ * modification, are permitted provided that the following conditions are met:
73
+ *
74
+ * 1. Redistributions of source code must retain the above copyright notice, this
75
+ * list of conditions and the following disclaimer.
76
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
77
+ * this list of conditions and the following disclaimer in the
78
+ * documentation and/or other materials provided with the distribution.
79
+ * 3. Neither the name of the copyright holder nor the names of its contributors
80
+ * may be used to endorse or promote products derived from this software without
81
+ * specific prior written permission.
82
+ *
83
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
84
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
85
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
86
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
87
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
88
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
89
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
90
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
91
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
92
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
93
+ */
94
+ let $e=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;var et=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match($e);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
95
+ /*!
96
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
97
+ * SPDX-License-Identifier: BSD-3-Clause
98
+ *
99
+ * Redistribution and use in source and binary forms, with or without
100
+ * modification, are permitted provided that the following conditions are met:
101
+ *
102
+ * 1. Redistributions of source code must retain the above copyright notice, this
103
+ * list of conditions and the following disclaimer.
104
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
105
+ * this list of conditions and the following disclaimer in the
106
+ * documentation and/or other materials provided with the distribution.
107
+ * 3. Neither the name of the copyright holder nor the names of its contributors
108
+ * may be used to endorse or promote products derived from this software without
109
+ * specific prior written permission.
110
+ *
111
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
112
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
113
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
114
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
115
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
116
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
117
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
118
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
119
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
120
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
121
+ */
122
+ let tt=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,nt=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,rt=/^[+-]?0[0-9_]/,it=/^[0-9a-f]{2,8}$/i,at={b:`\b`,t:` `,n:`
123
+ `,f:`\f`,r:`\r`,e:`\x1B`,'"':`"`,"\\":`\\`};function ot(e,t=0,n=e.length){let r=e[t]===`'`,i=e[t++]===e[t]&&e[t]===e[t+1];i&&(n-=2,e[t+=2]===`\r`&&t++,e[t]===`
124
+ `&&t++);let a=0,o,s=``,c=t;for(;t<n-1;){let n=e[t++];if(n===`
125
+ `||n===`\r`&&e[t]===`
126
+ `){if(!i)throw new W(`newlines are not allowed in strings`,{toml:e,ptr:t-1})}else if(n<` `&&n!==` `||n===``)throw new W(`control characters are not allowed in strings`,{toml:e,ptr:t-1});if(o){if(o=!1,n===`x`||n===`u`||n===`U`){let r=e.slice(t,t+=n===`x`?2:n===`u`?4:8);if(!it.test(r))throw new W(`invalid unicode escape`,{toml:e,ptr:a});try{s+=String.fromCodePoint(parseInt(r,16))}catch{throw new W(`invalid unicode escape`,{toml:e,ptr:a})}}else if(i&&(n===`
127
+ `||n===` `||n===` `||n===`\r`)){if(t=G(e,t-1,!0),e[t]!==`
128
+ `&&e[t]!==`\r`)throw new W(`invalid escape: only line-ending whitespace may be escaped`,{toml:e,ptr:a});t=G(e,t)}else if(n in at)s+=at[n];else throw new W(`unrecognized escape sequence`,{toml:e,ptr:a});c=t}else !r&&n===`\\`&&(a=t-1,o=!0,s+=e.slice(c,a))}return s+e.slice(c,n-1)}function st(e,t,n,r){if(e===`true`)return!0;if(e===`false`)return!1;if(e===`-inf`)return-1/0;if(e===`inf`||e===`+inf`)return 1/0;if(e===`nan`||e===`+nan`||e===`-nan`)return NaN;if(e===`-0`)return r?0n:0;let i=tt.test(e);if(i||nt.test(e)){if(rt.test(e))throw new W(`leading zeroes are not allowed`,{toml:t,ptr:n});e=e.replace(/_/g,``);let a=+e;if(isNaN(a))throw new W(`invalid number`,{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(a))&&!r)throw new W(`integer value cannot be represented losslessly`,{toml:t,ptr:n});(i||r===!0)&&(a=BigInt(e))}return a}let a=new et(e);if(!a.isValid())throw new W(`invalid value`,{toml:t,ptr:n});return a}
129
+ /*!
130
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
131
+ * SPDX-License-Identifier: BSD-3-Clause
132
+ *
133
+ * Redistribution and use in source and binary forms, with or without
134
+ * modification, are permitted provided that the following conditions are met:
135
+ *
136
+ * 1. Redistributions of source code must retain the above copyright notice, this
137
+ * list of conditions and the following disclaimer.
138
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
139
+ * this list of conditions and the following disclaimer in the
140
+ * documentation and/or other materials provided with the distribution.
141
+ * 3. Neither the name of the copyright holder nor the names of its contributors
142
+ * may be used to endorse or promote products derived from this software without
143
+ * specific prior written permission.
144
+ *
145
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
146
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
147
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
148
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
149
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
150
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
151
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
152
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
153
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
154
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
155
+ */
156
+ function ct(e,t,n){let r=e.slice(t,n),i=r.indexOf(`#`);return i>-1&&(Xe(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function lt(e,t,n,r,i){if(r===0)throw new W(`document contains excessively nested structures. aborting.`,{toml:e,ptr:t});let a=e[t];if(a===`[`||a===`{`){let[o,s]=a===`[`?pt(e,t,r,i):ft(e,t,r,i);if(n){if(s=G(e,s),e[s]===`,`)s++;else if(e[s]!==n)throw new W(`expected comma or end of structure`,{toml:e,ptr:s})}return[o,s]}let o;if(a===`"`||a===`'`){o=Qe(e,t);let r=ot(e,t,o);if(n){if(o=G(e,o),e[o]&&e[o]!==`,`&&e[o]!==n&&e[o]!==`
157
+ `&&e[o]!==`\r`)throw new W(`unexpected character encountered`,{toml:e,ptr:o});o+=+(e[o]===`,`)}return[r,o]}o=Ze(e,t,`,`,n);let s=ct(e,t,o-+(e[o-1]===`,`));if(!s[0])throw new W(`incomplete key-value declaration: no value specified`,{toml:e,ptr:t});return n&&s[1]>-1&&(o=G(e,t+s[1]),o+=+(e[o]===`,`)),[st(s[0],e,t,i),o]}
158
+ /*!
159
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
160
+ * SPDX-License-Identifier: BSD-3-Clause
161
+ *
162
+ * Redistribution and use in source and binary forms, with or without
163
+ * modification, are permitted provided that the following conditions are met:
164
+ *
165
+ * 1. Redistributions of source code must retain the above copyright notice, this
166
+ * list of conditions and the following disclaimer.
167
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
168
+ * this list of conditions and the following disclaimer in the
169
+ * documentation and/or other materials provided with the distribution.
170
+ * 3. Neither the name of the copyright holder nor the names of its contributors
171
+ * may be used to endorse or promote products derived from this software without
172
+ * specific prior written permission.
173
+ *
174
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
175
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
176
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
177
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
178
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
179
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
180
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
181
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
182
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
183
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
184
+ */
185
+ let ut=/^[a-zA-Z0-9-_]+[ \t]*$/;function dt(e,t,n=`=`){let r=t-1,i=[],a=e.indexOf(n,t);if(a<0)throw new W(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});do{let o=e[t=++r];if(o!==` `&&o!==` `)if(o===`"`||o===`'`){if(o===e[t+1]&&o===e[t+2])throw new W(`multiline strings are not allowed in keys`,{toml:e,ptr:t});let s=Qe(e,t);if(s<0)throw new W(`unfinished string encountered`,{toml:e,ptr:t});r=e.indexOf(`.`,s);let c=e.slice(s,r<0||r>a?a:r),l=Ye(c);if(l>-1)throw new W(`newlines are not allowed in keys`,{toml:e,ptr:t+r+l});if(c.trimStart())throw new W(`found extra tokens after the string part`,{toml:e,ptr:s});if(a<s&&(a=e.indexOf(n,s),a<0))throw new W(`incomplete key-value: cannot find end of key`,{toml:e,ptr:t});i.push(ot(e,t,s))}else{r=e.indexOf(`.`,t);let n=e.slice(t,r<0||r>a?a:r);if(!ut.test(n))throw new W(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e,ptr:t});i.push(n.trimEnd())}}while(r+1&&r<a);return[i,G(e,a+1,!0,!0)]}function ft(e,t,n,r){let i={},a=new Set,o;for(t++;(o=e[t++])!==`}`&&o;)if(o===`,`)throw new W(`expected value, found comma`,{toml:e,ptr:t-1});else if(o===`#`)t=Xe(e,t);else if(o!==` `&&o!==` `&&o!==`
186
+ `&&o!==`\r`){let o,s=i,c=!1,[l,u]=dt(e,t-1);for(let n=0;n<l.length;n++){if(n&&(s=c?s[o]:s[o]={}),o=l[n],(c=Object.hasOwn(s,o))&&(typeof s[o]!=`object`||a.has(s[o])))throw new W(`trying to redefine an already defined value`,{toml:e,ptr:t});!c&&o===`__proto__`&&Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(c)throw new W(`trying to redefine an already defined value`,{toml:e,ptr:t});let[d,f]=lt(e,u,`}`,n-1,r);a.add(d),s[o]=d,t=f}if(!o)throw new W(`unfinished table encountered`,{toml:e,ptr:t});return[i,t]}function pt(e,t,n,r){let i=[],a;for(t++;(a=e[t++])!==`]`&&a;)if(a===`,`)throw new W(`expected value, found comma`,{toml:e,ptr:t-1});else if(a===`#`)t=Xe(e,t);else if(a!==` `&&a!==` `&&a!==`
187
+ `&&a!==`\r`){let a=lt(e,t-1,`]`,n-1,r);i.push(a[0]),t=a[1]}if(!a)throw new W(`unfinished array encountered`,{toml:e,ptr:t});return[i,t]}
188
+ /*!
189
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
190
+ * SPDX-License-Identifier: BSD-3-Clause
191
+ *
192
+ * Redistribution and use in source and binary forms, with or without
193
+ * modification, are permitted provided that the following conditions are met:
194
+ *
195
+ * 1. Redistributions of source code must retain the above copyright notice, this
196
+ * list of conditions and the following disclaimer.
197
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
198
+ * this list of conditions and the following disclaimer in the
199
+ * documentation and/or other materials provided with the distribution.
200
+ * 3. Neither the name of the copyright holder nor the names of its contributors
201
+ * may be used to endorse or promote products derived from this software without
202
+ * specific prior written permission.
203
+ *
204
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
205
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
206
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
207
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
208
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
209
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
210
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
211
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
212
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
213
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
214
+ */
215
+ function mt(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function ht(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},a=r,o=i;for(let s=G(e,0);s<e.length;){if(e[s]===`[`){let t=e[++s]===`[`,n=dt(e,s+=+t,`]`);if(t){if(e[n[1]-1]!==`]`)throw new W(`expected end of table declaration`,{toml:e,ptr:n[1]-1});n[1]++}let c=mt(n[0],r,i,t?2:1);if(!c)throw new W(`trying to redefine an already defined table or value`,{toml:e,ptr:s});o=c[2],a=c[1],s=n[1]}else{let r=dt(e,s),i=mt(r[0],a,o,0);if(!i)throw new W(`trying to redefine an already defined table or value`,{toml:e,ptr:s});let c=lt(e,r[1],void 0,t,n);i[1][i[0]]=c[0],s=c[1]}if(s=G(e,s,!0),e[s]&&e[s]!==`
216
+ `&&e[s]!==`\r`)throw new W(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:s});s=G(e,s)}return r}
217
+ /*!
218
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
219
+ * SPDX-License-Identifier: BSD-3-Clause
220
+ *
221
+ * Redistribution and use in source and binary forms, with or without
222
+ * modification, are permitted provided that the following conditions are met:
223
+ *
224
+ * 1. Redistributions of source code must retain the above copyright notice, this
225
+ * list of conditions and the following disclaimer.
226
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
227
+ * this list of conditions and the following disclaimer in the
228
+ * documentation and/or other materials provided with the distribution.
229
+ * 3. Neither the name of the copyright holder nor the names of its contributors
230
+ * may be used to endorse or promote products derived from this software without
231
+ * specific prior written permission.
232
+ *
233
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
234
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
235
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
236
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
237
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
238
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
239
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
240
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
241
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
242
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
243
+ */
244
+ let gt=/^[a-z0-9-_]+$/i;function K(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(e instanceof Date)return`date`}return t}function _t(e){for(let t=0;t<e.length;t++)if(K(e[t])!==`object`)return!1;return e.length!=0}function vt(e){return JSON.stringify(e).replace(/\x7f/g,`\\u007f`)}function yt(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);if(t===`number`)return isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t===`bigint`||t===`boolean`)return e.toString();if(t===`string`)return vt(e);if(t===`date`){if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString()}if(t===`object`)return bt(e,n,r);if(t===`array`)return xt(e,n,r)}function bt(e,t,n){let r=Object.keys(e);if(r.length===0)return`{}`;let i=`{ `;for(let a=0;a<r.length;a++){let o=r[a];a&&(i+=`, `),i+=gt.test(o)?o:vt(o),i+=` = `,i+=yt(e[o],K(e[o]),t-1,n)}return i+` }`}function xt(e,t,n){if(e.length===0)return`[]`;let r=`[ `;for(let i=0;i<e.length;i++){if(i&&(r+=`, `),e[i]===null||e[i]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);r+=yt(e[i],K(e[i]),t-1,n)}return r+` ]`}function St(e,t,n,r){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let i=``;for(let a=0;a<e.length;a++)i+=`${i&&`
245
+ `}[[${t}]]\n`,i+=Ct(0,e[a],t,n,r);return i}function Ct(e,t,n,r,i){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``,o=``,s=Object.keys(t);for(let e=0;e<s.length;e++){let c=s[e];if(t[c]!==null&&t[c]!==void 0){let e=K(t[c]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let s=gt.test(c)?c:vt(c);if(e===`array`&&_t(t[c]))o+=(o&&`
246
+ `)+St(t[c],n?`${n}.${s}`:s,r-1,i);else if(e===`object`){let e=n?`${n}.${s}`:s;o+=(o&&`
247
+ `)+Ct(e,t[c],e,r-1,i)}else a+=s,a+=` = `,a+=yt(t[c],e,r,i),a+=`
248
+ `}}return e&&(a||!o)&&(a=a?`[${e}]\n${a}`:`[${e}]`),a&&o?`${a}\n${o}`:a||o}function wt(e,{maxDepth:t=1e3,numbersAsFloat:n=!1}={}){if(K(e)!==`object`)throw TypeError(`stringify can only be called with an object`);let r=Ct(0,e,``,t,n);return r[r.length-1]===`
249
+ `?r:r+`
250
+ `}function q(e,t){try{return ht(e,t)}catch(e){throw e instanceof Error?TypeError(`Failed to parse TOML: ${e.message}`):Error(`Failed to parse TOML: Unknown error`)}}function Tt(e,t){try{return wt(e,t)}catch(e){throw e instanceof Error?TypeError(`Failed to stringify to TOML: ${e.message}`):Error(`Failed to stringify to TOML: Unknown error`)}}function Et(e){try{return q(e),!0}catch{return!1}}function Dt(e){try{return q(e)}catch{return null}}function Ot(e,t){return async(n,r)=>{if(t.mode!==`server`)throw new z(`This operation is only available in server mode`);return e(n,r)}}function kt(e,t){return async(n,r)=>{if(t.mode!==`client`)throw new z(`This operation is only available in client mode`);return e(n,r)}}function J(e){return(t,n)=>async(n,r)=>{let i=e(n.payload);if(!i.valid)throw new R(i.error||`Validation failed`);return t(n,r)}}function Y(e,t){return async(t,n)=>{try{return await e(t,n)}catch(e){return jt(e)}}}function At(e,t){return async(n,r)=>{if(!t.nodeManager)throw new z(`Node manager not available`);return e(n,r)}}function X(...e){return(t,n)=>e.reduceRight((e,t)=>t(e,n),t)}function jt(e){return e instanceof R||e instanceof z?{status:`failed`,error:{code:e.code,message:e.message}}:e instanceof Error?{status:`failed`,error:{code:`RUNTIME_ERROR`,message:e.message}}:{status:`failed`,error:{code:`UNKNOWN_ERROR`,message:`An unknown error occurred`}}}const Mt={required:(e=`payload`)=>t=>t?{valid:!0}:{valid:!1,error:`${e} is required`},string:e=>t=>{let n=t[e];return!n||typeof n!=`string`||!n.trim()?{valid:!1,error:`${String(e)} is required and must be a non-empty string`}:{valid:!0}},number:(e,t,n)=>r=>{let i=r[String(e)];return typeof i==`number`?t!==void 0&&i<t?{valid:!1,error:`${String(e)} must be >= ${t}`}:n!==void 0&&i>n?{valid:!1,error:`${String(e)} must be <= ${n}`}:{valid:!0}:{valid:!1,error:`${String(e)} must be a number`}},all:(...e)=>t=>{for(let n of e){let e=n(t);if(!e.valid)return e}return{valid:!0}}};function Nt(e,t,n){return(r,i)=>async(r,a)=>{let o=r.payload;if(i.mode===`server`){if(!o.nodeId)return{status:`failed`,error:{code:`VALIDATION_ERROR`,message:`nodeId is required in server mode`}};if(!i.rpcServer)return{status:`failed`,error:{code:`RPC_NOT_AVAILABLE`,message:`RPC server is not available`}};try{let e=n?n(o):o;return{status:`success`,result:await i.rpcServer.rpcCall(o.nodeId,t,e)}}catch(e){return{status:`failed`,error:{code:`RPC_ERROR`,message:e instanceof Error?e.message:`RPC call failed`}}}}return e(o,i)}}function Pt(e,t){return async(n,r)=>{let i=n.payload,a=i.proxy;if(a?.remotePort&&a?.type&&H(a.type)){let e=t.nodeManager?.isRemotePortInUse(a.remotePort,i.nodeId);if(e?.inUse)return{status:`failed`,error:{code:`PORT_CONFLICT`,message:`Remote port ${a.remotePort} is already in use by tunnel "${e.tunnelName}" on node ${e.nodeId}`}}}return e(n,r)}}const Ft={serverOnly:(e,t)=>X(Y,At,Ot)(e,t),clientOnly:(e,t)=>X(Y,kt)(e,t),withValidation:(e,t,n)=>X(Y,J(e))(t,n),serverWithRequired:(...e)=>(t,n)=>X(Y,At,Ot,J(Mt.all(...e.map(e=>Mt.string(e)))))(t,n)};async function It(e,t,n,r){await t();let i=n??!0,a;return i&&(e.isRunning()&&await e.stop(),await e.start(),a=[{type:`process:started`,timestamp:Date.now()}]),r.requestVersionBump(),{status:`success`,events:a}}const Lt=e=>e?.config?{valid:!0}:{valid:!1,error:`config.apply requires payload.config`},Rt=e=>(e?.content)?.trim()?{valid:!0}:{valid:!1,error:`config.applyRaw requires payload.content`};function zt(e){return async(t,n)=>It(e.process,async()=>{e.process.updateConfig(t.payload.config)},t.payload.restart,n)}function Bt(e){return X(Y,J(Lt))(zt(e),e)}function Vt(e){return async(t,n)=>{let r=t.payload.content;try{q(r)}catch(e){throw new L(`config.applyRaw received invalid TOML content: ${e instanceof Error?e.message:`Unknown error`}`)}return It(e.process,async()=>{e.process.updateConfigRaw(r)},t.payload.restart,n)}}function Ht(e){return X(Y,J(Rt))(Vt(e),e)}function Ut(e){return Y(async()=>e.process.isRunning()?(await e.process.stop(),{status:`success`,events:[{type:`process:stopped`,timestamp:Date.now()}]}):{status:`success`},e)}const Wt=e=>e?.nodeId?{valid:!0}:{valid:!1,error:`node.heartbeat requires nodeId`},Gt=e=>e?.nodeId?{valid:!0}:{valid:!1,error:`node.unregister requires nodeId`};function Kt(e){return async t=>({status:`success`,result:await e.nodeManager.registerNode(t.payload)})}function qt(e){return Ft.serverWithRequired(`hostname`,`serverAddr`,`serverPort`)(Kt(e),e)}function Jt(e){return async t=>(await e.nodeManager.updateHeartbeat(t.payload),{status:`success`})}function Yt(e){return X(Y,At,Ot,J(Wt))(Jt(e),e)}function Xt(e){return async t=>(e.nodeManager.unregisterNode(t.payload.nodeId),{status:`success`})}function Zt(e){return X(Y,At,Ot,J(Gt))(Xt(e),e)}const Qt=e=>e?.proxy?{valid:!0}:{valid:!1,error:`proxy.add requires payload.proxy`},$t=e=>e?.name?{valid:!0}:{valid:!1,error:`proxy.update requires payload.name`},en=e=>e?.name?{valid:!0}:{valid:!1,error:`proxy.remove requires payload.name`};async function tn(e,t){return t.process.addTunnel(e.proxy),{status:`success`,result:e.proxy}}function nn(e){return X(Y,J(Qt),Pt)(Nt(tn,`proxy.add`,e=>({proxy:e.proxy}))(async()=>({status:`success`}),e),e)}async function rn(e,t){return t.process.updateTunnel(e.name,e.proxy),{status:`success`,result:{name:e.name,...e.proxy}}}function an(e){return X(Y,J($t),Pt)(Nt(rn,`proxy.update`,e=>({name:e.name,proxy:e.proxy}))(async()=>({status:`success`}),e),e)}async function on(e,t){return t.process.removeTunnel(e.name),{status:`success`,result:{name:e.name}}}function sn(e){return X(Y,J(en))(Nt(on,`proxy.remove`,e=>({name:e.name}))(async()=>({status:`success`}),e),e)}function cn(e){return Y(async()=>({status:`success`,result:e.process.getPresetConfig()}),e)}function ln(e){return Y(async(t,n)=>{let r=t.payload?.config;if(!r||typeof r!=`object`)throw new R(`preset.set requires payload.config`);let i=t.payload?.restart??!0;return e.process.savePresetConfig(r),await e.process.generateConfig(!0),i&&e.process.isRunning()&&(await e.process.stop(),await e.process.start()),n.requestVersionBump(),{status:`success`,result:r}},e)}function un(e){return Y(async t=>{let n=t.payload?.force??!1;return await e.process.generateConfig(n),{status:`success`,result:{configPath:e.process.getConfigPath()}}},e)}function dn(e){return{"config.apply":Bt(e),"config.applyRaw":Ht(e),"config.generate":un(e),"preset.get":cn(e),"preset.set":ln(e),"process.stop":Ut(e),"node.register":qt(e),"node.heartbeat":Yt(e),"node.unregister":Zt(e),"node.delete":bn(e),"proxy.add":nn(e),"proxy.update":an(e),"proxy.remove":sn(e),"tunnel.add":gn(e),"tunnel.delete":vn(e)}}const fn=e=>e?!e.name||typeof e.name!=`string`?{valid:!1,error:`tunnel.add requires payload.name`}:!e.type||typeof e.type!=`string`?{valid:!1,error:`tunnel.add requires payload.type`}:typeof e.localPort==`number`?{valid:!0}:{valid:!1,error:`tunnel.add requires payload.localPort to be a number`}:{valid:!1,error:`tunnel.add requires payload`},pn=e=>e?.name?{valid:!0}:{valid:!1,error:`tunnel.delete requires payload.name`},mn=e=>e?.name?{valid:!0}:{valid:!1,error:`node.delete requires payload.name`};async function hn(e,t){let n=Ue({name:e.name,type:e.type,localIP:`127.0.0.1`,localPort:e.localPort,remotePort:e.remotePort,customDomains:e.customDomains,subdomain:e.subdomain});return t.process.addTunnel(n),{status:`success`,result:{...n,success:!0}}}function gn(e){return X(Y,J(fn),Pt)(Nt(hn,`tunnel.add`,e=>({proxy:e}))(async()=>({status:`success`}),e),e)}async function _n(e,t){return t.process.removeTunnel(e.name),{status:`success`,result:{name:e.name,success:!0}}}function vn(e){return X(Y,J(pn))(Nt(_n,`tunnel.delete`,e=>({name:e.name}))(async()=>({status:`success`}),e),e)}function yn(e){return async t=>{let n=t.payload.name;return e.nodeManager.unregisterNode(n),{status:`success`,result:{deletedNode:n,success:!0}}}}function bn(e){return X(Y,At,Ot,J(mn))(yn(e),e)}function xn(e){return async()=>{let t=e.runtime.snapshot();return{result:{running:e.process.isRunning(),config:e.process.getConfig()},version:t.version}}}function Sn(e){return async()=>{let t=e.runtime.snapshot();return{result:t,version:t.version}}}function Cn(e){return async()=>e.nodeManager?{result:e.nodeManager.listNodes({page:1,pageSize:100}),version:e.runtime.snapshot().version}:{result:{items:[],total:0,page:1,pageSize:100,hasMore:!1},version:e.runtime.snapshot().version}}function wn(e){return async t=>{if(!e.nodeManager)return{result:null,version:e.runtime.snapshot().version};let n=t.payload?.nodeId;return n?{result:e.nodeManager.getNode(n)??null,version:e.runtime.snapshot().version}:{result:null,version:e.runtime.snapshot().version}}}function Tn(e){return async()=>e.nodeManager?{result:e.nodeManager.getStatistics(),version:e.runtime.snapshot().version}:{result:{total:0,online:0,offline:0,connecting:0,error:0},version:e.runtime.snapshot().version}}function En(e){return async()=>{if(e.mode!==`client`)return{result:[],version:e.runtime.snapshot().version};try{return{result:await e.process.listTunnels(),version:e.runtime.snapshot().version}}catch{return{result:[],version:e.runtime.snapshot().version}}}}function Dn(e){return async t=>{if(e.mode!==`client`)return{result:null,version:e.runtime.snapshot().version};let n=t.payload?.name;if(!n)return{result:null,version:e.runtime.snapshot().version};try{return{result:await e.process.getTunnel(n)??null,version:e.runtime.snapshot().version}}catch{return{result:null,version:e.runtime.snapshot().version}}}}function On(e){return{"process.status":xn(e),"runtime.snapshot":Sn(e),"node.list":Cn(e),"node.get":wn(e),"node.statistics":Tn(e),"proxy.list":En(e),"proxy.get":Dn(e)}}const kn=/^[a-z]:/i,An={debug:0,info:1,success:1,warn:2,error:3},jn={reset:`\x1B[0m`,dim:`\x1B[2m`,debug:`\x1B[36m`,info:`\x1B[34m`,success:`\x1B[32m`,warn:`\x1B[33m`,error:`\x1B[31m`};function Mn(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}`}function Nn(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function Pn(e){return e.padEnd(7)}function Fn(){return ne()}function In(e,t){return e.startsWith(`/`)||kn.test(e)?e:se(t,e)}var Ln=class{currentDate;logFilePath;logDir;constructor(e){this.logDir=e,this.currentDate=Nn(new Date),this.ensureLogDir(),this.logFilePath=this.getLogFilePath()}ensureLogDir(){i(this.logDir)||a(this.logDir,{recursive:!0})}getLogFilePath(){return se(this.logDir,`frp-bridge-${this.currentDate}.log`)}write(e){let n=Nn(new Date);n!==this.currentDate&&(this.currentDate=n,this.logFilePath=this.getLogFilePath());try{t(this.logFilePath,`${e}\n`,`utf-8`)}catch{}}};let Rn={};function zn(e){Rn={...Rn,...e}}function Z(e,t){let n={};n=typeof t==`string`?{level:t}:t??{};let{level:r=`info`,dir:i=`logs`,workspaceRoot:a=Rn.workspaceRoot??Fn(),enableConsole:o=!0,enableFile:s=!0}=n,c=In(i,a),l={value:r},u=s?new Ln(c):null;function d(e,t){return(n,r)=>{if(An[t]<An[l.value])return;let i=Mn(new Date),a=`[${e}]`,s=Pn(t.toUpperCase()),c=``;r&&(c=r instanceof Error?` ${r.message}${r.stack?`\n${r.stack}`:``}`:` ${JSON.stringify(r)}`);let d=`${i} ${s} ${a} ${n}${c}`;if(o){let e=jn[t],r=`${jn.dim}${i}${jn.reset} ${e}${s}${jn.reset} ${a} ${n}${c}`;console.log(r)}u&&u.write(d)}}return{debug:d(e,`debug`),info:d(e,`info`),success:d(e,`success`),warn:d(e,`warn`),error:d(e,`error`),setLevel(e){l.value=e}}}Z(`Core`);const Bn=Z(`ConfigMerger`),Vn=Z(`NodeMgr`),Hn=Z(`RpcClient`),Un=Z(`RpcServer`),Wn=Z(`RpcMiddleware`),Gn=Z(`Process`);Z(`Node`),Z(`Tunnel`);const Kn=Z(`BinaryManager`),qn=Z(`PresetConfig`),Jn=Z(`ConfigStore`),Yn=Z(`ClientCollector`);Z(`Runtime`),Z(`ProcessManager`);var Xn=class{nodeId;heartbeatInterval;log=Yn;heartbeatTimer;constructor(e={}){this.nodeId=e.nodeId,this.heartbeatInterval=e.heartbeatInterval??3e4}setNodeId(e){this.nodeId=e}collectNodeInfo(){let e=te(),t=oe();return{hostname:re(),osType:ie(),osRelease:ae(),cpuCores:e.length,memTotal:t,protocol:`tcp`,serverAddr:``,serverPort:0}}collectHeartbeat(){if(!this.nodeId)throw new R(`Node ID not set. Call setNodeId() first or wait for registration.`);let e=te(),t=oe();return{nodeId:this.nodeId,status:`online`,lastHeartbeat:Date.now(),cpuCores:e.length,memTotal:t}}startHeartbeat(e,t){if(this.heartbeatTimer){this.log.debug?.(`Heartbeat already running`);return}let n=t??this.heartbeatInterval;try{e(this.collectHeartbeat())}catch(e){this.log.error?.(`Failed to collect initial heartbeat`,e)}this.heartbeatTimer=setInterval(()=>{try{e(this.collectHeartbeat())}catch(e){this.log.error?.(`Failed to collect heartbeat`,e)}},n),this.log.info?.(`Heartbeat started with interval ${n}ms`)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0,this.log.info?.(`Heartbeat stopped`))}isHeartbeatRunning(){return!!this.heartbeatTimer}},Zn=class{indexPath;nodeDir;constructor(e){this.storagePath=e,this.nodeDir=e,this.indexPath=j(e,`nodes.json`),i(this.nodeDir)||a(this.nodeDir,{recursive:!0})}async save(e){await _(j(this.nodeDir,`node-${e.id}.json`),JSON.stringify(e,null,2),`utf-8`),await this.updateIndex(e.id,!0)}async delete(e){let t=j(this.nodeDir,`node-${e}.json`);try{await g(t)}catch{}await this.updateIndex(e,!1)}async load(e){let t=j(this.nodeDir,`node-${e}.json`);try{let e=await p(t,`utf-8`);return JSON.parse(e)}catch{return}}async list(){try{let e=await p(this.indexPath,`utf-8`),t=JSON.parse(e),n=[];for(let e of t)try{let t=await this.load(e);t&&n.push(t)}catch{}return n}catch{return[]}}async updateIndex(e,t){let n=[];try{let e=await p(this.indexPath,`utf-8`);n=JSON.parse(e)}catch{}t?n.includes(e)||n.push(e):n=n.filter(t=>t!==e),await _(this.indexPath,JSON.stringify(n,null,2),`utf-8`)}},Qn=class extends w{nodes=new Map;heartbeatTimers=new Map;tunnelRegistry=new Map;storage;heartbeatTimeout;log=Vn;constructor(e,t={},n){super(),this.context=e,this.heartbeatTimeout=t.heartbeatTimeout??9e4,this.storage=n}async initialize(){if(this.storage)try{let e=await this.storage.list();for(let t of e)this.nodes.set(t.id,t),this.setupHeartbeatTimer(t.id);this.log.info(`Loaded ${e.length} nodes from storage`)}catch(e){this.log.error(`Failed to load nodes from storage`,{error:e})}}async registerNode(e){let t=Date.now(),n=C(),r={id:n,ip:e.ip,port:e.port,protocol:e.protocol,serverAddr:e.serverAddr,serverPort:e.serverPort,hostname:e.hostname,osType:e.osType,osRelease:e.osRelease,platform:e.platform,cpuCores:e.cpuCores,memTotal:e.memTotal,frpVersion:e.frpVersion,bridgeVersion:e.bridgeVersion,token:e.token,status:`online`,connectedAt:t,lastHeartbeat:t,createdAt:t,updatedAt:t};if(this.nodes.set(n,r),this.setupHeartbeatTimer(n),this.storage)try{await this.storage.save(r)}catch(e){this.log.error(`Failed to save node`,{nodeId:n,error:e})}return this.emit(`node:registered`,{type:`node:registered`,timestamp:t,payload:{nodeId:n,nodeInfo:r}}),this.log.success(`Node registered`,{nodeId:n,hostname:e.hostname,ip:e.ip}),r}async updateHeartbeat(e){let t=this.nodes.get(e.nodeId);if(!t){this.log.debug(`Heartbeat for unknown node`,{nodeId:e.nodeId});return}let n=t.status,r=Date.now();if(t.status=e.status,t.lastHeartbeat=r,t.updatedAt=r,e.cpuCores!==void 0&&(t.cpuCores=e.cpuCores),e.memTotal!==void 0&&(t.memTotal=e.memTotal),this.setupHeartbeatTimer(e.nodeId),this.storage)try{await this.storage.save(t)}catch(t){this.log.error(`Failed to save node heartbeat`,{nodeId:e.nodeId,error:t})}this.emit(`node:heartbeat`,{type:`node:heartbeat`,timestamp:r,payload:{nodeId:e.nodeId}}),n!==e.status&&(this.log.info(`Node status changed`,{nodeId:e.nodeId,oldStatus:n,newStatus:e.status}),this.emit(`node:statusChanged`,{type:`node:statusChanged`,timestamp:r,payload:{nodeId:e.nodeId,oldStatus:n,newStatus:e.status}}))}async unregisterNode(e){let t=this.nodes.get(e);if(!t){this.log.debug(`Attempted to unregister unknown node`,{nodeId:e});return}let n=Date.now();if(this.nodes.delete(e),this.clearHeartbeatTimer(e),this.clearNodeTunnels(e),this.storage)try{await this.storage.delete(e)}catch(t){this.log.error(`Failed to delete node`,{nodeId:e,error:t})}this.emit(`node:unregistered`,{type:`node:unregistered`,timestamp:n,payload:{nodeId:e}}),this.log.info(`Node unregistered`,{nodeId:e,hostname:t.hostname})}async getNode(e){return this.nodes.get(e)}async listNodes(e){let t=e?.page??1,n=e?.pageSize??20,r=e?.status,i=e?.search?.toLowerCase(),a=Array.from(this.nodes.values());r&&(a=a.filter(e=>e.status===r)),e?.labels&&(a=a.filter(t=>t.labels?Object.entries(e.labels).every(([e,n])=>t.labels?.[e]===n):!1)),i&&(a=a.filter(e=>e.hostname?.toLowerCase().includes(i)||e.ip.toLowerCase().includes(i)||e.id.toLowerCase().includes(i)));let o=a.length,s=(t-1)*n,c=s+n;return{items:a.slice(s,c),total:o,page:t,pageSize:n,hasMore:c<o}}async getStatistics(){let e=Array.from(this.nodes.values());return{total:e.length,online:e.filter(e=>e.status===`online`).length,offline:e.filter(e=>e.status===`offline`).length,connecting:e.filter(e=>e.status===`connecting`).length,error:e.filter(e=>e.status===`error`).length}}hasNode(e){return this.nodes.has(e)}getOnlineNodes(){return Array.from(this.nodes.values()).filter(e=>e.status===`online`)}getOfflineNodes(){return Array.from(this.nodes.values()).filter(e=>e.status===`offline`)}getNodesByStatus(e){return Array.from(this.nodes.values()).filter(t=>t.status===e)}setupHeartbeatTimer(e){this.clearHeartbeatTimer(e);let t=setTimeout(()=>{this.handleHeartbeatTimeout(e)},this.heartbeatTimeout);this.heartbeatTimers.set(e,t)}clearHeartbeatTimer(e){let t=this.heartbeatTimers.get(e);t&&(clearTimeout(t),this.heartbeatTimers.delete(e))}async handleHeartbeatTimeout(e){let t=this.nodes.get(e);if(!t)return;let n=t.status;if(t.status=`offline`,t.updatedAt=Date.now(),this.storage)try{await this.storage.save(t)}catch(t){this.log.error(`Failed to save node after timeout`,{nodeId:e,error:t})}this.emit(`node:statusChanged`,{type:`node:statusChanged`,timestamp:Date.now(),payload:{nodeId:e,oldStatus:n,newStatus:`offline`,reason:`heartbeat_timeout`}}),this.log.warn(`Node heartbeat timeout`,{nodeId:e,hostname:t.hostname})}async syncTunnels(e){let{nodeId:t,tunnels:n,timestamp:r}=e,i=this.nodes.get(t);if(!i){this.log.warn(`Tunnel sync failed: node not found`,{nodeId:t});return}if(this.tunnelRegistry.set(t,n),i.tunnels=n,i.updatedAt=r,this.storage)try{await this.storage.save(i)}catch(e){this.log.error(`Failed to save node after tunnel sync`,{nodeId:t,error:e})}this.emit(`tunnel:synced`,{type:`tunnel:synced`,timestamp:Date.now(),payload:{nodeId:t,tunnelCount:n.length}}),this.log.success(`Tunnels synced for node`,{nodeId:t,tunnelCount:n.length})}getNodeTunnels(e){return this.tunnelRegistry.get(e)||[]}getAllTunnels(){return new Map(this.tunnelRegistry)}isRemotePortInUse(e,t){for(let[n,r]of this.tunnelRegistry.entries())if(!(t&&n===t))for(let t of r){let r=t.remotePort;if(r&&r===e)return{inUse:!0,nodeId:n,tunnelName:t.name}}return{inUse:!1}}clearNodeTunnels(e){this.tunnelRegistry.delete(e),this.log.debug(`Cleared tunnels for node`,{nodeId:e})}async dispose(){for(let e of this.heartbeatTimers.values())clearTimeout(e);this.heartbeatTimers.clear(),this.tunnelRegistry.clear(),this.log.info(`NodeManager disposed`)}};const $n={frps:{bindPort:7e3,vhostHTTPPort:7e3,vhostHTTPSPort:443,dashboardPort:7500,dashboardUser:`admin`,dashboardPassword:`admin`},frpc:{serverPort:7e3}};function er(e,t,n){let r=[],i=n===`frps`?e.frps:e.frpc;if(!i)return Bn.warn(`No config found for type ${n}, returning userConfig only`),t;let a={};if(n===`frps`){let e=i;if(e.bindPort&&(a.bindPort=e.bindPort),e.vhostHTTPPort&&(a.vhostHTTPPort=e.vhostHTTPPort),e.vhostHTTPSPort&&(a.vhostHTTPSPort=e.vhostHTTPSPort),e.domain&&(a.domain=e.domain),e.subdomainHost&&(a.subdomainHost=e.subdomainHost),e.dashboardPort||e.dashboardUser||e.dashboardPassword){let t={};e.dashboardPort&&(t.addr=`0.0.0.0`,t.port=e.dashboardPort),e.dashboardUser&&(t.user=e.dashboardUser),e.dashboardPassword&&(t.password=e.dashboardPassword),a.webServer=t,Bn.info(`webServer config added:`,{webServer:t})}e.authToken&&(a.auth={token:e.authToken})}else{let e=i;e.serverAddr&&(a.serverAddr=e.serverAddr),e.serverPort&&(a.serverPort=e.serverPort),e.user&&(a.user=e.user),e.heartbeatInterval&&(a.heartbeatInterval=e.heartbeatInterval),e.authToken&&(a.auth={token:e.authToken})}return r.push(ir(a,``)),t.trim()&&r.push(t.trim()),r.filter(Boolean).join(`
251
+ `)}async function tr(e,t,n,r){let i=er(n,rr(t),r);U(e.includes(`/`)||e.includes(`\\`)?e.substring(0,Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))):`.`),await _(e,i,`utf-8`)}function nr(e){let t=new Set([`name`,`type`,`localIP`,`localPort`,`annotations`,`metadatas`]);return{tcp:new Set([...t,`remotePort`]),udp:new Set([...t,`remotePort`]),http:new Set([...t,`customDomains`,`subdomain`,`locations`,`hostHeaderRewrite`,`httpUser`,`httpPassword`]),https:new Set([...t,`customDomains`,`subdomain`]),stcp:new Set([...t,`secretKey`,`allowUsers`]),xtcp:new Set([...t,`secretKey`,`allowUsers`]),sudp:new Set([...t,`secretKey`,`allowUsers`]),tcpmux:new Set([...t,`customDomains`,`subdomain`,`multiplexer`,`httpUser`,`httpPassword`,`routeByHTTPUser`])}[e.toLowerCase()]||t}function rr(e){if(!e||e.length===0)return``;let t=[];for(let n of e){t.push(``),t.push(`[[proxies]]`);let e=nr(n.type);for(let[r,i]of Object.entries(n))if(i!=null&&e.has(r)){if(typeof i==`string`)t.push(`${r} = "${i}"`);else if(typeof i==`number`||typeof i==`boolean`)t.push(`${r} = ${i}`);else if(Array.isArray(i))i.length>0&&t.push(`${r} = ${JSON.stringify(i)}`);else if(typeof i==`object`){let e=[];for(let[t,n]of Object.entries(i))n!=null&&(typeof n==`string`?e.push(`${t} = "${n}"`):typeof n==`boolean`||typeof n==`number`?e.push(`${t} = ${n}`):Array.isArray(n)&&n.length>0&&e.push(`${t} = ${JSON.stringify(n)}`));e.length>0&&(t.push(`[${r}]`),t.push(...e))}}}return t.join(`
252
+ `)}function ir(e,t=``){let n=[];for(let[r,i]of Object.entries(e))if(i!=null)if(typeof i==`object`&&!Array.isArray(i)){let e=t?`${t}.${r}`:r;n.push(`[${e}]`);for(let[e,t]of Object.entries(i))typeof t==`string`?n.push(`${e} = "${t}"`):(typeof t==`boolean`||typeof t==`number`)&&n.push(`${e} = ${t}`)}else typeof i==`string`?n.push(`${r} = "${i}"`):(typeof i==`boolean`||typeof i==`number`)&&n.push(`${r} = ${i}`);return n.join(`
253
+ `)}function ar(e){return Tt(e)}function or(e,t){let n=[],r=t===`frps`?e.frps:e.frpc;if(!r)return{valid:!0,errors:[]};if(t===`frps`){let e=r;e.bindPort!==void 0&&(e.bindPort<1||e.bindPort>65535)&&n.push(`bindPort must be between 1 and 65535`),e.vhostHTTPPort!==void 0&&(e.vhostHTTPPort<1||e.vhostHTTPPort>65535)&&n.push(`vhostHTTPPort must be between 1 and 65535`),e.dashboardPort!==void 0&&(e.dashboardPort<1||e.dashboardPort>65535)&&n.push(`dashboardPort must be between 1 and 65535`)}else{let e=r;e.serverPort!==void 0&&(e.serverPort<1||e.serverPort>65535)&&n.push(`serverPort must be between 1 and 65535`),e.serverAddr&&typeof e.serverAddr!=`string`&&n.push(`serverAddr must be a string`)}return{valid:n.length===0,errors:n}}var sr=class{async extractArchive(e,t){if(!await Ve(`unzip`))throw new je(`unzip is required for extraction on Windows`);await Be(`unzip -o "${e}" -d "${t}"`)}setExecutable(e){}getArchiveExtension(){return`zip`}},cr=class{async extractArchive(e,t){let n=await Ve(`gzip`),r=await Ve(`tar`);if(!n||!r)throw new je(`gzip and tar are required for extraction`);await Be(`tar -xzf "${e}" -C "${t}"`)}setExecutable(e){n(e,493)}getArchiveExtension(){return`tar.gz`}},lr=class{static create(){return x.platform===`win32`?new sr:new cr}},ur=class{workDir;mode;log=Kn;platformStrategy=lr.create();version=null;binaryPath=``;constructor(e){this.workDir=e.workDir,this.mode=e.mode}async ensureInstalled(e){if(!this.version){this.version=e||He(this.workDir)||``;let t=this.mode===`client`?P.client:P.server;this.binaryPath=j(this.workDir,`bin`,this.version,t)}return this.hasBinary()||await this.download(),this.binaryPath}async download(e){let t=e||this.version||await this.getLatest(),n=Le(),r=Re(t,n),a=this.platformStrategy.getArchiveExtension(),o=j(this.workDir,`frp_${t}.${a}`);U(j(this.workDir,`bin`,t)),await ze(r,o);let s=j(this.workDir,`temp`);U(s),await this.platformStrategy.extractArchive(o,s);let c=j(j(s,`frp_${t}_${n}`),this.mode===`client`?P.client:P.server);if(!i(c))throw new ke(`Binary not found: ${c}`);await f(c,this.binaryPath),this.platformStrategy.setExecutable(this.binaryPath),this.version=t;let l=this.mode===`client`?P.client:P.server;this.binaryPath=j(this.workDir,`bin`,t,l),await h(o,{recursive:!0,force:!0}),await h(s,{recursive:!0,force:!0})}async update(e){if(this.version!==e){if(this.hasBinary()){let e=`${this.binaryPath}.bak`;await f(this.binaryPath,e)}await this.download(e)}}getInstalledVersion(){return this.version}getBinaryPath(){return this.binaryPath}hasBinary(){return i(this.binaryPath)}async remove(e){let t=e||this.version;if(!t)return;let n=this.mode===`client`?P.client:P.server,r=j(this.workDir,`bin`,t,n);i(r)&&await h(r,{recursive:!0,force:!0}),t===this.version&&(this.version=null,this.binaryPath=``)}async getLatest(){return Ie()}async checkUpdate(){let e=await this.getLatest();return{current:this.version,latest:e}}},dr=class{log=Jn;cache=new Map;cacheTTL;constructor(e={}){this.cacheTTL=e.cacheTTL??5e3}async load(e){let t=this.getFromCache(e);if(t)return t;if(!i(e))throw new I(`Config file not found: ${e}`);let n=o(e,`utf-8`),r=this.getFileMtime(e),a;try{a=q(n)}catch(e){throw new L(`Failed to parse config: ${e instanceof Error?e.message:String(e)}`)}return this.setToCache(e,a,r),a}async save(e,t){let n=this.validate(t);if(!n.valid)throw new L(`Config validation failed: ${n.errors.join(`, `)}`);let r=Tt(t),a=`${e}.tmp`;this.ensureDirectory(e),d(a,r,`utf-8`);try{c(a,e);let n=this.getFileMtime(e);this.setToCache(e,t,n)}catch(e){throw i(a)&&u(a),e}}merge(e,t){let n={...e};for(let r of Object.keys(t)){let i=t[r];r===`auth`?n[r]={...e.auth,...i}:n[r]=i??e[r]}return n}validate(e){let t=[];return!e||typeof e!=`object`?(t.push(`Config must be an object`),{valid:!1,errors:t}):{valid:t.length===0,errors:t}}exists(e){return i(e)}getRaw(e){return i(e)?o(e,`utf-8`):null}writeRaw(e,t){this.ensureDirectory(e),d(e,t,`utf-8`),this.invalidateCache(e)}invalidateCache(e){this.cache.delete(e)}clearCache(){this.cache.clear()}getFromCache(e){let t=this.cache.get(e);if(!t)return null;let n=Date.now(),r=this.getFileMtime(e);return t.mtime===r&&n-t.cachedAt<this.cacheTTL?t.config:(this.cache.delete(e),null)}setToCache(e,t,n){this.cache.set(e,{path:e,config:t,mtime:n,cachedAt:Date.now()})}getFileMtime(e){try{return l(e).mtimeMs}catch{return 0}}ensureDirectory(e){let t=e.substring(0,Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`)));t&&t!==e&&!i(t)&&a(t,{recursive:!0})}},fr=class{configStore;configPath;log=Z(`Node`);constructor(e){this.configStore=e.configStore,this.configPath=e.configPath}async setNode(e){let t=await this.loadConfig()||{};t.serverAddr=e.serverAddr,t.serverPort=e.serverPort??7e3,e.token&&(t.auth={...t.auth,token:e.token}),e.config&&Object.assign(t,e.config),await this.configStore.save(this.configPath,t),this.log.success(`Node configured`,{serverAddr:e.serverAddr,serverPort:e.serverPort??7e3})}async getNode(){let e=await this.loadConfig();return!e||!e.serverAddr?(this.log.debug(`Node not configured`),null):{id:`default`,name:`default`,serverAddr:e.serverAddr,serverPort:e.serverPort,token:e.auth?.token}}async updateNode(e){let t=await this.loadConfig()||{};e.serverAddr&&(t.serverAddr=e.serverAddr),e.serverPort&&(t.serverPort=e.serverPort),e.token&&(t.auth={...t.auth,token:e.token}),e.config&&Object.assign(t,e.config),await this.configStore.save(this.configPath,t),this.log.success(`Node updated`,{updates:Object.keys(e)})}async clearNode(){let{unlinkSync:e}=await import(`node:fs`),{existsSync:t}=await import(`node:fs`);t(this.configPath)?(e(this.configPath),this.log.success(`Node configuration cleared`)):this.log.debug(`No node configuration to clear`)}validateNode(e){let t=[];e.serverAddr||t.push(`Server address is required`),e.serverPort!==void 0&&(e.serverPort<1||e.serverPort>65535)&&t.push(`Server port must be between 1-65535`);let n=t.length===0;return n?this.log.debug(`Node validation passed`,{serverAddr:e.serverAddr}):this.log.warn(`Node validation failed`,{errors:t}),{valid:n,errors:t}}async loadConfig(){return this.configStore.exists(this.configPath)?this.configStore.load(this.configPath):null}},pr=class{log=qn;configDir;constructor(e){this.configDir=e.configDir||j(e.workDir,`config`)}getPresetConfigPath(e){return j(this.configDir,`${e}-preset.json`)}load(e){let t=this.getPresetConfigPath(e);if(!i(t))return this.log.info(`Preset config not found at ${t}, using defaults for ${e}`),{[e]:$n[e]||{}};try{let n=o(t,`utf-8`),r=JSON.parse(n);return{[e]:r}}catch(t){return this.log.error(`Failed to load preset config for ${e}:`,{error:t}),{[e]:$n[e]||{}}}}save(e,t){let n=this.getPresetConfigPath(e);U(this.configDir),d(n,JSON.stringify(t,null,2),`utf-8`),this.log.info(`Preset config saved for ${e}`)}getDefaultConfig(e){return $n[e]||{}}},mr=class extends w{log=Z(`Process`);process=null;processStartTime=null;currentBinaryPath=``;currentConfigPath=``;isManualStop=!1;gracefulTimeout=5e3;constructor(){super()}async start(e,t){this.validateStartPrerequisites(e,t),this.isRunning()&&await this.stop(),this.currentBinaryPath=e,this.currentConfigPath=t,this.log.info(`Starting process`,{binaryPath:e,configPath:t}),this.process=ee(e,[`-c`,t],{stdio:`inherit`}),this.processStartTime=Date.now(),this.isManualStop=!1,this.setupProcessListeners();let n=this.createProcessHandle();return this.log.success(`Process started`,{pid:n.pid,configPath:t}),this.emit(`process:started`,{type:`process:started`,timestamp:Date.now(),payload:{pid:n.pid,uptime:0,running:!0}}),n}async stop(){if(!this.process)return;this.isManualStop=!0;let e=this.process,t=e.pid;return this.log.info(`Stopping process`,{pid:t}),new Promise(n=>{let r=()=>{let e=this.processStartTime?Date.now()-this.processStartTime:void 0;this.emit(`process:stopped`,{type:`process:stopped`,timestamp:Date.now(),payload:{uptime:e,running:!1}}),this.processStartTime=null,this.log.success(`Process stopped`,{pid:t,uptime:e}),n()};e.exitCode===null?(e.once(`exit`,r),e.kill(`SIGTERM`),setTimeout(()=>{e.exitCode===null&&(this.log.warn(`Process did not exit gracefully, forcing kill`,{pid:t}),e.kill(`SIGKILL`))},this.gracefulTimeout)):r()}).finally(()=>{this.process=null})}async restart(e,t){let n=e,r=t;return this.log.info(`Restarting process`,{binaryPath:e,configPath:t}),this.isRunning()&&await this.stop(),await new Promise(e=>setTimeout(e,500)),this.start(n,r)}isRunning(){if(!this.process)return!1;let e=this.process.exitCode===null&&this.process.signalCode===null;return e||(this.process=null,this.processStartTime=null),e}getStatus(){return!this.process||!this.processStartTime?null:{pid:this.process.pid??0,running:this.isRunning(),uptime:Date.now()-this.processStartTime,startTime:this.processStartTime,exitCode:this.process.exitCode,signal:this.process.signalCode}}getPid(){return this.process?.pid??null}getUptime(){return this.processStartTime?Date.now()-this.processStartTime:0}validateStartPrerequisites(e,t){if(!i(e))throw new ke(`Binary not found: ${e}`);if(!i(t))throw new I(`Config file not found: ${t}`)}setupProcessListeners(){if(!this.process)return;let e=this.process,t=this.processStartTime;this.process.on(`exit`,(n,r)=>{if(this.process!==e)return;let i=t?Date.now()-t:void 0;this.isManualStop||(this.log.error(`Process exited unexpectedly`,{code:n,signal:r,uptime:i}),this.emit(`process:exited`,{type:`process:exited`,timestamp:Date.now(),payload:{code:n??void 0,signal:r??void 0,uptime:i,unexpected:!0,running:!1}})),this.process=null,this.processStartTime=null}),this.process.on(`error`,e=>{this.log.error(`Process error`,{error:e.message,pid:this.process?.pid}),this.emit(`process:error`,{type:`process:error`,timestamp:Date.now(),payload:{error:e.message,pid:this.process?.pid,running:!1}})})}createProcessHandle(){if(!this.process)throw new Te(`Process not initialized`,`PROCESS_NOT_INITIALIZED`);return{pid:this.process.pid??0,startTime:Date.now(),running:!0,exitCode:null,signal:null,configPath:this.currentConfigPath,binaryPath:this.currentBinaryPath}}},hr=class{configStore;configPath;log=Z(`Tunnel`);constructor(e){this.configStore=e.configStore,this.configPath=e.configPath}async add(e){let t=await this.loadConfig()||{};Array.isArray(t.proxies)||(t.proxies=[]),this.validateUniqueness(t,e),t.proxies.push(e),await this.configStore.save(this.configPath,t),this.log.success(`Tunnel added`,{name:e.name,type:e.type})}async get(e){let t=await this.loadConfig();if(!t)return this.log.debug(`Tunnel not found: config is empty`,{name:e}),null;if(Array.isArray(t.proxies)){let n=t.proxies.find(t=>t&&t.name===e)||null;return n||this.log.debug(`Tunnel not found in proxies array`,{name:e}),n}return t[e]||null}async update(e,t){let n=await this.loadConfig();if(!n)throw new B(`Tunnel ${e} not found`);if(Array.isArray(n.proxies)){let r=n.proxies.findIndex(t=>t&&t.name===e);if(r===-1)throw new B(`Tunnel ${e} not found`);let i=n.proxies[r],a={...i,...t},o=t.remotePort,s=i.remotePort;o&&o!==s&&this.validateRemotePort(n.proxies,o,a.type,r),n.proxies[r]=a}else if(n[e])n[e]={...n[e],...t};else throw new B(`Tunnel ${e} not found`);await this.configStore.save(this.configPath,n),this.log.success(`Tunnel updated`,{name:e,changes:Object.keys(t)})}async remove(e){let t=await this.loadConfig();if(!t){this.log.debug(`Cannot remove tunnel: config is empty`,{name:e});return}let n=!1;if(Array.isArray(t.proxies)){let r=t.proxies.findIndex(t=>t&&t.name===e);r===-1?this.log.debug(`Tunnel not found for removal`,{name:e}):(t.proxies.splice(r,1),n=!0,this.log.success(`Tunnel removed`,{name:e}))}else t[e]?(delete t[e],n=!0,this.log.success(`Tunnel removed`,{name:e})):this.log.debug(`Tunnel not found for removal`,{name:e});n&&await this.configStore.save(this.configPath,t)}async list(){let e=await this.loadConfig();if(!e)return this.log.debug(`List tunnels: config is empty`),[];let t=[];if(Array.isArray(e.proxies))for(let n of e.proxies)n&&typeof n==`object`&&`type`in n&&t.push(n);let n=new Set(t.map(e=>e.name));for(let[r,i]of Object.entries(e))if(r!==`proxies`&&typeof i==`object`&&i&&`type`in i&&!Array.isArray(i)){let e={...i,name:i.name||r};n.has(e.name)||(t.push(e),n.add(e.name))}return this.log.debug(`Listed tunnels`,{count:t.length}),t}async exists(e){return await this.get(e)!==null}validate(e){let t=[];e.name||t.push(`Tunnel name is required`),e.type||t.push(`Tunnel type is required`);let n=t.length===0;return n?this.log.debug(`Tunnel validation passed`,{name:e.name,type:e.type}):this.log.warn(`Tunnel validation failed`,{errors:t}),{valid:n,errors:t}}async loadConfig(){return this.configStore.exists(this.configPath)?this.configStore.load(this.configPath):null}validateUniqueness(e,t){let n=e.proxies||[];if(n.find(e=>e&&e.name===t.name))throw this.log.warn(`Tunnel name already exists`,{name:t.name}),new L(`Tunnel ${t.name} already exists`);let r=t.remotePort;r&&H(t.type)&&this.validateRemotePort(n,r,t.type),this.log.debug(`Tunnel uniqueness validation passed`,{name:t.name})}validateRemotePort(e,t,n,r=-1){if(H(n)){if(e.some((e,n)=>{if(n===r)return!1;let i=e.remotePort;return e&&i===t&&H(e.type)}))throw this.log.warn(`Remote port already in use`,{remotePort:t,type:n}),new L(`Remote port ${t} is already in use`);this.log.debug(`Remote port validation passed`,{remotePort:t,type:n})}}},gr=class extends w{workDir;mode;specifiedVersion;configPath;configDir;processController;configStore;binaryManager;presetConfigManager;tunnelManager=null;nodeManager=null;uptime=null;isManualStop=!1;constructor(e){super(),this.mode=e.mode,this.specifiedVersion=e.version,this.workDir=e.workDir||j(ne(),`.frp-bridge`),this.configPath=e.configPath||j(this.workDir,`frp${this.mode===`client`?`c`:`s`}.toml`),this.configDir=e.configDir||j(this.workDir,`config`),this.configStore=new dr,this.processController=new mr,this.binaryManager=new ur({workDir:this.workDir,mode:this.mode}),this.presetConfigManager=new pr({workDir:this.workDir,configDir:this.configDir}),this.mode===`client`&&(this.tunnelManager=new hr({configStore:this.configStore,configPath:this.configPath}),this.nodeManager=new fr({configStore:this.configStore,configPath:this.configPath})),this.processController.on(`process:started`,e=>{this.emit(e.type,e)}),this.processController.on(`process:stopped`,e=>{this.emit(e.type,e)}),this.processController.on(`process:exited`,e=>{this.emit(e.type,e)}),this.processController.on(`process:error`,e=>{this.emit(e.type,e)})}async ensureVersion(){return await this.binaryManager.ensureInstalled(this.specifiedVersion)}async downloadFrpBinary(){await this.binaryManager.download()}async updateFrpBinary(e){let t=e||await this.binaryManager.getLatest();await this.binaryManager.update(t)}hasBinary(){return this.binaryManager.hasBinary()}async getConfig(){return this.configStore.exists(this.configPath)?this.configStore.load(this.configPath):null}async updateConfig(e){let t=await this.getConfig(),n=this.configStore.merge(t||{},e);await this.configStore.save(this.configPath,n)}async backupConfig(){if(!this.configStore.exists(this.configPath))throw new I(`Config file does not exist`);let e=Date.now(),t=`${this.configPath}.${e}.bak`,{copyFile:n}=await import(`node:fs/promises`);return await n(this.configPath,t),t}getConfigPath(){return this.configPath}getConfigRaw(){return this.configStore.getRaw(this.configPath)}updateConfigRaw(e){this.configStore.writeRaw(this.configPath,e)}async start(){let e=await this.ensureVersion();if(this.isRunning()&&await this.stop(),this.hasBinary()||await this.downloadFrpBinary(),!this.configStore.exists(this.configPath))throw new I(`Config file does not exist`);await this.processController.start(e,this.configPath)}async stop(){this.processController.isRunning()&&(this.isManualStop=!0,await this.processController.stop(),this.uptime=null)}isRunning(){return this.processController.isRunning()}async addNode(e){if(!this.nodeManager)throw new z(`Nodes can only be added in client mode`);await this.nodeManager.setNode(e)}async getNode(){if(!this.nodeManager)throw new z(`Nodes are only available in client mode`);return this.nodeManager.getNode()}async updateNode(e){if(!this.nodeManager)throw new z(`Nodes can only be updated in client mode`);await this.nodeManager.updateNode(e)}async removeNode(){if(!this.nodeManager)throw new z(`Nodes can only be removed in client mode`);await this.nodeManager.clearNode()}async addTunnel(e){if(!this.tunnelManager)throw new z(`Tunnels can only be added in client mode`);await this.tunnelManager.add(e)}async getTunnel(e){if(!this.tunnelManager)throw new z(`Tunnels are only available in client mode`);return this.tunnelManager.get(e)}async updateTunnel(e,t){if(!this.tunnelManager)throw new z(`Tunnels can only be updated in client mode`);await this.tunnelManager.update(e,t)}async removeTunnel(e){if(!this.tunnelManager)throw new z(`Tunnels can only be removed in client mode`);await this.tunnelManager.remove(e)}async listTunnels(){if(!this.tunnelManager)throw new z(`Tunnels are only available in client mode`);return this.tunnelManager.list()}async generateConfig(e=!1){let t=this.mode===`server`?`frps`:`frpc`;if(!e&&this.configStore.exists(this.configPath))return;let n=this.presetConfigManager.load(t),r=[];this.mode===`client`&&this.tunnelManager&&(r=await this.tunnelManager.list()),await tr(this.configPath,r,n,t),Gn.info(`Generated FRP config: ${this.configPath}`)}getPresetConfig(){let e=this.mode===`server`?`frps`:`frpc`;return this.presetConfigManager.load(e)}savePresetConfig(e){let t=this.mode===`server`?`frps`:`frpc`;this.presetConfigManager.save(t,e)}queryProcess(){let e=this.uptime?Date.now()-this.uptime:0;return{pid:this.processController.getStatus()?.pid,uptime:e}}async dispose(){this.isRunning()&&await this.stop(),this.removeAllListeners()}};let _r=function(e){return e.REGISTER=`register`,e.COMMAND=`command`,e.RESPONSE=`response`,e.PING=`ping`,e.PONG=`pong`,e}({});function vr(e){return typeof e==`object`&&!!e&&e.type===_r.REGISTER}function yr(e){return typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.method==`string`}function br(e){return typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.status==`string`}function xr(e){return typeof e==`object`&&!!e&&e.type===_r.PING}function Sr(e){return typeof e==`object`&&!!e&&e.type===_r.PONG}function Cr(e){return typeof e==`object`&&!!e&&(e.type===`command`||e.type===`event`)&&typeof e.action==`string`&&`payload`in e}function wr(e){return Cr(e)&&e.type===`command`&&typeof e.id==`string`}function Tr(e){return Cr(e)&&e.type===`event`}function Er(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.name==`string`&&typeof t.type==`string`&&typeof t.localPort==`number`&&(t.remotePort===void 0||typeof t.remotePort==`number`)}function Dr(e){return typeof e==`object`&&!!e&&typeof e.name==`string`}function Or(e){return typeof e==`object`&&!!e&&typeof e.name==`string`}function kr(){return async(e,t)=>{let{request:n}=e;Wn.info(`RPC request`,{method:n.method,params:n.params});try{await t(),Wn.info(`RPC response`,{method:n.method,duration:Date.now()-e.startTime,status:e.response.status})}catch(e){throw Wn.error(`RPC error`,{method:n.method,error:e instanceof Error?e.message:`Unknown error`}),e}}}function Ar(e){return async(t,n)=>{let{request:r,response:i}=t,a=r.params.token;if(!await e(a)){i.status=`error`,i.error={code:`UNAUTHORIZED`,message:`Invalid or missing token`};return}await n()}}function jr(e){return async(t,n)=>{let{request:r}=t,i=r.timeout??e,a=new Promise((e,t)=>{setTimeout(()=>{t(Error(`RPC timeout: ${r.method}`))},i)});try{await Promise.race([n(),a])}catch(e){throw t.response.status=`error`,t.response.error={code:`TIMEOUT`,message:e instanceof Error?e.message:`Request timeout`},e}}}function Mr(){return async(e,t)=>{try{await t()}catch(t){e.response.status=`error`,e.response.error={code:t instanceof Error?t.name:`UNKNOWN_ERROR`,message:t instanceof Error?t.message:`Unknown error`},Wn.error(`RPC middleware error`,t)}}}var Nr=class{middlewares=[];use(e){return this.middlewares.push(e),this}async execute(e,t){let n={request:e,response:{id:e.id},startTime:Date.now()},r=async()=>this.executeHandler(n,t);for(let e=this.middlewares.length-1;e>=0;e--){let t=this.middlewares[e],i=r;r=async()=>t(n,i)}return await r(),n.response}async executeHandler(e,t){let n=await t();e.response.result=n,e.response.status=`success`}clear(){this.middlewares=[]}},Pr=class{constructor(e=10,t=1e3,n=3e4){this.maxAttempts=e,this.baseDelay=t,this.maxDelay=n}shouldReconnect(e){return e<this.maxAttempts}getDelay(e){let t=Math.min(this.baseDelay*2**e,this.maxDelay),n=t*.25*(Math.random()*2-1);return Math.max(0,Math.floor(t+n))}onMaxAttemptsReached(){let e=`Max reconnection attempts reached (${this.maxAttempts})`;Hn.error(e)}},Fr=class{constructor(e=10,t=5e3){this.maxAttempts=e,this.interval=t}shouldReconnect(e){return e<this.maxAttempts}getDelay(){return this.interval}onMaxAttemptsReached(){let e=`Max reconnection attempts reached (${this.maxAttempts})`;Hn.error(e)}},Ir=class{constructor(e=10,t=1e3,n=1e3,r=3e4){this.maxAttempts=e,this.baseDelay=t,this.increment=n,this.maxDelay=r}shouldReconnect(e){return e<this.maxAttempts}getDelay(e){return Math.min(this.baseDelay+e*this.increment,this.maxDelay)}onMaxAttemptsReached(){let e=`Max reconnection attempts reached (${this.maxAttempts})`;Hn.error(e)}},Lr=class{constructor(e=1e3,t=3e4){this.baseDelay=e,this.maxDelay=t}shouldReconnect(){return!0}getDelay(e){return Math.min(this.baseDelay*2**e,this.maxDelay)}onMaxAttemptsReached(){}},Q=k(((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:()=>{}}})),Rr=k(((e,t)=>{let{EMPTY_BUFFER:n}=Q(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=A(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),zr=k(((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])}}}})),Br=k(((e,t)=>{let n=A(`zlib`),r=Rr(),i=zr(),{kStatusCode:a}=Q(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Vr=k(((e,t)=>{let{isUtf8:n}=A(`buffer`),{hasBlob:r}=Q(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=A(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Hr=k(((e,t)=>{let{Writable:n}=A(`stream`),r=Br(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Q(),{concat:c,toArrayBuffer:l,unmask:u}=Rr(),{isValidStatusCode:d,isValidUTF8:f}=Vr(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),Ur=k(((e,t)=>{let{Duplex:n}=A(`stream`),{randomFillSync:r}=A(`crypto`),i=Br(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Q(),{isBlob:c,isValidStatusCode:l}=Vr(),{mask:u,toBuffer:d}=Rr(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(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`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]: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,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(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):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(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[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],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(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],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 _(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 v(e,t,n){_(e,t,n),e.onerror(t)}})),Wr=k(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Q(),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?!1: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)}})),Gr=k(((e,t)=>{let{tokenChars:n}=Vr();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}})),Kr=k(((e,t)=>{let n=A(`events`),r=A(`https`),i=A(`http`),a=A(`net`),o=A(`tls`),{randomBytes:s,createHash:c}=A(`crypto`),{Duplex:l,Readable:u}=A(`stream`),{URL:d}=A(`url`),f=Br(),p=Hr(),m=Ur(),{isBlob:h}=Vr(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:ee,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:te}=Q(),{EventTarget:{addEventListener:ne,removeEventListener:re}}=Wr(),{format:ie,parse:ae}=Gr(),{toBuffer:oe}=Rr(),se=Symbol(`kAborted`),C=[8,13],w=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],T=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var E=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ce(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,de),i.on(`drain`,fe),i.on(`error`,pe),i.on(`message`,he),i.on(`ping`,ge),i.on(`pong`,_e),a.onerror=j,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,be),t.on(`data`,M),t.on(`end`,xe),t.on(`error`,N),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){O(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())}),ye(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){k(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){k(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){k(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){O(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(E,`CONNECTING`,{enumerable:!0,value:w.indexOf(`CONNECTING`)}),Object.defineProperty(E.prototype,`CONNECTING`,{enumerable:!0,value:w.indexOf(`CONNECTING`)}),Object.defineProperty(E,`OPEN`,{enumerable:!0,value:w.indexOf(`OPEN`)}),Object.defineProperty(E.prototype,`OPEN`,{enumerable:!0,value:w.indexOf(`OPEN`)}),Object.defineProperty(E,`CLOSING`,{enumerable:!0,value:w.indexOf(`CLOSING`)}),Object.defineProperty(E.prototype,`CLOSING`,{enumerable:!0,value:w.indexOf(`CLOSING`)}),Object.defineProperty(E,`CLOSED`,{enumerable:!0,value:w.indexOf(`CLOSED`)}),Object.defineProperty(E.prototype,`CLOSED`,{enumerable:!0,value:w.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(E.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(E.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),E.prototype.addEventListener=ne,E.prototype.removeEventListener=re,t.exports=E;function ce(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:C[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!C.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${C.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;D(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?ue:le),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=ie({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!T.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=v(o);o.timeout&&x.on(`timeout`,()=>{O(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[se]||(x=e._req=null,D(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){O(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{D(e,SyntaxError(`Invalid URL: ${i}`));return}ce(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||O(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==E.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){O(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+ee).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){O(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){O(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){O(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=ae(u)}catch{O(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){O(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{O(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function D(e,t){e._readyState=E.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function le(e){return e.path=e.socketPath,a.connect(e)}function ue(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function O(e,t,n){e._readyState=E.CLOSING;let r=Error(n);Error.captureStackTrace(r,O),t.setHeader?(t[se]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(D,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function k(e,t,n){if(t){let n=h(t)?t.size:oe(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${w[e.readyState]})`);process.nextTick(n,t)}}function de(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,M),process.nextTick(ve,n._socket),e===1005?n.close():n.close(e,t))}function fe(){let e=this[S];e.isPaused||e._socket.resume()}function pe(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,M),process.nextTick(ve,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function me(){this[S].emitClose()}function he(e,t){this[S].emit(`message`,e,t)}function ge(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,te),t.emit(`ping`,e)}function _e(e){this[S].emit(`pong`,e)}function ve(e){e.resume()}function j(e){let t=this[S];t.readyState!==E.CLOSED&&(t.readyState===E.OPEN&&(t._readyState=E.CLOSING,ye(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ye(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function be(){let e=this[S];if(this.removeListener(`close`,be),this.removeListener(`data`,M),this.removeListener(`end`,xe),e._readyState=E.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,me),e._receiver.on(`finish`,me))}function M(e){this[S]._receiver.write(e)||this.pause()}function xe(){let e=this[S];e._readyState=E.CLOSING,e._receiver.end(),this.end()}function N(){let e=this[S];this.removeListener(`error`,N),this.on(`error`,te),e&&(e._readyState=E.CLOSING,this.destroy())}})),qr=k(((e,t)=>{Kr();let{Duplex:n}=A(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Jr=k(((e,t)=>{let{tokenChars:n}=Vr();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}})),Yr=k(((e,t)=>{let n=A(`events`),r=A(`http`),{Duplex:i}=A(`stream`),{createHash:a}=A(`crypto`),o=Gr(),s=Br(),c=Jr(),l=Kr(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=Q(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
254
+ `).join(`\r
255
+ `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
256
+ `)+`\r
257
+ \r
258
+ `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));qr(),Hr(),Ur();var $=fe(Kr(),1),Xr=fe(Yr(),1);function Zr(e){return typeof e==`string`?e:T.isBuffer(e)?e.toString():e instanceof ArrayBuffer?T.from(new Uint8Array(e)).toString():Array.isArray(e)?T.concat(e.map(e=>T.isBuffer(e)?e:T.from(e))).toString():T.from(e).toString()}function Qr(e){try{let t=Zr(e);return JSON.parse(t)}catch(e){Wn.warn(`parse message failed`,e);return}}var $r=class{ws=null;reconnectTimer;reconnectAttempt=0;reconnectStrategy;connectionState=`disconnected`;log=Hn;constructor(e){this.options=e,this.reconnectStrategy=e.reconnectStrategy??new Pr}async connect(){this.reconnectAttempt=0,await this.createConnection()}disconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.ws?.close(),this.ws=null,this.connectionState=`disconnected`,this.log.info(`Disconnected from server`)}getConnectionState(){return this.connectionState}isConnected(){return this.connectionState===`connected`&&this.ws?.readyState===$.default.OPEN}sendEvent(e){if(!this.isConnected())return this.log.warn(`Not connected, cannot send event`),!1;try{return this.send(e),!0}catch(e){return this.log.error(`Send event error:`,{error:e}),!1}}async createConnection(){return new Promise((e,t)=>{let n=new $.default(this.options.url);this.ws=n,this.connectionState=`connecting`,n.on(`open`,async()=>{try{let t=await this.options.getRegisterPayload();this.send({type:`register`,nodeId:this.options.nodeId,payload:t}),this.connectionState=`connected`,this.reconnectAttempt=0,this.log.success(`Connected to server as ${this.options.nodeId}`),e()}catch(e){this.connectionState=`disconnected`,this.log.error(`rpc client register failed`,{error:e}),t(e)}}),n.on(`message`,e=>{this.handleMessage(e).catch(e=>{this.log.error(`rpc client handle message failed`,{error:e})})}),n.on(`close`,()=>{this.connectionState=`disconnected`,this.log.info(`Connection closed, scheduling reconnect`),this.scheduleReconnect()}),n.on(`error`,e=>{this.log.warn(`rpc client socket error`,{error:e}),this.scheduleReconnect(),t(e)})})}async handleMessage(e){let t=Qr(e);if(t){if(xr(t)){this.send({type:`pong`,timestamp:Date.now()});return}if(wr(t)){await this.handleCommandEvent(t);return}yr(t)&&await this.handleRpcRequest(t)}}async handleCommandEvent(e){this.log.info(`Received command: ${e.action}`);try{if(this.options.handleCommand){let t=await this.options.handleCommand(e),n={type:`event`,action:`${e.action}ed`,payload:{success:!0,result:t},id:e.id};this.send(n)}else{let t={type:`event`,action:`${e.action}ed`,payload:{success:!1,error:`No command handler registered`},id:e.id};this.send(t)}}catch(t){let n={type:`event`,action:`${e.action}ed`,payload:{success:!1,error:t instanceof Error?t.message:`Unknown error`},id:e.id};this.send(n)}}async handleRpcRequest(e){try{let t=await this.options.handleRequest(e);this.send({id:e.id,status:`success`,result:t})}catch(t){this.send({id:e.id,status:`error`,error:{code:`EXECUTION_ERROR`,message:t instanceof Error?t.message:`Unknown error`}})}}send(e){this.ws?.readyState===$.default.OPEN&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.reconnectTimer)return;if(!this.reconnectStrategy.shouldReconnect(this.reconnectAttempt)){this.reconnectStrategy.onMaxAttemptsReached(),this.log.error(`Max reconnection attempts reached`);return}let e=this.reconnectStrategy.getDelay(this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.createConnection().catch(e=>{this.log.error(`rpc client reconnect failed`,{error:e}),this.scheduleReconnect()})},e),this.log.info(`Reconnecting in ${e}ms (attempt ${this.reconnectAttempt})`)}},ei=class{clients=new Map;pendingRequests=new Map;commandStatuses=new Map;commandTimers=new Map;wsToNode=new Map;heartbeatTimer;cleanupTimer;server;defaultCommandTimeout;log=Un;constructor(e){this.options=e,this.defaultCommandTimeout=e.commandTimeout??6e4,this.cleanupTimer=setInterval(()=>{this.clearOldStatuses()},600*1e3)}start(){this.server||(this.server=new Xr.default({port:this.options.port}),this.server.on(`connection`,(e,t)=>{let n=new URL(t.url??`/`,`ws://localhost`).searchParams.get(`token`)??void 0;e.on(`message`,t=>{this.handleMessage(e,t,n).catch(e=>{this.log.error(`rpc server handle message failed`,{error:e})})}),e.on(`close`,()=>{this.handleClose(e)})}),this.startHeartbeat(),this.log.success(`RpcServer started`,{port:this.options.port}))}stop(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0,this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,this.pendingRequests.forEach(e=>clearTimeout(e.timer)),this.pendingRequests.clear(),this.commandTimers.forEach(e=>clearTimeout(e)),this.commandTimers.clear(),this.clients.forEach(e=>e.close()),this.clients.clear(),this.wsToNode.clear(),this.commandStatuses.clear(),this.server?.close(),this.server=void 0}async rpcCall(e,t,n,r=3e4){let i=this.clients.get(e);if(!i||i.readyState!==$.default.OPEN)throw new B(`Client not connected: ${e}`);if(this.options.authorize&&!await this.options.authorize(e,t))throw new z(`Unauthorized: ${e} not allowed to call ${t}`);let a=C(),o={id:a,method:t,params:n,timeout:r};return new Promise((e,n)=>{let s=setTimeout(()=>{this.pendingRequests.delete(a),n(Error(`RPC timeout: ${t}`))},r);this.pendingRequests.set(a,{resolve:e,reject:n,timer:s}),i.send(JSON.stringify(o))})}sendToNode(e,t){let n=this.clients.get(e);if(!n)return this.log.error(`Node not found: ${e}`),!1;if(n.readyState!==$.default.OPEN)return this.log.error(`Node not ready: ${e}`),!1;try{if(n.send(JSON.stringify(t)),t.type===`command`&&t.id){this.commandStatuses.set(t.id,{commandId:t.id,nodeId:e,action:t.action,status:`pending`,timestamp:Date.now()});let n=this.commandTimers.get(t.id);n&&clearTimeout(n);let r=setTimeout(()=>{this.commandTimers.delete(t.id);let e=this.commandStatuses.get(t.id);e&&e.status===`pending`&&(e.status=`failed`,e.error=`Command timeout`,this.log.warn(`Command ${t.id} (${t.action}) timeout`))},this.defaultCommandTimeout);this.commandTimers.set(t.id,r)}return!0}catch(t){return this.log.error(`Send failed to ${e}:`,{error:t}),!1}}broadcast(e){let t=JSON.stringify(e),n=0,r=0;for(let[e,i]of this.clients.entries())if(i.readyState===$.default.OPEN)try{i.send(t),n++}catch(t){this.log.error(`Broadcast failed to ${e}:`,{error:t}),r++}this.log.info(`Broadcast completed`,{total:this.clients.size,success:n,failed:r})}getOnlineNodes(){return Array.from(this.clients.keys())}isNodeOnline(e){let t=this.clients.get(e);return t!==void 0&&t.readyState===$.default.OPEN}getOnlineNodeCount(){let e=0;for(let t of this.clients.values())t.readyState===$.default.OPEN&&e++;return e}getRpcCommandStatus(e){return this.commandStatuses.get(e)}getAllRpcCommandStatuses(){return Array.from(this.commandStatuses.values())}clearOldStatuses(e=3e5){let t=Date.now();for(let[n,r]of this.commandStatuses.entries())if(r.status!==`pending`&&t-r.timestamp>e){this.commandStatuses.delete(n);let e=this.commandTimers.get(n);e&&(clearTimeout(e),this.commandTimers.delete(n))}}async handleMessage(e,t,n){let r=Qr(t);if(r){if(vr(r)){await this.handleRegister(e,r,n);return}if(!Sr(r)){if(Tr(r)){await this.handleEventMessage(e,r);return}br(r)&&this.handleRpcResponse(r)}}}async handleEventMessage(e,t){let n=this.wsToNode.get(e);if(!n){this.log.warn(`Received event from unregistered client`);return}if(this.log.info(`Event from ${n}`,{action:t.action,payload:t.payload}),t.id){let e=this.commandStatuses.get(t.id);if(e){let n=t.payload;e.status=n?.success?`completed`:`failed`,e.result=n?.result,e.error=n?.error}}this.options.onEvent&&await this.options.onEvent(n,t)}async handleRegister(e,t,n){let{nodeId:r}=t;if(!r){e.close();return}if(!(!this.options.validateToken||await this.options.validateToken(n,r))){this.log.warn(`Node ${r} rejected: invalid token`),e.close();return}this.clients.set(r,e),this.wsToNode.set(e,r),this.log.success(`Node connected: ${r}`);let i=t.payload;i&&this.options.onRegister&&await this.options.onRegister(r,i)}handleRpcResponse(e){let t=this.pendingRequests.get(e.id);t&&(clearTimeout(t.timer),this.pendingRequests.delete(e.id),e.status===`success`?t.resolve(e.result):t.reject(Error(e.error?.message??`RPC error`)))}handleClose(e){let t=this.wsToNode.get(e);t&&(this.clients.delete(t),this.wsToNode.delete(e),this.log.info(`Node disconnected: ${t}`))}startHeartbeat(){let e=this.options.heartbeatInterval??3e4;this.heartbeatTimer=setInterval(()=>{let e=[],t={type:`ping`,timestamp:Date.now()};this.clients.forEach((n,r)=>{if(n.readyState===$.default.OPEN)try{n.send(JSON.stringify(t))}catch(t){this.log.warn(`Failed to send ping to ${r}:`,{error:t}),e.push(r)}else e.push(r)});for(let t of e)this.clients.delete(t),this.log.info(`Node ${t} disconnected (heartbeat)`)},e)}},ti=class{constructor(e){this.config=e}initialize(){let{rootWorkDir:e,runtimeDir:t,processDir:n}=this.setupDirectories();zn({workspaceRoot:e,enableFile:!0});let r=this.createProcessManager(e,n),i=this.createRuntimeContext(t),a=this.createNodeManager(i,t),o=this.createClientCollector(),{rpcServer:s,rpcClient:c}=this.createRpcComponents();return{runtimeContext:i,process:r,nodeManager:a,clientCollector:o,rpcServer:s,rpcClient:c,rootWorkDir:e,runtimeDir:t,processDir:n}}setupDirectories(){let e=this.config.workDir??j(ne(),`.frp-web`),t=this.config.runtime?.workDir??j(e,`runtime`),n=this.config.process?.workDir??j(e,`process`);return U(e),U(t),U(n),{rootWorkDir:e,runtimeDir:t,processDir:n}}createProcessManager(e,t){return new gr({mode:this.config.process?.mode??this.config.mode,version:this.config.process?.version,workDir:t,configPath:this.config.configPath,configDir:j(e,`config`)})}createRuntimeContext(e){return{id:this.config.runtime?.id??`default`,mode:this.config.runtime?.mode??this.config.mode,workDir:e,platform:this.config.runtime?.platform??x.platform,clock:this.config.runtime?.clock}}createNodeManager(e,t){if(this.config.mode!==`server`)return;let n=j(t,`nodes`);return U(n),new Qn(e,{heartbeatTimeout:9e4},new Zn(n))}createClientCollector(){if(this.config.mode===`client`)return new Xn({heartbeatInterval:3e4})}createRpcComponents(){let e=this.config.rpc,t={};return this.config.mode===`server`&&e?.serverPort&&(t.rpcServer=new ei({port:e.serverPort,heartbeatInterval:e.serverHeartbeatInterval,validateToken:e.serverValidateToken,authorize:e.serverAuthorize,onRegister:e.serverOnRegister,onEvent:e.serverOnEvent,commandTimeout:e.serverCommandTimeout})),this.config.mode===`client`&&e?.clientUrl&&e.clientNodeId&&(t.rpcClient=new $r({url:this.appendToken(e.clientUrl,e.clientToken),nodeId:e.clientNodeId,getRegisterPayload:e.getRegisterPayload??(async()=>{throw new R(`rpc getRegisterPayload is required in client mode`)}),handleRequest:e.handleRequest??(async()=>void 0)})),t}appendToken(e,t){if(!t)return e;let n=new URL(e);return n.searchParams.set(`token`,t),n.toString()}};function ni(e,t){t&&(e.on(`process:started`,e=>{t(e)}),e.on(`process:stopped`,e=>{t(e)}),e.on(`process:exited`,e=>{t(e)}),e.on(`process:error`,e=>{t(e)}))}var ri=class{runtime;process;mode;eventSink;nodeManager;clientCollector;rpcServer;rpcClient;constructor(e){this.mode=e.mode;let t=new ti(e).initialize();this.process=t.process,this.nodeManager=t.nodeManager,this.clientCollector=t.clientCollector,this.rpcServer=t.rpcServer,this.rpcClient=t.rpcClient;let n=e.storage??new Ge(j(t.runtimeDir,`snapshots`));this.runtime=new xe(t.runtimeContext,{storage:n,commands:{},queries:{}});let r={process:this.process,nodeManager:this.nodeManager,rpcServer:this.rpcServer,mode:this.mode},i={process:this.process,nodeManager:this.nodeManager,runtime:this.runtime,mode:this.mode},a=dn(r),o=On(i),s={...a,...e.commands??{}},c={...o,...e.queries??{}};Object.entries(s).forEach(([e,t])=>{this.runtime.registerCommand(e,t)}),Object.entries(c).forEach(([e,t])=>{this.runtime.registerQuery(e,t)}),this.eventSink=e.eventSink,ni(this.process,this.eventSink)}execute(e){return this.runtime.execute(e).finally(()=>{this.forwardEvents()})}query(e){return this.runtime.query(e).finally(()=>{this.forwardEvents()})}snapshot(){return this.runtime.snapshot()}drainEvents(){return this.runtime.drainEvents()}getProcessManager(){return this.process}getRuntime(){return this.runtime}getNodeManager(){return this.nodeManager}getClientCollector(){return this.clientCollector}getRpcServer(){return this.rpcServer}getRpcClient(){return this.rpcClient}async initialize(){this.nodeManager&&await this.nodeManager.initialize(),this.rpcServer&&this.rpcServer.start(),this.rpcClient&&await this.rpcClient.connect()}async dispose(){this.nodeManager&&this.nodeManager.dispose(),this.clientCollector&&this.clientCollector.stopHeartbeat(),this.rpcServer&&this.rpcServer.stop(),this.rpcClient&&this.rpcClient.disconnect(),await this.process.dispose()}forwardEvents(){this.eventSink&&this.runtime.drainEvents().forEach(e=>this.eventSink?.(e))}};export{Ce as ARCH_MAP,P as BINARY_NAMES,ke as BinaryNotFoundError,Xn as ClientNodeCollector,L as ConfigInvalidError,I as ConfigNotFoundError,$n as DEFAULT_PRESET_CONFIG,Ae as DownloadFailedError,Pr as ExponentialBackoffStrategy,je as ExtractionFailedError,Zn as FileNodeStorage,Ge as FileSnapshotStorage,Fr as FixedIntervalStrategy,ri as FrpBridge,F as FrpBridgeErrorBase,gr as FrpProcessManager,xe as FrpRuntime,N as GITHUB_OWNER,Se as GITHUB_REPO,Te as GenericError,Lr as InfiniteReconnectStrategy,Ir as LinearBackoffStrategy,Nr as MiddlewarePipeline,z as ModeError,Qn as NodeManager,B as NotFoundError,we as OS_MAP,Ne as PlatformError,De as ProcessAlreadyRunningError,Ee as ProcessNotRunningError,Oe as ProcessStartFailedError,$r as RpcClient,_r as RpcMessageType,ei as RpcServer,R as ValidationError,Me as VersionFetchError,Ar as authMiddleware,Ve as commandExists,ar as configToToml,ze as downloadFile,U as ensureDir,Mr as errorHandlerMiddleware,Be as executeCommand,He as findExistingVersion,Re as getDownloadUrl,Ie as getLatestVersion,Le as getPlatform,wr as isCommandMessage,Tr as isEventMessage,Cr as isEventRpcMessage,Or as isNodeDeletePayload,xr as isPingMessage,Sr as isPongMessage,vr as isRegisterMessage,yr as isRpcRequest,br as isRpcResponse,Er as isTunnelAddPayload,Dr as isTunnelDeletePayload,Et as isValidToml,kr as loggingMiddleware,er as mergeConfigs,Ue as omitUndefined,q as parse,Dt as safeParse,tr as saveFrpConfigFile,Tt as stringify,jr as timeoutMiddleware,H as typeUsesRemotePort,or as validatePresetConfig};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@frp-bridge/core",
3
3
  "type": "module",
4
- "version": "0.0.2",
4
+ "version": "0.0.4",
5
5
  "description": "Frp bridge core",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/frp-web/bridge#readme",
@@ -24,20 +24,17 @@
24
24
  "dist"
25
25
  ],
26
26
  "dependencies": {
27
- "axios": "^1.13.2",
28
- "consola": "^3.4.2",
29
- "execa": "^9.6.0",
30
- "fs-extra": "^11.3.2",
31
27
  "pathe": "^2.0.3",
32
- "ws": "^8.18.0",
33
- "@frp-bridge/types": "0.0.2"
28
+ "smol-toml": "^1.6.0",
29
+ "ws": "^8.19.0",
30
+ "@frp-bridge/shared": "0.0.4",
31
+ "@frp-bridge/types": "0.0.4"
34
32
  },
35
33
  "devDependencies": {
36
- "@types/fs-extra": "^11.0.4",
37
- "@types/ws": "^8.5.14"
34
+ "@types/ws": "^8.18.1"
38
35
  },
39
36
  "scripts": {
40
- "stub": "unbuild --stub",
41
- "build": "unbuild"
37
+ "dev": "rolldown -c --watch",
38
+ "build": "rolldown -c"
42
39
  }
43
40
  }