@hugomrdias/fil 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +136 -2
  3. package/bin/fil.js +7 -0
  4. package/dist/chunks/_esm-BBXTTBLC.js +9 -0
  5. package/dist/chunks/_esm-BBXTTBLC.js.map +7 -0
  6. package/dist/chunks/ccip-TGFMQFIR.js +3 -0
  7. package/dist/chunks/ccip-TGFMQFIR.js.map +7 -0
  8. package/dist/chunks/chunk-2KPBBDBJ.js +3 -0
  9. package/dist/chunks/chunk-2KPBBDBJ.js.map +7 -0
  10. package/dist/chunks/chunk-35V77X3C.js +12 -0
  11. package/dist/chunks/chunk-35V77X3C.js.map +7 -0
  12. package/dist/chunks/chunk-46FBFEBX.js +3 -0
  13. package/dist/chunks/chunk-46FBFEBX.js.map +7 -0
  14. package/dist/chunks/chunk-4BBXH7CB.js +6 -0
  15. package/dist/chunks/chunk-4BBXH7CB.js.map +7 -0
  16. package/dist/chunks/chunk-4DUACCJB.js +186 -0
  17. package/dist/chunks/chunk-4DUACCJB.js.map +7 -0
  18. package/dist/chunks/chunk-5EYSPKTK.js +3 -0
  19. package/dist/chunks/chunk-5EYSPKTK.js.map +7 -0
  20. package/dist/chunks/chunk-7MEK5RQ7.js +11 -0
  21. package/dist/chunks/chunk-7MEK5RQ7.js.map +7 -0
  22. package/dist/chunks/chunk-7WN6TT5U.js +4 -0
  23. package/dist/chunks/chunk-7WN6TT5U.js.map +7 -0
  24. package/dist/chunks/chunk-CU3SGKNA.js +3 -0
  25. package/dist/chunks/chunk-CU3SGKNA.js.map +7 -0
  26. package/dist/chunks/chunk-EDF5XCIN.js +4 -0
  27. package/dist/chunks/chunk-EDF5XCIN.js.map +7 -0
  28. package/dist/chunks/chunk-GVAFHRPJ.js +124 -0
  29. package/dist/chunks/chunk-GVAFHRPJ.js.map +7 -0
  30. package/dist/chunks/chunk-IJ2NNDTJ.js +3 -0
  31. package/dist/chunks/chunk-IJ2NNDTJ.js.map +7 -0
  32. package/dist/chunks/chunk-ISML2NA2.js +3 -0
  33. package/dist/chunks/chunk-ISML2NA2.js.map +7 -0
  34. package/dist/chunks/chunk-KAQPCD23.js +4 -0
  35. package/dist/chunks/chunk-KAQPCD23.js.map +7 -0
  36. package/dist/chunks/chunk-LOTWVNDB.js +3 -0
  37. package/dist/chunks/chunk-LOTWVNDB.js.map +7 -0
  38. package/dist/chunks/chunk-NPYAGWD6.js +4 -0
  39. package/dist/chunks/chunk-NPYAGWD6.js.map +7 -0
  40. package/dist/chunks/chunk-QYPR6473.js +3 -0
  41. package/dist/chunks/chunk-QYPR6473.js.map +7 -0
  42. package/dist/chunks/chunk-RK6JJQZL.js +41 -0
  43. package/dist/chunks/chunk-RK6JJQZL.js.map +7 -0
  44. package/dist/chunks/chunk-UJQDDRQD.js +59 -0
  45. package/dist/chunks/chunk-UJQDDRQD.js.map +7 -0
  46. package/dist/chunks/chunk-UVXTIEPU.js +4 -0
  47. package/dist/chunks/chunk-UVXTIEPU.js.map +7 -0
  48. package/dist/chunks/chunk-VTR7BON5.js +4 -0
  49. package/dist/chunks/chunk-VTR7BON5.js.map +7 -0
  50. package/dist/chunks/chunk-XQRC2SUG.js +4 -0
  51. package/dist/chunks/chunk-XQRC2SUG.js.map +7 -0
  52. package/dist/chunks/chunk-YIAP3JO3.js +3 -0
  53. package/dist/chunks/chunk-YIAP3JO3.js.map +7 -0
  54. package/dist/chunks/chunk-ZD6MKB4J.js +5 -0
  55. package/dist/chunks/chunk-ZD6MKB4J.js.map +7 -0
  56. package/dist/chunks/delete-XVYLEMHB.js +3 -0
  57. package/dist/chunks/delete-XVYLEMHB.js.map +7 -0
  58. package/dist/chunks/doctor-2W65SQJS.js +3 -0
  59. package/dist/chunks/doctor-2W65SQJS.js.map +7 -0
  60. package/dist/chunks/get-ZP66WVWT.js +3 -0
  61. package/dist/chunks/get-ZP66WVWT.js.map +7 -0
  62. package/dist/chunks/inspect-HV2SQPTB.js +3 -0
  63. package/dist/chunks/inspect-HV2SQPTB.js.map +7 -0
  64. package/dist/chunks/inspect-PQCV7LQT.js +3 -0
  65. package/dist/chunks/inspect-PQCV7LQT.js.map +7 -0
  66. package/dist/chunks/login-GQ4PM7SA.js +4 -0
  67. package/dist/chunks/login-GQ4PM7SA.js.map +7 -0
  68. package/dist/chunks/logout-7N23QWWM.js +3 -0
  69. package/dist/chunks/logout-7N23QWWM.js.map +7 -0
  70. package/dist/chunks/ls-7XYH5VPL.js +3 -0
  71. package/dist/chunks/ls-7XYH5VPL.js.map +7 -0
  72. package/dist/chunks/ls-ARM57VNR.js +3 -0
  73. package/dist/chunks/ls-ARM57VNR.js.map +7 -0
  74. package/dist/chunks/map-error-7POTPJ7R.js +3 -0
  75. package/dist/chunks/map-error-7POTPJ7R.js.map +7 -0
  76. package/dist/chunks/put-EHRNCZHT.js +3 -0
  77. package/dist/chunks/put-EHRNCZHT.js.map +7 -0
  78. package/dist/chunks/resume-RLZB7L3C.js +3 -0
  79. package/dist/chunks/resume-RLZB7L3C.js.map +7 -0
  80. package/dist/chunks/secp256k1-2OHXXNYZ.js +3 -0
  81. package/dist/chunks/secp256k1-2OHXXNYZ.js.map +7 -0
  82. package/dist/chunks/skills.run-IDY347MW.js +5 -0
  83. package/dist/chunks/skills.run-IDY347MW.js.map +7 -0
  84. package/dist/chunks/status-D4CXVYRA.js +3 -0
  85. package/dist/chunks/status-D4CXVYRA.js.map +7 -0
  86. package/dist/main.js +3 -0
  87. package/dist/main.js.map +7 -0
  88. package/dist/tsconfig.tsbuildinfo +1 -0
  89. package/package.json +52 -3
  90. package/skills/fil/SKILL.md +28 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hugo Dias
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,137 @@
1
- # Temporary Holding Version
1
+ # fil-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `fil` is a prototype command-line interface for Filecoin. It stores a file or a folder as one copy on one Curio provider and returns retrieval URLs on [fil-api](../../apps/fil-api/README.md#retrieval). It runs on the calibration network unless you choose mainnet.
4
+
5
+ `fil` calls [synapse-core](https://github.com/FilOzone/synapse-sdk/tree/master/packages/synapse-core) directly. It uses [clipact](../clipact/README.md) for the agent output contract and [iso-conf](https://github.com/hugomrdias/iso-repo/tree/main/packages/iso-conf) for configuration. The design follows the [CLI interface research](../../docs/fil/interface-research.md) and the [CLI guidelines for agents](../../docs/agent-cli/guidelines.md). The [architecture](../../docs/fil/architecture.md) describes the modules and flows.
6
+
7
+ Releases publish to npm as [`@hugomrdias/fil`](https://www.npmjs.com/package/@hugomrdias/fil). It needs Node.js 24 or newer:
8
+
9
+ ```sh
10
+ npm install --global @hugomrdias/fil
11
+ fil --help
12
+ ```
13
+
14
+ To build `fil` from source and put it on your path, run these commands from the repository root:
15
+
16
+ ```sh
17
+ pnpm turbo run build --filter=@hugomrdias/fil
18
+ alias fil="node $PWD/packages/fil-cli/bin/fil.js"
19
+ fil --help
20
+ ```
21
+
22
+ ## Log in
23
+
24
+ ```sh
25
+ fil login
26
+ ```
27
+
28
+ `fil login` generates a session key and saves it locally. It then opens the [fil-app](https://fil-app.hugomrdias.dev) setup page with the key's address. The wallet owner reviews the request there and approves it with their wallet. The private key never leaves the machine, and the CLI finds the approval on chain, so there is nothing to copy back.
29
+
30
+ By default, `fil login` requests the `createDataSet`, `addPieces`, and `schedulePieceRemovals` scopes for 30 days, under the name `fil-cli`. To request other scopes, repeat `--scopes`. `--name` sets the name the owner sees, which is recorded on chain, and `--days` sets the expiry. The owner can change all three on the page before approving.
31
+
32
+ The session key signs each request, the provider submits the transactions, and the wallet pays for storage.
33
+
34
+ In a terminal, `fil login` opens the browser and waits for approval. An agent, or any run without a terminal, gets a `login_pending` error instead and never waits. The error's `next` steps are the approval link for the user and `fil login` for the agent to run after the user approves. An interrupted login resumes with the same key. To generate a new key, pass `--fresh`.
35
+
36
+ For CI, set `FIL_SESSION_KEY` and `FIL_ROOT_ADDRESS` instead of running `fil login`. `fil` reads the session key only from the environment and never prints it.
37
+
38
+ ## Check the account
39
+
40
+ The session key cannot fund the account. `fil status` reports the expiry of each scope, the USDFC funds, and the Warm Storage (FWSS) approval. When the account needs a deposit, `fil status` also returns a prefilled funding link to the fil-app setup page.
41
+
42
+ `fil doctor` shows the network, RPC, fil-app origin (`console`), fil-api origin (`api`), and state directory that `fil` resolved, with the source of each value. It also checks the database and the RPC.
43
+
44
+ ## Store and retrieve
45
+
46
+ ```sh
47
+ fil put ./report.pdf # raw piece → <api>/get/<pieceCid>
48
+ fil put ./site # UnixFS CAR → <api>/get/<rootCid>?browser=true
49
+ fil put ./site --dry-run # size, provider, cost, and authorization; stores nothing
50
+ fil publish ./site # alias of put
51
+ fil get res_… --output ./copy # verifies the PieceCID and extracts folders
52
+ fil ls # add --all to include resources pending removal
53
+ fil inspect res_… --check # sends a HEAD request to the piece URL
54
+ fil delete res_… --yes # alias rm; schedules removal
55
+ ```
56
+
57
+ `fil` stores a file as its exact bytes. It packs a folder into a UnixFS CAR with the IPIP-499 `unixfs-v1-2025` profile, the same way as [Filecoin Pin](https://github.com/filecoin-project/filecoin-pin). The CAR goes into a data set with `withIPFSIndexing`, so Curio serves it at `/ipfs/<rootCid>/`. Curio's `/ipfs` endpoint is a trustless gateway. It returns blocks and CARs, not rendered pages.
58
+
59
+ `put` returns two links on fil-api's `/get/{cid}` route, which redirects without proxying the bytes:
60
+
61
+ - `urls.piece` redirects to the exact stored bytes at a provider's `/piece/<pieceCid>`.
62
+ - `urls.browser` is the link to share. A browser renders a file from the same `/piece` URL. A folder goes through [inbrowser.link](https://inbrowser.link), which verifies the blocks in the browser.
63
+
64
+ fil-api finds providers through its indexer, so a new piece link returns 404 until the indexer has the piece. A folder's browser link works at once. `fil get` downloads from the provider directly.
65
+
66
+ Packing skips dotfiles and rejects symlinks. The file or the packed CAR must be between 127 and 1,065,353,216 bytes (1016 MiB).
67
+
68
+ `delete` schedules removal, and the provider then deletes the stored copy. The resource state becomes `removal_pending`. Without `--yes`, `delete` asks a human at a terminal to confirm. In every other case, including for agents, it returns `confirmation_required` with a step for the user (`by: "user"`).
69
+
70
+ ## Resume an interrupted put or delete
71
+
72
+ ```sh
73
+ fil operations ls --incomplete
74
+ fil operations inspect op_…
75
+ fil operations resume op_…
76
+ ```
77
+
78
+ Each `put` and `delete` saves an operation in the local SQLite database before it changes anything on chain or at the provider. It prints the operation ID to stderr at once, so the ID survives even a SIGKILL. It then saves a checkpoint after each step.
79
+
80
+ An error from a put or delete carries a `fil operations resume <id>` step and is never `retryable`. Running the original command again would start a new paid operation. Errors with a `fil` code also carry the ID in `error.details.operationId`. clipact's built-in codes, such as `invalid_input`, keep their own `details`.
81
+
82
+ A resumed put never commits twice. `fil` signs the commit with a fresh nonce and saves it before sending it. A resume first asks FWSS (`clientNonces`) whether that nonce landed. If it did not, the resume sends the same signature again, and FWSS accepts it at most once.
83
+
84
+ A resume also does the following:
85
+
86
+ - Skips the upload when the provider already has the piece.
87
+ - Fails with `source_changed` when the source file changed.
88
+ - Returns the saved result of an operation that already completed.
89
+
90
+ If a removal transaction reverts, the resource stays active and you can resume the delete.
91
+
92
+ Ctrl+C, SIGTERM, or SIGHUP stops the work at the next step. `fil` returns an `interrupted` result with the resume step, then re-raises the signal, so the shell sees `130`, `143`, or `129`.
93
+
94
+ ## Output and errors
95
+
96
+ `fil` follows the [clipact](../clipact/README.md) output contract. It uses machine mode when you pass `--json`, set `FIL_OUTPUT=json`, run it from a detected agent, or redirect stdout away from a terminal. In machine mode, it writes one JSON object to stdout, with `data` on success or `error` on failure, then optional `next` steps. The exit code is `0` when the result has `data` and `1` when it has `error`. Diagnostics and progress go to stderr in every mode.
97
+
98
+ | Command | Prints |
99
+ | --- | --- |
100
+ | `fil schema --list` | Every command, offline |
101
+ | `fil schema <command>` | The command's input and output as JSON Schema, and its error codes |
102
+ | `fil completion <shell>` | A completion script for `bash`, `zsh`, or `fish` |
103
+ | `fil skills install` | Installs the bundled [agent skill](../../skills/fil/SKILL.md), which the build copies from the repository root |
104
+
105
+ | Error code | Meaning |
106
+ | --- | --- |
107
+ | `auth_required`, `login_pending`, `session_expired`, `permission_denied` | The user must log in or approve scopes |
108
+ | `insufficient_funds` | The user must fund the account at the fil-app link |
109
+ | `not_found` | No resource, operation, provider, or piece has that name |
110
+ | `output_exists` | The `fil get` output path exists. Pass `--force` to overwrite it |
111
+ | `operation_failed`, `commit_rejected`, `removal_reverted`, `source_changed`, `staging_missing`, `operation_running` | A put or delete stopped. Follow the `next` steps |
112
+ | `verification_failed` | Retrieved bytes or blocks do not match their CIDs |
113
+ | `unsafe_path` | A retrieved archive tried to write outside the output directory |
114
+ | `invalid_input`, `confirmation_required`, `interrupted`, `internal_error`, `service_unavailable`, `timeout` | Built into clipact. See [clipact errors](../clipact/README.md#errors) |
115
+
116
+ ## Configuration and state
117
+
118
+ | Variable | Purpose |
119
+ | --- | --- |
120
+ | `FIL_NETWORK` | `mainnet` or `calibration`. `--network` takes precedence, then `FIL_NETWORK`, then the config file, then `calibration` |
121
+ | `FIL_SESSION_KEY`, `FIL_ROOT_ADDRESS` | Session key and wallet address, used instead of `fil login` |
122
+ | `FIL_CONFIG_DIR` | Config directory. Default: the platform config directory for `fil` |
123
+ | `FIL_STATE_DIR` | SQLite state and staged CARs. Default: the platform data directory for `fil` |
124
+ | `FIL_RPC_URL` | RPC endpoint. Default: synapse-core's fallback transport for the chain |
125
+ | `FIL_CONSOLE_URL` | fil-app origin for approval and funding links, such as `http://localhost:5173` for a local app. Default: `https://fil-app.hugomrdias.dev` |
126
+ | `FIL_API_URL` | fil-api origin for retrieval links, such as `http://localhost:8787` for a local API. Default: `https://fil-api.hugomrdias.dev` |
127
+ | `FIL_OUTPUT`, `FIL_AGENT` | Override clipact's output mode and agent detection |
128
+
129
+ The prototype saves the session private key in the config file with mode 0600, so only its owner can read it. `fil logout` deletes the local key. The key stays authorized on chain until it expires or you revoke it on the fil-app session keys page.
130
+
131
+ ## Development
132
+
133
+ Each command has a definition in `src/commands/` and a handler in `src/handlers/`. Definitions import only zod and clipact. clipact loads a handler only when its command runs, so `--help`, `--version`, and `schema` never import synapse-core.
134
+
135
+ `pnpm build` bundles the CLI with esbuild into `dist/`, with one chunk per handler. `bin/fil.js` turns on Node's compile cache, then loads the bundle.
136
+
137
+ Most tests run the CLI in process with `clipact/testing`. `test/contract.test.ts` spawns the built `bin/fil.js` to test stdout, exit codes, and signals on a real process.
package/bin/fil.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ // Entry shim: enable the compile cache first, then load the bundle
3
+ // dynamically so it is compiled with the cache on.
4
+ import module from 'node:module'
5
+
6
+ module.enableCompileCache?.()
7
+ await import('../dist/main.js')
@@ -0,0 +1,9 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import{a as p,b as x,c as sr,d as L}from"./chunk-YIAP3JO3.js";var O=x((ks,He)=>{"use strict";var Ve=["nodebuffer","arraybuffer","fragments"],ze=typeof Blob<"u";ze&&Ve.push("blob");He.exports={BINARY_TYPES:Ve,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ze,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Z=x((Os,ie)=>{"use strict";var{EMPTY_BUFFER:ir}=O(),xe=Buffer[Symbol.species];function nr(t,e){if(t.length===0)return ir;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),s=0;for(let i=0;i<t.length;i++){let n=t[i];r.set(n,s),s+=n.length}return s<e?new xe(r.buffer,r.byteOffset,s):r}function Ye(t,e,r,s,i){for(let n=0;n<i;n++)r[s+n]=t[n]^e[n&3]}function Ke(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function or(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ee(t){if(Ee.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new xe(t):ArrayBuffer.isView(t)?e=new xe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ee.readOnly=!1),e}ie.exports={concat:nr,mask:Ye,toArrayBuffer:or,toBuffer:Ee,unmask:Ke};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=p("bufferutil");ie.exports.mask=function(e,r,s,i,n){n<48?Ye(e,r,s,i,n):t.mask(e,r,s,i,n)},ie.exports.unmask=function(e,r){e.length<32?Ke(e,r):t.unmask(e,r)}}catch{}});var Qe=x((Ts,Ze)=>{"use strict";var Xe=Symbol("kDone"),be=Symbol("kRun"),ve=class{constructor(e){this[Xe]=()=>{this.pending--,this[be]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[be]()}[be](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Xe])}}};Ze.exports=ve});var G=x((Cs,rt)=>{"use strict";var Q=p("zlib"),Je=Z(),ar=Qe(),{kStatusCode:et}=O(),fr=Buffer[Symbol.species],lr=Buffer.from([0,0,255,255]),oe=Symbol("permessage-deflate"),T=Symbol("total-length"),A=Symbol("callback"),P=Symbol("buffers"),q=Symbol("error"),ne,we=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ne){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ne=new ar(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[A];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,s=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(s.server_no_context_takeover=!0),r.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(s.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?s.client_max_window_bits=r.clientMaxWindowBits:(s.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(s=>{let i=r[s];if(i.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(i=i[0],s==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else if(s==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=n}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else throw new Error(`Unknown parameter "${s}"`);r[s]=i})}),e}decompress(e,r,s){ne.add(i=>{this._decompress(e,r,(n,o)=>{i(),s(n,o)})})}compress(e,r,s){ne.add(i=>{this._compress(e,r,(n,o)=>{i(),s(n,o)})})}_decompress(e,r,s){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?Q.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=Q.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[oe]=this,this._inflate[T]=0,this._inflate[P]=[],this._inflate.on("error",cr),this._inflate.on("data",tt)}this._inflate[A]=s,this._inflate.write(e),r&&this._inflate.write(lr),this._inflate.flush(()=>{let n=this._inflate[q];if(n){this._inflate.close(),this._inflate=null,s(n);return}let o=Je.concat(this._inflate[P],this._inflate[T]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[T]=0,this._inflate[P]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,r,s){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?Q.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=Q.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[T]=0,this._deflate[P]=[],this._deflate.on("data",hr)}this._deflate[A]=s,this._deflate.write(e),this._deflate.flush(Q.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=Je.concat(this._deflate[P],this._deflate[T]);r&&(n=new fr(n.buffer,n.byteOffset,n.length-4)),this._deflate[A]=null,this._deflate[T]=0,this._deflate[P]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),s(null,n)})}};rt.exports=we;function hr(t){this[P].push(t),this[T]+=t.length}function tt(t){if(this[T]+=t.length,this[oe]._maxPayload<1||this[T]<=this[oe]._maxPayload){this[P].push(t);return}this[q]=new RangeError("Max payload size exceeded"),this[q].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[q][et]=1009,this.removeListener("data",tt),this.reset()}function cr(t){if(this[oe]._inflate=null,this[q]){this[A](this[q]);return}t[et]=1007,this[A](t)}});var $=x((Ns,ae)=>{"use strict";var{isUtf8:st}=p("buffer"),{hasBlob:ur}=O(),dr=[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 _r(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ke(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function mr(t){return ur&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ae.exports={isBlob:mr,isValidStatusCode:_r,isValidUTF8:ke,tokenChars:dr};if(st)ae.exports.isValidUTF8=function(t){return t.length<24?ke(t):st(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=p("utf-8-validate");ae.exports.isValidUTF8=function(e){return e.length<32?ke(e):t(e)}}catch{}});var Le=x((Ls,ht)=>{"use strict";var{Writable:pr}=p("stream"),it=G(),{BINARY_TYPES:gr,EMPTY_BUFFER:nt,kStatusCode:yr,kWebSocket:Sr}=O(),{concat:Oe,toArrayBuffer:xr,unmask:Er}=Z(),{isValidStatusCode:br,isValidUTF8:ot}=$(),fe=Buffer[Symbol.species],b=0,at=1,ft=2,lt=3,Te=4,Ce=5,le=6,Ne=class extends pr{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||gr[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Sr]=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=b}_write(e,r,s){if(this._opcode===8&&this._state==b)return s();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){s(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new fe(s.buffer,s.byteOffset+e,s.length-e),new fe(s.buffer,s.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let s=this._buffers[0],i=r.length-e;e>=s.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(s.buffer,s.byteOffset,e),i),this._buffers[0]=new fe(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case b:this.getInfo(e);break;case at:this.getPayloadLength16(e);break;case ft:this.getPayloadLength64(e);break;case lt:this.getMask();break;case Te:this.getData(e);break;case Ce:case le:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let s=(r[0]&64)===64;if(s&&!this._extensions[it.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(s){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(s){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=at:this._payloadLength===127?this._state=ft: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 r=this.consume(8),s=r.readUInt32BE(0);if(s>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=s*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=lt:this._state=Te}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Te}getData(e){let r=nt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Er(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Ce,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(s);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[it.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return r(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(o);return}this._fragments.push(n)}this.dataMessage(r),this._state===b&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=b;return}let r=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Oe(s,r):this._binaryType==="arraybuffer"?i=xr(Oe(s,r)):this._binaryType==="blob"?i=new Blob(s):i=s,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=b):(this._state=le,setImmediate(()=>{this.emit("message",i,!0),this._state=b,this.startLoop(e)}))}else{let i=Oe(s,r);if(!this._skipUTF8Validation&&!ot(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===Ce||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=b):(this._state=le,setImmediate(()=>{this.emit("message",i,!1),this._state=b,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,nt),this.end();else{let s=e.readUInt16BE(0);if(!br(s)){let n=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(n);return}let i=new fe(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ot(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(n);return}this._loop=!1,this.emit("conclude",s,i),this.end()}this._state=b;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=b):(this._state=le,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=b,this.startLoop(r)}))}createError(e,r,s,i,n){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=n,o[yr]=i,o}};ht.exports=Ne});var Re=x((Bs,dt)=>{"use strict";var{Duplex:Ps}=p("stream"),{randomFillSync:vr}=p("crypto"),{types:{isUint8Array:wr}}=p("util"),ct=G(),{EMPTY_BUFFER:kr,kWebSocket:Or,NOOP:Tr}=O(),{isBlob:j,isValidStatusCode:Cr}=$(),{mask:ut,toBuffer:R}=Z(),v=Symbol("kByteLength"),Nr=Buffer.alloc(4),he=8*1024,U,V=he,w=0,Lr=1,Pr=2,Pe=class t{constructor(e,r,s){this._extensions=r||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=Tr,this[Or]=void 0}static frame(e,r){let s,i=!1,n=2,o=!1;r.mask&&(s=r.maskBuffer||Nr,r.generateMask?r.generateMask(s):(V===he&&(U===void 0&&(U=Buffer.alloc(he)),vr(U,0,he),V=0),s[0]=U[V++],s[1]=U[V++],s[2]=U[V++],s[3]=U[V++]),o=(s[0]|s[1]|s[2]|s[3])===0,n=6);let f;typeof e=="string"?(!r.mask||o)&&r[v]!==void 0?f=r[v]:(e=Buffer.from(e),f=e.length):(f=e.length,i=r.mask&&r.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),r.mask?(a[1]|=128,a[n-4]=s[0],a[n-3]=s[1],a[n-2]=s[2],a[n-1]=s[3],o?[a,e]:i?(ut(e,s,a,n,f),[a]):(ut(e,s,e,0,f),[a,e])):[a,e]}close(e,r,s,i){let n;if(e===void 0)n=kr;else{if(typeof e!="number"||!Cr(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let f=Buffer.byteLength(r);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof r=="string")n.write(r,2);else if(wr(r))n.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[v]:n.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,r,s){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):j(e)?(i=e.size,n=!1):(e=R(e),i=e.length,n=R.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[v]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};j(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==w?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}pong(e,r,s){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):j(e)?(i=e.size,n=!1):(e=R(e),i=e.length,n=R.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[v]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};j(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==w?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(t.frame(e,o),s)}send(e,r,s){let i=this._extensions[ct.extensionName],n=r.binary?2:1,o=r.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=!1):j(e)?(f=e.size,l=!1):(e=R(e),f=e.length,l=R.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=!1,n=0),r.fin&&(this._firstFragment=!0);let a={[v]:f,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};j(e)?this._state!==w?this.enqueue([this.getBlobData,e,this._compress,a,s]):this.getBlobData(e,this._compress,a,s):this._state!==w?this.enqueue([this.dispatch,e,this._compress,a,s]):this.dispatch(e,this._compress,a,s)}getBlobData(e,r,s,i){this._bufferedBytes+=s[v],this._state=Pr,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(Be,this,f,i);return}this._bufferedBytes-=s[v];let o=R(n);r?this.dispatch(o,r,s,i):(this._state=w,this.sendFrame(t.frame(o,s),i),this.dequeue())}).catch(n=>{process.nextTick(Br,this,n,i)})}dispatch(e,r,s,i){if(!r){this.sendFrame(t.frame(e,s),i);return}let n=this._extensions[ct.extensionName];this._bufferedBytes+=s[v],this._state=Lr,n.compress(e,s.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Be(this,l,i);return}this._bufferedBytes-=s[v],this._state=w,s.readOnly=!1,this.sendFrame(t.frame(f,s),i),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][v],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][v],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};dt.exports=Pe;function Be(t,e,r){typeof r=="function"&&r(e);for(let s=0;s<t._queue.length;s++){let i=t._queue[s],n=i[i.length-1];typeof n=="function"&&n(e)}}function Br(t,e,r){Be(t,e,r),t.onerror(e)}});var bt=x((Rs,Et)=>{"use strict";var{kForOnEventAttribute:J,kListener:Ue}=O(),_t=Symbol("kCode"),mt=Symbol("kData"),pt=Symbol("kError"),gt=Symbol("kMessage"),yt=Symbol("kReason"),z=Symbol("kTarget"),St=Symbol("kType"),xt=Symbol("kWasClean"),C=class{constructor(e){this[z]=null,this[St]=e}get target(){return this[z]}get type(){return this[St]}};Object.defineProperty(C.prototype,"target",{enumerable:!0});Object.defineProperty(C.prototype,"type",{enumerable:!0});var I=class extends C{constructor(e,r={}){super(e),this[_t]=r.code===void 0?0:r.code,this[yt]=r.reason===void 0?"":r.reason,this[xt]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[_t]}get reason(){return this[yt]}get wasClean(){return this[xt]}};Object.defineProperty(I.prototype,"code",{enumerable:!0});Object.defineProperty(I.prototype,"reason",{enumerable:!0});Object.defineProperty(I.prototype,"wasClean",{enumerable:!0});var H=class extends C{constructor(e,r={}){super(e),this[pt]=r.error===void 0?null:r.error,this[gt]=r.message===void 0?"":r.message}get error(){return this[pt]}get message(){return this[gt]}};Object.defineProperty(H.prototype,"error",{enumerable:!0});Object.defineProperty(H.prototype,"message",{enumerable:!0});var ee=class extends C{constructor(e,r={}){super(e),this[mt]=r.data===void 0?null:r.data}get data(){return this[mt]}};Object.defineProperty(ee.prototype,"data",{enumerable:!0});var Rr={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[J]&&i[Ue]===e&&!i[J])return;let s;if(t==="message")s=function(n,o){let f=new ee("message",{data:o?n:n.toString()});f[z]=this,ce(e,this,f)};else if(t==="close")s=function(n,o){let f=new I("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[z]=this,ce(e,this,f)};else if(t==="error")s=function(n){let o=new H("error",{error:n,message:n.message});o[z]=this,ce(e,this,o)};else if(t==="open")s=function(){let n=new C("open");n[z]=this,ce(e,this,n)};else return;s[J]=!!r[J],s[Ue]=e,r.once?this.once(t,s):this.on(t,s)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Ue]===e&&!r[J]){this.removeListener(t,r);break}}};Et.exports={CloseEvent:I,ErrorEvent:H,Event:C,EventTarget:Rr,MessageEvent:ee};function ce(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var ue=x((Us,vt)=>{"use strict";var{tokenChars:te}=$();function k(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Ur(t){let e=Object.create(null),r=Object.create(null),s=!1,i=!1,n=!1,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&te[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);a===44?(k(e,g,r),r=Object.create(null)):o=g,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&te[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),k(r,t.slice(l,h),!0),a===44&&(k(e,o,r),r=Object.create(null),o=void 0),l=h=-1}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(te[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:s||(s=!0),i=!1}else if(n)if(te[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=!1,h=c;else if(a===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=!0;else if(h===-1&&te[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);s&&(g=g.replace(/\\/g,""),s=!1),k(r,f,g),a===44&&(k(e,o,r),r=Object.create(null),o=void 0),f=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let _=t.slice(l,h);return o===void 0?k(e,_,r):(f===void 0?k(r,_,!0):s?k(r,f,_.replace(/\\/g,"")):k(r,f,_),k(e,o,r)),e}function Ir(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(s=>[e].concat(Object.keys(s).map(i=>{let n=s[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}vt.exports={format:Ir,parse:Ur}});var pe=x((Ws,It)=>{"use strict";var Dr=p("events"),Wr=p("https"),Mr=p("http"),Ot=p("net"),Fr=p("tls"),{randomBytes:Ar,createHash:qr}=p("crypto"),{Duplex:Is,Readable:Ds}=p("stream"),{URL:Ie}=p("url"),B=G(),Gr=Le(),$r=Re(),{isBlob:jr}=$(),{BINARY_TYPES:wt,CLOSE_TIMEOUT:Vr,EMPTY_BUFFER:de,GUID:zr,kForOnEventAttribute:De,kListener:Hr,kStatusCode:Yr,kWebSocket:y,NOOP:Tt}=O(),{EventTarget:{addEventListener:Kr,removeEventListener:Xr}}=bt(),{format:Zr,parse:Qr}=ue(),{toBuffer:Jr}=Z(),Ct=Symbol("kAborted"),We=[8,13],N=["CONNECTING","OPEN","CLOSING","CLOSED"],es=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,d=class t extends Dr{constructor(e,r,s){super(),this._binaryType=wt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=de,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(s=r,r=[]):r=[r]),Nt(this,e,r,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,s){let i=new Gr({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),n=new $r(e,this._extensions,s.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[y]=this,n[y]=this,e[y]=this,i.on("conclude",ss),i.on("drain",is),i.on("error",ns),i.on("message",os),i.on("ping",as),i.on("pong",fs),n.onerror=ls,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Bt),e.on("data",me),e.on("end",Rt),e.on("error",Ut),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[B.extensionName]&&this._extensions[B.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Pt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Me(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||de,r,s)}pong(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=r=void 0):typeof r=="function"&&(s=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Me(this,e,s);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||de,r,s)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,s){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(s=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Me(this,e,s);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[B.extensionName]||(i.compress=!1),this._sender.send(e||de,i,s)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:N.indexOf("CONNECTING")});Object.defineProperty(d.prototype,"CONNECTING",{enumerable:!0,value:N.indexOf("CONNECTING")});Object.defineProperty(d,"OPEN",{enumerable:!0,value:N.indexOf("OPEN")});Object.defineProperty(d.prototype,"OPEN",{enumerable:!0,value:N.indexOf("OPEN")});Object.defineProperty(d,"CLOSING",{enumerable:!0,value:N.indexOf("CLOSING")});Object.defineProperty(d.prototype,"CLOSING",{enumerable:!0,value:N.indexOf("CLOSING")});Object.defineProperty(d,"CLOSED",{enumerable:!0,value:N.indexOf("CLOSED")});Object.defineProperty(d.prototype,"CLOSED",{enumerable:!0,value:N.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(d.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(d.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[De])return e[Hr];return null},set(e){for(let r of this.listeners(t))if(r[De]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[De]:!0})}})});d.prototype.addEventListener=Kr;d.prototype.removeEventListener=Xr;It.exports=d;function Nt(t,e,r,s){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Vr,protocolVersion:We[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!We.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${We.join(", ")})`);let n;if(e instanceof Ie)n=e;else try{n=new Ie(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;_e(t,u);return}let a=o?443:80,h=Ar(16).toString("base64"),c=o?Wr.request:Mr.request,_=new Set,g;if(i.createConnection=i.createConnection||(o?rs:ts),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new B({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Zr({[B.extensionName]:g.offer()})),r.length){for(let u of r){if(typeof u!="string"||!es.test(u)||_.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(u)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=s&&s.headers;if(s={...s,headers:{}},u)for(let[S,M]of Object.entries(u))s.headers[S.toLowerCase()]=M}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=c(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=c(i);i.timeout&&m.on("timeout",()=>{E(t,m,"Opening handshake has timed out")}),m.on("error",u=>{m===null||m[Ct]||(m=t._req=null,_e(t,u))}),m.on("response",u=>{let S=u.headers.location,M=u.statusCode;if(S&&i.followRedirects&&M>=300&&M<400){if(++t._redirects>i.maxRedirects){E(t,m,"Maximum redirects exceeded");return}m.abort();let K;try{K=new Ie(S,e)}catch{let F=new SyntaxError(`Invalid URL: ${S}`);_e(t,F);return}Nt(t,K,r,s)}else t.emit("unexpected-response",m,u)||E(t,m,`Unexpected server response: ${u.statusCode}`)}),m.on("upgrade",(u,S,M)=>{if(t.emit("upgrade",u),t.readyState!==d.CONNECTING)return;m=t._req=null;let K=u.headers.upgrade;if(K===void 0||K.toLowerCase()!=="websocket"){E(t,S,"Invalid Upgrade header");return}let Ge=qr("sha1").update(h+zr).digest("base64");if(u.headers["sec-websocket-accept"]!==Ge){E(t,S,"Invalid Sec-WebSocket-Accept header");return}let F=u.headers["sec-websocket-protocol"],X;if(F!==void 0?_.size?_.has(F)||(X="Server sent an invalid subprotocol"):X="Server sent a subprotocol but none was requested":_.size&&(X="Server sent no subprotocol"),X){E(t,S,X);return}F&&(t._protocol=F);let $e=u.headers["sec-websocket-extensions"];if($e!==void 0){if(!g){E(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ye;try{ye=Qr($e)}catch{E(t,S,"Invalid Sec-WebSocket-Extensions header");return}let je=Object.keys(ye);if(je.length!==1||je[0]!==B.extensionName){E(t,S,"Server indicated an extension that was not requested");return}try{g.accept(ye[B.extensionName])}catch{E(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[B.extensionName]=g}t.setSocket(S,M,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function _e(t,e){t._readyState=d.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function ts(t){return t.path=t.socketPath,Ot.connect(t)}function rs(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ot.isIP(t.host)?"":t.host),Fr.connect(t)}function E(t,e,r){t._readyState=d.CLOSING;let s=new Error(r);Error.captureStackTrace(s,E),e.setHeader?(e[Ct]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_e,t,s)):(e.destroy(s),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Me(t,e,r){if(e){let s=jr(e)?e.size:Jr(e).length;t._socket?t._sender._bufferedBytes+=s:t._bufferedAmount+=s}if(r){let s=new Error(`WebSocket is not open: readyState ${t.readyState} (${N[t.readyState]})`);process.nextTick(r,s)}}function ss(t,e){let r=this[y];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[y]!==void 0&&(r._socket.removeListener("data",me),process.nextTick(Lt,r._socket),t===1005?r.close():r.close(t,e))}function is(){let t=this[y];t.isPaused||t._socket.resume()}function ns(t){let e=this[y];e._socket[y]!==void 0&&(e._socket.removeListener("data",me),process.nextTick(Lt,e._socket),e.close(t[Yr])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function kt(){this[y].emitClose()}function os(t,e){this[y].emit("message",t,e)}function as(t){let e=this[y];e._autoPong&&e.pong(t,!this._isServer,Tt),e.emit("ping",t)}function fs(t){this[y].emit("pong",t)}function Lt(t){t.resume()}function ls(t){let e=this[y];e.readyState!==d.CLOSED&&(e.readyState===d.OPEN&&(e._readyState=d.CLOSING,Pt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Pt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Bt(){let t=this[y];if(this.removeListener("close",Bt),this.removeListener("data",me),this.removeListener("end",Rt),t._readyState=d.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[y]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",kt),t._receiver.on("finish",kt))}function me(t){this[y]._receiver.write(t)||this.pause()}function Rt(){let t=this[y];t._readyState=d.CLOSING,t._receiver.end(),this.end()}function Ut(){let t=this[y];this.removeListener("error",Ut),this.on("error",Tt),t&&(t._readyState=d.CLOSING,this.destroy())}});var Ft=x((Fs,Mt)=>{"use strict";var Ms=pe(),{Duplex:hs}=p("stream");function Dt(t){t.emit("close")}function cs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Wt(t){this.removeListener("error",Wt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function us(t,e){let r=!0,s=new hs({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let f=!o&&s._readableState.objectMode?n.toString():n;s.push(f)||t.pause()}),t.once("error",function(n){s.destroyed||(r=!1,s.destroy(n))}),t.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Dt,s);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(Dt,s)}),r&&t.terminate()},s._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){s._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),s._readableState.endEmitted&&s.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},s._read=function(){t.isPaused&&t.resume()},s._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){s._write(i,n,o)});return}t.send(i,o)},s.on("end",cs),s.on("error",Wt),s}Mt.exports=us});var Fe=x((As,At)=>{"use strict";var{tokenChars:ds}=$();function _s(t){let e=new Set,r=-1,s=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(s===-1&&ds[o]===1)r===-1&&(r=i);else if(i!==0&&(o===32||o===9))s===-1&&r!==-1&&(s=i);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);s===-1&&(s=i);let f=t.slice(r,s);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),r=s=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(r,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}At.exports={parse:_s}});var Ht=x((Gs,zt)=>{"use strict";var ms=p("events"),ge=p("http"),{Duplex:qs}=p("stream"),{createHash:ps}=p("crypto"),qt=ue(),D=G(),gs=Fe(),ys=pe(),{CLOSE_TIMEOUT:Ss,GUID:xs,kWebSocket:Es}=O(),bs=/^[+/0-9A-Za-z]{22}==$/,Gt=0,$t=1,Vt=2,Ae=class extends ms{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Ss,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ys,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ge.createServer((s,i)=>{let n=ge.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=vs(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Gt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Vt){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(re,this);return}if(e&&this.once("close",e),this._state!==$t)if(this._state=$t,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(re,this):process.nextTick(re,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{re(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,s,i){r.on("error",jt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){W(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){W(this,e,r,400,"Invalid Upgrade header");return}if(n===void 0||!bs.test(n)){W(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){W(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){se(r,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=gs.parse(l)}catch{W(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let _=new D({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=qt.parse(h);g[D.extensionName]&&(_.accept(g[D.extensionName]),c[D.extensionName]=_)}catch{W(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(g,m,u,S)=>{if(!g)return se(r,m||401,u,S);this.completeUpgrade(c,n,a,e,r,s,i)});return}if(!this.options.verifyClient(_))return se(r,401)}this.completeUpgrade(c,n,a,e,r,s,i)}completeUpgrade(e,r,s,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[Es])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Gt)return se(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ps("sha1").update(r+xs).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(s.size){let c=this.options.handleProtocols?this.options.handleProtocols(s,i):s.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c)}if(e[D.extensionName]){let c=e[D.extensionName].params,_=qt.format({[D.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${_}`),h._extensions=e}this.emit("headers",a,i),n.write(a.concat(`\r
3
+ `).join(`\r
4
+ `)),n.removeListener("error",jt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(re,this)})),f(h,i)}};zt.exports=Ae;function vs(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let s of Object.keys(e))t.removeListener(s,e[s])}}function re(t){t._state=Vt,t.emit("close")}function jt(){this.destroy()}function se(t,e,r,s){r=r||ge.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...s},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ge.STATUS_CODES[e]}\r
5
+ `+Object.keys(s).map(i=>`${i}: ${s[i]}`).join(`\r
6
+ `)+`\r
7
+ \r
8
+ `+r)}function W(t,e,r,s,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,W),t.emit("wsClientError",o,r,e)}else se(r,s,i,n)}});var qe={};sr(qe,{PerMessageDeflate:()=>Xt.default,Receiver:()=>Zt.default,Sender:()=>Qt.default,WebSocket:()=>Y.default,WebSocketServer:()=>er.default,createWebSocketStream:()=>Yt.default,default:()=>ws,extension:()=>Kt.default,subprotocol:()=>Jt.default});var Yt=L(Ft(),1),Kt=L(ue(),1),Xt=L(G(),1),Zt=L(Le(),1),Qt=L(Re(),1),Jt=L(Fe(),1),Y=L(pe(),1),er=L(Ht(),1);var ws=Y.default;function tr(){if(typeof WebSocket<"u")return WebSocket;if(typeof global.WebSocket<"u")return global.WebSocket;if(typeof window.WebSocket<"u")return window.WebSocket;if(typeof self.WebSocket<"u")return self.WebSocket;throw new Error("`WebSocket` is not supported in this environment")}var Vs=(()=>{try{return tr()}catch{return Y.default?Y.default:qe}})();export{Vs as WebSocket};
9
+ //# sourceMappingURL=_esm-BBXTTBLC.js.map