shioricode 0.5.2 → 0.5.3

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