@brickkit/cli 0.11.0 → 0.13.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 (177) hide show
  1. package/dashboard-dist/CollapsiblePanel-CbUysOp5.js +2 -0
  2. package/dashboard-dist/CompositeRoot-D4sRkYq3.js +1 -0
  3. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  4. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  5. package/dashboard-dist/PopoverPopup-CiI2avT_.js +1 -0
  6. package/dashboard-dist/api-reference-mT9VNcPb.js +265 -0
  7. package/dashboard-dist/app.css +2 -2
  8. package/dashboard-dist/app.js +12 -13
  9. package/dashboard-dist/ccount-CcG1m-Yh.js +1 -0
  10. package/dashboard-dist/client-CwATkLJa.js +1 -0
  11. package/dashboard-dist/core-BEUWp6B5.js +1 -0
  12. package/dashboard-dist/docs-BRrtyxDB.js +4 -0
  13. package/dashboard-dist/docs.css +1 -1
  14. package/dashboard-dist/kit.js +1 -1
  15. package/dashboard-dist/popover-Bj9x-88h.js +1 -0
  16. package/dist/bin.d.ts +0 -2
  17. package/dist/bin.js +309 -211
  18. package/dist/bin.js.map +1 -1
  19. package/dist/build.js +463 -0
  20. package/dist/build.js.map +1 -0
  21. package/dist/client-contract-file.js +356 -1
  22. package/dist/client-contract-file.js.map +1 -0
  23. package/dist/compiler.d.ts +12 -3
  24. package/dist/compiler.js +1 -1
  25. package/dist/compiler2.js +13 -7
  26. package/dist/compiler2.js.map +1 -1
  27. package/dist/config.d.ts +3 -0
  28. package/dist/config.js +1 -252
  29. package/dist/config2.d.ts +122 -0
  30. package/dist/config2.js +207 -0
  31. package/dist/config2.js.map +1 -0
  32. package/dist/dashboard-extension.d.ts +3 -2
  33. package/dist/{dev-telemetry-store.js → dashboard-host.js} +1381 -1432
  34. package/dist/dashboard-host.js.map +1 -0
  35. package/dist/dashboard-protocol.js +189 -0
  36. package/dist/dashboard-protocol.js.map +1 -0
  37. package/dist/dashboard.d.ts +8 -135
  38. package/dist/definitions.js +33 -0
  39. package/dist/definitions.js.map +1 -0
  40. package/dist/dev-application.js +34 -0
  41. package/dist/dev-application.js.map +1 -0
  42. package/dist/dev-protocol.js +21 -0
  43. package/dist/dev-protocol.js.map +1 -0
  44. package/dist/dev-reporter.d.ts +0 -2
  45. package/dist/dev-reporter.js +3 -3
  46. package/dist/dev-reporter.js.map +1 -1
  47. package/dist/dev-telemetry.js +8 -24
  48. package/dist/dev-telemetry.js.map +1 -1
  49. package/dist/dev-worker.js +80 -21
  50. package/dist/dev-worker.js.map +1 -1
  51. package/dist/index.d.ts +18 -87
  52. package/dist/index.js +12 -6
  53. package/dist/index.js.map +1 -0
  54. package/dist/lint/oxlint.d.ts +0 -2
  55. package/dist/lint/oxlint.js +6 -5
  56. package/dist/lint/oxlint.js.map +1 -1
  57. package/dist/own-module.js +7 -0
  58. package/dist/own-module.js.map +1 -0
  59. package/dist/plugin.d.ts +6 -11
  60. package/dist/plugin.js +6 -42
  61. package/dist/plugin.js.map +1 -1
  62. package/dist/production-dashboard.d.ts +2 -0
  63. package/dist/production-dashboard.js +51 -0
  64. package/dist/production-dashboard.js.map +1 -0
  65. package/dist/production-dashboard2.d.ts +34 -0
  66. package/dist/{presets.js → project.js} +107 -113
  67. package/dist/project.js.map +1 -0
  68. package/dist/serve.d.ts +24 -0
  69. package/dist/serve.js +1 -0
  70. package/dist/serve2.js +49 -0
  71. package/dist/serve2.js.map +1 -0
  72. package/dist/vite.d.ts +0 -2
  73. package/dist/vite.js +28 -51
  74. package/dist/vite.js.map +1 -1
  75. package/dist/workflows.d.ts +2 -4
  76. package/dist/workflows2.js +60 -39
  77. package/dist/workflows2.js.map +1 -1
  78. package/inspector-dist/client/assets/api.rpc-BvRk9kiK.js +0 -0
  79. package/inspector-dist/client/assets/api.stream._streamId-BvRk9kiK.js +0 -0
  80. package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
  81. package/inspector-dist/client/assets/dist-BK8w6xOr.js +3930 -0
  82. package/inspector-dist/client/assets/dist-CG2aVufI.js +197 -0
  83. package/inspector-dist/client/assets/entry.client-D9jbgmTR.js +9391 -0
  84. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-CfRnuITN.js +34 -0
  85. package/inspector-dist/client/assets/home-hwPlkNhv.js +4034 -0
  86. package/inspector-dist/client/assets/jsx-runtime-CPEah4WQ.js +7084 -0
  87. package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
  88. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
  89. package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
  90. package/inspector-dist/client/assets/root-SLeEf-sT.js +320 -0
  91. package/inspector-dist/client/assets/run-detail-DYbVkIFH.js +1871 -0
  92. package/inspector-dist/client/assets/tabs-CaJisoyb.js +73751 -0
  93. package/inspector-dist/client/assets/tabs-L5XKzOpP.css +1 -0
  94. package/inspector-dist/client/assets/zstd-browser-decoder-D94wmfAU.js +41 -0
  95. package/inspector-dist/server/assets/app-DGlfWVUI.js +99330 -0
  96. package/inspector-dist/server/assets/chunk-RLXIAIE6-F0SJZlei.js +42975 -0
  97. package/inspector-dist/server/assets/dist-BCbwm6jl.js +10325 -0
  98. package/inspector-dist/server/assets/dist-CG2aVufI.js +197 -0
  99. package/inspector-dist/server/assets/dist-Ce0I2PUv.js +1137 -0
  100. package/inspector-dist/server/assets/dist-DY0UlahA.js +1642 -0
  101. package/inspector-dist/server/assets/encryption-DdQgC8Rk.js +886 -0
  102. package/inspector-dist/server/assets/event-metadata-n7E4zEmT.js +145 -0
  103. package/inspector-dist/server/assets/functions-CNVQtbgg.js +1170 -0
  104. package/inspector-dist/server/assets/global-singleton-D8sIN5du.js +80 -0
  105. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-CWRzMxYD.js +34 -0
  106. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
  107. package/inspector-dist/server/assets/parse-Begau9cA.js +469 -0
  108. package/inspector-dist/server/assets/rolldown-runtime-C1I3wEg2.js +43 -0
  109. package/inspector-dist/server/assets/serialization-format-BbuGfHog.js +476 -0
  110. package/inspector-dist/server/assets/token-BgMmJNP5.js +60 -0
  111. package/inspector-dist/server/assets/token-BrUX0bxz.js +55 -0
  112. package/inspector-dist/server/assets/token-util-DZN32qmT.js +455 -0
  113. package/inspector-dist/server/assets/wrapper-CIC3w0oC.js +3624 -0
  114. package/inspector-dist/server/assets/ws-transport-CxTYB11n.js +29476 -0
  115. package/inspector-dist/server/assets/zstd-browser-decoder-D7bCXbGg.js +38 -0
  116. package/inspector-dist/server/index.js +1 -58
  117. package/package.json +39 -28
  118. package/vite-client.d.ts +1 -1
  119. package/dashboard-dist/CollapsiblePanel-BX79_W-b.js +0 -2
  120. package/dashboard-dist/CompositeRoot-xzybXjnx.js +0 -1
  121. package/dashboard-dist/PopoverPopup-CvlmC7EL.js +0 -1
  122. package/dashboard-dist/api-reference-BcAYVYwJ.js +0 -260
  123. package/dashboard-dist/core-BGO9JZ1r.js +0 -1
  124. package/dashboard-dist/docs-DHikPD2v.js +0 -4
  125. package/dashboard-dist/popover-DG498XHH.js +0 -1
  126. package/dist/app-entry.js +0 -1
  127. package/dist/app-entry2.js +0 -19
  128. package/dist/app-entry2.js.map +0 -1
  129. package/dist/bin.d.ts.map +0 -1
  130. package/dist/client-contract-file2.js +0 -34
  131. package/dist/client-contract-file2.js.map +0 -1
  132. package/dist/client-contract.js +0 -1
  133. package/dist/client-contract2.js +0 -294
  134. package/dist/client-contract2.js.map +0 -1
  135. package/dist/config.js.map +0 -1
  136. package/dist/dashboard-extension.d.ts.map +0 -1
  137. package/dist/dev-reporter.d.ts.map +0 -1
  138. package/dist/dev-telemetry-store.js.map +0 -1
  139. package/dist/emit.d.ts +0 -7
  140. package/dist/emit.d.ts.map +0 -1
  141. package/dist/index.d.ts.map +0 -1
  142. package/dist/lint/oxlint.d.ts.map +0 -1
  143. package/dist/plugin.d.ts.map +0 -1
  144. package/dist/presets.js.map +0 -1
  145. package/dist/runner.js +0 -523
  146. package/dist/runner.js.map +0 -1
  147. package/dist/vite.d.ts.map +0 -1
  148. package/dist/workflows.d.ts.map +0 -1
  149. package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +0 -1
  150. package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +0 -1
  151. package/inspector-dist/client/assets/app-CvoGgWcV.css +0 -1
  152. package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +0 -11697
  153. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +0 -19
  154. package/inspector-dist/client/assets/home-CSKAS4P2.js +0 -4979
  155. package/inspector-dist/client/assets/index-DECCyMR0.js +0 -4482
  156. package/inspector-dist/client/assets/index-Dot7CgrA.js +0 -9837
  157. package/inspector-dist/client/assets/index-HqNj_XIX.js +0 -200
  158. package/inspector-dist/client/assets/manifest-139c9319.js +0 -1
  159. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +0 -58626
  160. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +0 -1
  161. package/inspector-dist/client/assets/root-BMHd_XHz.css +0 -1
  162. package/inspector-dist/client/assets/root-cbi6iYwg.js +0 -305
  163. package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +0 -1
  164. package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +0 -6237
  165. package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +0 -26
  166. package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +0 -28
  167. package/inspector-dist/server/assets/app-DUP5RybL.js +0 -174880
  168. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-D2g4hL2-.js +0 -71
  169. package/inspector-dist/server/assets/index-BfLBLRRi.js +0 -204
  170. package/inspector-dist/server/assets/index-BzrGWk7J.js +0 -1164
  171. package/inspector-dist/server/assets/index-D71yP6AL.js +0 -191
  172. package/inspector-dist/server/assets/index-wGSWRns3.js +0 -1296
  173. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-DsvuKoEV.js +0 -58
  174. package/inspector-dist/server/assets/token-ClUZZwXl.js +0 -95
  175. package/inspector-dist/server/assets/token-util-DSxMZ6nI.js +0 -33
  176. package/inspector-dist/server/assets/wrapper-B3vstpCO.js +0 -67
  177. package/inspector-dist/server/assets/zstd-browser-decoder-Dn82m2BU.js +0 -77
@@ -0,0 +1,3624 @@
1
+ import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "./rolldown-runtime-C1I3wEg2.js";
2
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/constants.js
3
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4
+ var BINARY_TYPES = [
5
+ "nodebuffer",
6
+ "arraybuffer",
7
+ "fragments"
8
+ ];
9
+ var hasBlob = typeof Blob !== "undefined";
10
+ if (hasBlob) BINARY_TYPES.push("blob");
11
+ module.exports = {
12
+ BINARY_TYPES,
13
+ CLOSE_TIMEOUT: 3e4,
14
+ EMPTY_BUFFER: Buffer.alloc(0),
15
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
16
+ hasBlob,
17
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
18
+ kListener: Symbol("kListener"),
19
+ kStatusCode: Symbol("status-code"),
20
+ kWebSocket: Symbol("websocket"),
21
+ NOOP: () => {}
22
+ };
23
+ }));
24
+ // __vite-optional-peer-dep:bufferutil:ws
25
+ var __vite_optional_peer_dep_bufferutil_ws_exports = /* @__PURE__ */ __exportAll({ default: () => __vite_optional_peer_dep_bufferutil_ws_default });
26
+ var __vite_optional_peer_dep_bufferutil_ws_default;
27
+ var init___vite_optional_peer_dep_bufferutil_ws = __esmMin((() => {
28
+ __vite_optional_peer_dep_bufferutil_ws_default = {};
29
+ throw new Error(`Could not resolve "bufferutil" imported by "ws". Is it installed?`);
30
+ }));
31
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/buffer-util.js
32
+ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
33
+ var { websocketMask, websocketUnmask } = __require("http");
34
+ var { EMPTY_BUFFER } = require_constants();
35
+ var FastBuffer = Buffer[Symbol.species];
36
+ /**
37
+ * Merges an array of buffers into a new buffer.
38
+ *
39
+ * @param {Buffer[]} list The array of buffers to concat
40
+ * @param {Number} totalLength The total length of buffers in the list
41
+ * @return {Buffer} The resulting buffer
42
+ * @public
43
+ */
44
+ function concat(list, totalLength) {
45
+ if (list.length === 0) return EMPTY_BUFFER;
46
+ if (list.length === 1) return list[0];
47
+ const target = Buffer.allocUnsafe(totalLength);
48
+ let offset = 0;
49
+ for (let i = 0; i < list.length; i++) {
50
+ const buf = list[i];
51
+ target.set(buf, offset);
52
+ offset += buf.length;
53
+ }
54
+ if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
55
+ return target;
56
+ }
57
+ /**
58
+ * Masks a buffer using the given mask.
59
+ *
60
+ * @param {Buffer} source The buffer to mask
61
+ * @param {Buffer} mask The mask to use
62
+ * @param {Buffer} output The buffer where to store the result
63
+ * @param {Number} offset The offset at which to start writing
64
+ * @param {Number} length The number of bytes to mask.
65
+ * @public
66
+ */
67
+ function _mask(source, mask, output, offset, length) {
68
+ for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
69
+ }
70
+ /**
71
+ * Unmasks a buffer using the given mask.
72
+ *
73
+ * @param {Buffer} buffer The buffer to unmask
74
+ * @param {Buffer} mask The mask to use
75
+ * @public
76
+ */
77
+ function _unmask(buffer, mask) {
78
+ for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
79
+ }
80
+ /**
81
+ * Converts a buffer to an `ArrayBuffer`.
82
+ *
83
+ * @param {Buffer} buf The buffer to convert
84
+ * @return {ArrayBuffer} Converted buffer
85
+ * @public
86
+ */
87
+ function toArrayBuffer(buf) {
88
+ if (buf.length === buf.buffer.byteLength) return buf.buffer;
89
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
90
+ }
91
+ /**
92
+ * Converts `data` to a `Buffer`.
93
+ *
94
+ * @param {*} data The data to convert
95
+ * @return {Buffer} The buffer
96
+ * @throws {TypeError}
97
+ * @public
98
+ */
99
+ function toBuffer(data) {
100
+ toBuffer.readOnly = true;
101
+ if (Buffer.isBuffer(data)) return data;
102
+ let buf;
103
+ if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
104
+ else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
105
+ else {
106
+ buf = Buffer.from(data);
107
+ toBuffer.readOnly = false;
108
+ }
109
+ return buf;
110
+ }
111
+ module.exports = {
112
+ concat,
113
+ mask: _mask,
114
+ toArrayBuffer,
115
+ toBuffer,
116
+ unmask: _unmask
117
+ };
118
+ if (websocketMask) {
119
+ module.exports.mask = function(source, mask, output, offset, length) {
120
+ if (length < 24) _mask(source, mask, output, offset, length);
121
+ else websocketMask(source, mask, output, offset, length);
122
+ };
123
+ module.exports.unmask = function(buffer, mask) {
124
+ if (buffer.length < 24) _unmask(buffer, mask);
125
+ else websocketUnmask(buffer, mask);
126
+ };
127
+ } else if (!process.env.WS_NO_BUFFER_UTIL) try {
128
+ const bufferUtil = (init___vite_optional_peer_dep_bufferutil_ws(), __toCommonJS(__vite_optional_peer_dep_bufferutil_ws_exports));
129
+ module.exports.mask = function(source, mask, output, offset, length) {
130
+ if (length < 48) _mask(source, mask, output, offset, length);
131
+ else bufferUtil.mask(source, mask, output, offset, length);
132
+ };
133
+ module.exports.unmask = function(buffer, mask) {
134
+ if (buffer.length < 32) _unmask(buffer, mask);
135
+ else bufferUtil.unmask(buffer, mask);
136
+ };
137
+ } catch (e) {}
138
+ }));
139
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/limiter.js
140
+ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
141
+ var kDone = Symbol("kDone");
142
+ var kRun = Symbol("kRun");
143
+ /**
144
+ * A very simple job queue with adjustable concurrency. Adapted from
145
+ * https://github.com/STRML/async-limiter
146
+ */
147
+ var Limiter = class {
148
+ /**
149
+ * Creates a new `Limiter`.
150
+ *
151
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
152
+ * to run concurrently
153
+ */
154
+ constructor(concurrency) {
155
+ this[kDone] = () => {
156
+ this.pending--;
157
+ this[kRun]();
158
+ };
159
+ this.concurrency = concurrency || Infinity;
160
+ this.jobs = [];
161
+ this.pending = 0;
162
+ }
163
+ /**
164
+ * Adds a job to the queue.
165
+ *
166
+ * @param {Function} job The job to run
167
+ * @public
168
+ */
169
+ add(job) {
170
+ this.jobs.push(job);
171
+ this[kRun]();
172
+ }
173
+ /**
174
+ * Removes a job from the queue and runs it if possible.
175
+ *
176
+ * @private
177
+ */
178
+ [kRun]() {
179
+ if (this.pending === this.concurrency) return;
180
+ if (this.jobs.length) {
181
+ const job = this.jobs.shift();
182
+ this.pending++;
183
+ job(this[kDone]);
184
+ }
185
+ }
186
+ };
187
+ module.exports = Limiter;
188
+ }));
189
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/permessage-deflate.js
190
+ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
191
+ var zlib = __require("zlib");
192
+ var bufferUtil = require_buffer_util();
193
+ var Limiter = require_limiter();
194
+ var { kStatusCode } = require_constants();
195
+ var FastBuffer = Buffer[Symbol.species];
196
+ var TRAILER = Buffer.from([
197
+ 0,
198
+ 0,
199
+ 255,
200
+ 255
201
+ ]);
202
+ var kPerMessageDeflate = Symbol("permessage-deflate");
203
+ var kTotalLength = Symbol("total-length");
204
+ var kCallback = Symbol("callback");
205
+ var kBuffers = Symbol("buffers");
206
+ var kError = Symbol("error");
207
+ var zlibLimiter;
208
+ /**
209
+ * permessage-deflate implementation.
210
+ */
211
+ var PerMessageDeflate = class {
212
+ /**
213
+ * Creates a PerMessageDeflate instance.
214
+ *
215
+ * @param {Object} [options] Configuration options
216
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
217
+ * for, or request, a custom client window size
218
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
219
+ * acknowledge disabling of client context takeover
220
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
221
+ * calls to zlib
222
+ * @param {Boolean} [options.isServer=false] Create the instance in either
223
+ * server or client mode
224
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
225
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
226
+ * use of a custom server window size
227
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
228
+ * disabling of server context takeover
229
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
230
+ * messages should not be compressed if context takeover is disabled
231
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
232
+ * deflate
233
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
234
+ * inflate
235
+ */
236
+ constructor(options) {
237
+ this._options = options || {};
238
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
239
+ this._maxPayload = this._options.maxPayload | 0;
240
+ this._isServer = !!this._options.isServer;
241
+ this._deflate = null;
242
+ this._inflate = null;
243
+ this.params = null;
244
+ if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
245
+ }
246
+ /**
247
+ * @type {String}
248
+ */
249
+ static get extensionName() {
250
+ return "permessage-deflate";
251
+ }
252
+ /**
253
+ * Create an extension negotiation offer.
254
+ *
255
+ * @return {Object} Extension parameters
256
+ * @public
257
+ */
258
+ offer() {
259
+ const params = {};
260
+ if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
261
+ if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
262
+ if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
263
+ if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
264
+ else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
265
+ return params;
266
+ }
267
+ /**
268
+ * Accept an extension negotiation offer/response.
269
+ *
270
+ * @param {Array} configurations The extension negotiation offers/reponse
271
+ * @return {Object} Accepted configuration
272
+ * @public
273
+ */
274
+ accept(configurations) {
275
+ configurations = this.normalizeParams(configurations);
276
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
277
+ return this.params;
278
+ }
279
+ /**
280
+ * Releases all resources used by the extension.
281
+ *
282
+ * @public
283
+ */
284
+ cleanup() {
285
+ if (this._inflate) {
286
+ this._inflate.close();
287
+ this._inflate = null;
288
+ }
289
+ if (this._deflate) {
290
+ const callback = this._deflate[kCallback];
291
+ this._deflate.close();
292
+ this._deflate = null;
293
+ if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
294
+ }
295
+ }
296
+ /**
297
+ * Accept an extension negotiation offer.
298
+ *
299
+ * @param {Array} offers The extension negotiation offers
300
+ * @return {Object} Accepted configuration
301
+ * @private
302
+ */
303
+ acceptAsServer(offers) {
304
+ const opts = this._options;
305
+ const accepted = offers.find((params) => {
306
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) return false;
307
+ return true;
308
+ });
309
+ if (!accepted) throw new Error("None of the extension offers can be accepted");
310
+ if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
311
+ if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
312
+ if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
313
+ if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
314
+ else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
315
+ return accepted;
316
+ }
317
+ /**
318
+ * Accept the extension negotiation response.
319
+ *
320
+ * @param {Array} response The extension negotiation response
321
+ * @return {Object} Accepted configuration
322
+ * @private
323
+ */
324
+ acceptAsClient(response) {
325
+ const params = response[0];
326
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
327
+ if (!params.client_max_window_bits) {
328
+ if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
329
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
330
+ return params;
331
+ }
332
+ /**
333
+ * Normalize parameters.
334
+ *
335
+ * @param {Array} configurations The extension negotiation offers/reponse
336
+ * @return {Array} The offers/response with normalized parameters
337
+ * @private
338
+ */
339
+ normalizeParams(configurations) {
340
+ configurations.forEach((params) => {
341
+ Object.keys(params).forEach((key) => {
342
+ let value = params[key];
343
+ if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
344
+ value = value[0];
345
+ if (key === "client_max_window_bits") {
346
+ if (value !== true) {
347
+ const num = +value;
348
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
349
+ value = num;
350
+ } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
351
+ } else if (key === "server_max_window_bits") {
352
+ const num = +value;
353
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
354
+ value = num;
355
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
356
+ if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
357
+ } else throw new Error(`Unknown parameter "${key}"`);
358
+ params[key] = value;
359
+ });
360
+ });
361
+ return configurations;
362
+ }
363
+ /**
364
+ * Decompress data. Concurrency limited.
365
+ *
366
+ * @param {Buffer} data Compressed data
367
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
368
+ * @param {Function} callback Callback
369
+ * @public
370
+ */
371
+ decompress(data, fin, callback) {
372
+ zlibLimiter.add((done) => {
373
+ this._decompress(data, fin, (err, result) => {
374
+ done();
375
+ callback(err, result);
376
+ });
377
+ });
378
+ }
379
+ /**
380
+ * Compress data. Concurrency limited.
381
+ *
382
+ * @param {(Buffer|String)} data Data to compress
383
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
384
+ * @param {Function} callback Callback
385
+ * @public
386
+ */
387
+ compress(data, fin, callback) {
388
+ zlibLimiter.add((done) => {
389
+ this._compress(data, fin, (err, result) => {
390
+ done();
391
+ callback(err, result);
392
+ });
393
+ });
394
+ }
395
+ /**
396
+ * Decompress data.
397
+ *
398
+ * @param {Buffer} data Compressed data
399
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
400
+ * @param {Function} callback Callback
401
+ * @private
402
+ */
403
+ _decompress(data, fin, callback) {
404
+ const endpoint = this._isServer ? "client" : "server";
405
+ if (!this._inflate) {
406
+ const key = `${endpoint}_max_window_bits`;
407
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
408
+ this._inflate = zlib.createInflateRaw({
409
+ ...this._options.zlibInflateOptions,
410
+ windowBits
411
+ });
412
+ this._inflate[kPerMessageDeflate] = this;
413
+ this._inflate[kTotalLength] = 0;
414
+ this._inflate[kBuffers] = [];
415
+ this._inflate.on("error", inflateOnError);
416
+ this._inflate.on("data", inflateOnData);
417
+ }
418
+ this._inflate[kCallback] = callback;
419
+ this._inflate.write(data);
420
+ if (fin) this._inflate.write(TRAILER);
421
+ this._inflate.flush(() => {
422
+ const err = this._inflate[kError];
423
+ if (err) {
424
+ this._inflate.close();
425
+ this._inflate = null;
426
+ callback(err);
427
+ return;
428
+ }
429
+ const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
430
+ if (this._inflate._readableState.endEmitted) {
431
+ this._inflate.close();
432
+ this._inflate = null;
433
+ } else {
434
+ this._inflate[kTotalLength] = 0;
435
+ this._inflate[kBuffers] = [];
436
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
437
+ }
438
+ callback(null, data);
439
+ });
440
+ }
441
+ /**
442
+ * Compress data.
443
+ *
444
+ * @param {(Buffer|String)} data Data to compress
445
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
446
+ * @param {Function} callback Callback
447
+ * @private
448
+ */
449
+ _compress(data, fin, callback) {
450
+ const endpoint = this._isServer ? "server" : "client";
451
+ if (!this._deflate) {
452
+ const key = `${endpoint}_max_window_bits`;
453
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
454
+ this._deflate = zlib.createDeflateRaw({
455
+ ...this._options.zlibDeflateOptions,
456
+ windowBits
457
+ });
458
+ this._deflate[kTotalLength] = 0;
459
+ this._deflate[kBuffers] = [];
460
+ this._deflate.on("data", deflateOnData);
461
+ }
462
+ this._deflate[kCallback] = callback;
463
+ this._deflate.write(data);
464
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
465
+ if (!this._deflate) return;
466
+ let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
467
+ if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
468
+ this._deflate[kCallback] = null;
469
+ this._deflate[kTotalLength] = 0;
470
+ this._deflate[kBuffers] = [];
471
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
472
+ callback(null, data);
473
+ });
474
+ }
475
+ };
476
+ module.exports = PerMessageDeflate;
477
+ /**
478
+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.
479
+ *
480
+ * @param {Buffer} chunk A chunk of data
481
+ * @private
482
+ */
483
+ function deflateOnData(chunk) {
484
+ this[kBuffers].push(chunk);
485
+ this[kTotalLength] += chunk.length;
486
+ }
487
+ /**
488
+ * The listener of the `zlib.InflateRaw` stream `'data'` event.
489
+ *
490
+ * @param {Buffer} chunk A chunk of data
491
+ * @private
492
+ */
493
+ function inflateOnData(chunk) {
494
+ this[kTotalLength] += chunk.length;
495
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
496
+ this[kBuffers].push(chunk);
497
+ return;
498
+ }
499
+ this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
500
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
501
+ this[kError][kStatusCode] = 1009;
502
+ this.removeListener("data", inflateOnData);
503
+ this.reset();
504
+ }
505
+ /**
506
+ * The listener of the `zlib.InflateRaw` stream `'error'` event.
507
+ *
508
+ * @param {Error} err The emitted error
509
+ * @private
510
+ */
511
+ function inflateOnError(err) {
512
+ this[kPerMessageDeflate]._inflate = null;
513
+ if (this[kError]) {
514
+ this[kCallback](this[kError]);
515
+ return;
516
+ }
517
+ err[kStatusCode] = 1007;
518
+ this[kCallback](err);
519
+ }
520
+ }));
521
+ // __vite-optional-peer-dep:utf-8-validate:ws
522
+ var __vite_optional_peer_dep_utf_8_validate_ws_exports = /* @__PURE__ */ __exportAll({ default: () => __vite_optional_peer_dep_utf_8_validate_ws_default });
523
+ var __vite_optional_peer_dep_utf_8_validate_ws_default;
524
+ var init___vite_optional_peer_dep_utf_8_validate_ws = __esmMin((() => {
525
+ __vite_optional_peer_dep_utf_8_validate_ws_default = {};
526
+ throw new Error(`Could not resolve "utf-8-validate" imported by "ws". Is it installed?`);
527
+ }));
528
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/validation.js
529
+ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
530
+ var { isUtf8 } = __require("buffer");
531
+ var { hasBlob } = require_constants();
532
+ var tokenChars = [
533
+ 0,
534
+ 0,
535
+ 0,
536
+ 0,
537
+ 0,
538
+ 0,
539
+ 0,
540
+ 0,
541
+ 0,
542
+ 0,
543
+ 0,
544
+ 0,
545
+ 0,
546
+ 0,
547
+ 0,
548
+ 0,
549
+ 0,
550
+ 0,
551
+ 0,
552
+ 0,
553
+ 0,
554
+ 0,
555
+ 0,
556
+ 0,
557
+ 0,
558
+ 0,
559
+ 0,
560
+ 0,
561
+ 0,
562
+ 0,
563
+ 0,
564
+ 0,
565
+ 0,
566
+ 1,
567
+ 0,
568
+ 1,
569
+ 1,
570
+ 1,
571
+ 1,
572
+ 1,
573
+ 0,
574
+ 0,
575
+ 1,
576
+ 1,
577
+ 0,
578
+ 1,
579
+ 1,
580
+ 0,
581
+ 1,
582
+ 1,
583
+ 1,
584
+ 1,
585
+ 1,
586
+ 1,
587
+ 1,
588
+ 1,
589
+ 1,
590
+ 1,
591
+ 0,
592
+ 0,
593
+ 0,
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 1,
599
+ 1,
600
+ 1,
601
+ 1,
602
+ 1,
603
+ 1,
604
+ 1,
605
+ 1,
606
+ 1,
607
+ 1,
608
+ 1,
609
+ 1,
610
+ 1,
611
+ 1,
612
+ 1,
613
+ 1,
614
+ 1,
615
+ 1,
616
+ 1,
617
+ 1,
618
+ 1,
619
+ 1,
620
+ 1,
621
+ 1,
622
+ 1,
623
+ 1,
624
+ 0,
625
+ 0,
626
+ 0,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 1,
637
+ 1,
638
+ 1,
639
+ 1,
640
+ 1,
641
+ 1,
642
+ 1,
643
+ 1,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 0,
657
+ 1,
658
+ 0,
659
+ 1,
660
+ 0
661
+ ];
662
+ /**
663
+ * Checks if a status code is allowed in a close frame.
664
+ *
665
+ * @param {Number} code The status code
666
+ * @return {Boolean} `true` if the status code is valid, else `false`
667
+ * @public
668
+ */
669
+ function isValidStatusCode(code) {
670
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
671
+ }
672
+ /**
673
+ * Checks if a given buffer contains only correct UTF-8.
674
+ * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
675
+ * Markus Kuhn.
676
+ *
677
+ * @param {Buffer} buf The buffer to check
678
+ * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
679
+ * @public
680
+ */
681
+ function _isValidUTF8(buf) {
682
+ const len = buf.length;
683
+ let i = 0;
684
+ while (i < len) if ((buf[i] & 128) === 0) i++;
685
+ else if ((buf[i] & 224) === 192) {
686
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
687
+ i += 2;
688
+ } else if ((buf[i] & 240) === 224) {
689
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) return false;
690
+ i += 3;
691
+ } else if ((buf[i] & 248) === 240) {
692
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
693
+ i += 4;
694
+ } else return false;
695
+ return true;
696
+ }
697
+ /**
698
+ * Determines whether a value is a `Blob`.
699
+ *
700
+ * @param {*} value The value to be tested
701
+ * @return {Boolean} `true` if `value` is a `Blob`, else `false`
702
+ * @private
703
+ */
704
+ function isBlob(value) {
705
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
706
+ }
707
+ module.exports = {
708
+ isBlob,
709
+ isValidStatusCode,
710
+ isValidUTF8: _isValidUTF8,
711
+ tokenChars
712
+ };
713
+ if (isUtf8) module.exports.isValidUTF8 = function(buf) {
714
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
715
+ };
716
+ else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
717
+ const isValidUTF8 = (init___vite_optional_peer_dep_utf_8_validate_ws(), __toCommonJS(__vite_optional_peer_dep_utf_8_validate_ws_exports));
718
+ module.exports.isValidUTF8 = function(buf) {
719
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
720
+ };
721
+ } catch (e) {}
722
+ }));
723
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/receiver.js
724
+ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
725
+ var { Writable } = __require("stream");
726
+ var PerMessageDeflate = require_permessage_deflate();
727
+ var { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
728
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
729
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
730
+ var FastBuffer = Buffer[Symbol.species];
731
+ var GET_INFO = 0;
732
+ var GET_PAYLOAD_LENGTH_16 = 1;
733
+ var GET_PAYLOAD_LENGTH_64 = 2;
734
+ var GET_MASK = 3;
735
+ var GET_DATA = 4;
736
+ var INFLATING = 5;
737
+ var DEFER_EVENT = 6;
738
+ /**
739
+ * HyBi Receiver implementation.
740
+ *
741
+ * @extends Writable
742
+ */
743
+ var Receiver = class extends Writable {
744
+ /**
745
+ * Creates a Receiver instance.
746
+ *
747
+ * @param {Object} [options] Options object
748
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
749
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
750
+ * multiple times in the same tick
751
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
752
+ * @param {Object} [options.extensions] An object containing the negotiated
753
+ * extensions
754
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
755
+ * client or server mode
756
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
757
+ * buffered data chunks
758
+ * @param {Number} [options.maxFragments=0] The maximum number of message
759
+ * fragments
760
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
761
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
762
+ * not to skip UTF-8 validation for text and close messages
763
+ */
764
+ constructor(options = {}) {
765
+ super();
766
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
767
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
768
+ this._extensions = options.extensions || {};
769
+ this._isServer = !!options.isServer;
770
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
771
+ this._maxFragments = options.maxFragments | 0;
772
+ this._maxPayload = options.maxPayload | 0;
773
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
774
+ this[kWebSocket] = void 0;
775
+ this._bufferedBytes = 0;
776
+ this._buffers = [];
777
+ this._compressed = false;
778
+ this._payloadLength = 0;
779
+ this._mask = void 0;
780
+ this._fragmented = 0;
781
+ this._masked = false;
782
+ this._fin = false;
783
+ this._opcode = 0;
784
+ this._totalPayloadLength = 0;
785
+ this._messageLength = 0;
786
+ this._numFragments = 0;
787
+ this._fragments = [];
788
+ this._errored = false;
789
+ this._loop = false;
790
+ this._state = GET_INFO;
791
+ }
792
+ /**
793
+ * Implements `Writable.prototype._write()`.
794
+ *
795
+ * @param {Buffer} chunk The chunk of data to write
796
+ * @param {String} encoding The character encoding of `chunk`
797
+ * @param {Function} cb Callback
798
+ * @private
799
+ */
800
+ _write(chunk, encoding, cb) {
801
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
802
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
803
+ cb(this.createError(RangeError, "Too many buffered chunks", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
804
+ return;
805
+ }
806
+ this._bufferedBytes += chunk.length;
807
+ this._buffers.push(chunk);
808
+ this.startLoop(cb);
809
+ }
810
+ /**
811
+ * Consumes `n` bytes from the buffered data.
812
+ *
813
+ * @param {Number} n The number of bytes to consume
814
+ * @return {Buffer} The consumed bytes
815
+ * @private
816
+ */
817
+ consume(n) {
818
+ this._bufferedBytes -= n;
819
+ if (n === this._buffers[0].length) return this._buffers.shift();
820
+ if (n < this._buffers[0].length) {
821
+ const buf = this._buffers[0];
822
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
823
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
824
+ }
825
+ const dst = Buffer.allocUnsafe(n);
826
+ do {
827
+ const buf = this._buffers[0];
828
+ const offset = dst.length - n;
829
+ if (n >= buf.length) dst.set(this._buffers.shift(), offset);
830
+ else {
831
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
832
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
833
+ }
834
+ n -= buf.length;
835
+ } while (n > 0);
836
+ return dst;
837
+ }
838
+ /**
839
+ * Starts the parsing loop.
840
+ *
841
+ * @param {Function} cb Callback
842
+ * @private
843
+ */
844
+ startLoop(cb) {
845
+ this._loop = true;
846
+ do
847
+ switch (this._state) {
848
+ case GET_INFO:
849
+ this.getInfo(cb);
850
+ break;
851
+ case GET_PAYLOAD_LENGTH_16:
852
+ this.getPayloadLength16(cb);
853
+ break;
854
+ case GET_PAYLOAD_LENGTH_64:
855
+ this.getPayloadLength64(cb);
856
+ break;
857
+ case GET_MASK:
858
+ this.getMask();
859
+ break;
860
+ case GET_DATA:
861
+ this.getData(cb);
862
+ break;
863
+ case INFLATING:
864
+ case DEFER_EVENT:
865
+ this._loop = false;
866
+ return;
867
+ }
868
+ while (this._loop);
869
+ if (!this._errored) cb();
870
+ }
871
+ /**
872
+ * Reads the first two bytes of a frame.
873
+ *
874
+ * @param {Function} cb Callback
875
+ * @private
876
+ */
877
+ getInfo(cb) {
878
+ if (this._bufferedBytes < 2) {
879
+ this._loop = false;
880
+ return;
881
+ }
882
+ const buf = this.consume(2);
883
+ if ((buf[0] & 48) !== 0) {
884
+ cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
885
+ return;
886
+ }
887
+ const compressed = (buf[0] & 64) === 64;
888
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
889
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
890
+ return;
891
+ }
892
+ this._fin = (buf[0] & 128) === 128;
893
+ this._opcode = buf[0] & 15;
894
+ this._payloadLength = buf[1] & 127;
895
+ if (this._opcode === 0) {
896
+ if (compressed) {
897
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
898
+ return;
899
+ }
900
+ if (!this._fragmented) {
901
+ cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
902
+ return;
903
+ }
904
+ this._opcode = this._fragmented;
905
+ } else if (this._opcode === 1 || this._opcode === 2) {
906
+ if (this._fragmented) {
907
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
908
+ return;
909
+ }
910
+ this._compressed = compressed;
911
+ } else if (this._opcode > 7 && this._opcode < 11) {
912
+ if (!this._fin) {
913
+ cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
914
+ return;
915
+ }
916
+ if (compressed) {
917
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
918
+ return;
919
+ }
920
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
921
+ cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
922
+ return;
923
+ }
924
+ } else {
925
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
926
+ return;
927
+ }
928
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
929
+ this._masked = (buf[1] & 128) === 128;
930
+ if (this._isServer) {
931
+ if (!this._masked) {
932
+ cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
933
+ return;
934
+ }
935
+ } else if (this._masked) {
936
+ cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
937
+ return;
938
+ }
939
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
940
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
941
+ else this.haveLength(cb);
942
+ }
943
+ /**
944
+ * Gets extended payload length (7+16).
945
+ *
946
+ * @param {Function} cb Callback
947
+ * @private
948
+ */
949
+ getPayloadLength16(cb) {
950
+ if (this._bufferedBytes < 2) {
951
+ this._loop = false;
952
+ return;
953
+ }
954
+ this._payloadLength = this.consume(2).readUInt16BE(0);
955
+ this.haveLength(cb);
956
+ }
957
+ /**
958
+ * Gets extended payload length (7+64).
959
+ *
960
+ * @param {Function} cb Callback
961
+ * @private
962
+ */
963
+ getPayloadLength64(cb) {
964
+ if (this._bufferedBytes < 8) {
965
+ this._loop = false;
966
+ return;
967
+ }
968
+ const buf = this.consume(8);
969
+ const num = buf.readUInt32BE(0);
970
+ if (num > Math.pow(2, 21) - 1) {
971
+ cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
972
+ return;
973
+ }
974
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
975
+ this.haveLength(cb);
976
+ }
977
+ /**
978
+ * Payload length has been read.
979
+ *
980
+ * @param {Function} cb Callback
981
+ * @private
982
+ */
983
+ haveLength(cb) {
984
+ if (this._payloadLength && this._opcode < 8) {
985
+ this._totalPayloadLength += this._payloadLength;
986
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
987
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
988
+ return;
989
+ }
990
+ }
991
+ if (this._masked) this._state = GET_MASK;
992
+ else this._state = GET_DATA;
993
+ }
994
+ /**
995
+ * Reads mask bytes.
996
+ *
997
+ * @private
998
+ */
999
+ getMask() {
1000
+ if (this._bufferedBytes < 4) {
1001
+ this._loop = false;
1002
+ return;
1003
+ }
1004
+ this._mask = this.consume(4);
1005
+ this._state = GET_DATA;
1006
+ }
1007
+ /**
1008
+ * Reads data bytes.
1009
+ *
1010
+ * @param {Function} cb Callback
1011
+ * @private
1012
+ */
1013
+ getData(cb) {
1014
+ let data = EMPTY_BUFFER;
1015
+ if (this._payloadLength) {
1016
+ if (this._bufferedBytes < this._payloadLength) {
1017
+ this._loop = false;
1018
+ return;
1019
+ }
1020
+ data = this.consume(this._payloadLength);
1021
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
1022
+ }
1023
+ if (this._opcode > 7) {
1024
+ this.controlMessage(data, cb);
1025
+ return;
1026
+ }
1027
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1028
+ cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
1029
+ return;
1030
+ }
1031
+ if (this._compressed) {
1032
+ this._state = INFLATING;
1033
+ this.decompress(data, cb);
1034
+ return;
1035
+ }
1036
+ if (data.length) {
1037
+ this._messageLength = this._totalPayloadLength;
1038
+ this._fragments.push(data);
1039
+ }
1040
+ this.dataMessage(cb);
1041
+ }
1042
+ /**
1043
+ * Decompresses data.
1044
+ *
1045
+ * @param {Buffer} data Compressed data
1046
+ * @param {Function} cb Callback
1047
+ * @private
1048
+ */
1049
+ decompress(data, cb) {
1050
+ this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
1051
+ if (err) return cb(err);
1052
+ if (buf.length) {
1053
+ this._messageLength += buf.length;
1054
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1055
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
1056
+ return;
1057
+ }
1058
+ this._fragments.push(buf);
1059
+ }
1060
+ this.dataMessage(cb);
1061
+ if (this._state === GET_INFO) this.startLoop(cb);
1062
+ });
1063
+ }
1064
+ /**
1065
+ * Handles a data message.
1066
+ *
1067
+ * @param {Function} cb Callback
1068
+ * @private
1069
+ */
1070
+ dataMessage(cb) {
1071
+ if (!this._fin) {
1072
+ this._state = GET_INFO;
1073
+ return;
1074
+ }
1075
+ const messageLength = this._messageLength;
1076
+ const fragments = this._fragments;
1077
+ this._totalPayloadLength = 0;
1078
+ this._messageLength = 0;
1079
+ this._fragmented = 0;
1080
+ this._numFragments = 0;
1081
+ this._fragments = [];
1082
+ if (this._opcode === 2) {
1083
+ let data;
1084
+ if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
1085
+ else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
1086
+ else if (this._binaryType === "blob") data = new Blob(fragments);
1087
+ else data = fragments;
1088
+ if (this._allowSynchronousEvents) {
1089
+ this.emit("message", data, true);
1090
+ this._state = GET_INFO;
1091
+ } else {
1092
+ this._state = DEFER_EVENT;
1093
+ setImmediate(() => {
1094
+ this.emit("message", data, true);
1095
+ this._state = GET_INFO;
1096
+ this.startLoop(cb);
1097
+ });
1098
+ }
1099
+ } else {
1100
+ const buf = concat(fragments, messageLength);
1101
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1102
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1103
+ return;
1104
+ }
1105
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1106
+ this.emit("message", buf, false);
1107
+ this._state = GET_INFO;
1108
+ } else {
1109
+ this._state = DEFER_EVENT;
1110
+ setImmediate(() => {
1111
+ this.emit("message", buf, false);
1112
+ this._state = GET_INFO;
1113
+ this.startLoop(cb);
1114
+ });
1115
+ }
1116
+ }
1117
+ }
1118
+ /**
1119
+ * Handles a control message.
1120
+ *
1121
+ * @param {Buffer} data Data to handle
1122
+ * @return {(Error|RangeError|undefined)} A possible error
1123
+ * @private
1124
+ */
1125
+ controlMessage(data, cb) {
1126
+ if (this._opcode === 8) {
1127
+ if (data.length === 0) {
1128
+ this._loop = false;
1129
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1130
+ this.end();
1131
+ } else {
1132
+ const code = data.readUInt16BE(0);
1133
+ if (!isValidStatusCode(code)) {
1134
+ cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
1135
+ return;
1136
+ }
1137
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
1138
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1139
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1140
+ return;
1141
+ }
1142
+ this._loop = false;
1143
+ this.emit("conclude", code, buf);
1144
+ this.end();
1145
+ }
1146
+ this._state = GET_INFO;
1147
+ return;
1148
+ }
1149
+ if (this._allowSynchronousEvents) {
1150
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1151
+ this._state = GET_INFO;
1152
+ } else {
1153
+ this._state = DEFER_EVENT;
1154
+ setImmediate(() => {
1155
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1156
+ this._state = GET_INFO;
1157
+ this.startLoop(cb);
1158
+ });
1159
+ }
1160
+ }
1161
+ /**
1162
+ * Builds an error object.
1163
+ *
1164
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1165
+ * @param {String} message The error message
1166
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1167
+ * `message`
1168
+ * @param {Number} statusCode The status code
1169
+ * @param {String} errorCode The exposed error code
1170
+ * @return {(Error|RangeError)} The error
1171
+ * @private
1172
+ */
1173
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1174
+ this._loop = false;
1175
+ this._errored = true;
1176
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
1177
+ Error.captureStackTrace(err, this.createError);
1178
+ err.code = errorCode;
1179
+ err[kStatusCode] = statusCode;
1180
+ return err;
1181
+ }
1182
+ };
1183
+ module.exports = Receiver;
1184
+ }));
1185
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/sender.js
1186
+ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1187
+ var { Duplex } = __require("stream");
1188
+ var { randomFillSync } = __require("crypto");
1189
+ var { types: { isUint8Array } } = __require("util");
1190
+ var PerMessageDeflate = require_permessage_deflate();
1191
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1192
+ var { isBlob, isValidStatusCode } = require_validation();
1193
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1194
+ var kByteLength = Symbol("kByteLength");
1195
+ var maskBuffer = Buffer.alloc(4);
1196
+ var RANDOM_POOL_SIZE = 8192;
1197
+ var randomPool;
1198
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1199
+ var DEFAULT = 0;
1200
+ var DEFLATING = 1;
1201
+ var GET_BLOB_DATA = 2;
1202
+ module.exports = class Sender {
1203
+ /**
1204
+ * Creates a Sender instance.
1205
+ *
1206
+ * @param {Duplex} socket The connection socket
1207
+ * @param {Object} [extensions] An object containing the negotiated extensions
1208
+ * @param {Function} [generateMask] The function used to generate the masking
1209
+ * key
1210
+ */
1211
+ constructor(socket, extensions, generateMask) {
1212
+ this._extensions = extensions || {};
1213
+ if (generateMask) {
1214
+ this._generateMask = generateMask;
1215
+ this._maskBuffer = Buffer.alloc(4);
1216
+ }
1217
+ this._socket = socket;
1218
+ this._firstFragment = true;
1219
+ this._compress = false;
1220
+ this._bufferedBytes = 0;
1221
+ this._queue = [];
1222
+ this._state = DEFAULT;
1223
+ this.onerror = NOOP;
1224
+ this[kWebSocket] = void 0;
1225
+ }
1226
+ /**
1227
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1228
+ *
1229
+ * @param {(Buffer|String)} data The data to frame
1230
+ * @param {Object} options Options object
1231
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1232
+ * FIN bit
1233
+ * @param {Function} [options.generateMask] The function used to generate the
1234
+ * masking key
1235
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1236
+ * `data`
1237
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1238
+ * key
1239
+ * @param {Number} options.opcode The opcode
1240
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1241
+ * modified
1242
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1243
+ * RSV1 bit
1244
+ * @return {(Buffer|String)[]} The framed data
1245
+ * @public
1246
+ */
1247
+ static frame(data, options) {
1248
+ let mask;
1249
+ let merge = false;
1250
+ let offset = 2;
1251
+ let skipMasking = false;
1252
+ if (options.mask) {
1253
+ mask = options.maskBuffer || maskBuffer;
1254
+ if (options.generateMask) options.generateMask(mask);
1255
+ else {
1256
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1257
+ /* istanbul ignore else */
1258
+ if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1259
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1260
+ randomPoolPointer = 0;
1261
+ }
1262
+ mask[0] = randomPool[randomPoolPointer++];
1263
+ mask[1] = randomPool[randomPoolPointer++];
1264
+ mask[2] = randomPool[randomPoolPointer++];
1265
+ mask[3] = randomPool[randomPoolPointer++];
1266
+ }
1267
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1268
+ offset = 6;
1269
+ }
1270
+ let dataLength;
1271
+ if (typeof data === "string") {
1272
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
1273
+ else {
1274
+ data = Buffer.from(data);
1275
+ dataLength = data.length;
1276
+ }
1277
+ } else {
1278
+ dataLength = data.length;
1279
+ merge = options.mask && options.readOnly && !skipMasking;
1280
+ }
1281
+ let payloadLength = dataLength;
1282
+ if (dataLength >= 65536) {
1283
+ offset += 8;
1284
+ payloadLength = 127;
1285
+ } else if (dataLength > 125) {
1286
+ offset += 2;
1287
+ payloadLength = 126;
1288
+ }
1289
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1290
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1291
+ if (options.rsv1) target[0] |= 64;
1292
+ target[1] = payloadLength;
1293
+ if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
1294
+ else if (payloadLength === 127) {
1295
+ target[2] = target[3] = 0;
1296
+ target.writeUIntBE(dataLength, 4, 6);
1297
+ }
1298
+ if (!options.mask) return dataLength ? [target, data] : [target];
1299
+ target[1] |= 128;
1300
+ target[offset - 4] = mask[0];
1301
+ target[offset - 3] = mask[1];
1302
+ target[offset - 2] = mask[2];
1303
+ target[offset - 1] = mask[3];
1304
+ if (!dataLength) return [target];
1305
+ if (skipMasking) return [target, data];
1306
+ if (merge) {
1307
+ applyMask(data, mask, target, offset, dataLength);
1308
+ return [target];
1309
+ }
1310
+ applyMask(data, mask, data, 0, dataLength);
1311
+ return [target, data];
1312
+ }
1313
+ /**
1314
+ * Sends a close message to the other peer.
1315
+ *
1316
+ * @param {Number} [code] The status code component of the body
1317
+ * @param {(String|Buffer)} [data] The message component of the body
1318
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1319
+ * @param {Function} [cb] Callback
1320
+ * @public
1321
+ */
1322
+ close(code, data, mask, cb) {
1323
+ let buf;
1324
+ if (code === void 0) buf = EMPTY_BUFFER;
1325
+ else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
1326
+ else if (data === void 0 || !data.length) {
1327
+ buf = Buffer.allocUnsafe(2);
1328
+ buf.writeUInt16BE(code, 0);
1329
+ } else {
1330
+ const length = Buffer.byteLength(data);
1331
+ if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
1332
+ buf = Buffer.allocUnsafe(2 + length);
1333
+ buf.writeUInt16BE(code, 0);
1334
+ if (typeof data === "string") buf.write(data, 2);
1335
+ else if (isUint8Array(data)) buf.set(data, 2);
1336
+ else throw new TypeError("Second argument must be a string or a Uint8Array");
1337
+ }
1338
+ const options = {
1339
+ [kByteLength]: buf.length,
1340
+ fin: true,
1341
+ generateMask: this._generateMask,
1342
+ mask,
1343
+ maskBuffer: this._maskBuffer,
1344
+ opcode: 8,
1345
+ readOnly: false,
1346
+ rsv1: false
1347
+ };
1348
+ if (this._state !== DEFAULT) this.enqueue([
1349
+ this.dispatch,
1350
+ buf,
1351
+ false,
1352
+ options,
1353
+ cb
1354
+ ]);
1355
+ else this.sendFrame(Sender.frame(buf, options), cb);
1356
+ }
1357
+ /**
1358
+ * Sends a ping message to the other peer.
1359
+ *
1360
+ * @param {*} data The message to send
1361
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1362
+ * @param {Function} [cb] Callback
1363
+ * @public
1364
+ */
1365
+ ping(data, mask, cb) {
1366
+ let byteLength;
1367
+ let readOnly;
1368
+ if (typeof data === "string") {
1369
+ byteLength = Buffer.byteLength(data);
1370
+ readOnly = false;
1371
+ } else if (isBlob(data)) {
1372
+ byteLength = data.size;
1373
+ readOnly = false;
1374
+ } else {
1375
+ data = toBuffer(data);
1376
+ byteLength = data.length;
1377
+ readOnly = toBuffer.readOnly;
1378
+ }
1379
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1380
+ const options = {
1381
+ [kByteLength]: byteLength,
1382
+ fin: true,
1383
+ generateMask: this._generateMask,
1384
+ mask,
1385
+ maskBuffer: this._maskBuffer,
1386
+ opcode: 9,
1387
+ readOnly,
1388
+ rsv1: false
1389
+ };
1390
+ if (isBlob(data)) {
1391
+ if (this._state !== DEFAULT) this.enqueue([
1392
+ this.getBlobData,
1393
+ data,
1394
+ false,
1395
+ options,
1396
+ cb
1397
+ ]);
1398
+ else this.getBlobData(data, false, options, cb);
1399
+ } else if (this._state !== DEFAULT) this.enqueue([
1400
+ this.dispatch,
1401
+ data,
1402
+ false,
1403
+ options,
1404
+ cb
1405
+ ]);
1406
+ else this.sendFrame(Sender.frame(data, options), cb);
1407
+ }
1408
+ /**
1409
+ * Sends a pong message to the other peer.
1410
+ *
1411
+ * @param {*} data The message to send
1412
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1413
+ * @param {Function} [cb] Callback
1414
+ * @public
1415
+ */
1416
+ pong(data, mask, cb) {
1417
+ let byteLength;
1418
+ let readOnly;
1419
+ if (typeof data === "string") {
1420
+ byteLength = Buffer.byteLength(data);
1421
+ readOnly = false;
1422
+ } else if (isBlob(data)) {
1423
+ byteLength = data.size;
1424
+ readOnly = false;
1425
+ } else {
1426
+ data = toBuffer(data);
1427
+ byteLength = data.length;
1428
+ readOnly = toBuffer.readOnly;
1429
+ }
1430
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1431
+ const options = {
1432
+ [kByteLength]: byteLength,
1433
+ fin: true,
1434
+ generateMask: this._generateMask,
1435
+ mask,
1436
+ maskBuffer: this._maskBuffer,
1437
+ opcode: 10,
1438
+ readOnly,
1439
+ rsv1: false
1440
+ };
1441
+ if (isBlob(data)) {
1442
+ if (this._state !== DEFAULT) this.enqueue([
1443
+ this.getBlobData,
1444
+ data,
1445
+ false,
1446
+ options,
1447
+ cb
1448
+ ]);
1449
+ else this.getBlobData(data, false, options, cb);
1450
+ } else if (this._state !== DEFAULT) this.enqueue([
1451
+ this.dispatch,
1452
+ data,
1453
+ false,
1454
+ options,
1455
+ cb
1456
+ ]);
1457
+ else this.sendFrame(Sender.frame(data, options), cb);
1458
+ }
1459
+ /**
1460
+ * Sends a data message to the other peer.
1461
+ *
1462
+ * @param {*} data The message to send
1463
+ * @param {Object} options Options object
1464
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1465
+ * or text
1466
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1467
+ * compress `data`
1468
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1469
+ * last one
1470
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1471
+ * `data`
1472
+ * @param {Function} [cb] Callback
1473
+ * @public
1474
+ */
1475
+ send(data, options, cb) {
1476
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1477
+ let opcode = options.binary ? 2 : 1;
1478
+ let rsv1 = options.compress;
1479
+ let byteLength;
1480
+ let readOnly;
1481
+ if (typeof data === "string") {
1482
+ byteLength = Buffer.byteLength(data);
1483
+ readOnly = false;
1484
+ } else if (isBlob(data)) {
1485
+ byteLength = data.size;
1486
+ readOnly = false;
1487
+ } else {
1488
+ data = toBuffer(data);
1489
+ byteLength = data.length;
1490
+ readOnly = toBuffer.readOnly;
1491
+ }
1492
+ if (this._firstFragment) {
1493
+ this._firstFragment = false;
1494
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
1495
+ this._compress = rsv1;
1496
+ } else {
1497
+ rsv1 = false;
1498
+ opcode = 0;
1499
+ }
1500
+ if (options.fin) this._firstFragment = true;
1501
+ const opts = {
1502
+ [kByteLength]: byteLength,
1503
+ fin: options.fin,
1504
+ generateMask: this._generateMask,
1505
+ mask: options.mask,
1506
+ maskBuffer: this._maskBuffer,
1507
+ opcode,
1508
+ readOnly,
1509
+ rsv1
1510
+ };
1511
+ if (isBlob(data)) {
1512
+ if (this._state !== DEFAULT) this.enqueue([
1513
+ this.getBlobData,
1514
+ data,
1515
+ this._compress,
1516
+ opts,
1517
+ cb
1518
+ ]);
1519
+ else this.getBlobData(data, this._compress, opts, cb);
1520
+ } else if (this._state !== DEFAULT) this.enqueue([
1521
+ this.dispatch,
1522
+ data,
1523
+ this._compress,
1524
+ opts,
1525
+ cb
1526
+ ]);
1527
+ else this.dispatch(data, this._compress, opts, cb);
1528
+ }
1529
+ /**
1530
+ * Gets the contents of a blob as binary data.
1531
+ *
1532
+ * @param {Blob} blob The blob
1533
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1534
+ * the data
1535
+ * @param {Object} options Options object
1536
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1537
+ * FIN bit
1538
+ * @param {Function} [options.generateMask] The function used to generate the
1539
+ * masking key
1540
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1541
+ * `data`
1542
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1543
+ * key
1544
+ * @param {Number} options.opcode The opcode
1545
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1546
+ * modified
1547
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1548
+ * RSV1 bit
1549
+ * @param {Function} [cb] Callback
1550
+ * @private
1551
+ */
1552
+ getBlobData(blob, compress, options, cb) {
1553
+ this._bufferedBytes += options[kByteLength];
1554
+ this._state = GET_BLOB_DATA;
1555
+ blob.arrayBuffer().then((arrayBuffer) => {
1556
+ if (this._socket.destroyed) {
1557
+ const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
1558
+ process.nextTick(callCallbacks, this, err, cb);
1559
+ return;
1560
+ }
1561
+ this._bufferedBytes -= options[kByteLength];
1562
+ const data = toBuffer(arrayBuffer);
1563
+ if (!compress) {
1564
+ this._state = DEFAULT;
1565
+ this.sendFrame(Sender.frame(data, options), cb);
1566
+ this.dequeue();
1567
+ } else this.dispatch(data, compress, options, cb);
1568
+ }).catch((err) => {
1569
+ process.nextTick(onError, this, err, cb);
1570
+ });
1571
+ }
1572
+ /**
1573
+ * Dispatches a message.
1574
+ *
1575
+ * @param {(Buffer|String)} data The message to send
1576
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1577
+ * `data`
1578
+ * @param {Object} options Options object
1579
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1580
+ * FIN bit
1581
+ * @param {Function} [options.generateMask] The function used to generate the
1582
+ * masking key
1583
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1584
+ * `data`
1585
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1586
+ * key
1587
+ * @param {Number} options.opcode The opcode
1588
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1589
+ * modified
1590
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1591
+ * RSV1 bit
1592
+ * @param {Function} [cb] Callback
1593
+ * @private
1594
+ */
1595
+ dispatch(data, compress, options, cb) {
1596
+ if (!compress) {
1597
+ this.sendFrame(Sender.frame(data, options), cb);
1598
+ return;
1599
+ }
1600
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1601
+ this._bufferedBytes += options[kByteLength];
1602
+ this._state = DEFLATING;
1603
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1604
+ if (this._socket.destroyed) {
1605
+ const err = /* @__PURE__ */ new Error("The socket was closed while data was being compressed");
1606
+ callCallbacks(this, err, cb);
1607
+ return;
1608
+ }
1609
+ this._bufferedBytes -= options[kByteLength];
1610
+ this._state = DEFAULT;
1611
+ options.readOnly = false;
1612
+ this.sendFrame(Sender.frame(buf, options), cb);
1613
+ this.dequeue();
1614
+ });
1615
+ }
1616
+ /**
1617
+ * Executes queued send operations.
1618
+ *
1619
+ * @private
1620
+ */
1621
+ dequeue() {
1622
+ while (this._state === DEFAULT && this._queue.length) {
1623
+ const params = this._queue.shift();
1624
+ this._bufferedBytes -= params[3][kByteLength];
1625
+ Reflect.apply(params[0], this, params.slice(1));
1626
+ }
1627
+ }
1628
+ /**
1629
+ * Enqueues a send operation.
1630
+ *
1631
+ * @param {Array} params Send operation parameters.
1632
+ * @private
1633
+ */
1634
+ enqueue(params) {
1635
+ this._bufferedBytes += params[3][kByteLength];
1636
+ this._queue.push(params);
1637
+ }
1638
+ /**
1639
+ * Sends a frame.
1640
+ *
1641
+ * @param {(Buffer | String)[]} list The frame to send
1642
+ * @param {Function} [cb] Callback
1643
+ * @private
1644
+ */
1645
+ sendFrame(list, cb) {
1646
+ if (list.length === 2) {
1647
+ this._socket.cork();
1648
+ this._socket.write(list[0]);
1649
+ this._socket.write(list[1], cb);
1650
+ this._socket.uncork();
1651
+ } else this._socket.write(list[0], cb);
1652
+ }
1653
+ };
1654
+ /**
1655
+ * Calls queued callbacks with an error.
1656
+ *
1657
+ * @param {Sender} sender The `Sender` instance
1658
+ * @param {Error} err The error to call the callbacks with
1659
+ * @param {Function} [cb] The first callback
1660
+ * @private
1661
+ */
1662
+ function callCallbacks(sender, err, cb) {
1663
+ if (typeof cb === "function") cb(err);
1664
+ for (let i = 0; i < sender._queue.length; i++) {
1665
+ const params = sender._queue[i];
1666
+ const callback = params[params.length - 1];
1667
+ if (typeof callback === "function") callback(err);
1668
+ }
1669
+ }
1670
+ /**
1671
+ * Handles a `Sender` error.
1672
+ *
1673
+ * @param {Sender} sender The `Sender` instance
1674
+ * @param {Error} err The error
1675
+ * @param {Function} [cb] The first pending callback
1676
+ * @private
1677
+ */
1678
+ function onError(sender, err, cb) {
1679
+ callCallbacks(sender, err, cb);
1680
+ sender.onerror(err);
1681
+ }
1682
+ }));
1683
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/event-target.js
1684
+ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1685
+ var { kForOnEventAttribute, kListener } = require_constants();
1686
+ var kCode = Symbol("kCode");
1687
+ var kData = Symbol("kData");
1688
+ var kError = Symbol("kError");
1689
+ var kMessage = Symbol("kMessage");
1690
+ var kReason = Symbol("kReason");
1691
+ var kTarget = Symbol("kTarget");
1692
+ var kType = Symbol("kType");
1693
+ var kWasClean = Symbol("kWasClean");
1694
+ /**
1695
+ * Class representing an event.
1696
+ */
1697
+ var Event = class {
1698
+ /**
1699
+ * Create a new `Event`.
1700
+ *
1701
+ * @param {String} type The name of the event
1702
+ * @throws {TypeError} If the `type` argument is not specified
1703
+ */
1704
+ constructor(type) {
1705
+ this[kTarget] = null;
1706
+ this[kType] = type;
1707
+ }
1708
+ /**
1709
+ * @type {*}
1710
+ */
1711
+ get target() {
1712
+ return this[kTarget];
1713
+ }
1714
+ /**
1715
+ * @type {String}
1716
+ */
1717
+ get type() {
1718
+ return this[kType];
1719
+ }
1720
+ };
1721
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1722
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1723
+ /**
1724
+ * Class representing a close event.
1725
+ *
1726
+ * @extends Event
1727
+ */
1728
+ var CloseEvent = class extends Event {
1729
+ /**
1730
+ * Create a new `CloseEvent`.
1731
+ *
1732
+ * @param {String} type The name of the event
1733
+ * @param {Object} [options] A dictionary object that allows for setting
1734
+ * attributes via object members of the same name
1735
+ * @param {Number} [options.code=0] The status code explaining why the
1736
+ * connection was closed
1737
+ * @param {String} [options.reason=''] A human-readable string explaining why
1738
+ * the connection was closed
1739
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1740
+ * connection was cleanly closed
1741
+ */
1742
+ constructor(type, options = {}) {
1743
+ super(type);
1744
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1745
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1746
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1747
+ }
1748
+ /**
1749
+ * @type {Number}
1750
+ */
1751
+ get code() {
1752
+ return this[kCode];
1753
+ }
1754
+ /**
1755
+ * @type {String}
1756
+ */
1757
+ get reason() {
1758
+ return this[kReason];
1759
+ }
1760
+ /**
1761
+ * @type {Boolean}
1762
+ */
1763
+ get wasClean() {
1764
+ return this[kWasClean];
1765
+ }
1766
+ };
1767
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1768
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1769
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1770
+ /**
1771
+ * Class representing an error event.
1772
+ *
1773
+ * @extends Event
1774
+ */
1775
+ var ErrorEvent = class extends Event {
1776
+ /**
1777
+ * Create a new `ErrorEvent`.
1778
+ *
1779
+ * @param {String} type The name of the event
1780
+ * @param {Object} [options] A dictionary object that allows for setting
1781
+ * attributes via object members of the same name
1782
+ * @param {*} [options.error=null] The error that generated this event
1783
+ * @param {String} [options.message=''] The error message
1784
+ */
1785
+ constructor(type, options = {}) {
1786
+ super(type);
1787
+ this[kError] = options.error === void 0 ? null : options.error;
1788
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1789
+ }
1790
+ /**
1791
+ * @type {*}
1792
+ */
1793
+ get error() {
1794
+ return this[kError];
1795
+ }
1796
+ /**
1797
+ * @type {String}
1798
+ */
1799
+ get message() {
1800
+ return this[kMessage];
1801
+ }
1802
+ };
1803
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1804
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1805
+ /**
1806
+ * Class representing a message event.
1807
+ *
1808
+ * @extends Event
1809
+ */
1810
+ var MessageEvent = class extends Event {
1811
+ /**
1812
+ * Create a new `MessageEvent`.
1813
+ *
1814
+ * @param {String} type The name of the event
1815
+ * @param {Object} [options] A dictionary object that allows for setting
1816
+ * attributes via object members of the same name
1817
+ * @param {*} [options.data=null] The message content
1818
+ */
1819
+ constructor(type, options = {}) {
1820
+ super(type);
1821
+ this[kData] = options.data === void 0 ? null : options.data;
1822
+ }
1823
+ /**
1824
+ * @type {*}
1825
+ */
1826
+ get data() {
1827
+ return this[kData];
1828
+ }
1829
+ };
1830
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1831
+ module.exports = {
1832
+ CloseEvent,
1833
+ ErrorEvent,
1834
+ Event,
1835
+ EventTarget: {
1836
+ /**
1837
+ * Register an event listener.
1838
+ *
1839
+ * @param {String} type A string representing the event type to listen for
1840
+ * @param {(Function|Object)} handler The listener to add
1841
+ * @param {Object} [options] An options object specifies characteristics about
1842
+ * the event listener
1843
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1844
+ * listener should be invoked at most once after being added. If `true`,
1845
+ * the listener would be automatically removed when invoked.
1846
+ * @public
1847
+ */
1848
+ addEventListener(type, handler, options = {}) {
1849
+ for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
1850
+ let wrapper;
1851
+ if (type === "message") wrapper = function onMessage(data, isBinary) {
1852
+ const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
1853
+ event[kTarget] = this;
1854
+ callListener(handler, this, event);
1855
+ };
1856
+ else if (type === "close") wrapper = function onClose(code, message) {
1857
+ const event = new CloseEvent("close", {
1858
+ code,
1859
+ reason: message.toString(),
1860
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1861
+ });
1862
+ event[kTarget] = this;
1863
+ callListener(handler, this, event);
1864
+ };
1865
+ else if (type === "error") wrapper = function onError(error) {
1866
+ const event = new ErrorEvent("error", {
1867
+ error,
1868
+ message: error.message
1869
+ });
1870
+ event[kTarget] = this;
1871
+ callListener(handler, this, event);
1872
+ };
1873
+ else if (type === "open") wrapper = function onOpen() {
1874
+ const event = new Event("open");
1875
+ event[kTarget] = this;
1876
+ callListener(handler, this, event);
1877
+ };
1878
+ else return;
1879
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1880
+ wrapper[kListener] = handler;
1881
+ if (options.once) this.once(type, wrapper);
1882
+ else this.on(type, wrapper);
1883
+ },
1884
+ /**
1885
+ * Remove an event listener.
1886
+ *
1887
+ * @param {String} type A string representing the event type to remove
1888
+ * @param {(Function|Object)} handler The listener to remove
1889
+ * @public
1890
+ */
1891
+ removeEventListener(type, handler) {
1892
+ for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1893
+ this.removeListener(type, listener);
1894
+ break;
1895
+ }
1896
+ }
1897
+ },
1898
+ MessageEvent
1899
+ };
1900
+ /**
1901
+ * Call an event listener
1902
+ *
1903
+ * @param {(Function|Object)} listener The listener to call
1904
+ * @param {*} thisArg The value to use as `this`` when calling the listener
1905
+ * @param {Event} event The event to pass to the listener
1906
+ * @private
1907
+ */
1908
+ function callListener(listener, thisArg, event) {
1909
+ if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
1910
+ else listener.call(thisArg, event);
1911
+ }
1912
+ }));
1913
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/extension.js
1914
+ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1915
+ var { tokenChars } = require_validation();
1916
+ /**
1917
+ * Adds an offer to the map of extension offers or a parameter to the map of
1918
+ * parameters.
1919
+ *
1920
+ * @param {Object} dest The map of extension offers or parameters
1921
+ * @param {String} name The extension or parameter name
1922
+ * @param {(Object|Boolean|String)} elem The extension parameters or the
1923
+ * parameter value
1924
+ * @private
1925
+ */
1926
+ function push(dest, name, elem) {
1927
+ if (dest[name] === void 0) dest[name] = [elem];
1928
+ else dest[name].push(elem);
1929
+ }
1930
+ /**
1931
+ * Parses the `Sec-WebSocket-Extensions` header into an object.
1932
+ *
1933
+ * @param {String} header The field value of the header
1934
+ * @return {Object} The parsed object
1935
+ * @public
1936
+ */
1937
+ function parse(header) {
1938
+ const offers = Object.create(null);
1939
+ let params = Object.create(null);
1940
+ let mustUnescape = false;
1941
+ let isEscaping = false;
1942
+ let inQuotes = false;
1943
+ let extensionName;
1944
+ let paramName;
1945
+ let start = -1;
1946
+ let code = -1;
1947
+ let end = -1;
1948
+ let i = 0;
1949
+ for (; i < header.length; i++) {
1950
+ code = header.charCodeAt(i);
1951
+ if (extensionName === void 0) {
1952
+ if (end === -1 && tokenChars[code] === 1) {
1953
+ if (start === -1) start = i;
1954
+ } else if (i !== 0 && (code === 32 || code === 9)) {
1955
+ if (end === -1 && start !== -1) end = i;
1956
+ } else if (code === 59 || code === 44) {
1957
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1958
+ if (end === -1) end = i;
1959
+ const name = header.slice(start, end);
1960
+ if (code === 44) {
1961
+ push(offers, name, params);
1962
+ params = Object.create(null);
1963
+ } else extensionName = name;
1964
+ start = end = -1;
1965
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
1966
+ } else if (paramName === void 0) {
1967
+ if (end === -1 && tokenChars[code] === 1) {
1968
+ if (start === -1) start = i;
1969
+ } else if (code === 32 || code === 9) {
1970
+ if (end === -1 && start !== -1) end = i;
1971
+ } else if (code === 59 || code === 44) {
1972
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1973
+ if (end === -1) end = i;
1974
+ push(params, header.slice(start, end), true);
1975
+ if (code === 44) {
1976
+ push(offers, extensionName, params);
1977
+ params = Object.create(null);
1978
+ extensionName = void 0;
1979
+ }
1980
+ start = end = -1;
1981
+ } else if (code === 61 && start !== -1 && end === -1) {
1982
+ paramName = header.slice(start, i);
1983
+ start = end = -1;
1984
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
1985
+ } else if (isEscaping) {
1986
+ if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
1987
+ if (start === -1) start = i;
1988
+ else if (!mustUnescape) mustUnescape = true;
1989
+ isEscaping = false;
1990
+ } else if (inQuotes) {
1991
+ if (tokenChars[code] === 1) {
1992
+ if (start === -1) start = i;
1993
+ } else if (code === 34 && start !== -1) {
1994
+ inQuotes = false;
1995
+ end = i;
1996
+ } else if (code === 92) isEscaping = true;
1997
+ else throw new SyntaxError(`Unexpected character at index ${i}`);
1998
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
1999
+ else if (end === -1 && tokenChars[code] === 1) {
2000
+ if (start === -1) start = i;
2001
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2002
+ if (end === -1) end = i;
2003
+ } else if (code === 59 || code === 44) {
2004
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
2005
+ if (end === -1) end = i;
2006
+ let value = header.slice(start, end);
2007
+ if (mustUnescape) {
2008
+ value = value.replace(/\\/g, "");
2009
+ mustUnescape = false;
2010
+ }
2011
+ push(params, paramName, value);
2012
+ if (code === 44) {
2013
+ push(offers, extensionName, params);
2014
+ params = Object.create(null);
2015
+ extensionName = void 0;
2016
+ }
2017
+ paramName = void 0;
2018
+ start = end = -1;
2019
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
2020
+ }
2021
+ if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
2022
+ if (end === -1) end = i;
2023
+ const token = header.slice(start, end);
2024
+ if (extensionName === void 0) push(offers, token, params);
2025
+ else {
2026
+ if (paramName === void 0) push(params, token, true);
2027
+ else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
2028
+ else push(params, paramName, token);
2029
+ push(offers, extensionName, params);
2030
+ }
2031
+ return offers;
2032
+ }
2033
+ /**
2034
+ * Builds the `Sec-WebSocket-Extensions` header field value.
2035
+ *
2036
+ * @param {Object} extensions The map of extensions and parameters to format
2037
+ * @return {String} A string representing the given object
2038
+ * @public
2039
+ */
2040
+ function format(extensions) {
2041
+ return Object.keys(extensions).map((extension) => {
2042
+ let configurations = extensions[extension];
2043
+ if (!Array.isArray(configurations)) configurations = [configurations];
2044
+ return configurations.map((params) => {
2045
+ return [extension].concat(Object.keys(params).map((k) => {
2046
+ let values = params[k];
2047
+ if (!Array.isArray(values)) values = [values];
2048
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2049
+ })).join("; ");
2050
+ }).join(", ");
2051
+ }).join(", ");
2052
+ }
2053
+ module.exports = {
2054
+ format,
2055
+ parse
2056
+ };
2057
+ }));
2058
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/websocket.js
2059
+ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2060
+ var EventEmitter = __require("events");
2061
+ var https = __require("https");
2062
+ var http = __require("http");
2063
+ var net = __require("net");
2064
+ var tls = __require("tls");
2065
+ var { randomBytes, createHash } = __require("crypto");
2066
+ var { Duplex, Readable } = __require("stream");
2067
+ var { URL } = __require("url");
2068
+ var PerMessageDeflate = require_permessage_deflate();
2069
+ var Receiver = require_receiver();
2070
+ var Sender = require_sender();
2071
+ var { isBlob } = require_validation();
2072
+ var { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
2073
+ var { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
2074
+ var { format, parse } = require_extension();
2075
+ var { toBuffer } = require_buffer_util();
2076
+ var kAborted = Symbol("kAborted");
2077
+ var protocolVersions = [8, 13];
2078
+ var readyStates = [
2079
+ "CONNECTING",
2080
+ "OPEN",
2081
+ "CLOSING",
2082
+ "CLOSED"
2083
+ ];
2084
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2085
+ /**
2086
+ * Class representing a WebSocket.
2087
+ *
2088
+ * @extends EventEmitter
2089
+ */
2090
+ var WebSocket = class WebSocket extends EventEmitter {
2091
+ /**
2092
+ * Create a new `WebSocket`.
2093
+ *
2094
+ * @param {(String|URL)} address The URL to which to connect
2095
+ * @param {(String|String[])} [protocols] The subprotocols
2096
+ * @param {Object} [options] Connection options
2097
+ */
2098
+ constructor(address, protocols, options) {
2099
+ super();
2100
+ this._binaryType = BINARY_TYPES[0];
2101
+ this._closeCode = 1006;
2102
+ this._closeFrameReceived = false;
2103
+ this._closeFrameSent = false;
2104
+ this._closeMessage = EMPTY_BUFFER;
2105
+ this._closeTimer = null;
2106
+ this._errorEmitted = false;
2107
+ this._extensions = {};
2108
+ this._paused = false;
2109
+ this._protocol = "";
2110
+ this._readyState = WebSocket.CONNECTING;
2111
+ this._receiver = null;
2112
+ this._sender = null;
2113
+ this._socket = null;
2114
+ if (address !== null) {
2115
+ this._bufferedAmount = 0;
2116
+ this._isServer = false;
2117
+ this._redirects = 0;
2118
+ if (protocols === void 0) {
2119
+ if (!options || options.protocols === void 0) protocols = [];
2120
+ else if (Array.isArray(options.protocols)) protocols = options.protocols;
2121
+ else protocols = [options.protocols];
2122
+ } else if (!Array.isArray(protocols)) {
2123
+ if (typeof protocols === "object" && protocols !== null) {
2124
+ options = protocols;
2125
+ if (options.protocols === void 0) protocols = [];
2126
+ else if (Array.isArray(options.protocols)) protocols = options.protocols;
2127
+ else protocols = [options.protocols];
2128
+ } else protocols = [protocols];
2129
+ }
2130
+ initAsClient(this, address, protocols, options);
2131
+ } else {
2132
+ this._autoPong = options.autoPong;
2133
+ this._closeTimeout = options.closeTimeout;
2134
+ this._isServer = true;
2135
+ }
2136
+ }
2137
+ /**
2138
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2139
+ * instead of "blob".
2140
+ *
2141
+ * @type {String}
2142
+ */
2143
+ get binaryType() {
2144
+ return this._binaryType;
2145
+ }
2146
+ set binaryType(type) {
2147
+ if (!BINARY_TYPES.includes(type)) return;
2148
+ this._binaryType = type;
2149
+ if (this._receiver) this._receiver._binaryType = type;
2150
+ }
2151
+ /**
2152
+ * @type {Number}
2153
+ */
2154
+ get bufferedAmount() {
2155
+ if (!this._socket) return this._bufferedAmount;
2156
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2157
+ }
2158
+ /**
2159
+ * @type {String}
2160
+ */
2161
+ get extensions() {
2162
+ return Object.keys(this._extensions).join();
2163
+ }
2164
+ /**
2165
+ * @type {Boolean}
2166
+ */
2167
+ get isPaused() {
2168
+ return this._paused;
2169
+ }
2170
+ /**
2171
+ * @type {Function}
2172
+ */
2173
+ /* istanbul ignore next */
2174
+ get onclose() {
2175
+ return null;
2176
+ }
2177
+ /**
2178
+ * @type {Function}
2179
+ */
2180
+ /* istanbul ignore next */
2181
+ get onerror() {
2182
+ return null;
2183
+ }
2184
+ /**
2185
+ * @type {Function}
2186
+ */
2187
+ /* istanbul ignore next */
2188
+ get onopen() {
2189
+ return null;
2190
+ }
2191
+ /**
2192
+ * @type {Function}
2193
+ */
2194
+ /* istanbul ignore next */
2195
+ get onmessage() {
2196
+ return null;
2197
+ }
2198
+ /**
2199
+ * @type {String}
2200
+ */
2201
+ get protocol() {
2202
+ return this._protocol;
2203
+ }
2204
+ /**
2205
+ * @type {Number}
2206
+ */
2207
+ get readyState() {
2208
+ return this._readyState;
2209
+ }
2210
+ /**
2211
+ * @type {String}
2212
+ */
2213
+ get url() {
2214
+ return this._url;
2215
+ }
2216
+ /**
2217
+ * Set up the socket and the internal resources.
2218
+ *
2219
+ * @param {Duplex} socket The network socket between the server and client
2220
+ * @param {Buffer} head The first packet of the upgraded stream
2221
+ * @param {Object} options Options object
2222
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2223
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2224
+ * multiple times in the same tick
2225
+ * @param {Function} [options.generateMask] The function used to generate the
2226
+ * masking key
2227
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2228
+ * buffered data chunks
2229
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2230
+ * fragments
2231
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2232
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2233
+ * not to skip UTF-8 validation for text and close messages
2234
+ * @private
2235
+ */
2236
+ setSocket(socket, head, options) {
2237
+ const receiver = new Receiver({
2238
+ allowSynchronousEvents: options.allowSynchronousEvents,
2239
+ binaryType: this.binaryType,
2240
+ extensions: this._extensions,
2241
+ isServer: this._isServer,
2242
+ maxBufferedChunks: options.maxBufferedChunks,
2243
+ maxFragments: options.maxFragments,
2244
+ maxPayload: options.maxPayload,
2245
+ skipUTF8Validation: options.skipUTF8Validation
2246
+ });
2247
+ const sender = new Sender(socket, this._extensions, options.generateMask);
2248
+ this._receiver = receiver;
2249
+ this._sender = sender;
2250
+ this._socket = socket;
2251
+ receiver[kWebSocket] = this;
2252
+ sender[kWebSocket] = this;
2253
+ socket[kWebSocket] = this;
2254
+ receiver.on("conclude", receiverOnConclude);
2255
+ receiver.on("drain", receiverOnDrain);
2256
+ receiver.on("error", receiverOnError);
2257
+ receiver.on("message", receiverOnMessage);
2258
+ receiver.on("ping", receiverOnPing);
2259
+ receiver.on("pong", receiverOnPong);
2260
+ sender.onerror = senderOnError;
2261
+ if (socket.setTimeout) socket.setTimeout(0);
2262
+ if (socket.setNoDelay) socket.setNoDelay();
2263
+ if (head.length > 0) socket.unshift(head);
2264
+ socket.on("close", socketOnClose);
2265
+ socket.on("data", socketOnData);
2266
+ socket.on("end", socketOnEnd);
2267
+ socket.on("error", socketOnError);
2268
+ this._readyState = WebSocket.OPEN;
2269
+ this.emit("open");
2270
+ }
2271
+ /**
2272
+ * Emit the `'close'` event.
2273
+ *
2274
+ * @private
2275
+ */
2276
+ emitClose() {
2277
+ if (!this._socket) {
2278
+ this._readyState = WebSocket.CLOSED;
2279
+ this.emit("close", this._closeCode, this._closeMessage);
2280
+ return;
2281
+ }
2282
+ if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
2283
+ this._receiver.removeAllListeners();
2284
+ this._readyState = WebSocket.CLOSED;
2285
+ this.emit("close", this._closeCode, this._closeMessage);
2286
+ }
2287
+ /**
2288
+ * Start a closing handshake.
2289
+ *
2290
+ * +----------+ +-----------+ +----------+
2291
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2292
+ * | +----------+ +-----------+ +----------+ |
2293
+ * +----------+ +-----------+ |
2294
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2295
+ * +----------+ +-----------+ |
2296
+ * | | | +---+ |
2297
+ * +------------------------+-->|fin| - - - -
2298
+ * | +---+ | +---+
2299
+ * - - - - -|fin|<---------------------+
2300
+ * +---+
2301
+ *
2302
+ * @param {Number} [code] Status code explaining why the connection is closing
2303
+ * @param {(String|Buffer)} [data] The reason why the connection is
2304
+ * closing
2305
+ * @public
2306
+ */
2307
+ close(code, data) {
2308
+ if (this.readyState === WebSocket.CLOSED) return;
2309
+ if (this.readyState === WebSocket.CONNECTING) {
2310
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2311
+ return;
2312
+ }
2313
+ if (this.readyState === WebSocket.CLOSING) {
2314
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
2315
+ return;
2316
+ }
2317
+ this._sender.close(code, data, !this._isServer, (err) => {
2318
+ if (err) return;
2319
+ this._closeFrameSent = true;
2320
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
2321
+ });
2322
+ this._readyState = WebSocket.CLOSING;
2323
+ setCloseTimer(this);
2324
+ }
2325
+ /**
2326
+ * Pause the socket.
2327
+ *
2328
+ * @public
2329
+ */
2330
+ pause() {
2331
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2332
+ this._paused = true;
2333
+ this._socket.pause();
2334
+ }
2335
+ /**
2336
+ * Send a ping.
2337
+ *
2338
+ * @param {*} [data] The data to send
2339
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2340
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2341
+ * @public
2342
+ */
2343
+ ping(data, mask, cb) {
2344
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2345
+ if (typeof data === "function") {
2346
+ cb = data;
2347
+ data = mask = void 0;
2348
+ } else if (typeof mask === "function") {
2349
+ cb = mask;
2350
+ mask = void 0;
2351
+ }
2352
+ if (typeof data === "number") data = data.toString();
2353
+ if (this.readyState !== WebSocket.OPEN) {
2354
+ sendAfterClose(this, data, cb);
2355
+ return;
2356
+ }
2357
+ if (mask === void 0) mask = !this._isServer;
2358
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2359
+ }
2360
+ /**
2361
+ * Send a pong.
2362
+ *
2363
+ * @param {*} [data] The data to send
2364
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2365
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2366
+ * @public
2367
+ */
2368
+ pong(data, mask, cb) {
2369
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2370
+ if (typeof data === "function") {
2371
+ cb = data;
2372
+ data = mask = void 0;
2373
+ } else if (typeof mask === "function") {
2374
+ cb = mask;
2375
+ mask = void 0;
2376
+ }
2377
+ if (typeof data === "number") data = data.toString();
2378
+ if (this.readyState !== WebSocket.OPEN) {
2379
+ sendAfterClose(this, data, cb);
2380
+ return;
2381
+ }
2382
+ if (mask === void 0) mask = !this._isServer;
2383
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2384
+ }
2385
+ /**
2386
+ * Resume the socket.
2387
+ *
2388
+ * @public
2389
+ */
2390
+ resume() {
2391
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2392
+ this._paused = false;
2393
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2394
+ }
2395
+ /**
2396
+ * Send a data message.
2397
+ *
2398
+ * @param {*} data The message to send
2399
+ * @param {Object} [options] Options object
2400
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2401
+ * text
2402
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2403
+ * `data`
2404
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2405
+ * last one
2406
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2407
+ * @param {Function} [cb] Callback which is executed when data is written out
2408
+ * @public
2409
+ */
2410
+ send(data, options, cb) {
2411
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2412
+ if (typeof options === "function") {
2413
+ cb = options;
2414
+ options = {};
2415
+ }
2416
+ if (typeof data === "number") data = data.toString();
2417
+ if (this.readyState !== WebSocket.OPEN) {
2418
+ sendAfterClose(this, data, cb);
2419
+ return;
2420
+ }
2421
+ const opts = {
2422
+ binary: typeof data !== "string",
2423
+ mask: !this._isServer,
2424
+ compress: true,
2425
+ fin: true,
2426
+ ...options
2427
+ };
2428
+ if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
2429
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2430
+ }
2431
+ /**
2432
+ * Forcibly close the connection.
2433
+ *
2434
+ * @public
2435
+ */
2436
+ terminate() {
2437
+ if (this.readyState === WebSocket.CLOSED) return;
2438
+ if (this.readyState === WebSocket.CONNECTING) {
2439
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2440
+ return;
2441
+ }
2442
+ if (this._socket) {
2443
+ this._readyState = WebSocket.CLOSING;
2444
+ this._socket.destroy();
2445
+ }
2446
+ }
2447
+ };
2448
+ /**
2449
+ * @constant {Number} CONNECTING
2450
+ * @memberof WebSocket
2451
+ */
2452
+ Object.defineProperty(WebSocket, "CONNECTING", {
2453
+ enumerable: true,
2454
+ value: readyStates.indexOf("CONNECTING")
2455
+ });
2456
+ /**
2457
+ * @constant {Number} CONNECTING
2458
+ * @memberof WebSocket.prototype
2459
+ */
2460
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
2461
+ enumerable: true,
2462
+ value: readyStates.indexOf("CONNECTING")
2463
+ });
2464
+ /**
2465
+ * @constant {Number} OPEN
2466
+ * @memberof WebSocket
2467
+ */
2468
+ Object.defineProperty(WebSocket, "OPEN", {
2469
+ enumerable: true,
2470
+ value: readyStates.indexOf("OPEN")
2471
+ });
2472
+ /**
2473
+ * @constant {Number} OPEN
2474
+ * @memberof WebSocket.prototype
2475
+ */
2476
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
2477
+ enumerable: true,
2478
+ value: readyStates.indexOf("OPEN")
2479
+ });
2480
+ /**
2481
+ * @constant {Number} CLOSING
2482
+ * @memberof WebSocket
2483
+ */
2484
+ Object.defineProperty(WebSocket, "CLOSING", {
2485
+ enumerable: true,
2486
+ value: readyStates.indexOf("CLOSING")
2487
+ });
2488
+ /**
2489
+ * @constant {Number} CLOSING
2490
+ * @memberof WebSocket.prototype
2491
+ */
2492
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
2493
+ enumerable: true,
2494
+ value: readyStates.indexOf("CLOSING")
2495
+ });
2496
+ /**
2497
+ * @constant {Number} CLOSED
2498
+ * @memberof WebSocket
2499
+ */
2500
+ Object.defineProperty(WebSocket, "CLOSED", {
2501
+ enumerable: true,
2502
+ value: readyStates.indexOf("CLOSED")
2503
+ });
2504
+ /**
2505
+ * @constant {Number} CLOSED
2506
+ * @memberof WebSocket.prototype
2507
+ */
2508
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
2509
+ enumerable: true,
2510
+ value: readyStates.indexOf("CLOSED")
2511
+ });
2512
+ [
2513
+ "binaryType",
2514
+ "bufferedAmount",
2515
+ "extensions",
2516
+ "isPaused",
2517
+ "protocol",
2518
+ "readyState",
2519
+ "url"
2520
+ ].forEach((property) => {
2521
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
2522
+ });
2523
+ [
2524
+ "open",
2525
+ "error",
2526
+ "close",
2527
+ "message"
2528
+ ].forEach((method) => {
2529
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
2530
+ enumerable: true,
2531
+ get() {
2532
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
2533
+ return null;
2534
+ },
2535
+ set(handler) {
2536
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
2537
+ this.removeListener(method, listener);
2538
+ break;
2539
+ }
2540
+ if (typeof handler !== "function") return;
2541
+ this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
2542
+ }
2543
+ });
2544
+ });
2545
+ WebSocket.prototype.addEventListener = addEventListener;
2546
+ WebSocket.prototype.removeEventListener = removeEventListener;
2547
+ module.exports = WebSocket;
2548
+ /**
2549
+ * Initialize a WebSocket client.
2550
+ *
2551
+ * @param {WebSocket} websocket The client to initialize
2552
+ * @param {(String|URL)} address The URL to which to connect
2553
+ * @param {Array} protocols The subprotocols
2554
+ * @param {Object} [options] Connection options
2555
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
2556
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
2557
+ * times in the same tick
2558
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
2559
+ * automatically send a pong in response to a ping
2560
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
2561
+ * for the closing handshake to finish after `websocket.close()` is called
2562
+ * @param {Function} [options.finishRequest] A function which can be used to
2563
+ * customize the headers of each http request before it is sent
2564
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
2565
+ * redirects
2566
+ * @param {Function} [options.generateMask] The function used to generate the
2567
+ * masking key
2568
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
2569
+ * handshake request
2570
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
2571
+ * buffered data chunks
2572
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
2573
+ * fragments
2574
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2575
+ * size
2576
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
2577
+ * allowed
2578
+ * @param {String} [options.origin] Value of the `Origin` or
2579
+ * `Sec-WebSocket-Origin` header
2580
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
2581
+ * permessage-deflate
2582
+ * @param {Number} [options.protocolVersion=13] Value of the
2583
+ * `Sec-WebSocket-Version` header
2584
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2585
+ * not to skip UTF-8 validation for text and close messages
2586
+ * @private
2587
+ */
2588
+ function initAsClient(websocket, address, protocols, options) {
2589
+ const opts = {
2590
+ allowSynchronousEvents: true,
2591
+ autoPong: true,
2592
+ closeTimeout: CLOSE_TIMEOUT,
2593
+ protocolVersion: protocolVersions[1],
2594
+ maxBufferedChunks: 262144,
2595
+ maxFragments: 16384,
2596
+ maxPayload: 104857600,
2597
+ skipUTF8Validation: false,
2598
+ perMessageDeflate: true,
2599
+ followRedirects: false,
2600
+ maxRedirects: 10,
2601
+ ...options,
2602
+ socketPath: void 0,
2603
+ hostname: void 0,
2604
+ protocol: void 0,
2605
+ protocols: void 0,
2606
+ timeout: void 0,
2607
+ method: "GET",
2608
+ host: void 0,
2609
+ path: void 0,
2610
+ port: void 0
2611
+ };
2612
+ websocket._autoPong = opts.autoPong;
2613
+ websocket._closeTimeout = opts.closeTimeout;
2614
+ if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
2615
+ let parsedUrl;
2616
+ if (address instanceof URL) parsedUrl = address;
2617
+ else try {
2618
+ parsedUrl = new URL(address);
2619
+ } catch {
2620
+ throw new SyntaxError(`Invalid URL: ${address}`);
2621
+ }
2622
+ if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
2623
+ else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
2624
+ websocket._url = parsedUrl.href;
2625
+ const isSecure = parsedUrl.protocol === "wss:";
2626
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2627
+ let invalidUrlMessage;
2628
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
2629
+ else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
2630
+ else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
2631
+ if (invalidUrlMessage) {
2632
+ const err = new SyntaxError(invalidUrlMessage);
2633
+ if (websocket._redirects === 0) throw err;
2634
+ else {
2635
+ emitErrorAndClose(websocket, err);
2636
+ return;
2637
+ }
2638
+ }
2639
+ const defaultPort = isSecure ? 443 : 80;
2640
+ const key = randomBytes(16).toString("base64");
2641
+ const request = isSecure ? https.request : http.request;
2642
+ const protocolSet = /* @__PURE__ */ new Set();
2643
+ let perMessageDeflate;
2644
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2645
+ opts.defaultPort = opts.defaultPort || defaultPort;
2646
+ opts.port = parsedUrl.port || defaultPort;
2647
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2648
+ opts.headers = {
2649
+ ...opts.headers,
2650
+ "Sec-WebSocket-Version": opts.protocolVersion,
2651
+ "Sec-WebSocket-Key": key,
2652
+ Connection: "Upgrade",
2653
+ Upgrade: "websocket"
2654
+ };
2655
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2656
+ opts.timeout = opts.handshakeTimeout;
2657
+ if (opts.perMessageDeflate) {
2658
+ perMessageDeflate = new PerMessageDeflate({
2659
+ ...opts.perMessageDeflate,
2660
+ isServer: false,
2661
+ maxPayload: opts.maxPayload
2662
+ });
2663
+ opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
2664
+ }
2665
+ if (protocols.length) {
2666
+ for (const protocol of protocols) {
2667
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2668
+ protocolSet.add(protocol);
2669
+ }
2670
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2671
+ }
2672
+ if (opts.origin) {
2673
+ if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2674
+ else opts.headers.Origin = opts.origin;
2675
+ }
2676
+ if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2677
+ if (isIpcUrl) {
2678
+ const i = opts.path.indexOf(":");
2679
+ if (i === -1) {
2680
+ opts.socketPath = opts.path;
2681
+ opts.path = "";
2682
+ } else {
2683
+ opts.socketPath = opts.path.slice(0, i);
2684
+ opts.path = opts.path.slice(i + 1);
2685
+ }
2686
+ }
2687
+ let req;
2688
+ if (opts.followRedirects) {
2689
+ if (websocket._redirects === 0) {
2690
+ websocket._originalIpc = isIpcUrl;
2691
+ websocket._originalSecure = isSecure;
2692
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2693
+ const headers = options && options.headers;
2694
+ options = {
2695
+ ...options,
2696
+ headers: {}
2697
+ };
2698
+ if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
2699
+ } else if (websocket.listenerCount("redirect") === 0) {
2700
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2701
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2702
+ delete opts.headers.authorization;
2703
+ delete opts.headers.cookie;
2704
+ if (!isSameHost) delete opts.headers.host;
2705
+ opts.auth = void 0;
2706
+ }
2707
+ }
2708
+ if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2709
+ req = websocket._req = request(opts);
2710
+ if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
2711
+ } else req = websocket._req = request(opts);
2712
+ if (opts.timeout) req.on("timeout", () => {
2713
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2714
+ });
2715
+ req.on("error", (err) => {
2716
+ if (req === null || req[kAborted]) return;
2717
+ req = websocket._req = null;
2718
+ emitErrorAndClose(websocket, err);
2719
+ });
2720
+ req.on("response", (res) => {
2721
+ const location = res.headers.location;
2722
+ const statusCode = res.statusCode;
2723
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2724
+ if (++websocket._redirects > opts.maxRedirects) {
2725
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2726
+ return;
2727
+ }
2728
+ req.abort();
2729
+ let addr;
2730
+ try {
2731
+ addr = new URL(location, address);
2732
+ } catch (e) {
2733
+ emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
2734
+ return;
2735
+ }
2736
+ initAsClient(websocket, addr, protocols, options);
2737
+ } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2738
+ });
2739
+ req.on("upgrade", (res, socket, head) => {
2740
+ websocket.emit("upgrade", res);
2741
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
2742
+ req = websocket._req = null;
2743
+ const upgrade = res.headers.upgrade;
2744
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2745
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2746
+ return;
2747
+ }
2748
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2749
+ if (res.headers["sec-websocket-accept"] !== digest) {
2750
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2751
+ return;
2752
+ }
2753
+ const serverProt = res.headers["sec-websocket-protocol"];
2754
+ let protError;
2755
+ if (serverProt !== void 0) {
2756
+ if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
2757
+ else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
2758
+ } else if (protocolSet.size) protError = "Server sent no subprotocol";
2759
+ if (protError) {
2760
+ abortHandshake(websocket, socket, protError);
2761
+ return;
2762
+ }
2763
+ if (serverProt) websocket._protocol = serverProt;
2764
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2765
+ if (secWebSocketExtensions !== void 0) {
2766
+ if (!perMessageDeflate) {
2767
+ abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2768
+ return;
2769
+ }
2770
+ let extensions;
2771
+ try {
2772
+ extensions = parse(secWebSocketExtensions);
2773
+ } catch (err) {
2774
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2775
+ return;
2776
+ }
2777
+ const extensionNames = Object.keys(extensions);
2778
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2779
+ abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
2780
+ return;
2781
+ }
2782
+ try {
2783
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2784
+ } catch (err) {
2785
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2786
+ return;
2787
+ }
2788
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2789
+ }
2790
+ websocket.setSocket(socket, head, {
2791
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2792
+ generateMask: opts.generateMask,
2793
+ maxBufferedChunks: opts.maxBufferedChunks,
2794
+ maxFragments: opts.maxFragments,
2795
+ maxPayload: opts.maxPayload,
2796
+ skipUTF8Validation: opts.skipUTF8Validation
2797
+ });
2798
+ });
2799
+ if (opts.finishRequest) opts.finishRequest(req, websocket);
2800
+ else req.end();
2801
+ }
2802
+ /**
2803
+ * Emit the `'error'` and `'close'` events.
2804
+ *
2805
+ * @param {WebSocket} websocket The WebSocket instance
2806
+ * @param {Error} The error to emit
2807
+ * @private
2808
+ */
2809
+ function emitErrorAndClose(websocket, err) {
2810
+ websocket._readyState = WebSocket.CLOSING;
2811
+ websocket._errorEmitted = true;
2812
+ websocket.emit("error", err);
2813
+ websocket.emitClose();
2814
+ }
2815
+ /**
2816
+ * Create a `net.Socket` and initiate a connection.
2817
+ *
2818
+ * @param {Object} options Connection options
2819
+ * @return {net.Socket} The newly created socket used to start the connection
2820
+ * @private
2821
+ */
2822
+ function netConnect(options) {
2823
+ options.path = options.socketPath;
2824
+ return net.connect(options);
2825
+ }
2826
+ /**
2827
+ * Create a `tls.TLSSocket` and initiate a connection.
2828
+ *
2829
+ * @param {Object} options Connection options
2830
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
2831
+ * @private
2832
+ */
2833
+ function tlsConnect(options) {
2834
+ options.path = void 0;
2835
+ if (!options.servername && options.servername !== "") options.servername = net.isIP(options.host) ? "" : options.host;
2836
+ return tls.connect(options);
2837
+ }
2838
+ /**
2839
+ * Abort the handshake and emit an error.
2840
+ *
2841
+ * @param {WebSocket} websocket The WebSocket instance
2842
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
2843
+ * abort or the socket to destroy
2844
+ * @param {String} message The error message
2845
+ * @private
2846
+ */
2847
+ function abortHandshake(websocket, stream, message) {
2848
+ websocket._readyState = WebSocket.CLOSING;
2849
+ const err = new Error(message);
2850
+ Error.captureStackTrace(err, abortHandshake);
2851
+ if (stream.setHeader) {
2852
+ stream[kAborted] = true;
2853
+ stream.abort();
2854
+ if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
2855
+ process.nextTick(emitErrorAndClose, websocket, err);
2856
+ } else {
2857
+ stream.destroy(err);
2858
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2859
+ stream.once("close", websocket.emitClose.bind(websocket));
2860
+ }
2861
+ }
2862
+ /**
2863
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
2864
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
2865
+ *
2866
+ * @param {WebSocket} websocket The WebSocket instance
2867
+ * @param {*} [data] The data to send
2868
+ * @param {Function} [cb] Callback
2869
+ * @private
2870
+ */
2871
+ function sendAfterClose(websocket, data, cb) {
2872
+ if (data) {
2873
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2874
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
2875
+ else websocket._bufferedAmount += length;
2876
+ }
2877
+ if (cb) {
2878
+ const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
2879
+ process.nextTick(cb, err);
2880
+ }
2881
+ }
2882
+ /**
2883
+ * The listener of the `Receiver` `'conclude'` event.
2884
+ *
2885
+ * @param {Number} code The status code
2886
+ * @param {Buffer} reason The reason for closing
2887
+ * @private
2888
+ */
2889
+ function receiverOnConclude(code, reason) {
2890
+ const websocket = this[kWebSocket];
2891
+ websocket._closeFrameReceived = true;
2892
+ websocket._closeMessage = reason;
2893
+ websocket._closeCode = code;
2894
+ if (websocket._socket[kWebSocket] === void 0) return;
2895
+ websocket._socket.removeListener("data", socketOnData);
2896
+ process.nextTick(resume, websocket._socket);
2897
+ if (code === 1005) websocket.close();
2898
+ else websocket.close(code, reason);
2899
+ }
2900
+ /**
2901
+ * The listener of the `Receiver` `'drain'` event.
2902
+ *
2903
+ * @private
2904
+ */
2905
+ function receiverOnDrain() {
2906
+ const websocket = this[kWebSocket];
2907
+ if (!websocket.isPaused) websocket._socket.resume();
2908
+ }
2909
+ /**
2910
+ * The listener of the `Receiver` `'error'` event.
2911
+ *
2912
+ * @param {(RangeError|Error)} err The emitted error
2913
+ * @private
2914
+ */
2915
+ function receiverOnError(err) {
2916
+ const websocket = this[kWebSocket];
2917
+ if (websocket._socket[kWebSocket] !== void 0) {
2918
+ websocket._socket.removeListener("data", socketOnData);
2919
+ process.nextTick(resume, websocket._socket);
2920
+ websocket.close(err[kStatusCode]);
2921
+ }
2922
+ if (!websocket._errorEmitted) {
2923
+ websocket._errorEmitted = true;
2924
+ websocket.emit("error", err);
2925
+ }
2926
+ }
2927
+ /**
2928
+ * The listener of the `Receiver` `'finish'` event.
2929
+ *
2930
+ * @private
2931
+ */
2932
+ function receiverOnFinish() {
2933
+ this[kWebSocket].emitClose();
2934
+ }
2935
+ /**
2936
+ * The listener of the `Receiver` `'message'` event.
2937
+ *
2938
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
2939
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
2940
+ * @private
2941
+ */
2942
+ function receiverOnMessage(data, isBinary) {
2943
+ this[kWebSocket].emit("message", data, isBinary);
2944
+ }
2945
+ /**
2946
+ * The listener of the `Receiver` `'ping'` event.
2947
+ *
2948
+ * @param {Buffer} data The data included in the ping frame
2949
+ * @private
2950
+ */
2951
+ function receiverOnPing(data) {
2952
+ const websocket = this[kWebSocket];
2953
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
2954
+ websocket.emit("ping", data);
2955
+ }
2956
+ /**
2957
+ * The listener of the `Receiver` `'pong'` event.
2958
+ *
2959
+ * @param {Buffer} data The data included in the pong frame
2960
+ * @private
2961
+ */
2962
+ function receiverOnPong(data) {
2963
+ this[kWebSocket].emit("pong", data);
2964
+ }
2965
+ /**
2966
+ * Resume a readable stream
2967
+ *
2968
+ * @param {Readable} stream The readable stream
2969
+ * @private
2970
+ */
2971
+ function resume(stream) {
2972
+ stream.resume();
2973
+ }
2974
+ /**
2975
+ * The `Sender` error event handler.
2976
+ *
2977
+ * @param {Error} The error
2978
+ * @private
2979
+ */
2980
+ function senderOnError(err) {
2981
+ const websocket = this[kWebSocket];
2982
+ if (websocket.readyState === WebSocket.CLOSED) return;
2983
+ if (websocket.readyState === WebSocket.OPEN) {
2984
+ websocket._readyState = WebSocket.CLOSING;
2985
+ setCloseTimer(websocket);
2986
+ }
2987
+ this._socket.end();
2988
+ if (!websocket._errorEmitted) {
2989
+ websocket._errorEmitted = true;
2990
+ websocket.emit("error", err);
2991
+ }
2992
+ }
2993
+ /**
2994
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
2995
+ *
2996
+ * @param {WebSocket} websocket The WebSocket instance
2997
+ * @private
2998
+ */
2999
+ function setCloseTimer(websocket) {
3000
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
3001
+ }
3002
+ /**
3003
+ * The listener of the socket `'close'` event.
3004
+ *
3005
+ * @private
3006
+ */
3007
+ function socketOnClose() {
3008
+ const websocket = this[kWebSocket];
3009
+ this.removeListener("close", socketOnClose);
3010
+ this.removeListener("data", socketOnData);
3011
+ this.removeListener("end", socketOnEnd);
3012
+ websocket._readyState = WebSocket.CLOSING;
3013
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3014
+ const chunk = this.read(this._readableState.length);
3015
+ websocket._receiver.write(chunk);
3016
+ }
3017
+ websocket._receiver.end();
3018
+ this[kWebSocket] = void 0;
3019
+ clearTimeout(websocket._closeTimer);
3020
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
3021
+ else {
3022
+ websocket._receiver.on("error", receiverOnFinish);
3023
+ websocket._receiver.on("finish", receiverOnFinish);
3024
+ }
3025
+ }
3026
+ /**
3027
+ * The listener of the socket `'data'` event.
3028
+ *
3029
+ * @param {Buffer} chunk A chunk of data
3030
+ * @private
3031
+ */
3032
+ function socketOnData(chunk) {
3033
+ if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
3034
+ }
3035
+ /**
3036
+ * The listener of the socket `'end'` event.
3037
+ *
3038
+ * @private
3039
+ */
3040
+ function socketOnEnd() {
3041
+ const websocket = this[kWebSocket];
3042
+ websocket._readyState = WebSocket.CLOSING;
3043
+ websocket._receiver.end();
3044
+ this.end();
3045
+ }
3046
+ /**
3047
+ * The listener of the socket `'error'` event.
3048
+ *
3049
+ * @private
3050
+ */
3051
+ function socketOnError() {
3052
+ const websocket = this[kWebSocket];
3053
+ this.removeListener("error", socketOnError);
3054
+ this.on("error", NOOP);
3055
+ if (websocket) {
3056
+ websocket._readyState = WebSocket.CLOSING;
3057
+ this.destroy();
3058
+ }
3059
+ }
3060
+ }));
3061
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/stream.js
3062
+ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3063
+ require_websocket();
3064
+ var { Duplex } = __require("stream");
3065
+ /**
3066
+ * Emits the `'close'` event on a stream.
3067
+ *
3068
+ * @param {Duplex} stream The stream.
3069
+ * @private
3070
+ */
3071
+ function emitClose(stream) {
3072
+ stream.emit("close");
3073
+ }
3074
+ /**
3075
+ * The listener of the `'end'` event.
3076
+ *
3077
+ * @private
3078
+ */
3079
+ function duplexOnEnd() {
3080
+ if (!this.destroyed && this._writableState.finished) this.destroy();
3081
+ }
3082
+ /**
3083
+ * The listener of the `'error'` event.
3084
+ *
3085
+ * @param {Error} err The error
3086
+ * @private
3087
+ */
3088
+ function duplexOnError(err) {
3089
+ this.removeListener("error", duplexOnError);
3090
+ this.destroy();
3091
+ if (this.listenerCount("error") === 0) this.emit("error", err);
3092
+ }
3093
+ /**
3094
+ * Wraps a `WebSocket` in a duplex stream.
3095
+ *
3096
+ * @param {WebSocket} ws The `WebSocket` to wrap
3097
+ * @param {Object} [options] The options for the `Duplex` constructor
3098
+ * @return {Duplex} The duplex stream
3099
+ * @public
3100
+ */
3101
+ function createWebSocketStream(ws, options) {
3102
+ let terminateOnDestroy = true;
3103
+ const duplex = new Duplex({
3104
+ ...options,
3105
+ autoDestroy: false,
3106
+ emitClose: false,
3107
+ objectMode: false,
3108
+ writableObjectMode: false
3109
+ });
3110
+ ws.on("message", function message(msg, isBinary) {
3111
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3112
+ if (!duplex.push(data)) ws.pause();
3113
+ });
3114
+ ws.once("error", function error(err) {
3115
+ if (duplex.destroyed) return;
3116
+ terminateOnDestroy = false;
3117
+ duplex.destroy(err);
3118
+ });
3119
+ ws.once("close", function close() {
3120
+ if (duplex.destroyed) return;
3121
+ duplex.push(null);
3122
+ });
3123
+ duplex._destroy = function(err, callback) {
3124
+ if (ws.readyState === ws.CLOSED) {
3125
+ callback(err);
3126
+ process.nextTick(emitClose, duplex);
3127
+ return;
3128
+ }
3129
+ let called = false;
3130
+ ws.once("error", function error(err) {
3131
+ called = true;
3132
+ callback(err);
3133
+ });
3134
+ ws.once("close", function close() {
3135
+ if (!called) callback(err);
3136
+ process.nextTick(emitClose, duplex);
3137
+ });
3138
+ if (terminateOnDestroy) ws.terminate();
3139
+ };
3140
+ duplex._final = function(callback) {
3141
+ if (ws.readyState === ws.CONNECTING) {
3142
+ ws.once("open", function open() {
3143
+ duplex._final(callback);
3144
+ });
3145
+ return;
3146
+ }
3147
+ if (ws._socket === null) return;
3148
+ if (ws._socket._writableState.finished) {
3149
+ callback();
3150
+ if (duplex._readableState.endEmitted) duplex.destroy();
3151
+ } else {
3152
+ ws._socket.once("finish", function finish() {
3153
+ callback();
3154
+ });
3155
+ ws.close();
3156
+ }
3157
+ };
3158
+ duplex._read = function() {
3159
+ if (ws.isPaused) ws.resume();
3160
+ };
3161
+ duplex._write = function(chunk, encoding, callback) {
3162
+ if (ws.readyState === ws.CONNECTING) {
3163
+ ws.once("open", function open() {
3164
+ duplex._write(chunk, encoding, callback);
3165
+ });
3166
+ return;
3167
+ }
3168
+ ws.send(chunk, callback);
3169
+ };
3170
+ duplex.on("end", duplexOnEnd);
3171
+ duplex.on("error", duplexOnError);
3172
+ return duplex;
3173
+ }
3174
+ module.exports = createWebSocketStream;
3175
+ }));
3176
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/subprotocol.js
3177
+ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3178
+ var { tokenChars } = require_validation();
3179
+ /**
3180
+ * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
3181
+ *
3182
+ * @param {String} header The field value of the header
3183
+ * @return {Set} The subprotocol names
3184
+ * @public
3185
+ */
3186
+ function parse(header) {
3187
+ const protocols = /* @__PURE__ */ new Set();
3188
+ let start = -1;
3189
+ let end = -1;
3190
+ let i = 0;
3191
+ for (; i < header.length; i++) {
3192
+ const code = header.charCodeAt(i);
3193
+ if (end === -1 && tokenChars[code] === 1) {
3194
+ if (start === -1) start = i;
3195
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3196
+ if (end === -1 && start !== -1) end = i;
3197
+ } else if (code === 44) {
3198
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
3199
+ if (end === -1) end = i;
3200
+ const protocol = header.slice(start, end);
3201
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3202
+ protocols.add(protocol);
3203
+ start = end = -1;
3204
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
3205
+ }
3206
+ if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
3207
+ const protocol = header.slice(start, i);
3208
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3209
+ protocols.add(protocol);
3210
+ return protocols;
3211
+ }
3212
+ module.exports = { parse };
3213
+ }));
3214
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/lib/websocket-server.js
3215
+ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3216
+ var EventEmitter = __require("events");
3217
+ var http = __require("http");
3218
+ var { Duplex } = __require("stream");
3219
+ var { createHash } = __require("crypto");
3220
+ var extension = require_extension();
3221
+ var PerMessageDeflate = require_permessage_deflate();
3222
+ var subprotocol = require_subprotocol();
3223
+ var WebSocket = require_websocket();
3224
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3225
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3226
+ var RUNNING = 0;
3227
+ var CLOSING = 1;
3228
+ var CLOSED = 2;
3229
+ /**
3230
+ * Class representing a WebSocket server.
3231
+ *
3232
+ * @extends EventEmitter
3233
+ */
3234
+ var WebSocketServer = class extends EventEmitter {
3235
+ /**
3236
+ * Create a `WebSocketServer` instance.
3237
+ *
3238
+ * @param {Object} options Configuration options
3239
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3240
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3241
+ * multiple times in the same tick
3242
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3243
+ * automatically send a pong in response to a ping
3244
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3245
+ * pending connections
3246
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3247
+ * track clients
3248
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3249
+ * wait for the closing handshake to finish after `websocket.close()` is
3250
+ * called
3251
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3252
+ * @param {String} [options.host] The hostname where to bind the server
3253
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3254
+ * buffered data chunks
3255
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3256
+ * fragments
3257
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3258
+ * size
3259
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3260
+ * @param {String} [options.path] Accept only connections matching this path
3261
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3262
+ * permessage-deflate
3263
+ * @param {Number} [options.port] The port where to bind the server
3264
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3265
+ * server to use
3266
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3267
+ * not to skip UTF-8 validation for text and close messages
3268
+ * @param {Function} [options.verifyClient] A hook to reject connections
3269
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3270
+ * class to use. It must be the `WebSocket` class or class that extends it
3271
+ * @param {Function} [callback] A listener for the `listening` event
3272
+ */
3273
+ constructor(options, callback) {
3274
+ super();
3275
+ options = {
3276
+ allowSynchronousEvents: true,
3277
+ autoPong: true,
3278
+ maxBufferedChunks: 262144,
3279
+ maxFragments: 16384,
3280
+ maxPayload: 104857600,
3281
+ skipUTF8Validation: false,
3282
+ perMessageDeflate: false,
3283
+ handleProtocols: null,
3284
+ clientTracking: true,
3285
+ closeTimeout: CLOSE_TIMEOUT,
3286
+ verifyClient: null,
3287
+ noServer: false,
3288
+ backlog: null,
3289
+ server: null,
3290
+ host: null,
3291
+ path: null,
3292
+ port: null,
3293
+ WebSocket,
3294
+ ...options
3295
+ };
3296
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
3297
+ if (options.port != null) {
3298
+ this._server = http.createServer((req, res) => {
3299
+ const body = http.STATUS_CODES[426];
3300
+ res.writeHead(426, {
3301
+ "Content-Length": body.length,
3302
+ "Content-Type": "text/plain"
3303
+ });
3304
+ res.end(body);
3305
+ });
3306
+ this._server.listen(options.port, options.host, options.backlog, callback);
3307
+ } else if (options.server) this._server = options.server;
3308
+ if (this._server) {
3309
+ const emitConnection = this.emit.bind(this, "connection");
3310
+ this._removeListeners = addListeners(this._server, {
3311
+ listening: this.emit.bind(this, "listening"),
3312
+ error: this.emit.bind(this, "error"),
3313
+ upgrade: (req, socket, head) => {
3314
+ this.handleUpgrade(req, socket, head, emitConnection);
3315
+ }
3316
+ });
3317
+ }
3318
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3319
+ if (options.clientTracking) {
3320
+ this.clients = /* @__PURE__ */ new Set();
3321
+ this._shouldEmitClose = false;
3322
+ }
3323
+ this.options = options;
3324
+ this._state = RUNNING;
3325
+ }
3326
+ /**
3327
+ * Returns the bound address, the address family name, and port of the server
3328
+ * as reported by the operating system if listening on an IP socket.
3329
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3330
+ * returned as a string.
3331
+ *
3332
+ * @return {(Object|String|null)} The address of the server
3333
+ * @public
3334
+ */
3335
+ address() {
3336
+ if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
3337
+ if (!this._server) return null;
3338
+ return this._server.address();
3339
+ }
3340
+ /**
3341
+ * Stop the server from accepting new connections and emit the `'close'` event
3342
+ * when all existing connections are closed.
3343
+ *
3344
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3345
+ * @public
3346
+ */
3347
+ close(cb) {
3348
+ if (this._state === CLOSED) {
3349
+ if (cb) this.once("close", () => {
3350
+ cb(/* @__PURE__ */ new Error("The server is not running"));
3351
+ });
3352
+ process.nextTick(emitClose, this);
3353
+ return;
3354
+ }
3355
+ if (cb) this.once("close", cb);
3356
+ if (this._state === CLOSING) return;
3357
+ this._state = CLOSING;
3358
+ if (this.options.noServer || this.options.server) {
3359
+ if (this._server) {
3360
+ this._removeListeners();
3361
+ this._removeListeners = this._server = null;
3362
+ }
3363
+ if (this.clients) {
3364
+ if (!this.clients.size) process.nextTick(emitClose, this);
3365
+ else this._shouldEmitClose = true;
3366
+ } else process.nextTick(emitClose, this);
3367
+ } else {
3368
+ const server = this._server;
3369
+ this._removeListeners();
3370
+ this._removeListeners = this._server = null;
3371
+ server.close(() => {
3372
+ emitClose(this);
3373
+ });
3374
+ }
3375
+ }
3376
+ /**
3377
+ * See if a given request should be handled by this server instance.
3378
+ *
3379
+ * @param {http.IncomingMessage} req Request object to inspect
3380
+ * @return {Boolean} `true` if the request is valid, else `false`
3381
+ * @public
3382
+ */
3383
+ shouldHandle(req) {
3384
+ if (this.options.path) {
3385
+ const index = req.url.indexOf("?");
3386
+ if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
3387
+ }
3388
+ return true;
3389
+ }
3390
+ /**
3391
+ * Handle a HTTP Upgrade request.
3392
+ *
3393
+ * @param {http.IncomingMessage} req The request object
3394
+ * @param {Duplex} socket The network socket between the server and client
3395
+ * @param {Buffer} head The first packet of the upgraded stream
3396
+ * @param {Function} cb Callback
3397
+ * @public
3398
+ */
3399
+ handleUpgrade(req, socket, head, cb) {
3400
+ socket.on("error", socketOnError);
3401
+ const key = req.headers["sec-websocket-key"];
3402
+ const upgrade = req.headers.upgrade;
3403
+ const version = +req.headers["sec-websocket-version"];
3404
+ if (req.method !== "GET") {
3405
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
3406
+ return;
3407
+ }
3408
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3409
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
3410
+ return;
3411
+ }
3412
+ if (key === void 0 || !keyRegex.test(key)) {
3413
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
3414
+ return;
3415
+ }
3416
+ if (version !== 13 && version !== 8) {
3417
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
3418
+ return;
3419
+ }
3420
+ if (!this.shouldHandle(req)) {
3421
+ abortHandshake(socket, 400);
3422
+ return;
3423
+ }
3424
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3425
+ let protocols = /* @__PURE__ */ new Set();
3426
+ if (secWebSocketProtocol !== void 0) try {
3427
+ protocols = subprotocol.parse(secWebSocketProtocol);
3428
+ } catch (err) {
3429
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
3430
+ return;
3431
+ }
3432
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3433
+ const extensions = {};
3434
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3435
+ const perMessageDeflate = new PerMessageDeflate({
3436
+ ...this.options.perMessageDeflate,
3437
+ isServer: true,
3438
+ maxPayload: this.options.maxPayload
3439
+ });
3440
+ try {
3441
+ const offers = extension.parse(secWebSocketExtensions);
3442
+ if (offers[PerMessageDeflate.extensionName]) {
3443
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3444
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3445
+ }
3446
+ } catch (err) {
3447
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
3448
+ return;
3449
+ }
3450
+ }
3451
+ if (this.options.verifyClient) {
3452
+ const info = {
3453
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3454
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3455
+ req
3456
+ };
3457
+ if (this.options.verifyClient.length === 2) {
3458
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3459
+ if (!verified) return abortHandshake(socket, code || 401, message, headers);
3460
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3461
+ });
3462
+ return;
3463
+ }
3464
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3465
+ }
3466
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3467
+ }
3468
+ /**
3469
+ * Upgrade the connection to WebSocket.
3470
+ *
3471
+ * @param {Object} extensions The accepted extensions
3472
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3473
+ * @param {Set} protocols The subprotocols
3474
+ * @param {http.IncomingMessage} req The request object
3475
+ * @param {Duplex} socket The network socket between the server and client
3476
+ * @param {Buffer} head The first packet of the upgraded stream
3477
+ * @param {Function} cb Callback
3478
+ * @throws {Error} If called more than once with the same socket
3479
+ * @private
3480
+ */
3481
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3482
+ if (!socket.readable || !socket.writable) return socket.destroy();
3483
+ if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
3484
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3485
+ const headers = [
3486
+ "HTTP/1.1 101 Switching Protocols",
3487
+ "Upgrade: websocket",
3488
+ "Connection: Upgrade",
3489
+ `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
3490
+ ];
3491
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3492
+ if (protocols.size) {
3493
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3494
+ if (protocol) {
3495
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3496
+ ws._protocol = protocol;
3497
+ }
3498
+ }
3499
+ if (extensions[PerMessageDeflate.extensionName]) {
3500
+ const params = extensions[PerMessageDeflate.extensionName].params;
3501
+ const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
3502
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3503
+ ws._extensions = extensions;
3504
+ }
3505
+ this.emit("headers", headers, req);
3506
+ socket.write(headers.concat("\r\n").join("\r\n"));
3507
+ socket.removeListener("error", socketOnError);
3508
+ ws.setSocket(socket, head, {
3509
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3510
+ maxBufferedChunks: this.options.maxBufferedChunks,
3511
+ maxFragments: this.options.maxFragments,
3512
+ maxPayload: this.options.maxPayload,
3513
+ skipUTF8Validation: this.options.skipUTF8Validation
3514
+ });
3515
+ if (this.clients) {
3516
+ this.clients.add(ws);
3517
+ ws.on("close", () => {
3518
+ this.clients.delete(ws);
3519
+ if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
3520
+ });
3521
+ }
3522
+ cb(ws, req);
3523
+ }
3524
+ };
3525
+ module.exports = WebSocketServer;
3526
+ /**
3527
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
3528
+ * pairs.
3529
+ *
3530
+ * @param {EventEmitter} server The event emitter
3531
+ * @param {Object.<String, Function>} map The listeners to add
3532
+ * @return {Function} A function that will remove the added listeners when
3533
+ * called
3534
+ * @private
3535
+ */
3536
+ function addListeners(server, map) {
3537
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3538
+ return function removeListeners() {
3539
+ for (const event of Object.keys(map)) server.removeListener(event, map[event]);
3540
+ };
3541
+ }
3542
+ /**
3543
+ * Emit a `'close'` event on an `EventEmitter`.
3544
+ *
3545
+ * @param {EventEmitter} server The event emitter
3546
+ * @private
3547
+ */
3548
+ function emitClose(server) {
3549
+ server._state = CLOSED;
3550
+ server.emit("close");
3551
+ }
3552
+ /**
3553
+ * Handle socket errors.
3554
+ *
3555
+ * @private
3556
+ */
3557
+ function socketOnError() {
3558
+ this.destroy();
3559
+ }
3560
+ /**
3561
+ * Close the connection when preconditions are not fulfilled.
3562
+ *
3563
+ * @param {Duplex} socket The socket of the upgrade request
3564
+ * @param {Number} code The HTTP response status code
3565
+ * @param {String} [message] The HTTP response body
3566
+ * @param {Object} [headers] Additional HTTP response headers
3567
+ * @private
3568
+ */
3569
+ function abortHandshake(socket, code, message, headers) {
3570
+ message = message || http.STATUS_CODES[code];
3571
+ headers = {
3572
+ Connection: "close",
3573
+ "Content-Type": "text/html",
3574
+ "Content-Length": Buffer.byteLength(message),
3575
+ ...headers
3576
+ };
3577
+ socket.once("finish", socket.destroy);
3578
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
3579
+ }
3580
+ /**
3581
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
3582
+ * one listener for it, otherwise call `abortHandshake()`.
3583
+ *
3584
+ * @param {WebSocketServer} server The WebSocket server
3585
+ * @param {http.IncomingMessage} req The request object
3586
+ * @param {Duplex} socket The socket of the upgrade request
3587
+ * @param {Number} code The HTTP response status code
3588
+ * @param {String} message The HTTP response body
3589
+ * @param {Object} [headers] The HTTP response headers
3590
+ * @private
3591
+ */
3592
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3593
+ if (server.listenerCount("wsClientError")) {
3594
+ const err = new Error(message);
3595
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3596
+ server.emit("wsClientError", err, socket, req);
3597
+ } else abortHandshake(socket, code, message, headers);
3598
+ }
3599
+ }));
3600
+ // ../../node_modules/.bun/ws@8.22.1/node_modules/ws/wrapper.mjs
3601
+ var wrapper_exports = /* @__PURE__ */ __exportAll({
3602
+ PerMessageDeflate: () => import_permessage_deflate.default,
3603
+ Receiver: () => import_receiver.default,
3604
+ Sender: () => import_sender.default,
3605
+ WebSocket: () => import_websocket.default,
3606
+ WebSocketServer: () => import_websocket_server.default,
3607
+ createWebSocketStream: () => import_stream.default,
3608
+ default: () => wrapper_default,
3609
+ extension: () => import_extension.default,
3610
+ subprotocol: () => import_subprotocol.default
3611
+ });
3612
+ var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server, wrapper_default;
3613
+ var init_wrapper = __esmMin((() => {
3614
+ import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
3615
+ import_extension = /* @__PURE__ */ __toESM(require_extension(), 1);
3616
+ import_permessage_deflate = /* @__PURE__ */ __toESM(require_permessage_deflate(), 1);
3617
+ import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
3618
+ import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
3619
+ import_subprotocol = /* @__PURE__ */ __toESM(require_subprotocol(), 1);
3620
+ import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
3621
+ import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
3622
+ wrapper_default = import_websocket.default;
3623
+ }));
3624
+ export { init_wrapper as n, wrapper_exports as r, import_websocket as t };