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