lakesync 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +74 -0
  2. package/dist/adapter.d.ts +369 -0
  3. package/dist/adapter.js +39 -0
  4. package/dist/adapter.js.map +1 -0
  5. package/dist/analyst.d.ts +268 -0
  6. package/dist/analyst.js +495 -0
  7. package/dist/analyst.js.map +1 -0
  8. package/dist/auth-CAVutXzx.d.ts +30 -0
  9. package/dist/base-poller-Qo_SmCZs.d.ts +82 -0
  10. package/dist/catalogue.d.ts +65 -0
  11. package/dist/catalogue.js +17 -0
  12. package/dist/catalogue.js.map +1 -0
  13. package/dist/chunk-4ARO6KTJ.js +257 -0
  14. package/dist/chunk-4ARO6KTJ.js.map +1 -0
  15. package/dist/chunk-5YOFCJQ7.js +1115 -0
  16. package/dist/chunk-5YOFCJQ7.js.map +1 -0
  17. package/dist/chunk-7D4SUZUM.js +38 -0
  18. package/dist/chunk-7D4SUZUM.js.map +1 -0
  19. package/dist/chunk-BNJOGBYK.js +335 -0
  20. package/dist/chunk-BNJOGBYK.js.map +1 -0
  21. package/dist/chunk-ICNT7I3K.js +1180 -0
  22. package/dist/chunk-ICNT7I3K.js.map +1 -0
  23. package/dist/chunk-P5DRFKIT.js +413 -0
  24. package/dist/chunk-P5DRFKIT.js.map +1 -0
  25. package/dist/chunk-X3RO5SYJ.js +880 -0
  26. package/dist/chunk-X3RO5SYJ.js.map +1 -0
  27. package/dist/client.d.ts +428 -0
  28. package/dist/client.js +2048 -0
  29. package/dist/client.js.map +1 -0
  30. package/dist/compactor.d.ts +342 -0
  31. package/dist/compactor.js +793 -0
  32. package/dist/compactor.js.map +1 -0
  33. package/dist/coordinator-CxckTzYW.d.ts +396 -0
  34. package/dist/db-types-BR6Kt4uf.d.ts +29 -0
  35. package/dist/gateway-D5SaaMvT.d.ts +337 -0
  36. package/dist/gateway-server.d.ts +306 -0
  37. package/dist/gateway-server.js +4663 -0
  38. package/dist/gateway-server.js.map +1 -0
  39. package/dist/gateway.d.ts +196 -0
  40. package/dist/gateway.js +79 -0
  41. package/dist/gateway.js.map +1 -0
  42. package/dist/hlc-DiD8QNG3.d.ts +70 -0
  43. package/dist/index.d.ts +245 -0
  44. package/dist/index.js +102 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/json-dYtqiL0F.d.ts +18 -0
  47. package/dist/nessie-client-DrNikVXy.d.ts +160 -0
  48. package/dist/parquet.d.ts +78 -0
  49. package/dist/parquet.js +15 -0
  50. package/dist/parquet.js.map +1 -0
  51. package/dist/proto.d.ts +434 -0
  52. package/dist/proto.js +67 -0
  53. package/dist/proto.js.map +1 -0
  54. package/dist/react.d.ts +147 -0
  55. package/dist/react.js +224 -0
  56. package/dist/react.js.map +1 -0
  57. package/dist/resolver-C3Wphi6O.d.ts +10 -0
  58. package/dist/result-CojzlFE2.d.ts +64 -0
  59. package/dist/src-QU2YLPZY.js +383 -0
  60. package/dist/src-QU2YLPZY.js.map +1 -0
  61. package/dist/src-WYBF5LOI.js +102 -0
  62. package/dist/src-WYBF5LOI.js.map +1 -0
  63. package/dist/src-WZNPHANQ.js +426 -0
  64. package/dist/src-WZNPHANQ.js.map +1 -0
  65. package/dist/types-Bs-QyOe-.d.ts +143 -0
  66. package/dist/types-DAQL_vU_.d.ts +118 -0
  67. package/dist/types-DSC_EiwR.d.ts +45 -0
  68. package/dist/types-V_jVu2sA.d.ts +73 -0
  69. package/package.json +119 -0
@@ -0,0 +1,4663 @@
1
+ import {
2
+ DEFAULT_MAX_BUFFER_AGE_MS,
3
+ DEFAULT_MAX_BUFFER_BYTES,
4
+ MAX_PUSH_PAYLOAD_BYTES,
5
+ MemoryConfigStore,
6
+ SyncGateway,
7
+ handleActionRequest,
8
+ handleFlushRequest,
9
+ handleListConnectors,
10
+ handleMetrics,
11
+ handlePullRequest,
12
+ handlePushRequest,
13
+ handleRegisterConnector,
14
+ handleSaveSchema,
15
+ handleSaveSyncRules,
16
+ handleUnregisterConnector
17
+ } from "./chunk-5YOFCJQ7.js";
18
+ import {
19
+ createDatabaseAdapter,
20
+ createQueryFn
21
+ } from "./chunk-X3RO5SYJ.js";
22
+ import "./chunk-P5DRFKIT.js";
23
+ import {
24
+ TAG_SYNC_PULL,
25
+ TAG_SYNC_PUSH,
26
+ decodeSyncPull,
27
+ decodeSyncPush,
28
+ encodeBroadcastFrame,
29
+ encodeSyncResponse
30
+ } from "./chunk-BNJOGBYK.js";
31
+ import "./chunk-4ARO6KTJ.js";
32
+ import {
33
+ AuthError,
34
+ HLC,
35
+ bigintReplacer,
36
+ bigintReviver,
37
+ extractDelta,
38
+ filterDeltas,
39
+ isActionHandler,
40
+ verifyToken
41
+ } from "./chunk-ICNT7I3K.js";
42
+ import {
43
+ __commonJS,
44
+ __require,
45
+ __toESM
46
+ } from "./chunk-7D4SUZUM.js";
47
+
48
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/stream.js
49
+ var require_stream = __commonJS({
50
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/stream.js"(exports, module) {
51
+ "use strict";
52
+ var { Duplex } = __require("stream");
53
+ function emitClose(stream) {
54
+ stream.emit("close");
55
+ }
56
+ function duplexOnEnd() {
57
+ if (!this.destroyed && this._writableState.finished) {
58
+ this.destroy();
59
+ }
60
+ }
61
+ function duplexOnError(err) {
62
+ this.removeListener("error", duplexOnError);
63
+ this.destroy();
64
+ if (this.listenerCount("error") === 0) {
65
+ this.emit("error", err);
66
+ }
67
+ }
68
+ function createWebSocketStream2(ws, options) {
69
+ let terminateOnDestroy = true;
70
+ const duplex = new Duplex({
71
+ ...options,
72
+ autoDestroy: false,
73
+ emitClose: false,
74
+ objectMode: false,
75
+ writableObjectMode: false
76
+ });
77
+ ws.on("message", function message(msg, isBinary) {
78
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
79
+ if (!duplex.push(data)) ws.pause();
80
+ });
81
+ ws.once("error", function error(err) {
82
+ if (duplex.destroyed) return;
83
+ terminateOnDestroy = false;
84
+ duplex.destroy(err);
85
+ });
86
+ ws.once("close", function close() {
87
+ if (duplex.destroyed) return;
88
+ duplex.push(null);
89
+ });
90
+ duplex._destroy = function(err, callback) {
91
+ if (ws.readyState === ws.CLOSED) {
92
+ callback(err);
93
+ process.nextTick(emitClose, duplex);
94
+ return;
95
+ }
96
+ let called = false;
97
+ ws.once("error", function error(err2) {
98
+ called = true;
99
+ callback(err2);
100
+ });
101
+ ws.once("close", function close() {
102
+ if (!called) callback(err);
103
+ process.nextTick(emitClose, duplex);
104
+ });
105
+ if (terminateOnDestroy) ws.terminate();
106
+ };
107
+ duplex._final = function(callback) {
108
+ if (ws.readyState === ws.CONNECTING) {
109
+ ws.once("open", function open() {
110
+ duplex._final(callback);
111
+ });
112
+ return;
113
+ }
114
+ if (ws._socket === null) return;
115
+ if (ws._socket._writableState.finished) {
116
+ callback();
117
+ if (duplex._readableState.endEmitted) duplex.destroy();
118
+ } else {
119
+ ws._socket.once("finish", function finish() {
120
+ callback();
121
+ });
122
+ ws.close();
123
+ }
124
+ };
125
+ duplex._read = function() {
126
+ if (ws.isPaused) ws.resume();
127
+ };
128
+ duplex._write = function(chunk, encoding, callback) {
129
+ if (ws.readyState === ws.CONNECTING) {
130
+ ws.once("open", function open() {
131
+ duplex._write(chunk, encoding, callback);
132
+ });
133
+ return;
134
+ }
135
+ ws.send(chunk, callback);
136
+ };
137
+ duplex.on("end", duplexOnEnd);
138
+ duplex.on("error", duplexOnError);
139
+ return duplex;
140
+ }
141
+ module.exports = createWebSocketStream2;
142
+ }
143
+ });
144
+
145
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/constants.js
146
+ var require_constants = __commonJS({
147
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/constants.js"(exports, module) {
148
+ "use strict";
149
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
150
+ var hasBlob = typeof Blob !== "undefined";
151
+ if (hasBlob) BINARY_TYPES.push("blob");
152
+ module.exports = {
153
+ BINARY_TYPES,
154
+ EMPTY_BUFFER: Buffer.alloc(0),
155
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
156
+ hasBlob,
157
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
158
+ kListener: /* @__PURE__ */ Symbol("kListener"),
159
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
160
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
161
+ NOOP: () => {
162
+ }
163
+ };
164
+ }
165
+ });
166
+
167
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/buffer-util.js
168
+ var require_buffer_util = __commonJS({
169
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
170
+ "use strict";
171
+ var { EMPTY_BUFFER } = require_constants();
172
+ var FastBuffer = Buffer[Symbol.species];
173
+ function concat(list, totalLength) {
174
+ if (list.length === 0) return EMPTY_BUFFER;
175
+ if (list.length === 1) return list[0];
176
+ const target = Buffer.allocUnsafe(totalLength);
177
+ let offset = 0;
178
+ for (let i = 0; i < list.length; i++) {
179
+ const buf = list[i];
180
+ target.set(buf, offset);
181
+ offset += buf.length;
182
+ }
183
+ if (offset < totalLength) {
184
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
185
+ }
186
+ return target;
187
+ }
188
+ function _mask(source, mask, output, offset, length) {
189
+ for (let i = 0; i < length; i++) {
190
+ output[offset + i] = source[i] ^ mask[i & 3];
191
+ }
192
+ }
193
+ function _unmask(buffer, mask) {
194
+ for (let i = 0; i < buffer.length; i++) {
195
+ buffer[i] ^= mask[i & 3];
196
+ }
197
+ }
198
+ function toArrayBuffer(buf) {
199
+ if (buf.length === buf.buffer.byteLength) {
200
+ return buf.buffer;
201
+ }
202
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
203
+ }
204
+ function toBuffer(data) {
205
+ toBuffer.readOnly = true;
206
+ if (Buffer.isBuffer(data)) return data;
207
+ let buf;
208
+ if (data instanceof ArrayBuffer) {
209
+ buf = new FastBuffer(data);
210
+ } else if (ArrayBuffer.isView(data)) {
211
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
212
+ } else {
213
+ buf = Buffer.from(data);
214
+ toBuffer.readOnly = false;
215
+ }
216
+ return buf;
217
+ }
218
+ module.exports = {
219
+ concat,
220
+ mask: _mask,
221
+ toArrayBuffer,
222
+ toBuffer,
223
+ unmask: _unmask
224
+ };
225
+ if (!process.env.WS_NO_BUFFER_UTIL) {
226
+ try {
227
+ const bufferUtil = __require("bufferutil");
228
+ module.exports.mask = function(source, mask, output, offset, length) {
229
+ if (length < 48) _mask(source, mask, output, offset, length);
230
+ else bufferUtil.mask(source, mask, output, offset, length);
231
+ };
232
+ module.exports.unmask = function(buffer, mask) {
233
+ if (buffer.length < 32) _unmask(buffer, mask);
234
+ else bufferUtil.unmask(buffer, mask);
235
+ };
236
+ } catch (e) {
237
+ }
238
+ }
239
+ }
240
+ });
241
+
242
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/limiter.js
243
+ var require_limiter = __commonJS({
244
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/limiter.js"(exports, module) {
245
+ "use strict";
246
+ var kDone = /* @__PURE__ */ Symbol("kDone");
247
+ var kRun = /* @__PURE__ */ Symbol("kRun");
248
+ var Limiter = class {
249
+ /**
250
+ * Creates a new `Limiter`.
251
+ *
252
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
253
+ * to run concurrently
254
+ */
255
+ constructor(concurrency) {
256
+ this[kDone] = () => {
257
+ this.pending--;
258
+ this[kRun]();
259
+ };
260
+ this.concurrency = concurrency || Infinity;
261
+ this.jobs = [];
262
+ this.pending = 0;
263
+ }
264
+ /**
265
+ * Adds a job to the queue.
266
+ *
267
+ * @param {Function} job The job to run
268
+ * @public
269
+ */
270
+ add(job) {
271
+ this.jobs.push(job);
272
+ this[kRun]();
273
+ }
274
+ /**
275
+ * Removes a job from the queue and runs it if possible.
276
+ *
277
+ * @private
278
+ */
279
+ [kRun]() {
280
+ if (this.pending === this.concurrency) return;
281
+ if (this.jobs.length) {
282
+ const job = this.jobs.shift();
283
+ this.pending++;
284
+ job(this[kDone]);
285
+ }
286
+ }
287
+ };
288
+ module.exports = Limiter;
289
+ }
290
+ });
291
+
292
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/permessage-deflate.js
293
+ var require_permessage_deflate = __commonJS({
294
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
295
+ "use strict";
296
+ var zlib = __require("zlib");
297
+ var bufferUtil = require_buffer_util();
298
+ var Limiter = require_limiter();
299
+ var { kStatusCode } = require_constants();
300
+ var FastBuffer = Buffer[Symbol.species];
301
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
302
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
303
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
304
+ var kCallback = /* @__PURE__ */ Symbol("callback");
305
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
306
+ var kError = /* @__PURE__ */ Symbol("error");
307
+ var zlibLimiter;
308
+ var PerMessageDeflate = class {
309
+ /**
310
+ * Creates a PerMessageDeflate instance.
311
+ *
312
+ * @param {Object} [options] Configuration options
313
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
314
+ * for, or request, a custom client window size
315
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
316
+ * acknowledge disabling of client context takeover
317
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
318
+ * calls to zlib
319
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
320
+ * use of a custom server window size
321
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
322
+ * disabling of server context takeover
323
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
324
+ * messages should not be compressed if context takeover is disabled
325
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
326
+ * deflate
327
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
328
+ * inflate
329
+ * @param {Boolean} [isServer=false] Create the instance in either server or
330
+ * client mode
331
+ * @param {Number} [maxPayload=0] The maximum allowed message length
332
+ */
333
+ constructor(options, isServer, maxPayload) {
334
+ this._maxPayload = maxPayload | 0;
335
+ this._options = options || {};
336
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
337
+ this._isServer = !!isServer;
338
+ this._deflate = null;
339
+ this._inflate = null;
340
+ this.params = null;
341
+ if (!zlibLimiter) {
342
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
343
+ zlibLimiter = new Limiter(concurrency);
344
+ }
345
+ }
346
+ /**
347
+ * @type {String}
348
+ */
349
+ static get extensionName() {
350
+ return "permessage-deflate";
351
+ }
352
+ /**
353
+ * Create an extension negotiation offer.
354
+ *
355
+ * @return {Object} Extension parameters
356
+ * @public
357
+ */
358
+ offer() {
359
+ const params = {};
360
+ if (this._options.serverNoContextTakeover) {
361
+ params.server_no_context_takeover = true;
362
+ }
363
+ if (this._options.clientNoContextTakeover) {
364
+ params.client_no_context_takeover = true;
365
+ }
366
+ if (this._options.serverMaxWindowBits) {
367
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
368
+ }
369
+ if (this._options.clientMaxWindowBits) {
370
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
371
+ } else if (this._options.clientMaxWindowBits == null) {
372
+ params.client_max_window_bits = true;
373
+ }
374
+ return params;
375
+ }
376
+ /**
377
+ * Accept an extension negotiation offer/response.
378
+ *
379
+ * @param {Array} configurations The extension negotiation offers/reponse
380
+ * @return {Object} Accepted configuration
381
+ * @public
382
+ */
383
+ accept(configurations) {
384
+ configurations = this.normalizeParams(configurations);
385
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
386
+ return this.params;
387
+ }
388
+ /**
389
+ * Releases all resources used by the extension.
390
+ *
391
+ * @public
392
+ */
393
+ cleanup() {
394
+ if (this._inflate) {
395
+ this._inflate.close();
396
+ this._inflate = null;
397
+ }
398
+ if (this._deflate) {
399
+ const callback = this._deflate[kCallback];
400
+ this._deflate.close();
401
+ this._deflate = null;
402
+ if (callback) {
403
+ callback(
404
+ new Error(
405
+ "The deflate stream was closed while data was being processed"
406
+ )
407
+ );
408
+ }
409
+ }
410
+ }
411
+ /**
412
+ * Accept an extension negotiation offer.
413
+ *
414
+ * @param {Array} offers The extension negotiation offers
415
+ * @return {Object} Accepted configuration
416
+ * @private
417
+ */
418
+ acceptAsServer(offers) {
419
+ const opts = this._options;
420
+ const accepted = offers.find((params) => {
421
+ 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) {
422
+ return false;
423
+ }
424
+ return true;
425
+ });
426
+ if (!accepted) {
427
+ throw new Error("None of the extension offers can be accepted");
428
+ }
429
+ if (opts.serverNoContextTakeover) {
430
+ accepted.server_no_context_takeover = true;
431
+ }
432
+ if (opts.clientNoContextTakeover) {
433
+ accepted.client_no_context_takeover = true;
434
+ }
435
+ if (typeof opts.serverMaxWindowBits === "number") {
436
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
437
+ }
438
+ if (typeof opts.clientMaxWindowBits === "number") {
439
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
440
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
441
+ delete accepted.client_max_window_bits;
442
+ }
443
+ return accepted;
444
+ }
445
+ /**
446
+ * Accept the extension negotiation response.
447
+ *
448
+ * @param {Array} response The extension negotiation response
449
+ * @return {Object} Accepted configuration
450
+ * @private
451
+ */
452
+ acceptAsClient(response) {
453
+ const params = response[0];
454
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
455
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
456
+ }
457
+ if (!params.client_max_window_bits) {
458
+ if (typeof this._options.clientMaxWindowBits === "number") {
459
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
460
+ }
461
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
462
+ throw new Error(
463
+ 'Unexpected or invalid parameter "client_max_window_bits"'
464
+ );
465
+ }
466
+ return params;
467
+ }
468
+ /**
469
+ * Normalize parameters.
470
+ *
471
+ * @param {Array} configurations The extension negotiation offers/reponse
472
+ * @return {Array} The offers/response with normalized parameters
473
+ * @private
474
+ */
475
+ normalizeParams(configurations) {
476
+ configurations.forEach((params) => {
477
+ Object.keys(params).forEach((key) => {
478
+ let value = params[key];
479
+ if (value.length > 1) {
480
+ throw new Error(`Parameter "${key}" must have only a single value`);
481
+ }
482
+ value = value[0];
483
+ if (key === "client_max_window_bits") {
484
+ if (value !== true) {
485
+ const num = +value;
486
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
487
+ throw new TypeError(
488
+ `Invalid value for parameter "${key}": ${value}`
489
+ );
490
+ }
491
+ value = num;
492
+ } else if (!this._isServer) {
493
+ throw new TypeError(
494
+ `Invalid value for parameter "${key}": ${value}`
495
+ );
496
+ }
497
+ } else if (key === "server_max_window_bits") {
498
+ const num = +value;
499
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
500
+ throw new TypeError(
501
+ `Invalid value for parameter "${key}": ${value}`
502
+ );
503
+ }
504
+ value = num;
505
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
506
+ if (value !== true) {
507
+ throw new TypeError(
508
+ `Invalid value for parameter "${key}": ${value}`
509
+ );
510
+ }
511
+ } else {
512
+ throw new Error(`Unknown parameter "${key}"`);
513
+ }
514
+ params[key] = value;
515
+ });
516
+ });
517
+ return configurations;
518
+ }
519
+ /**
520
+ * Decompress data. Concurrency limited.
521
+ *
522
+ * @param {Buffer} data Compressed data
523
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
524
+ * @param {Function} callback Callback
525
+ * @public
526
+ */
527
+ decompress(data, fin, callback) {
528
+ zlibLimiter.add((done) => {
529
+ this._decompress(data, fin, (err, result) => {
530
+ done();
531
+ callback(err, result);
532
+ });
533
+ });
534
+ }
535
+ /**
536
+ * Compress data. Concurrency limited.
537
+ *
538
+ * @param {(Buffer|String)} data Data to compress
539
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
540
+ * @param {Function} callback Callback
541
+ * @public
542
+ */
543
+ compress(data, fin, callback) {
544
+ zlibLimiter.add((done) => {
545
+ this._compress(data, fin, (err, result) => {
546
+ done();
547
+ callback(err, result);
548
+ });
549
+ });
550
+ }
551
+ /**
552
+ * Decompress data.
553
+ *
554
+ * @param {Buffer} data Compressed data
555
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
556
+ * @param {Function} callback Callback
557
+ * @private
558
+ */
559
+ _decompress(data, fin, callback) {
560
+ const endpoint = this._isServer ? "client" : "server";
561
+ if (!this._inflate) {
562
+ const key = `${endpoint}_max_window_bits`;
563
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
564
+ this._inflate = zlib.createInflateRaw({
565
+ ...this._options.zlibInflateOptions,
566
+ windowBits
567
+ });
568
+ this._inflate[kPerMessageDeflate] = this;
569
+ this._inflate[kTotalLength] = 0;
570
+ this._inflate[kBuffers] = [];
571
+ this._inflate.on("error", inflateOnError);
572
+ this._inflate.on("data", inflateOnData);
573
+ }
574
+ this._inflate[kCallback] = callback;
575
+ this._inflate.write(data);
576
+ if (fin) this._inflate.write(TRAILER);
577
+ this._inflate.flush(() => {
578
+ const err = this._inflate[kError];
579
+ if (err) {
580
+ this._inflate.close();
581
+ this._inflate = null;
582
+ callback(err);
583
+ return;
584
+ }
585
+ const data2 = bufferUtil.concat(
586
+ this._inflate[kBuffers],
587
+ this._inflate[kTotalLength]
588
+ );
589
+ if (this._inflate._readableState.endEmitted) {
590
+ this._inflate.close();
591
+ this._inflate = null;
592
+ } else {
593
+ this._inflate[kTotalLength] = 0;
594
+ this._inflate[kBuffers] = [];
595
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
596
+ this._inflate.reset();
597
+ }
598
+ }
599
+ callback(null, data2);
600
+ });
601
+ }
602
+ /**
603
+ * Compress data.
604
+ *
605
+ * @param {(Buffer|String)} data Data to compress
606
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
607
+ * @param {Function} callback Callback
608
+ * @private
609
+ */
610
+ _compress(data, fin, callback) {
611
+ const endpoint = this._isServer ? "server" : "client";
612
+ if (!this._deflate) {
613
+ const key = `${endpoint}_max_window_bits`;
614
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
615
+ this._deflate = zlib.createDeflateRaw({
616
+ ...this._options.zlibDeflateOptions,
617
+ windowBits
618
+ });
619
+ this._deflate[kTotalLength] = 0;
620
+ this._deflate[kBuffers] = [];
621
+ this._deflate.on("data", deflateOnData);
622
+ }
623
+ this._deflate[kCallback] = callback;
624
+ this._deflate.write(data);
625
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
626
+ if (!this._deflate) {
627
+ return;
628
+ }
629
+ let data2 = bufferUtil.concat(
630
+ this._deflate[kBuffers],
631
+ this._deflate[kTotalLength]
632
+ );
633
+ if (fin) {
634
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
635
+ }
636
+ this._deflate[kCallback] = null;
637
+ this._deflate[kTotalLength] = 0;
638
+ this._deflate[kBuffers] = [];
639
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
640
+ this._deflate.reset();
641
+ }
642
+ callback(null, data2);
643
+ });
644
+ }
645
+ };
646
+ module.exports = PerMessageDeflate;
647
+ function deflateOnData(chunk) {
648
+ this[kBuffers].push(chunk);
649
+ this[kTotalLength] += chunk.length;
650
+ }
651
+ function inflateOnData(chunk) {
652
+ this[kTotalLength] += chunk.length;
653
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
654
+ this[kBuffers].push(chunk);
655
+ return;
656
+ }
657
+ this[kError] = new RangeError("Max payload size exceeded");
658
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
659
+ this[kError][kStatusCode] = 1009;
660
+ this.removeListener("data", inflateOnData);
661
+ this.reset();
662
+ }
663
+ function inflateOnError(err) {
664
+ this[kPerMessageDeflate]._inflate = null;
665
+ err[kStatusCode] = 1007;
666
+ this[kCallback](err);
667
+ }
668
+ }
669
+ });
670
+
671
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/validation.js
672
+ var require_validation = __commonJS({
673
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/validation.js"(exports, module) {
674
+ "use strict";
675
+ var { isUtf8 } = __require("buffer");
676
+ var { hasBlob } = require_constants();
677
+ var tokenChars = [
678
+ 0,
679
+ 0,
680
+ 0,
681
+ 0,
682
+ 0,
683
+ 0,
684
+ 0,
685
+ 0,
686
+ 0,
687
+ 0,
688
+ 0,
689
+ 0,
690
+ 0,
691
+ 0,
692
+ 0,
693
+ 0,
694
+ // 0 - 15
695
+ 0,
696
+ 0,
697
+ 0,
698
+ 0,
699
+ 0,
700
+ 0,
701
+ 0,
702
+ 0,
703
+ 0,
704
+ 0,
705
+ 0,
706
+ 0,
707
+ 0,
708
+ 0,
709
+ 0,
710
+ 0,
711
+ // 16 - 31
712
+ 0,
713
+ 1,
714
+ 0,
715
+ 1,
716
+ 1,
717
+ 1,
718
+ 1,
719
+ 1,
720
+ 0,
721
+ 0,
722
+ 1,
723
+ 1,
724
+ 0,
725
+ 1,
726
+ 1,
727
+ 0,
728
+ // 32 - 47
729
+ 1,
730
+ 1,
731
+ 1,
732
+ 1,
733
+ 1,
734
+ 1,
735
+ 1,
736
+ 1,
737
+ 1,
738
+ 1,
739
+ 0,
740
+ 0,
741
+ 0,
742
+ 0,
743
+ 0,
744
+ 0,
745
+ // 48 - 63
746
+ 0,
747
+ 1,
748
+ 1,
749
+ 1,
750
+ 1,
751
+ 1,
752
+ 1,
753
+ 1,
754
+ 1,
755
+ 1,
756
+ 1,
757
+ 1,
758
+ 1,
759
+ 1,
760
+ 1,
761
+ 1,
762
+ // 64 - 79
763
+ 1,
764
+ 1,
765
+ 1,
766
+ 1,
767
+ 1,
768
+ 1,
769
+ 1,
770
+ 1,
771
+ 1,
772
+ 1,
773
+ 1,
774
+ 0,
775
+ 0,
776
+ 0,
777
+ 1,
778
+ 1,
779
+ // 80 - 95
780
+ 1,
781
+ 1,
782
+ 1,
783
+ 1,
784
+ 1,
785
+ 1,
786
+ 1,
787
+ 1,
788
+ 1,
789
+ 1,
790
+ 1,
791
+ 1,
792
+ 1,
793
+ 1,
794
+ 1,
795
+ 1,
796
+ // 96 - 111
797
+ 1,
798
+ 1,
799
+ 1,
800
+ 1,
801
+ 1,
802
+ 1,
803
+ 1,
804
+ 1,
805
+ 1,
806
+ 1,
807
+ 1,
808
+ 0,
809
+ 1,
810
+ 0,
811
+ 1,
812
+ 0
813
+ // 112 - 127
814
+ ];
815
+ function isValidStatusCode(code) {
816
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
817
+ }
818
+ function _isValidUTF8(buf) {
819
+ const len = buf.length;
820
+ let i = 0;
821
+ while (i < len) {
822
+ if ((buf[i] & 128) === 0) {
823
+ i++;
824
+ } else if ((buf[i] & 224) === 192) {
825
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
826
+ return false;
827
+ }
828
+ i += 2;
829
+ } else if ((buf[i] & 240) === 224) {
830
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
831
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
832
+ return false;
833
+ }
834
+ i += 3;
835
+ } else if ((buf[i] & 248) === 240) {
836
+ 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 || // Overlong
837
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
838
+ return false;
839
+ }
840
+ i += 4;
841
+ } else {
842
+ return false;
843
+ }
844
+ }
845
+ return true;
846
+ }
847
+ function isBlob(value) {
848
+ 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");
849
+ }
850
+ module.exports = {
851
+ isBlob,
852
+ isValidStatusCode,
853
+ isValidUTF8: _isValidUTF8,
854
+ tokenChars
855
+ };
856
+ if (isUtf8) {
857
+ module.exports.isValidUTF8 = function(buf) {
858
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
859
+ };
860
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
861
+ try {
862
+ const isValidUTF8 = __require("utf-8-validate");
863
+ module.exports.isValidUTF8 = function(buf) {
864
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
865
+ };
866
+ } catch (e) {
867
+ }
868
+ }
869
+ }
870
+ });
871
+
872
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/receiver.js
873
+ var require_receiver = __commonJS({
874
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/receiver.js"(exports, module) {
875
+ "use strict";
876
+ var { Writable } = __require("stream");
877
+ var PerMessageDeflate = require_permessage_deflate();
878
+ var {
879
+ BINARY_TYPES,
880
+ EMPTY_BUFFER,
881
+ kStatusCode,
882
+ kWebSocket
883
+ } = require_constants();
884
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
885
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
886
+ var FastBuffer = Buffer[Symbol.species];
887
+ var GET_INFO = 0;
888
+ var GET_PAYLOAD_LENGTH_16 = 1;
889
+ var GET_PAYLOAD_LENGTH_64 = 2;
890
+ var GET_MASK = 3;
891
+ var GET_DATA = 4;
892
+ var INFLATING = 5;
893
+ var DEFER_EVENT = 6;
894
+ var Receiver2 = class extends Writable {
895
+ /**
896
+ * Creates a Receiver instance.
897
+ *
898
+ * @param {Object} [options] Options object
899
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
900
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
901
+ * multiple times in the same tick
902
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
903
+ * @param {Object} [options.extensions] An object containing the negotiated
904
+ * extensions
905
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
906
+ * client or server mode
907
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
908
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
909
+ * not to skip UTF-8 validation for text and close messages
910
+ */
911
+ constructor(options = {}) {
912
+ super();
913
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
914
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
915
+ this._extensions = options.extensions || {};
916
+ this._isServer = !!options.isServer;
917
+ this._maxPayload = options.maxPayload | 0;
918
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
919
+ this[kWebSocket] = void 0;
920
+ this._bufferedBytes = 0;
921
+ this._buffers = [];
922
+ this._compressed = false;
923
+ this._payloadLength = 0;
924
+ this._mask = void 0;
925
+ this._fragmented = 0;
926
+ this._masked = false;
927
+ this._fin = false;
928
+ this._opcode = 0;
929
+ this._totalPayloadLength = 0;
930
+ this._messageLength = 0;
931
+ this._fragments = [];
932
+ this._errored = false;
933
+ this._loop = false;
934
+ this._state = GET_INFO;
935
+ }
936
+ /**
937
+ * Implements `Writable.prototype._write()`.
938
+ *
939
+ * @param {Buffer} chunk The chunk of data to write
940
+ * @param {String} encoding The character encoding of `chunk`
941
+ * @param {Function} cb Callback
942
+ * @private
943
+ */
944
+ _write(chunk, encoding, cb) {
945
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
946
+ this._bufferedBytes += chunk.length;
947
+ this._buffers.push(chunk);
948
+ this.startLoop(cb);
949
+ }
950
+ /**
951
+ * Consumes `n` bytes from the buffered data.
952
+ *
953
+ * @param {Number} n The number of bytes to consume
954
+ * @return {Buffer} The consumed bytes
955
+ * @private
956
+ */
957
+ consume(n) {
958
+ this._bufferedBytes -= n;
959
+ if (n === this._buffers[0].length) return this._buffers.shift();
960
+ if (n < this._buffers[0].length) {
961
+ const buf = this._buffers[0];
962
+ this._buffers[0] = new FastBuffer(
963
+ buf.buffer,
964
+ buf.byteOffset + n,
965
+ buf.length - n
966
+ );
967
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
968
+ }
969
+ const dst = Buffer.allocUnsafe(n);
970
+ do {
971
+ const buf = this._buffers[0];
972
+ const offset = dst.length - n;
973
+ if (n >= buf.length) {
974
+ dst.set(this._buffers.shift(), offset);
975
+ } else {
976
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
977
+ this._buffers[0] = new FastBuffer(
978
+ buf.buffer,
979
+ buf.byteOffset + n,
980
+ buf.length - n
981
+ );
982
+ }
983
+ n -= buf.length;
984
+ } while (n > 0);
985
+ return dst;
986
+ }
987
+ /**
988
+ * Starts the parsing loop.
989
+ *
990
+ * @param {Function} cb Callback
991
+ * @private
992
+ */
993
+ startLoop(cb) {
994
+ this._loop = true;
995
+ do {
996
+ switch (this._state) {
997
+ case GET_INFO:
998
+ this.getInfo(cb);
999
+ break;
1000
+ case GET_PAYLOAD_LENGTH_16:
1001
+ this.getPayloadLength16(cb);
1002
+ break;
1003
+ case GET_PAYLOAD_LENGTH_64:
1004
+ this.getPayloadLength64(cb);
1005
+ break;
1006
+ case GET_MASK:
1007
+ this.getMask();
1008
+ break;
1009
+ case GET_DATA:
1010
+ this.getData(cb);
1011
+ break;
1012
+ case INFLATING:
1013
+ case DEFER_EVENT:
1014
+ this._loop = false;
1015
+ return;
1016
+ }
1017
+ } while (this._loop);
1018
+ if (!this._errored) cb();
1019
+ }
1020
+ /**
1021
+ * Reads the first two bytes of a frame.
1022
+ *
1023
+ * @param {Function} cb Callback
1024
+ * @private
1025
+ */
1026
+ getInfo(cb) {
1027
+ if (this._bufferedBytes < 2) {
1028
+ this._loop = false;
1029
+ return;
1030
+ }
1031
+ const buf = this.consume(2);
1032
+ if ((buf[0] & 48) !== 0) {
1033
+ const error = this.createError(
1034
+ RangeError,
1035
+ "RSV2 and RSV3 must be clear",
1036
+ true,
1037
+ 1002,
1038
+ "WS_ERR_UNEXPECTED_RSV_2_3"
1039
+ );
1040
+ cb(error);
1041
+ return;
1042
+ }
1043
+ const compressed = (buf[0] & 64) === 64;
1044
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1045
+ const error = this.createError(
1046
+ RangeError,
1047
+ "RSV1 must be clear",
1048
+ true,
1049
+ 1002,
1050
+ "WS_ERR_UNEXPECTED_RSV_1"
1051
+ );
1052
+ cb(error);
1053
+ return;
1054
+ }
1055
+ this._fin = (buf[0] & 128) === 128;
1056
+ this._opcode = buf[0] & 15;
1057
+ this._payloadLength = buf[1] & 127;
1058
+ if (this._opcode === 0) {
1059
+ if (compressed) {
1060
+ const error = this.createError(
1061
+ RangeError,
1062
+ "RSV1 must be clear",
1063
+ true,
1064
+ 1002,
1065
+ "WS_ERR_UNEXPECTED_RSV_1"
1066
+ );
1067
+ cb(error);
1068
+ return;
1069
+ }
1070
+ if (!this._fragmented) {
1071
+ const error = this.createError(
1072
+ RangeError,
1073
+ "invalid opcode 0",
1074
+ true,
1075
+ 1002,
1076
+ "WS_ERR_INVALID_OPCODE"
1077
+ );
1078
+ cb(error);
1079
+ return;
1080
+ }
1081
+ this._opcode = this._fragmented;
1082
+ } else if (this._opcode === 1 || this._opcode === 2) {
1083
+ if (this._fragmented) {
1084
+ const error = this.createError(
1085
+ RangeError,
1086
+ `invalid opcode ${this._opcode}`,
1087
+ true,
1088
+ 1002,
1089
+ "WS_ERR_INVALID_OPCODE"
1090
+ );
1091
+ cb(error);
1092
+ return;
1093
+ }
1094
+ this._compressed = compressed;
1095
+ } else if (this._opcode > 7 && this._opcode < 11) {
1096
+ if (!this._fin) {
1097
+ const error = this.createError(
1098
+ RangeError,
1099
+ "FIN must be set",
1100
+ true,
1101
+ 1002,
1102
+ "WS_ERR_EXPECTED_FIN"
1103
+ );
1104
+ cb(error);
1105
+ return;
1106
+ }
1107
+ if (compressed) {
1108
+ const error = this.createError(
1109
+ RangeError,
1110
+ "RSV1 must be clear",
1111
+ true,
1112
+ 1002,
1113
+ "WS_ERR_UNEXPECTED_RSV_1"
1114
+ );
1115
+ cb(error);
1116
+ return;
1117
+ }
1118
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1119
+ const error = this.createError(
1120
+ RangeError,
1121
+ `invalid payload length ${this._payloadLength}`,
1122
+ true,
1123
+ 1002,
1124
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1125
+ );
1126
+ cb(error);
1127
+ return;
1128
+ }
1129
+ } else {
1130
+ const error = this.createError(
1131
+ RangeError,
1132
+ `invalid opcode ${this._opcode}`,
1133
+ true,
1134
+ 1002,
1135
+ "WS_ERR_INVALID_OPCODE"
1136
+ );
1137
+ cb(error);
1138
+ return;
1139
+ }
1140
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1141
+ this._masked = (buf[1] & 128) === 128;
1142
+ if (this._isServer) {
1143
+ if (!this._masked) {
1144
+ const error = this.createError(
1145
+ RangeError,
1146
+ "MASK must be set",
1147
+ true,
1148
+ 1002,
1149
+ "WS_ERR_EXPECTED_MASK"
1150
+ );
1151
+ cb(error);
1152
+ return;
1153
+ }
1154
+ } else if (this._masked) {
1155
+ const error = this.createError(
1156
+ RangeError,
1157
+ "MASK must be clear",
1158
+ true,
1159
+ 1002,
1160
+ "WS_ERR_UNEXPECTED_MASK"
1161
+ );
1162
+ cb(error);
1163
+ return;
1164
+ }
1165
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1166
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1167
+ else this.haveLength(cb);
1168
+ }
1169
+ /**
1170
+ * Gets extended payload length (7+16).
1171
+ *
1172
+ * @param {Function} cb Callback
1173
+ * @private
1174
+ */
1175
+ getPayloadLength16(cb) {
1176
+ if (this._bufferedBytes < 2) {
1177
+ this._loop = false;
1178
+ return;
1179
+ }
1180
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1181
+ this.haveLength(cb);
1182
+ }
1183
+ /**
1184
+ * Gets extended payload length (7+64).
1185
+ *
1186
+ * @param {Function} cb Callback
1187
+ * @private
1188
+ */
1189
+ getPayloadLength64(cb) {
1190
+ if (this._bufferedBytes < 8) {
1191
+ this._loop = false;
1192
+ return;
1193
+ }
1194
+ const buf = this.consume(8);
1195
+ const num = buf.readUInt32BE(0);
1196
+ if (num > Math.pow(2, 53 - 32) - 1) {
1197
+ const error = this.createError(
1198
+ RangeError,
1199
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1200
+ false,
1201
+ 1009,
1202
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1203
+ );
1204
+ cb(error);
1205
+ return;
1206
+ }
1207
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1208
+ this.haveLength(cb);
1209
+ }
1210
+ /**
1211
+ * Payload length has been read.
1212
+ *
1213
+ * @param {Function} cb Callback
1214
+ * @private
1215
+ */
1216
+ haveLength(cb) {
1217
+ if (this._payloadLength && this._opcode < 8) {
1218
+ this._totalPayloadLength += this._payloadLength;
1219
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1220
+ const error = this.createError(
1221
+ RangeError,
1222
+ "Max payload size exceeded",
1223
+ false,
1224
+ 1009,
1225
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1226
+ );
1227
+ cb(error);
1228
+ return;
1229
+ }
1230
+ }
1231
+ if (this._masked) this._state = GET_MASK;
1232
+ else this._state = GET_DATA;
1233
+ }
1234
+ /**
1235
+ * Reads mask bytes.
1236
+ *
1237
+ * @private
1238
+ */
1239
+ getMask() {
1240
+ if (this._bufferedBytes < 4) {
1241
+ this._loop = false;
1242
+ return;
1243
+ }
1244
+ this._mask = this.consume(4);
1245
+ this._state = GET_DATA;
1246
+ }
1247
+ /**
1248
+ * Reads data bytes.
1249
+ *
1250
+ * @param {Function} cb Callback
1251
+ * @private
1252
+ */
1253
+ getData(cb) {
1254
+ let data = EMPTY_BUFFER;
1255
+ if (this._payloadLength) {
1256
+ if (this._bufferedBytes < this._payloadLength) {
1257
+ this._loop = false;
1258
+ return;
1259
+ }
1260
+ data = this.consume(this._payloadLength);
1261
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1262
+ unmask(data, this._mask);
1263
+ }
1264
+ }
1265
+ if (this._opcode > 7) {
1266
+ this.controlMessage(data, cb);
1267
+ return;
1268
+ }
1269
+ if (this._compressed) {
1270
+ this._state = INFLATING;
1271
+ this.decompress(data, cb);
1272
+ return;
1273
+ }
1274
+ if (data.length) {
1275
+ this._messageLength = this._totalPayloadLength;
1276
+ this._fragments.push(data);
1277
+ }
1278
+ this.dataMessage(cb);
1279
+ }
1280
+ /**
1281
+ * Decompresses data.
1282
+ *
1283
+ * @param {Buffer} data Compressed data
1284
+ * @param {Function} cb Callback
1285
+ * @private
1286
+ */
1287
+ decompress(data, cb) {
1288
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1289
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1290
+ if (err) return cb(err);
1291
+ if (buf.length) {
1292
+ this._messageLength += buf.length;
1293
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1294
+ const error = this.createError(
1295
+ RangeError,
1296
+ "Max payload size exceeded",
1297
+ false,
1298
+ 1009,
1299
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1300
+ );
1301
+ cb(error);
1302
+ return;
1303
+ }
1304
+ this._fragments.push(buf);
1305
+ }
1306
+ this.dataMessage(cb);
1307
+ if (this._state === GET_INFO) this.startLoop(cb);
1308
+ });
1309
+ }
1310
+ /**
1311
+ * Handles a data message.
1312
+ *
1313
+ * @param {Function} cb Callback
1314
+ * @private
1315
+ */
1316
+ dataMessage(cb) {
1317
+ if (!this._fin) {
1318
+ this._state = GET_INFO;
1319
+ return;
1320
+ }
1321
+ const messageLength = this._messageLength;
1322
+ const fragments = this._fragments;
1323
+ this._totalPayloadLength = 0;
1324
+ this._messageLength = 0;
1325
+ this._fragmented = 0;
1326
+ this._fragments = [];
1327
+ if (this._opcode === 2) {
1328
+ let data;
1329
+ if (this._binaryType === "nodebuffer") {
1330
+ data = concat(fragments, messageLength);
1331
+ } else if (this._binaryType === "arraybuffer") {
1332
+ data = toArrayBuffer(concat(fragments, messageLength));
1333
+ } else if (this._binaryType === "blob") {
1334
+ data = new Blob(fragments);
1335
+ } else {
1336
+ data = fragments;
1337
+ }
1338
+ if (this._allowSynchronousEvents) {
1339
+ this.emit("message", data, true);
1340
+ this._state = GET_INFO;
1341
+ } else {
1342
+ this._state = DEFER_EVENT;
1343
+ setImmediate(() => {
1344
+ this.emit("message", data, true);
1345
+ this._state = GET_INFO;
1346
+ this.startLoop(cb);
1347
+ });
1348
+ }
1349
+ } else {
1350
+ const buf = concat(fragments, messageLength);
1351
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1352
+ const error = this.createError(
1353
+ Error,
1354
+ "invalid UTF-8 sequence",
1355
+ true,
1356
+ 1007,
1357
+ "WS_ERR_INVALID_UTF8"
1358
+ );
1359
+ cb(error);
1360
+ return;
1361
+ }
1362
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1363
+ this.emit("message", buf, false);
1364
+ this._state = GET_INFO;
1365
+ } else {
1366
+ this._state = DEFER_EVENT;
1367
+ setImmediate(() => {
1368
+ this.emit("message", buf, false);
1369
+ this._state = GET_INFO;
1370
+ this.startLoop(cb);
1371
+ });
1372
+ }
1373
+ }
1374
+ }
1375
+ /**
1376
+ * Handles a control message.
1377
+ *
1378
+ * @param {Buffer} data Data to handle
1379
+ * @return {(Error|RangeError|undefined)} A possible error
1380
+ * @private
1381
+ */
1382
+ controlMessage(data, cb) {
1383
+ if (this._opcode === 8) {
1384
+ if (data.length === 0) {
1385
+ this._loop = false;
1386
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1387
+ this.end();
1388
+ } else {
1389
+ const code = data.readUInt16BE(0);
1390
+ if (!isValidStatusCode(code)) {
1391
+ const error = this.createError(
1392
+ RangeError,
1393
+ `invalid status code ${code}`,
1394
+ true,
1395
+ 1002,
1396
+ "WS_ERR_INVALID_CLOSE_CODE"
1397
+ );
1398
+ cb(error);
1399
+ return;
1400
+ }
1401
+ const buf = new FastBuffer(
1402
+ data.buffer,
1403
+ data.byteOffset + 2,
1404
+ data.length - 2
1405
+ );
1406
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1407
+ const error = this.createError(
1408
+ Error,
1409
+ "invalid UTF-8 sequence",
1410
+ true,
1411
+ 1007,
1412
+ "WS_ERR_INVALID_UTF8"
1413
+ );
1414
+ cb(error);
1415
+ return;
1416
+ }
1417
+ this._loop = false;
1418
+ this.emit("conclude", code, buf);
1419
+ this.end();
1420
+ }
1421
+ this._state = GET_INFO;
1422
+ return;
1423
+ }
1424
+ if (this._allowSynchronousEvents) {
1425
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1426
+ this._state = GET_INFO;
1427
+ } else {
1428
+ this._state = DEFER_EVENT;
1429
+ setImmediate(() => {
1430
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1431
+ this._state = GET_INFO;
1432
+ this.startLoop(cb);
1433
+ });
1434
+ }
1435
+ }
1436
+ /**
1437
+ * Builds an error object.
1438
+ *
1439
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1440
+ * @param {String} message The error message
1441
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1442
+ * `message`
1443
+ * @param {Number} statusCode The status code
1444
+ * @param {String} errorCode The exposed error code
1445
+ * @return {(Error|RangeError)} The error
1446
+ * @private
1447
+ */
1448
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1449
+ this._loop = false;
1450
+ this._errored = true;
1451
+ const err = new ErrorCtor(
1452
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1453
+ );
1454
+ Error.captureStackTrace(err, this.createError);
1455
+ err.code = errorCode;
1456
+ err[kStatusCode] = statusCode;
1457
+ return err;
1458
+ }
1459
+ };
1460
+ module.exports = Receiver2;
1461
+ }
1462
+ });
1463
+
1464
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/sender.js
1465
+ var require_sender = __commonJS({
1466
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/sender.js"(exports, module) {
1467
+ "use strict";
1468
+ var { Duplex } = __require("stream");
1469
+ var { randomFillSync } = __require("crypto");
1470
+ var PerMessageDeflate = require_permessage_deflate();
1471
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1472
+ var { isBlob, isValidStatusCode } = require_validation();
1473
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1474
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1475
+ var maskBuffer = Buffer.alloc(4);
1476
+ var RANDOM_POOL_SIZE = 8 * 1024;
1477
+ var randomPool;
1478
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1479
+ var DEFAULT = 0;
1480
+ var DEFLATING = 1;
1481
+ var GET_BLOB_DATA = 2;
1482
+ var Sender2 = class _Sender {
1483
+ /**
1484
+ * Creates a Sender instance.
1485
+ *
1486
+ * @param {Duplex} socket The connection socket
1487
+ * @param {Object} [extensions] An object containing the negotiated extensions
1488
+ * @param {Function} [generateMask] The function used to generate the masking
1489
+ * key
1490
+ */
1491
+ constructor(socket, extensions, generateMask) {
1492
+ this._extensions = extensions || {};
1493
+ if (generateMask) {
1494
+ this._generateMask = generateMask;
1495
+ this._maskBuffer = Buffer.alloc(4);
1496
+ }
1497
+ this._socket = socket;
1498
+ this._firstFragment = true;
1499
+ this._compress = false;
1500
+ this._bufferedBytes = 0;
1501
+ this._queue = [];
1502
+ this._state = DEFAULT;
1503
+ this.onerror = NOOP;
1504
+ this[kWebSocket] = void 0;
1505
+ }
1506
+ /**
1507
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1508
+ *
1509
+ * @param {(Buffer|String)} data The data to frame
1510
+ * @param {Object} options Options object
1511
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1512
+ * FIN bit
1513
+ * @param {Function} [options.generateMask] The function used to generate the
1514
+ * masking key
1515
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1516
+ * `data`
1517
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1518
+ * key
1519
+ * @param {Number} options.opcode The opcode
1520
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1521
+ * modified
1522
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1523
+ * RSV1 bit
1524
+ * @return {(Buffer|String)[]} The framed data
1525
+ * @public
1526
+ */
1527
+ static frame(data, options) {
1528
+ let mask;
1529
+ let merge = false;
1530
+ let offset = 2;
1531
+ let skipMasking = false;
1532
+ if (options.mask) {
1533
+ mask = options.maskBuffer || maskBuffer;
1534
+ if (options.generateMask) {
1535
+ options.generateMask(mask);
1536
+ } else {
1537
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1538
+ if (randomPool === void 0) {
1539
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1540
+ }
1541
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1542
+ randomPoolPointer = 0;
1543
+ }
1544
+ mask[0] = randomPool[randomPoolPointer++];
1545
+ mask[1] = randomPool[randomPoolPointer++];
1546
+ mask[2] = randomPool[randomPoolPointer++];
1547
+ mask[3] = randomPool[randomPoolPointer++];
1548
+ }
1549
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1550
+ offset = 6;
1551
+ }
1552
+ let dataLength;
1553
+ if (typeof data === "string") {
1554
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1555
+ dataLength = options[kByteLength];
1556
+ } else {
1557
+ data = Buffer.from(data);
1558
+ dataLength = data.length;
1559
+ }
1560
+ } else {
1561
+ dataLength = data.length;
1562
+ merge = options.mask && options.readOnly && !skipMasking;
1563
+ }
1564
+ let payloadLength = dataLength;
1565
+ if (dataLength >= 65536) {
1566
+ offset += 8;
1567
+ payloadLength = 127;
1568
+ } else if (dataLength > 125) {
1569
+ offset += 2;
1570
+ payloadLength = 126;
1571
+ }
1572
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1573
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1574
+ if (options.rsv1) target[0] |= 64;
1575
+ target[1] = payloadLength;
1576
+ if (payloadLength === 126) {
1577
+ target.writeUInt16BE(dataLength, 2);
1578
+ } else if (payloadLength === 127) {
1579
+ target[2] = target[3] = 0;
1580
+ target.writeUIntBE(dataLength, 4, 6);
1581
+ }
1582
+ if (!options.mask) return [target, data];
1583
+ target[1] |= 128;
1584
+ target[offset - 4] = mask[0];
1585
+ target[offset - 3] = mask[1];
1586
+ target[offset - 2] = mask[2];
1587
+ target[offset - 1] = mask[3];
1588
+ if (skipMasking) return [target, data];
1589
+ if (merge) {
1590
+ applyMask(data, mask, target, offset, dataLength);
1591
+ return [target];
1592
+ }
1593
+ applyMask(data, mask, data, 0, dataLength);
1594
+ return [target, data];
1595
+ }
1596
+ /**
1597
+ * Sends a close message to the other peer.
1598
+ *
1599
+ * @param {Number} [code] The status code component of the body
1600
+ * @param {(String|Buffer)} [data] The message component of the body
1601
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1602
+ * @param {Function} [cb] Callback
1603
+ * @public
1604
+ */
1605
+ close(code, data, mask, cb) {
1606
+ let buf;
1607
+ if (code === void 0) {
1608
+ buf = EMPTY_BUFFER;
1609
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1610
+ throw new TypeError("First argument must be a valid error code number");
1611
+ } else if (data === void 0 || !data.length) {
1612
+ buf = Buffer.allocUnsafe(2);
1613
+ buf.writeUInt16BE(code, 0);
1614
+ } else {
1615
+ const length = Buffer.byteLength(data);
1616
+ if (length > 123) {
1617
+ throw new RangeError("The message must not be greater than 123 bytes");
1618
+ }
1619
+ buf = Buffer.allocUnsafe(2 + length);
1620
+ buf.writeUInt16BE(code, 0);
1621
+ if (typeof data === "string") {
1622
+ buf.write(data, 2);
1623
+ } else {
1624
+ buf.set(data, 2);
1625
+ }
1626
+ }
1627
+ const options = {
1628
+ [kByteLength]: buf.length,
1629
+ fin: true,
1630
+ generateMask: this._generateMask,
1631
+ mask,
1632
+ maskBuffer: this._maskBuffer,
1633
+ opcode: 8,
1634
+ readOnly: false,
1635
+ rsv1: false
1636
+ };
1637
+ if (this._state !== DEFAULT) {
1638
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1639
+ } else {
1640
+ this.sendFrame(_Sender.frame(buf, options), cb);
1641
+ }
1642
+ }
1643
+ /**
1644
+ * Sends a ping message to the other peer.
1645
+ *
1646
+ * @param {*} data The message to send
1647
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1648
+ * @param {Function} [cb] Callback
1649
+ * @public
1650
+ */
1651
+ ping(data, mask, cb) {
1652
+ let byteLength;
1653
+ let readOnly;
1654
+ if (typeof data === "string") {
1655
+ byteLength = Buffer.byteLength(data);
1656
+ readOnly = false;
1657
+ } else if (isBlob(data)) {
1658
+ byteLength = data.size;
1659
+ readOnly = false;
1660
+ } else {
1661
+ data = toBuffer(data);
1662
+ byteLength = data.length;
1663
+ readOnly = toBuffer.readOnly;
1664
+ }
1665
+ if (byteLength > 125) {
1666
+ throw new RangeError("The data size must not be greater than 125 bytes");
1667
+ }
1668
+ const options = {
1669
+ [kByteLength]: byteLength,
1670
+ fin: true,
1671
+ generateMask: this._generateMask,
1672
+ mask,
1673
+ maskBuffer: this._maskBuffer,
1674
+ opcode: 9,
1675
+ readOnly,
1676
+ rsv1: false
1677
+ };
1678
+ if (isBlob(data)) {
1679
+ if (this._state !== DEFAULT) {
1680
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1681
+ } else {
1682
+ this.getBlobData(data, false, options, cb);
1683
+ }
1684
+ } else if (this._state !== DEFAULT) {
1685
+ this.enqueue([this.dispatch, data, false, options, cb]);
1686
+ } else {
1687
+ this.sendFrame(_Sender.frame(data, options), cb);
1688
+ }
1689
+ }
1690
+ /**
1691
+ * Sends a pong message to the other peer.
1692
+ *
1693
+ * @param {*} data The message to send
1694
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1695
+ * @param {Function} [cb] Callback
1696
+ * @public
1697
+ */
1698
+ pong(data, mask, cb) {
1699
+ let byteLength;
1700
+ let readOnly;
1701
+ if (typeof data === "string") {
1702
+ byteLength = Buffer.byteLength(data);
1703
+ readOnly = false;
1704
+ } else if (isBlob(data)) {
1705
+ byteLength = data.size;
1706
+ readOnly = false;
1707
+ } else {
1708
+ data = toBuffer(data);
1709
+ byteLength = data.length;
1710
+ readOnly = toBuffer.readOnly;
1711
+ }
1712
+ if (byteLength > 125) {
1713
+ throw new RangeError("The data size must not be greater than 125 bytes");
1714
+ }
1715
+ const options = {
1716
+ [kByteLength]: byteLength,
1717
+ fin: true,
1718
+ generateMask: this._generateMask,
1719
+ mask,
1720
+ maskBuffer: this._maskBuffer,
1721
+ opcode: 10,
1722
+ readOnly,
1723
+ rsv1: false
1724
+ };
1725
+ if (isBlob(data)) {
1726
+ if (this._state !== DEFAULT) {
1727
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1728
+ } else {
1729
+ this.getBlobData(data, false, options, cb);
1730
+ }
1731
+ } else if (this._state !== DEFAULT) {
1732
+ this.enqueue([this.dispatch, data, false, options, cb]);
1733
+ } else {
1734
+ this.sendFrame(_Sender.frame(data, options), cb);
1735
+ }
1736
+ }
1737
+ /**
1738
+ * Sends a data message to the other peer.
1739
+ *
1740
+ * @param {*} data The message to send
1741
+ * @param {Object} options Options object
1742
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1743
+ * or text
1744
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1745
+ * compress `data`
1746
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1747
+ * last one
1748
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1749
+ * `data`
1750
+ * @param {Function} [cb] Callback
1751
+ * @public
1752
+ */
1753
+ send(data, options, cb) {
1754
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1755
+ let opcode = options.binary ? 2 : 1;
1756
+ let rsv1 = options.compress;
1757
+ let byteLength;
1758
+ let readOnly;
1759
+ if (typeof data === "string") {
1760
+ byteLength = Buffer.byteLength(data);
1761
+ readOnly = false;
1762
+ } else if (isBlob(data)) {
1763
+ byteLength = data.size;
1764
+ readOnly = false;
1765
+ } else {
1766
+ data = toBuffer(data);
1767
+ byteLength = data.length;
1768
+ readOnly = toBuffer.readOnly;
1769
+ }
1770
+ if (this._firstFragment) {
1771
+ this._firstFragment = false;
1772
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1773
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1774
+ }
1775
+ this._compress = rsv1;
1776
+ } else {
1777
+ rsv1 = false;
1778
+ opcode = 0;
1779
+ }
1780
+ if (options.fin) this._firstFragment = true;
1781
+ const opts = {
1782
+ [kByteLength]: byteLength,
1783
+ fin: options.fin,
1784
+ generateMask: this._generateMask,
1785
+ mask: options.mask,
1786
+ maskBuffer: this._maskBuffer,
1787
+ opcode,
1788
+ readOnly,
1789
+ rsv1
1790
+ };
1791
+ if (isBlob(data)) {
1792
+ if (this._state !== DEFAULT) {
1793
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1794
+ } else {
1795
+ this.getBlobData(data, this._compress, opts, cb);
1796
+ }
1797
+ } else if (this._state !== DEFAULT) {
1798
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1799
+ } else {
1800
+ this.dispatch(data, this._compress, opts, cb);
1801
+ }
1802
+ }
1803
+ /**
1804
+ * Gets the contents of a blob as binary data.
1805
+ *
1806
+ * @param {Blob} blob The blob
1807
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1808
+ * the data
1809
+ * @param {Object} options Options object
1810
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1811
+ * FIN bit
1812
+ * @param {Function} [options.generateMask] The function used to generate the
1813
+ * masking key
1814
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1815
+ * `data`
1816
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1817
+ * key
1818
+ * @param {Number} options.opcode The opcode
1819
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1820
+ * modified
1821
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1822
+ * RSV1 bit
1823
+ * @param {Function} [cb] Callback
1824
+ * @private
1825
+ */
1826
+ getBlobData(blob, compress, options, cb) {
1827
+ this._bufferedBytes += options[kByteLength];
1828
+ this._state = GET_BLOB_DATA;
1829
+ blob.arrayBuffer().then((arrayBuffer) => {
1830
+ if (this._socket.destroyed) {
1831
+ const err = new Error(
1832
+ "The socket was closed while the blob was being read"
1833
+ );
1834
+ process.nextTick(callCallbacks, this, err, cb);
1835
+ return;
1836
+ }
1837
+ this._bufferedBytes -= options[kByteLength];
1838
+ const data = toBuffer(arrayBuffer);
1839
+ if (!compress) {
1840
+ this._state = DEFAULT;
1841
+ this.sendFrame(_Sender.frame(data, options), cb);
1842
+ this.dequeue();
1843
+ } else {
1844
+ this.dispatch(data, compress, options, cb);
1845
+ }
1846
+ }).catch((err) => {
1847
+ process.nextTick(onError, this, err, cb);
1848
+ });
1849
+ }
1850
+ /**
1851
+ * Dispatches a message.
1852
+ *
1853
+ * @param {(Buffer|String)} data The message to send
1854
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1855
+ * `data`
1856
+ * @param {Object} options Options object
1857
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1858
+ * FIN bit
1859
+ * @param {Function} [options.generateMask] The function used to generate the
1860
+ * masking key
1861
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1862
+ * `data`
1863
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1864
+ * key
1865
+ * @param {Number} options.opcode The opcode
1866
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1867
+ * modified
1868
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1869
+ * RSV1 bit
1870
+ * @param {Function} [cb] Callback
1871
+ * @private
1872
+ */
1873
+ dispatch(data, compress, options, cb) {
1874
+ if (!compress) {
1875
+ this.sendFrame(_Sender.frame(data, options), cb);
1876
+ return;
1877
+ }
1878
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1879
+ this._bufferedBytes += options[kByteLength];
1880
+ this._state = DEFLATING;
1881
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1882
+ if (this._socket.destroyed) {
1883
+ const err = new Error(
1884
+ "The socket was closed while data was being compressed"
1885
+ );
1886
+ callCallbacks(this, err, cb);
1887
+ return;
1888
+ }
1889
+ this._bufferedBytes -= options[kByteLength];
1890
+ this._state = DEFAULT;
1891
+ options.readOnly = false;
1892
+ this.sendFrame(_Sender.frame(buf, options), cb);
1893
+ this.dequeue();
1894
+ });
1895
+ }
1896
+ /**
1897
+ * Executes queued send operations.
1898
+ *
1899
+ * @private
1900
+ */
1901
+ dequeue() {
1902
+ while (this._state === DEFAULT && this._queue.length) {
1903
+ const params = this._queue.shift();
1904
+ this._bufferedBytes -= params[3][kByteLength];
1905
+ Reflect.apply(params[0], this, params.slice(1));
1906
+ }
1907
+ }
1908
+ /**
1909
+ * Enqueues a send operation.
1910
+ *
1911
+ * @param {Array} params Send operation parameters.
1912
+ * @private
1913
+ */
1914
+ enqueue(params) {
1915
+ this._bufferedBytes += params[3][kByteLength];
1916
+ this._queue.push(params);
1917
+ }
1918
+ /**
1919
+ * Sends a frame.
1920
+ *
1921
+ * @param {Buffer[]} list The frame to send
1922
+ * @param {Function} [cb] Callback
1923
+ * @private
1924
+ */
1925
+ sendFrame(list, cb) {
1926
+ if (list.length === 2) {
1927
+ this._socket.cork();
1928
+ this._socket.write(list[0]);
1929
+ this._socket.write(list[1], cb);
1930
+ this._socket.uncork();
1931
+ } else {
1932
+ this._socket.write(list[0], cb);
1933
+ }
1934
+ }
1935
+ };
1936
+ module.exports = Sender2;
1937
+ function callCallbacks(sender, err, cb) {
1938
+ if (typeof cb === "function") cb(err);
1939
+ for (let i = 0; i < sender._queue.length; i++) {
1940
+ const params = sender._queue[i];
1941
+ const callback = params[params.length - 1];
1942
+ if (typeof callback === "function") callback(err);
1943
+ }
1944
+ }
1945
+ function onError(sender, err, cb) {
1946
+ callCallbacks(sender, err, cb);
1947
+ sender.onerror(err);
1948
+ }
1949
+ }
1950
+ });
1951
+
1952
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/event-target.js
1953
+ var require_event_target = __commonJS({
1954
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/event-target.js"(exports, module) {
1955
+ "use strict";
1956
+ var { kForOnEventAttribute, kListener } = require_constants();
1957
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1958
+ var kData = /* @__PURE__ */ Symbol("kData");
1959
+ var kError = /* @__PURE__ */ Symbol("kError");
1960
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1961
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1962
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1963
+ var kType = /* @__PURE__ */ Symbol("kType");
1964
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1965
+ var Event = class {
1966
+ /**
1967
+ * Create a new `Event`.
1968
+ *
1969
+ * @param {String} type The name of the event
1970
+ * @throws {TypeError} If the `type` argument is not specified
1971
+ */
1972
+ constructor(type) {
1973
+ this[kTarget] = null;
1974
+ this[kType] = type;
1975
+ }
1976
+ /**
1977
+ * @type {*}
1978
+ */
1979
+ get target() {
1980
+ return this[kTarget];
1981
+ }
1982
+ /**
1983
+ * @type {String}
1984
+ */
1985
+ get type() {
1986
+ return this[kType];
1987
+ }
1988
+ };
1989
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1990
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1991
+ var CloseEvent = class extends Event {
1992
+ /**
1993
+ * Create a new `CloseEvent`.
1994
+ *
1995
+ * @param {String} type The name of the event
1996
+ * @param {Object} [options] A dictionary object that allows for setting
1997
+ * attributes via object members of the same name
1998
+ * @param {Number} [options.code=0] The status code explaining why the
1999
+ * connection was closed
2000
+ * @param {String} [options.reason=''] A human-readable string explaining why
2001
+ * the connection was closed
2002
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
2003
+ * connection was cleanly closed
2004
+ */
2005
+ constructor(type, options = {}) {
2006
+ super(type);
2007
+ this[kCode] = options.code === void 0 ? 0 : options.code;
2008
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
2009
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
2010
+ }
2011
+ /**
2012
+ * @type {Number}
2013
+ */
2014
+ get code() {
2015
+ return this[kCode];
2016
+ }
2017
+ /**
2018
+ * @type {String}
2019
+ */
2020
+ get reason() {
2021
+ return this[kReason];
2022
+ }
2023
+ /**
2024
+ * @type {Boolean}
2025
+ */
2026
+ get wasClean() {
2027
+ return this[kWasClean];
2028
+ }
2029
+ };
2030
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
2031
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
2032
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
2033
+ var ErrorEvent = class extends Event {
2034
+ /**
2035
+ * Create a new `ErrorEvent`.
2036
+ *
2037
+ * @param {String} type The name of the event
2038
+ * @param {Object} [options] A dictionary object that allows for setting
2039
+ * attributes via object members of the same name
2040
+ * @param {*} [options.error=null] The error that generated this event
2041
+ * @param {String} [options.message=''] The error message
2042
+ */
2043
+ constructor(type, options = {}) {
2044
+ super(type);
2045
+ this[kError] = options.error === void 0 ? null : options.error;
2046
+ this[kMessage] = options.message === void 0 ? "" : options.message;
2047
+ }
2048
+ /**
2049
+ * @type {*}
2050
+ */
2051
+ get error() {
2052
+ return this[kError];
2053
+ }
2054
+ /**
2055
+ * @type {String}
2056
+ */
2057
+ get message() {
2058
+ return this[kMessage];
2059
+ }
2060
+ };
2061
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2062
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2063
+ var MessageEvent = class extends Event {
2064
+ /**
2065
+ * Create a new `MessageEvent`.
2066
+ *
2067
+ * @param {String} type The name of the event
2068
+ * @param {Object} [options] A dictionary object that allows for setting
2069
+ * attributes via object members of the same name
2070
+ * @param {*} [options.data=null] The message content
2071
+ */
2072
+ constructor(type, options = {}) {
2073
+ super(type);
2074
+ this[kData] = options.data === void 0 ? null : options.data;
2075
+ }
2076
+ /**
2077
+ * @type {*}
2078
+ */
2079
+ get data() {
2080
+ return this[kData];
2081
+ }
2082
+ };
2083
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2084
+ var EventTarget = {
2085
+ /**
2086
+ * Register an event listener.
2087
+ *
2088
+ * @param {String} type A string representing the event type to listen for
2089
+ * @param {(Function|Object)} handler The listener to add
2090
+ * @param {Object} [options] An options object specifies characteristics about
2091
+ * the event listener
2092
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2093
+ * listener should be invoked at most once after being added. If `true`,
2094
+ * the listener would be automatically removed when invoked.
2095
+ * @public
2096
+ */
2097
+ addEventListener(type, handler, options = {}) {
2098
+ for (const listener of this.listeners(type)) {
2099
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2100
+ return;
2101
+ }
2102
+ }
2103
+ let wrapper;
2104
+ if (type === "message") {
2105
+ wrapper = function onMessage(data, isBinary) {
2106
+ const event = new MessageEvent("message", {
2107
+ data: isBinary ? data : data.toString()
2108
+ });
2109
+ event[kTarget] = this;
2110
+ callListener(handler, this, event);
2111
+ };
2112
+ } else if (type === "close") {
2113
+ wrapper = function onClose(code, message) {
2114
+ const event = new CloseEvent("close", {
2115
+ code,
2116
+ reason: message.toString(),
2117
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2118
+ });
2119
+ event[kTarget] = this;
2120
+ callListener(handler, this, event);
2121
+ };
2122
+ } else if (type === "error") {
2123
+ wrapper = function onError(error) {
2124
+ const event = new ErrorEvent("error", {
2125
+ error,
2126
+ message: error.message
2127
+ });
2128
+ event[kTarget] = this;
2129
+ callListener(handler, this, event);
2130
+ };
2131
+ } else if (type === "open") {
2132
+ wrapper = function onOpen() {
2133
+ const event = new Event("open");
2134
+ event[kTarget] = this;
2135
+ callListener(handler, this, event);
2136
+ };
2137
+ } else {
2138
+ return;
2139
+ }
2140
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2141
+ wrapper[kListener] = handler;
2142
+ if (options.once) {
2143
+ this.once(type, wrapper);
2144
+ } else {
2145
+ this.on(type, wrapper);
2146
+ }
2147
+ },
2148
+ /**
2149
+ * Remove an event listener.
2150
+ *
2151
+ * @param {String} type A string representing the event type to remove
2152
+ * @param {(Function|Object)} handler The listener to remove
2153
+ * @public
2154
+ */
2155
+ removeEventListener(type, handler) {
2156
+ for (const listener of this.listeners(type)) {
2157
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2158
+ this.removeListener(type, listener);
2159
+ break;
2160
+ }
2161
+ }
2162
+ }
2163
+ };
2164
+ module.exports = {
2165
+ CloseEvent,
2166
+ ErrorEvent,
2167
+ Event,
2168
+ EventTarget,
2169
+ MessageEvent
2170
+ };
2171
+ function callListener(listener, thisArg, event) {
2172
+ if (typeof listener === "object" && listener.handleEvent) {
2173
+ listener.handleEvent.call(listener, event);
2174
+ } else {
2175
+ listener.call(thisArg, event);
2176
+ }
2177
+ }
2178
+ }
2179
+ });
2180
+
2181
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/extension.js
2182
+ var require_extension = __commonJS({
2183
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/extension.js"(exports, module) {
2184
+ "use strict";
2185
+ var { tokenChars } = require_validation();
2186
+ function push(dest, name, elem) {
2187
+ if (dest[name] === void 0) dest[name] = [elem];
2188
+ else dest[name].push(elem);
2189
+ }
2190
+ function parse(header) {
2191
+ const offers = /* @__PURE__ */ Object.create(null);
2192
+ let params = /* @__PURE__ */ Object.create(null);
2193
+ let mustUnescape = false;
2194
+ let isEscaping = false;
2195
+ let inQuotes = false;
2196
+ let extensionName;
2197
+ let paramName;
2198
+ let start = -1;
2199
+ let code = -1;
2200
+ let end = -1;
2201
+ let i = 0;
2202
+ for (; i < header.length; i++) {
2203
+ code = header.charCodeAt(i);
2204
+ if (extensionName === void 0) {
2205
+ if (end === -1 && tokenChars[code] === 1) {
2206
+ if (start === -1) start = i;
2207
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2208
+ if (end === -1 && start !== -1) end = i;
2209
+ } else if (code === 59 || code === 44) {
2210
+ if (start === -1) {
2211
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2212
+ }
2213
+ if (end === -1) end = i;
2214
+ const name = header.slice(start, end);
2215
+ if (code === 44) {
2216
+ push(offers, name, params);
2217
+ params = /* @__PURE__ */ Object.create(null);
2218
+ } else {
2219
+ extensionName = name;
2220
+ }
2221
+ start = end = -1;
2222
+ } else {
2223
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2224
+ }
2225
+ } else if (paramName === void 0) {
2226
+ if (end === -1 && tokenChars[code] === 1) {
2227
+ if (start === -1) start = i;
2228
+ } else if (code === 32 || code === 9) {
2229
+ if (end === -1 && start !== -1) end = i;
2230
+ } else if (code === 59 || code === 44) {
2231
+ if (start === -1) {
2232
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2233
+ }
2234
+ if (end === -1) end = i;
2235
+ push(params, header.slice(start, end), true);
2236
+ if (code === 44) {
2237
+ push(offers, extensionName, params);
2238
+ params = /* @__PURE__ */ Object.create(null);
2239
+ extensionName = void 0;
2240
+ }
2241
+ start = end = -1;
2242
+ } else if (code === 61 && start !== -1 && end === -1) {
2243
+ paramName = header.slice(start, i);
2244
+ start = end = -1;
2245
+ } else {
2246
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2247
+ }
2248
+ } else {
2249
+ if (isEscaping) {
2250
+ if (tokenChars[code] !== 1) {
2251
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2252
+ }
2253
+ if (start === -1) start = i;
2254
+ else if (!mustUnescape) mustUnescape = true;
2255
+ isEscaping = false;
2256
+ } else if (inQuotes) {
2257
+ if (tokenChars[code] === 1) {
2258
+ if (start === -1) start = i;
2259
+ } else if (code === 34 && start !== -1) {
2260
+ inQuotes = false;
2261
+ end = i;
2262
+ } else if (code === 92) {
2263
+ isEscaping = true;
2264
+ } else {
2265
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2266
+ }
2267
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2268
+ inQuotes = true;
2269
+ } else if (end === -1 && tokenChars[code] === 1) {
2270
+ if (start === -1) start = i;
2271
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2272
+ if (end === -1) end = i;
2273
+ } else if (code === 59 || code === 44) {
2274
+ if (start === -1) {
2275
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2276
+ }
2277
+ if (end === -1) end = i;
2278
+ let value = header.slice(start, end);
2279
+ if (mustUnescape) {
2280
+ value = value.replace(/\\/g, "");
2281
+ mustUnescape = false;
2282
+ }
2283
+ push(params, paramName, value);
2284
+ if (code === 44) {
2285
+ push(offers, extensionName, params);
2286
+ params = /* @__PURE__ */ Object.create(null);
2287
+ extensionName = void 0;
2288
+ }
2289
+ paramName = void 0;
2290
+ start = end = -1;
2291
+ } else {
2292
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2293
+ }
2294
+ }
2295
+ }
2296
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2297
+ throw new SyntaxError("Unexpected end of input");
2298
+ }
2299
+ if (end === -1) end = i;
2300
+ const token = header.slice(start, end);
2301
+ if (extensionName === void 0) {
2302
+ push(offers, token, params);
2303
+ } else {
2304
+ if (paramName === void 0) {
2305
+ push(params, token, true);
2306
+ } else if (mustUnescape) {
2307
+ push(params, paramName, token.replace(/\\/g, ""));
2308
+ } else {
2309
+ push(params, paramName, token);
2310
+ }
2311
+ push(offers, extensionName, params);
2312
+ }
2313
+ return offers;
2314
+ }
2315
+ function format(extensions) {
2316
+ return Object.keys(extensions).map((extension) => {
2317
+ let configurations = extensions[extension];
2318
+ if (!Array.isArray(configurations)) configurations = [configurations];
2319
+ return configurations.map((params) => {
2320
+ return [extension].concat(
2321
+ Object.keys(params).map((k) => {
2322
+ let values = params[k];
2323
+ if (!Array.isArray(values)) values = [values];
2324
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2325
+ })
2326
+ ).join("; ");
2327
+ }).join(", ");
2328
+ }).join(", ");
2329
+ }
2330
+ module.exports = { format, parse };
2331
+ }
2332
+ });
2333
+
2334
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/websocket.js
2335
+ var require_websocket = __commonJS({
2336
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/websocket.js"(exports, module) {
2337
+ "use strict";
2338
+ var EventEmitter = __require("events");
2339
+ var https = __require("https");
2340
+ var http = __require("http");
2341
+ var net = __require("net");
2342
+ var tls = __require("tls");
2343
+ var { randomBytes, createHash } = __require("crypto");
2344
+ var { Duplex, Readable } = __require("stream");
2345
+ var { URL: URL2 } = __require("url");
2346
+ var PerMessageDeflate = require_permessage_deflate();
2347
+ var Receiver2 = require_receiver();
2348
+ var Sender2 = require_sender();
2349
+ var { isBlob } = require_validation();
2350
+ var {
2351
+ BINARY_TYPES,
2352
+ EMPTY_BUFFER,
2353
+ GUID,
2354
+ kForOnEventAttribute,
2355
+ kListener,
2356
+ kStatusCode,
2357
+ kWebSocket,
2358
+ NOOP
2359
+ } = require_constants();
2360
+ var {
2361
+ EventTarget: { addEventListener, removeEventListener }
2362
+ } = require_event_target();
2363
+ var { format, parse } = require_extension();
2364
+ var { toBuffer } = require_buffer_util();
2365
+ var closeTimeout = 30 * 1e3;
2366
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2367
+ var protocolVersions = [8, 13];
2368
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2369
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2370
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2371
+ /**
2372
+ * Create a new `WebSocket`.
2373
+ *
2374
+ * @param {(String|URL)} address The URL to which to connect
2375
+ * @param {(String|String[])} [protocols] The subprotocols
2376
+ * @param {Object} [options] Connection options
2377
+ */
2378
+ constructor(address, protocols, options) {
2379
+ super();
2380
+ this._binaryType = BINARY_TYPES[0];
2381
+ this._closeCode = 1006;
2382
+ this._closeFrameReceived = false;
2383
+ this._closeFrameSent = false;
2384
+ this._closeMessage = EMPTY_BUFFER;
2385
+ this._closeTimer = null;
2386
+ this._errorEmitted = false;
2387
+ this._extensions = {};
2388
+ this._paused = false;
2389
+ this._protocol = "";
2390
+ this._readyState = _WebSocket.CONNECTING;
2391
+ this._receiver = null;
2392
+ this._sender = null;
2393
+ this._socket = null;
2394
+ if (address !== null) {
2395
+ this._bufferedAmount = 0;
2396
+ this._isServer = false;
2397
+ this._redirects = 0;
2398
+ if (protocols === void 0) {
2399
+ protocols = [];
2400
+ } else if (!Array.isArray(protocols)) {
2401
+ if (typeof protocols === "object" && protocols !== null) {
2402
+ options = protocols;
2403
+ protocols = [];
2404
+ } else {
2405
+ protocols = [protocols];
2406
+ }
2407
+ }
2408
+ initAsClient(this, address, protocols, options);
2409
+ } else {
2410
+ this._autoPong = options.autoPong;
2411
+ this._isServer = true;
2412
+ }
2413
+ }
2414
+ /**
2415
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2416
+ * instead of "blob".
2417
+ *
2418
+ * @type {String}
2419
+ */
2420
+ get binaryType() {
2421
+ return this._binaryType;
2422
+ }
2423
+ set binaryType(type) {
2424
+ if (!BINARY_TYPES.includes(type)) return;
2425
+ this._binaryType = type;
2426
+ if (this._receiver) this._receiver._binaryType = type;
2427
+ }
2428
+ /**
2429
+ * @type {Number}
2430
+ */
2431
+ get bufferedAmount() {
2432
+ if (!this._socket) return this._bufferedAmount;
2433
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2434
+ }
2435
+ /**
2436
+ * @type {String}
2437
+ */
2438
+ get extensions() {
2439
+ return Object.keys(this._extensions).join();
2440
+ }
2441
+ /**
2442
+ * @type {Boolean}
2443
+ */
2444
+ get isPaused() {
2445
+ return this._paused;
2446
+ }
2447
+ /**
2448
+ * @type {Function}
2449
+ */
2450
+ /* istanbul ignore next */
2451
+ get onclose() {
2452
+ return null;
2453
+ }
2454
+ /**
2455
+ * @type {Function}
2456
+ */
2457
+ /* istanbul ignore next */
2458
+ get onerror() {
2459
+ return null;
2460
+ }
2461
+ /**
2462
+ * @type {Function}
2463
+ */
2464
+ /* istanbul ignore next */
2465
+ get onopen() {
2466
+ return null;
2467
+ }
2468
+ /**
2469
+ * @type {Function}
2470
+ */
2471
+ /* istanbul ignore next */
2472
+ get onmessage() {
2473
+ return null;
2474
+ }
2475
+ /**
2476
+ * @type {String}
2477
+ */
2478
+ get protocol() {
2479
+ return this._protocol;
2480
+ }
2481
+ /**
2482
+ * @type {Number}
2483
+ */
2484
+ get readyState() {
2485
+ return this._readyState;
2486
+ }
2487
+ /**
2488
+ * @type {String}
2489
+ */
2490
+ get url() {
2491
+ return this._url;
2492
+ }
2493
+ /**
2494
+ * Set up the socket and the internal resources.
2495
+ *
2496
+ * @param {Duplex} socket The network socket between the server and client
2497
+ * @param {Buffer} head The first packet of the upgraded stream
2498
+ * @param {Object} options Options object
2499
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2500
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2501
+ * multiple times in the same tick
2502
+ * @param {Function} [options.generateMask] The function used to generate the
2503
+ * masking key
2504
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2505
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2506
+ * not to skip UTF-8 validation for text and close messages
2507
+ * @private
2508
+ */
2509
+ setSocket(socket, head, options) {
2510
+ const receiver = new Receiver2({
2511
+ allowSynchronousEvents: options.allowSynchronousEvents,
2512
+ binaryType: this.binaryType,
2513
+ extensions: this._extensions,
2514
+ isServer: this._isServer,
2515
+ maxPayload: options.maxPayload,
2516
+ skipUTF8Validation: options.skipUTF8Validation
2517
+ });
2518
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2519
+ this._receiver = receiver;
2520
+ this._sender = sender;
2521
+ this._socket = socket;
2522
+ receiver[kWebSocket] = this;
2523
+ sender[kWebSocket] = this;
2524
+ socket[kWebSocket] = this;
2525
+ receiver.on("conclude", receiverOnConclude);
2526
+ receiver.on("drain", receiverOnDrain);
2527
+ receiver.on("error", receiverOnError);
2528
+ receiver.on("message", receiverOnMessage);
2529
+ receiver.on("ping", receiverOnPing);
2530
+ receiver.on("pong", receiverOnPong);
2531
+ sender.onerror = senderOnError;
2532
+ if (socket.setTimeout) socket.setTimeout(0);
2533
+ if (socket.setNoDelay) socket.setNoDelay();
2534
+ if (head.length > 0) socket.unshift(head);
2535
+ socket.on("close", socketOnClose);
2536
+ socket.on("data", socketOnData);
2537
+ socket.on("end", socketOnEnd);
2538
+ socket.on("error", socketOnError);
2539
+ this._readyState = _WebSocket.OPEN;
2540
+ this.emit("open");
2541
+ }
2542
+ /**
2543
+ * Emit the `'close'` event.
2544
+ *
2545
+ * @private
2546
+ */
2547
+ emitClose() {
2548
+ if (!this._socket) {
2549
+ this._readyState = _WebSocket.CLOSED;
2550
+ this.emit("close", this._closeCode, this._closeMessage);
2551
+ return;
2552
+ }
2553
+ if (this._extensions[PerMessageDeflate.extensionName]) {
2554
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
2555
+ }
2556
+ this._receiver.removeAllListeners();
2557
+ this._readyState = _WebSocket.CLOSED;
2558
+ this.emit("close", this._closeCode, this._closeMessage);
2559
+ }
2560
+ /**
2561
+ * Start a closing handshake.
2562
+ *
2563
+ * +----------+ +-----------+ +----------+
2564
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2565
+ * | +----------+ +-----------+ +----------+ |
2566
+ * +----------+ +-----------+ |
2567
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2568
+ * +----------+ +-----------+ |
2569
+ * | | | +---+ |
2570
+ * +------------------------+-->|fin| - - - -
2571
+ * | +---+ | +---+
2572
+ * - - - - -|fin|<---------------------+
2573
+ * +---+
2574
+ *
2575
+ * @param {Number} [code] Status code explaining why the connection is closing
2576
+ * @param {(String|Buffer)} [data] The reason why the connection is
2577
+ * closing
2578
+ * @public
2579
+ */
2580
+ close(code, data) {
2581
+ if (this.readyState === _WebSocket.CLOSED) return;
2582
+ if (this.readyState === _WebSocket.CONNECTING) {
2583
+ const msg = "WebSocket was closed before the connection was established";
2584
+ abortHandshake(this, this._req, msg);
2585
+ return;
2586
+ }
2587
+ if (this.readyState === _WebSocket.CLOSING) {
2588
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2589
+ this._socket.end();
2590
+ }
2591
+ return;
2592
+ }
2593
+ this._readyState = _WebSocket.CLOSING;
2594
+ this._sender.close(code, data, !this._isServer, (err) => {
2595
+ if (err) return;
2596
+ this._closeFrameSent = true;
2597
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2598
+ this._socket.end();
2599
+ }
2600
+ });
2601
+ setCloseTimer(this);
2602
+ }
2603
+ /**
2604
+ * Pause the socket.
2605
+ *
2606
+ * @public
2607
+ */
2608
+ pause() {
2609
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2610
+ return;
2611
+ }
2612
+ this._paused = true;
2613
+ this._socket.pause();
2614
+ }
2615
+ /**
2616
+ * Send a ping.
2617
+ *
2618
+ * @param {*} [data] The data to send
2619
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2620
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2621
+ * @public
2622
+ */
2623
+ ping(data, mask, cb) {
2624
+ if (this.readyState === _WebSocket.CONNECTING) {
2625
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2626
+ }
2627
+ if (typeof data === "function") {
2628
+ cb = data;
2629
+ data = mask = void 0;
2630
+ } else if (typeof mask === "function") {
2631
+ cb = mask;
2632
+ mask = void 0;
2633
+ }
2634
+ if (typeof data === "number") data = data.toString();
2635
+ if (this.readyState !== _WebSocket.OPEN) {
2636
+ sendAfterClose(this, data, cb);
2637
+ return;
2638
+ }
2639
+ if (mask === void 0) mask = !this._isServer;
2640
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2641
+ }
2642
+ /**
2643
+ * Send a pong.
2644
+ *
2645
+ * @param {*} [data] The data to send
2646
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2647
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2648
+ * @public
2649
+ */
2650
+ pong(data, mask, cb) {
2651
+ if (this.readyState === _WebSocket.CONNECTING) {
2652
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2653
+ }
2654
+ if (typeof data === "function") {
2655
+ cb = data;
2656
+ data = mask = void 0;
2657
+ } else if (typeof mask === "function") {
2658
+ cb = mask;
2659
+ mask = void 0;
2660
+ }
2661
+ if (typeof data === "number") data = data.toString();
2662
+ if (this.readyState !== _WebSocket.OPEN) {
2663
+ sendAfterClose(this, data, cb);
2664
+ return;
2665
+ }
2666
+ if (mask === void 0) mask = !this._isServer;
2667
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2668
+ }
2669
+ /**
2670
+ * Resume the socket.
2671
+ *
2672
+ * @public
2673
+ */
2674
+ resume() {
2675
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2676
+ return;
2677
+ }
2678
+ this._paused = false;
2679
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2680
+ }
2681
+ /**
2682
+ * Send a data message.
2683
+ *
2684
+ * @param {*} data The message to send
2685
+ * @param {Object} [options] Options object
2686
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2687
+ * text
2688
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2689
+ * `data`
2690
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2691
+ * last one
2692
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2693
+ * @param {Function} [cb] Callback which is executed when data is written out
2694
+ * @public
2695
+ */
2696
+ send(data, options, cb) {
2697
+ if (this.readyState === _WebSocket.CONNECTING) {
2698
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2699
+ }
2700
+ if (typeof options === "function") {
2701
+ cb = options;
2702
+ options = {};
2703
+ }
2704
+ if (typeof data === "number") data = data.toString();
2705
+ if (this.readyState !== _WebSocket.OPEN) {
2706
+ sendAfterClose(this, data, cb);
2707
+ return;
2708
+ }
2709
+ const opts = {
2710
+ binary: typeof data !== "string",
2711
+ mask: !this._isServer,
2712
+ compress: true,
2713
+ fin: true,
2714
+ ...options
2715
+ };
2716
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
2717
+ opts.compress = false;
2718
+ }
2719
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2720
+ }
2721
+ /**
2722
+ * Forcibly close the connection.
2723
+ *
2724
+ * @public
2725
+ */
2726
+ terminate() {
2727
+ if (this.readyState === _WebSocket.CLOSED) return;
2728
+ if (this.readyState === _WebSocket.CONNECTING) {
2729
+ const msg = "WebSocket was closed before the connection was established";
2730
+ abortHandshake(this, this._req, msg);
2731
+ return;
2732
+ }
2733
+ if (this._socket) {
2734
+ this._readyState = _WebSocket.CLOSING;
2735
+ this._socket.destroy();
2736
+ }
2737
+ }
2738
+ };
2739
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2740
+ enumerable: true,
2741
+ value: readyStates.indexOf("CONNECTING")
2742
+ });
2743
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2744
+ enumerable: true,
2745
+ value: readyStates.indexOf("CONNECTING")
2746
+ });
2747
+ Object.defineProperty(WebSocket2, "OPEN", {
2748
+ enumerable: true,
2749
+ value: readyStates.indexOf("OPEN")
2750
+ });
2751
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2752
+ enumerable: true,
2753
+ value: readyStates.indexOf("OPEN")
2754
+ });
2755
+ Object.defineProperty(WebSocket2, "CLOSING", {
2756
+ enumerable: true,
2757
+ value: readyStates.indexOf("CLOSING")
2758
+ });
2759
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2760
+ enumerable: true,
2761
+ value: readyStates.indexOf("CLOSING")
2762
+ });
2763
+ Object.defineProperty(WebSocket2, "CLOSED", {
2764
+ enumerable: true,
2765
+ value: readyStates.indexOf("CLOSED")
2766
+ });
2767
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2768
+ enumerable: true,
2769
+ value: readyStates.indexOf("CLOSED")
2770
+ });
2771
+ [
2772
+ "binaryType",
2773
+ "bufferedAmount",
2774
+ "extensions",
2775
+ "isPaused",
2776
+ "protocol",
2777
+ "readyState",
2778
+ "url"
2779
+ ].forEach((property) => {
2780
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2781
+ });
2782
+ ["open", "error", "close", "message"].forEach((method) => {
2783
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2784
+ enumerable: true,
2785
+ get() {
2786
+ for (const listener of this.listeners(method)) {
2787
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2788
+ }
2789
+ return null;
2790
+ },
2791
+ set(handler) {
2792
+ for (const listener of this.listeners(method)) {
2793
+ if (listener[kForOnEventAttribute]) {
2794
+ this.removeListener(method, listener);
2795
+ break;
2796
+ }
2797
+ }
2798
+ if (typeof handler !== "function") return;
2799
+ this.addEventListener(method, handler, {
2800
+ [kForOnEventAttribute]: true
2801
+ });
2802
+ }
2803
+ });
2804
+ });
2805
+ WebSocket2.prototype.addEventListener = addEventListener;
2806
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2807
+ module.exports = WebSocket2;
2808
+ function initAsClient(websocket, address, protocols, options) {
2809
+ const opts = {
2810
+ allowSynchronousEvents: true,
2811
+ autoPong: true,
2812
+ protocolVersion: protocolVersions[1],
2813
+ maxPayload: 100 * 1024 * 1024,
2814
+ skipUTF8Validation: false,
2815
+ perMessageDeflate: true,
2816
+ followRedirects: false,
2817
+ maxRedirects: 10,
2818
+ ...options,
2819
+ socketPath: void 0,
2820
+ hostname: void 0,
2821
+ protocol: void 0,
2822
+ timeout: void 0,
2823
+ method: "GET",
2824
+ host: void 0,
2825
+ path: void 0,
2826
+ port: void 0
2827
+ };
2828
+ websocket._autoPong = opts.autoPong;
2829
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2830
+ throw new RangeError(
2831
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2832
+ );
2833
+ }
2834
+ let parsedUrl;
2835
+ if (address instanceof URL2) {
2836
+ parsedUrl = address;
2837
+ } else {
2838
+ try {
2839
+ parsedUrl = new URL2(address);
2840
+ } catch (e) {
2841
+ throw new SyntaxError(`Invalid URL: ${address}`);
2842
+ }
2843
+ }
2844
+ if (parsedUrl.protocol === "http:") {
2845
+ parsedUrl.protocol = "ws:";
2846
+ } else if (parsedUrl.protocol === "https:") {
2847
+ parsedUrl.protocol = "wss:";
2848
+ }
2849
+ websocket._url = parsedUrl.href;
2850
+ const isSecure = parsedUrl.protocol === "wss:";
2851
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2852
+ let invalidUrlMessage;
2853
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2854
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
2855
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2856
+ invalidUrlMessage = "The URL's pathname is empty";
2857
+ } else if (parsedUrl.hash) {
2858
+ invalidUrlMessage = "The URL contains a fragment identifier";
2859
+ }
2860
+ if (invalidUrlMessage) {
2861
+ const err = new SyntaxError(invalidUrlMessage);
2862
+ if (websocket._redirects === 0) {
2863
+ throw err;
2864
+ } else {
2865
+ emitErrorAndClose(websocket, err);
2866
+ return;
2867
+ }
2868
+ }
2869
+ const defaultPort = isSecure ? 443 : 80;
2870
+ const key = randomBytes(16).toString("base64");
2871
+ const request = isSecure ? https.request : http.request;
2872
+ const protocolSet = /* @__PURE__ */ new Set();
2873
+ let perMessageDeflate;
2874
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2875
+ opts.defaultPort = opts.defaultPort || defaultPort;
2876
+ opts.port = parsedUrl.port || defaultPort;
2877
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2878
+ opts.headers = {
2879
+ ...opts.headers,
2880
+ "Sec-WebSocket-Version": opts.protocolVersion,
2881
+ "Sec-WebSocket-Key": key,
2882
+ Connection: "Upgrade",
2883
+ Upgrade: "websocket"
2884
+ };
2885
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2886
+ opts.timeout = opts.handshakeTimeout;
2887
+ if (opts.perMessageDeflate) {
2888
+ perMessageDeflate = new PerMessageDeflate(
2889
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2890
+ false,
2891
+ opts.maxPayload
2892
+ );
2893
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2894
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2895
+ });
2896
+ }
2897
+ if (protocols.length) {
2898
+ for (const protocol of protocols) {
2899
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2900
+ throw new SyntaxError(
2901
+ "An invalid or duplicated subprotocol was specified"
2902
+ );
2903
+ }
2904
+ protocolSet.add(protocol);
2905
+ }
2906
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2907
+ }
2908
+ if (opts.origin) {
2909
+ if (opts.protocolVersion < 13) {
2910
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2911
+ } else {
2912
+ opts.headers.Origin = opts.origin;
2913
+ }
2914
+ }
2915
+ if (parsedUrl.username || parsedUrl.password) {
2916
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2917
+ }
2918
+ if (isIpcUrl) {
2919
+ const parts = opts.path.split(":");
2920
+ opts.socketPath = parts[0];
2921
+ opts.path = parts[1];
2922
+ }
2923
+ let req;
2924
+ if (opts.followRedirects) {
2925
+ if (websocket._redirects === 0) {
2926
+ websocket._originalIpc = isIpcUrl;
2927
+ websocket._originalSecure = isSecure;
2928
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2929
+ const headers = options && options.headers;
2930
+ options = { ...options, headers: {} };
2931
+ if (headers) {
2932
+ for (const [key2, value] of Object.entries(headers)) {
2933
+ options.headers[key2.toLowerCase()] = value;
2934
+ }
2935
+ }
2936
+ } else if (websocket.listenerCount("redirect") === 0) {
2937
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2938
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2939
+ delete opts.headers.authorization;
2940
+ delete opts.headers.cookie;
2941
+ if (!isSameHost) delete opts.headers.host;
2942
+ opts.auth = void 0;
2943
+ }
2944
+ }
2945
+ if (opts.auth && !options.headers.authorization) {
2946
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2947
+ }
2948
+ req = websocket._req = request(opts);
2949
+ if (websocket._redirects) {
2950
+ websocket.emit("redirect", websocket.url, req);
2951
+ }
2952
+ } else {
2953
+ req = websocket._req = request(opts);
2954
+ }
2955
+ if (opts.timeout) {
2956
+ req.on("timeout", () => {
2957
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2958
+ });
2959
+ }
2960
+ req.on("error", (err) => {
2961
+ if (req === null || req[kAborted]) return;
2962
+ req = websocket._req = null;
2963
+ emitErrorAndClose(websocket, err);
2964
+ });
2965
+ req.on("response", (res) => {
2966
+ const location = res.headers.location;
2967
+ const statusCode = res.statusCode;
2968
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2969
+ if (++websocket._redirects > opts.maxRedirects) {
2970
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2971
+ return;
2972
+ }
2973
+ req.abort();
2974
+ let addr;
2975
+ try {
2976
+ addr = new URL2(location, address);
2977
+ } catch (e) {
2978
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2979
+ emitErrorAndClose(websocket, err);
2980
+ return;
2981
+ }
2982
+ initAsClient(websocket, addr, protocols, options);
2983
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2984
+ abortHandshake(
2985
+ websocket,
2986
+ req,
2987
+ `Unexpected server response: ${res.statusCode}`
2988
+ );
2989
+ }
2990
+ });
2991
+ req.on("upgrade", (res, socket, head) => {
2992
+ websocket.emit("upgrade", res);
2993
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2994
+ req = websocket._req = null;
2995
+ const upgrade = res.headers.upgrade;
2996
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2997
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2998
+ return;
2999
+ }
3000
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3001
+ if (res.headers["sec-websocket-accept"] !== digest) {
3002
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3003
+ return;
3004
+ }
3005
+ const serverProt = res.headers["sec-websocket-protocol"];
3006
+ let protError;
3007
+ if (serverProt !== void 0) {
3008
+ if (!protocolSet.size) {
3009
+ protError = "Server sent a subprotocol but none was requested";
3010
+ } else if (!protocolSet.has(serverProt)) {
3011
+ protError = "Server sent an invalid subprotocol";
3012
+ }
3013
+ } else if (protocolSet.size) {
3014
+ protError = "Server sent no subprotocol";
3015
+ }
3016
+ if (protError) {
3017
+ abortHandshake(websocket, socket, protError);
3018
+ return;
3019
+ }
3020
+ if (serverProt) websocket._protocol = serverProt;
3021
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
3022
+ if (secWebSocketExtensions !== void 0) {
3023
+ if (!perMessageDeflate) {
3024
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
3025
+ abortHandshake(websocket, socket, message);
3026
+ return;
3027
+ }
3028
+ let extensions;
3029
+ try {
3030
+ extensions = parse(secWebSocketExtensions);
3031
+ } catch (err) {
3032
+ const message = "Invalid Sec-WebSocket-Extensions header";
3033
+ abortHandshake(websocket, socket, message);
3034
+ return;
3035
+ }
3036
+ const extensionNames = Object.keys(extensions);
3037
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
3038
+ const message = "Server indicated an extension that was not requested";
3039
+ abortHandshake(websocket, socket, message);
3040
+ return;
3041
+ }
3042
+ try {
3043
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
3044
+ } catch (err) {
3045
+ const message = "Invalid Sec-WebSocket-Extensions header";
3046
+ abortHandshake(websocket, socket, message);
3047
+ return;
3048
+ }
3049
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3050
+ }
3051
+ websocket.setSocket(socket, head, {
3052
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3053
+ generateMask: opts.generateMask,
3054
+ maxPayload: opts.maxPayload,
3055
+ skipUTF8Validation: opts.skipUTF8Validation
3056
+ });
3057
+ });
3058
+ if (opts.finishRequest) {
3059
+ opts.finishRequest(req, websocket);
3060
+ } else {
3061
+ req.end();
3062
+ }
3063
+ }
3064
+ function emitErrorAndClose(websocket, err) {
3065
+ websocket._readyState = WebSocket2.CLOSING;
3066
+ websocket._errorEmitted = true;
3067
+ websocket.emit("error", err);
3068
+ websocket.emitClose();
3069
+ }
3070
+ function netConnect(options) {
3071
+ options.path = options.socketPath;
3072
+ return net.connect(options);
3073
+ }
3074
+ function tlsConnect(options) {
3075
+ options.path = void 0;
3076
+ if (!options.servername && options.servername !== "") {
3077
+ options.servername = net.isIP(options.host) ? "" : options.host;
3078
+ }
3079
+ return tls.connect(options);
3080
+ }
3081
+ function abortHandshake(websocket, stream, message) {
3082
+ websocket._readyState = WebSocket2.CLOSING;
3083
+ const err = new Error(message);
3084
+ Error.captureStackTrace(err, abortHandshake);
3085
+ if (stream.setHeader) {
3086
+ stream[kAborted] = true;
3087
+ stream.abort();
3088
+ if (stream.socket && !stream.socket.destroyed) {
3089
+ stream.socket.destroy();
3090
+ }
3091
+ process.nextTick(emitErrorAndClose, websocket, err);
3092
+ } else {
3093
+ stream.destroy(err);
3094
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3095
+ stream.once("close", websocket.emitClose.bind(websocket));
3096
+ }
3097
+ }
3098
+ function sendAfterClose(websocket, data, cb) {
3099
+ if (data) {
3100
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3101
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3102
+ else websocket._bufferedAmount += length;
3103
+ }
3104
+ if (cb) {
3105
+ const err = new Error(
3106
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3107
+ );
3108
+ process.nextTick(cb, err);
3109
+ }
3110
+ }
3111
+ function receiverOnConclude(code, reason) {
3112
+ const websocket = this[kWebSocket];
3113
+ websocket._closeFrameReceived = true;
3114
+ websocket._closeMessage = reason;
3115
+ websocket._closeCode = code;
3116
+ if (websocket._socket[kWebSocket] === void 0) return;
3117
+ websocket._socket.removeListener("data", socketOnData);
3118
+ process.nextTick(resume, websocket._socket);
3119
+ if (code === 1005) websocket.close();
3120
+ else websocket.close(code, reason);
3121
+ }
3122
+ function receiverOnDrain() {
3123
+ const websocket = this[kWebSocket];
3124
+ if (!websocket.isPaused) websocket._socket.resume();
3125
+ }
3126
+ function receiverOnError(err) {
3127
+ const websocket = this[kWebSocket];
3128
+ if (websocket._socket[kWebSocket] !== void 0) {
3129
+ websocket._socket.removeListener("data", socketOnData);
3130
+ process.nextTick(resume, websocket._socket);
3131
+ websocket.close(err[kStatusCode]);
3132
+ }
3133
+ if (!websocket._errorEmitted) {
3134
+ websocket._errorEmitted = true;
3135
+ websocket.emit("error", err);
3136
+ }
3137
+ }
3138
+ function receiverOnFinish() {
3139
+ this[kWebSocket].emitClose();
3140
+ }
3141
+ function receiverOnMessage(data, isBinary) {
3142
+ this[kWebSocket].emit("message", data, isBinary);
3143
+ }
3144
+ function receiverOnPing(data) {
3145
+ const websocket = this[kWebSocket];
3146
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3147
+ websocket.emit("ping", data);
3148
+ }
3149
+ function receiverOnPong(data) {
3150
+ this[kWebSocket].emit("pong", data);
3151
+ }
3152
+ function resume(stream) {
3153
+ stream.resume();
3154
+ }
3155
+ function senderOnError(err) {
3156
+ const websocket = this[kWebSocket];
3157
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3158
+ if (websocket.readyState === WebSocket2.OPEN) {
3159
+ websocket._readyState = WebSocket2.CLOSING;
3160
+ setCloseTimer(websocket);
3161
+ }
3162
+ this._socket.end();
3163
+ if (!websocket._errorEmitted) {
3164
+ websocket._errorEmitted = true;
3165
+ websocket.emit("error", err);
3166
+ }
3167
+ }
3168
+ function setCloseTimer(websocket) {
3169
+ websocket._closeTimer = setTimeout(
3170
+ websocket._socket.destroy.bind(websocket._socket),
3171
+ closeTimeout
3172
+ );
3173
+ }
3174
+ function socketOnClose() {
3175
+ const websocket = this[kWebSocket];
3176
+ this.removeListener("close", socketOnClose);
3177
+ this.removeListener("data", socketOnData);
3178
+ this.removeListener("end", socketOnEnd);
3179
+ websocket._readyState = WebSocket2.CLOSING;
3180
+ let chunk;
3181
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
3182
+ websocket._receiver.write(chunk);
3183
+ }
3184
+ websocket._receiver.end();
3185
+ this[kWebSocket] = void 0;
3186
+ clearTimeout(websocket._closeTimer);
3187
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3188
+ websocket.emitClose();
3189
+ } else {
3190
+ websocket._receiver.on("error", receiverOnFinish);
3191
+ websocket._receiver.on("finish", receiverOnFinish);
3192
+ }
3193
+ }
3194
+ function socketOnData(chunk) {
3195
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3196
+ this.pause();
3197
+ }
3198
+ }
3199
+ function socketOnEnd() {
3200
+ const websocket = this[kWebSocket];
3201
+ websocket._readyState = WebSocket2.CLOSING;
3202
+ websocket._receiver.end();
3203
+ this.end();
3204
+ }
3205
+ function socketOnError() {
3206
+ const websocket = this[kWebSocket];
3207
+ this.removeListener("error", socketOnError);
3208
+ this.on("error", NOOP);
3209
+ if (websocket) {
3210
+ websocket._readyState = WebSocket2.CLOSING;
3211
+ this.destroy();
3212
+ }
3213
+ }
3214
+ }
3215
+ });
3216
+
3217
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/subprotocol.js
3218
+ var require_subprotocol = __commonJS({
3219
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
3220
+ "use strict";
3221
+ var { tokenChars } = require_validation();
3222
+ function parse(header) {
3223
+ const protocols = /* @__PURE__ */ new Set();
3224
+ let start = -1;
3225
+ let end = -1;
3226
+ let i = 0;
3227
+ for (i; i < header.length; i++) {
3228
+ const code = header.charCodeAt(i);
3229
+ if (end === -1 && tokenChars[code] === 1) {
3230
+ if (start === -1) start = i;
3231
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3232
+ if (end === -1 && start !== -1) end = i;
3233
+ } else if (code === 44) {
3234
+ if (start === -1) {
3235
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3236
+ }
3237
+ if (end === -1) end = i;
3238
+ const protocol2 = header.slice(start, end);
3239
+ if (protocols.has(protocol2)) {
3240
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3241
+ }
3242
+ protocols.add(protocol2);
3243
+ start = end = -1;
3244
+ } else {
3245
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3246
+ }
3247
+ }
3248
+ if (start === -1 || end !== -1) {
3249
+ throw new SyntaxError("Unexpected end of input");
3250
+ }
3251
+ const protocol = header.slice(start, i);
3252
+ if (protocols.has(protocol)) {
3253
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3254
+ }
3255
+ protocols.add(protocol);
3256
+ return protocols;
3257
+ }
3258
+ module.exports = { parse };
3259
+ }
3260
+ });
3261
+
3262
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/websocket-server.js
3263
+ var require_websocket_server = __commonJS({
3264
+ "../../node_modules/.bun/ws@8.18.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
3265
+ "use strict";
3266
+ var EventEmitter = __require("events");
3267
+ var http = __require("http");
3268
+ var { Duplex } = __require("stream");
3269
+ var { createHash } = __require("crypto");
3270
+ var extension = require_extension();
3271
+ var PerMessageDeflate = require_permessage_deflate();
3272
+ var subprotocol = require_subprotocol();
3273
+ var WebSocket2 = require_websocket();
3274
+ var { GUID, kWebSocket } = require_constants();
3275
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3276
+ var RUNNING = 0;
3277
+ var CLOSING = 1;
3278
+ var CLOSED = 2;
3279
+ var WebSocketServer2 = class extends EventEmitter {
3280
+ /**
3281
+ * Create a `WebSocketServer` instance.
3282
+ *
3283
+ * @param {Object} options Configuration options
3284
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3285
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3286
+ * multiple times in the same tick
3287
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3288
+ * automatically send a pong in response to a ping
3289
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3290
+ * pending connections
3291
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3292
+ * track clients
3293
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3294
+ * @param {String} [options.host] The hostname where to bind the server
3295
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3296
+ * size
3297
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3298
+ * @param {String} [options.path] Accept only connections matching this path
3299
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3300
+ * permessage-deflate
3301
+ * @param {Number} [options.port] The port where to bind the server
3302
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3303
+ * server to use
3304
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3305
+ * not to skip UTF-8 validation for text and close messages
3306
+ * @param {Function} [options.verifyClient] A hook to reject connections
3307
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3308
+ * class to use. It must be the `WebSocket` class or class that extends it
3309
+ * @param {Function} [callback] A listener for the `listening` event
3310
+ */
3311
+ constructor(options, callback) {
3312
+ super();
3313
+ options = {
3314
+ allowSynchronousEvents: true,
3315
+ autoPong: true,
3316
+ maxPayload: 100 * 1024 * 1024,
3317
+ skipUTF8Validation: false,
3318
+ perMessageDeflate: false,
3319
+ handleProtocols: null,
3320
+ clientTracking: true,
3321
+ verifyClient: null,
3322
+ noServer: false,
3323
+ backlog: null,
3324
+ // use default (511 as implemented in net.js)
3325
+ server: null,
3326
+ host: null,
3327
+ path: null,
3328
+ port: null,
3329
+ WebSocket: WebSocket2,
3330
+ ...options
3331
+ };
3332
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3333
+ throw new TypeError(
3334
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3335
+ );
3336
+ }
3337
+ if (options.port != null) {
3338
+ this._server = http.createServer((req, res) => {
3339
+ const body = http.STATUS_CODES[426];
3340
+ res.writeHead(426, {
3341
+ "Content-Length": body.length,
3342
+ "Content-Type": "text/plain"
3343
+ });
3344
+ res.end(body);
3345
+ });
3346
+ this._server.listen(
3347
+ options.port,
3348
+ options.host,
3349
+ options.backlog,
3350
+ callback
3351
+ );
3352
+ } else if (options.server) {
3353
+ this._server = options.server;
3354
+ }
3355
+ if (this._server) {
3356
+ const emitConnection = this.emit.bind(this, "connection");
3357
+ this._removeListeners = addListeners(this._server, {
3358
+ listening: this.emit.bind(this, "listening"),
3359
+ error: this.emit.bind(this, "error"),
3360
+ upgrade: (req, socket, head) => {
3361
+ this.handleUpgrade(req, socket, head, emitConnection);
3362
+ }
3363
+ });
3364
+ }
3365
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3366
+ if (options.clientTracking) {
3367
+ this.clients = /* @__PURE__ */ new Set();
3368
+ this._shouldEmitClose = false;
3369
+ }
3370
+ this.options = options;
3371
+ this._state = RUNNING;
3372
+ }
3373
+ /**
3374
+ * Returns the bound address, the address family name, and port of the server
3375
+ * as reported by the operating system if listening on an IP socket.
3376
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3377
+ * returned as a string.
3378
+ *
3379
+ * @return {(Object|String|null)} The address of the server
3380
+ * @public
3381
+ */
3382
+ address() {
3383
+ if (this.options.noServer) {
3384
+ throw new Error('The server is operating in "noServer" mode');
3385
+ }
3386
+ if (!this._server) return null;
3387
+ return this._server.address();
3388
+ }
3389
+ /**
3390
+ * Stop the server from accepting new connections and emit the `'close'` event
3391
+ * when all existing connections are closed.
3392
+ *
3393
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3394
+ * @public
3395
+ */
3396
+ close(cb) {
3397
+ if (this._state === CLOSED) {
3398
+ if (cb) {
3399
+ this.once("close", () => {
3400
+ cb(new Error("The server is not running"));
3401
+ });
3402
+ }
3403
+ process.nextTick(emitClose, this);
3404
+ return;
3405
+ }
3406
+ if (cb) this.once("close", cb);
3407
+ if (this._state === CLOSING) return;
3408
+ this._state = CLOSING;
3409
+ if (this.options.noServer || this.options.server) {
3410
+ if (this._server) {
3411
+ this._removeListeners();
3412
+ this._removeListeners = this._server = null;
3413
+ }
3414
+ if (this.clients) {
3415
+ if (!this.clients.size) {
3416
+ process.nextTick(emitClose, this);
3417
+ } else {
3418
+ this._shouldEmitClose = true;
3419
+ }
3420
+ } else {
3421
+ process.nextTick(emitClose, this);
3422
+ }
3423
+ } else {
3424
+ const server = this._server;
3425
+ this._removeListeners();
3426
+ this._removeListeners = this._server = null;
3427
+ server.close(() => {
3428
+ emitClose(this);
3429
+ });
3430
+ }
3431
+ }
3432
+ /**
3433
+ * See if a given request should be handled by this server instance.
3434
+ *
3435
+ * @param {http.IncomingMessage} req Request object to inspect
3436
+ * @return {Boolean} `true` if the request is valid, else `false`
3437
+ * @public
3438
+ */
3439
+ shouldHandle(req) {
3440
+ if (this.options.path) {
3441
+ const index = req.url.indexOf("?");
3442
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3443
+ if (pathname !== this.options.path) return false;
3444
+ }
3445
+ return true;
3446
+ }
3447
+ /**
3448
+ * Handle a HTTP Upgrade request.
3449
+ *
3450
+ * @param {http.IncomingMessage} req The request object
3451
+ * @param {Duplex} socket The network socket between the server and client
3452
+ * @param {Buffer} head The first packet of the upgraded stream
3453
+ * @param {Function} cb Callback
3454
+ * @public
3455
+ */
3456
+ handleUpgrade(req, socket, head, cb) {
3457
+ socket.on("error", socketOnError);
3458
+ const key = req.headers["sec-websocket-key"];
3459
+ const upgrade = req.headers.upgrade;
3460
+ const version = +req.headers["sec-websocket-version"];
3461
+ if (req.method !== "GET") {
3462
+ const message = "Invalid HTTP method";
3463
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3464
+ return;
3465
+ }
3466
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3467
+ const message = "Invalid Upgrade header";
3468
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3469
+ return;
3470
+ }
3471
+ if (key === void 0 || !keyRegex.test(key)) {
3472
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3473
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3474
+ return;
3475
+ }
3476
+ if (version !== 8 && version !== 13) {
3477
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3478
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3479
+ return;
3480
+ }
3481
+ if (!this.shouldHandle(req)) {
3482
+ abortHandshake(socket, 400);
3483
+ return;
3484
+ }
3485
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3486
+ let protocols = /* @__PURE__ */ new Set();
3487
+ if (secWebSocketProtocol !== void 0) {
3488
+ try {
3489
+ protocols = subprotocol.parse(secWebSocketProtocol);
3490
+ } catch (err) {
3491
+ const message = "Invalid Sec-WebSocket-Protocol header";
3492
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3493
+ return;
3494
+ }
3495
+ }
3496
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3497
+ const extensions = {};
3498
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3499
+ const perMessageDeflate = new PerMessageDeflate(
3500
+ this.options.perMessageDeflate,
3501
+ true,
3502
+ this.options.maxPayload
3503
+ );
3504
+ try {
3505
+ const offers = extension.parse(secWebSocketExtensions);
3506
+ if (offers[PerMessageDeflate.extensionName]) {
3507
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3508
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3509
+ }
3510
+ } catch (err) {
3511
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3512
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3513
+ return;
3514
+ }
3515
+ }
3516
+ if (this.options.verifyClient) {
3517
+ const info = {
3518
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3519
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3520
+ req
3521
+ };
3522
+ if (this.options.verifyClient.length === 2) {
3523
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3524
+ if (!verified) {
3525
+ return abortHandshake(socket, code || 401, message, headers);
3526
+ }
3527
+ this.completeUpgrade(
3528
+ extensions,
3529
+ key,
3530
+ protocols,
3531
+ req,
3532
+ socket,
3533
+ head,
3534
+ cb
3535
+ );
3536
+ });
3537
+ return;
3538
+ }
3539
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3540
+ }
3541
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3542
+ }
3543
+ /**
3544
+ * Upgrade the connection to WebSocket.
3545
+ *
3546
+ * @param {Object} extensions The accepted extensions
3547
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3548
+ * @param {Set} protocols The subprotocols
3549
+ * @param {http.IncomingMessage} req The request object
3550
+ * @param {Duplex} socket The network socket between the server and client
3551
+ * @param {Buffer} head The first packet of the upgraded stream
3552
+ * @param {Function} cb Callback
3553
+ * @throws {Error} If called more than once with the same socket
3554
+ * @private
3555
+ */
3556
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3557
+ if (!socket.readable || !socket.writable) return socket.destroy();
3558
+ if (socket[kWebSocket]) {
3559
+ throw new Error(
3560
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3561
+ );
3562
+ }
3563
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3564
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3565
+ const headers = [
3566
+ "HTTP/1.1 101 Switching Protocols",
3567
+ "Upgrade: websocket",
3568
+ "Connection: Upgrade",
3569
+ `Sec-WebSocket-Accept: ${digest}`
3570
+ ];
3571
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3572
+ if (protocols.size) {
3573
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3574
+ if (protocol) {
3575
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3576
+ ws._protocol = protocol;
3577
+ }
3578
+ }
3579
+ if (extensions[PerMessageDeflate.extensionName]) {
3580
+ const params = extensions[PerMessageDeflate.extensionName].params;
3581
+ const value = extension.format({
3582
+ [PerMessageDeflate.extensionName]: [params]
3583
+ });
3584
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3585
+ ws._extensions = extensions;
3586
+ }
3587
+ this.emit("headers", headers, req);
3588
+ socket.write(headers.concat("\r\n").join("\r\n"));
3589
+ socket.removeListener("error", socketOnError);
3590
+ ws.setSocket(socket, head, {
3591
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3592
+ maxPayload: this.options.maxPayload,
3593
+ skipUTF8Validation: this.options.skipUTF8Validation
3594
+ });
3595
+ if (this.clients) {
3596
+ this.clients.add(ws);
3597
+ ws.on("close", () => {
3598
+ this.clients.delete(ws);
3599
+ if (this._shouldEmitClose && !this.clients.size) {
3600
+ process.nextTick(emitClose, this);
3601
+ }
3602
+ });
3603
+ }
3604
+ cb(ws, req);
3605
+ }
3606
+ };
3607
+ module.exports = WebSocketServer2;
3608
+ function addListeners(server, map) {
3609
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3610
+ return function removeListeners() {
3611
+ for (const event of Object.keys(map)) {
3612
+ server.removeListener(event, map[event]);
3613
+ }
3614
+ };
3615
+ }
3616
+ function emitClose(server) {
3617
+ server._state = CLOSED;
3618
+ server.emit("close");
3619
+ }
3620
+ function socketOnError() {
3621
+ this.destroy();
3622
+ }
3623
+ function abortHandshake(socket, code, message, headers) {
3624
+ message = message || http.STATUS_CODES[code];
3625
+ headers = {
3626
+ Connection: "close",
3627
+ "Content-Type": "text/html",
3628
+ "Content-Length": Buffer.byteLength(message),
3629
+ ...headers
3630
+ };
3631
+ socket.once("finish", socket.destroy);
3632
+ socket.end(
3633
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3634
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3635
+ );
3636
+ }
3637
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
3638
+ if (server.listenerCount("wsClientError")) {
3639
+ const err = new Error(message);
3640
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3641
+ server.emit("wsClientError", err, socket, req);
3642
+ } else {
3643
+ abortHandshake(socket, code, message);
3644
+ }
3645
+ }
3646
+ }
3647
+ });
3648
+
3649
+ // ../gateway-server/src/cluster.ts
3650
+ var AdapterBasedLock = class {
3651
+ adapter;
3652
+ instanceId;
3653
+ constructor(adapter, instanceId) {
3654
+ this.adapter = adapter;
3655
+ this.instanceId = instanceId ?? crypto.randomUUID();
3656
+ }
3657
+ async acquire(key, ttlMs) {
3658
+ try {
3659
+ const result = await this.adapter.insertDeltas([
3660
+ this.makeLockDelta("INSERT", key, [
3661
+ { column: "holder", value: this.instanceId },
3662
+ { column: "expires_at", value: Date.now() + ttlMs }
3663
+ ])
3664
+ ]);
3665
+ return result.ok;
3666
+ } catch {
3667
+ return false;
3668
+ }
3669
+ }
3670
+ async release(key) {
3671
+ try {
3672
+ await this.adapter.insertDeltas([this.makeLockDelta("DELETE", key, [])]);
3673
+ } catch {
3674
+ }
3675
+ }
3676
+ makeLockDelta(op, key, columns) {
3677
+ return {
3678
+ op,
3679
+ table: "__lakesync_locks",
3680
+ rowId: key,
3681
+ clientId: this.instanceId,
3682
+ columns,
3683
+ hlc: BigInt(Date.now()) << 16n,
3684
+ deltaId: `${op === "INSERT" ? "lock" : "unlock"}-${key}-${Date.now()}`
3685
+ };
3686
+ }
3687
+ };
3688
+
3689
+ // ../gateway-server/src/ingest/poller.ts
3690
+ var DEFAULT_INTERVAL_MS = 1e4;
3691
+ var DEFAULT_LOOKBACK_MS = 5e3;
3692
+ var LARGE_SNAPSHOT_WARN = 5e4;
3693
+ var SourcePoller = class {
3694
+ config;
3695
+ gateway;
3696
+ hlc;
3697
+ clientId;
3698
+ timer = null;
3699
+ running = false;
3700
+ /** Cursor state per table (keyed by table name). */
3701
+ cursorStates = /* @__PURE__ */ new Map();
3702
+ /** Diff snapshot per table (keyed by table name). */
3703
+ diffStates = /* @__PURE__ */ new Map();
3704
+ constructor(config, gateway) {
3705
+ this.config = config;
3706
+ this.gateway = gateway;
3707
+ this.hlc = new HLC();
3708
+ this.clientId = `ingest:${config.name}`;
3709
+ }
3710
+ /** Start the polling loop. */
3711
+ start() {
3712
+ if (this.running) return;
3713
+ this.running = true;
3714
+ this.schedulePoll();
3715
+ }
3716
+ /** Stop the polling loop. */
3717
+ stop() {
3718
+ this.running = false;
3719
+ if (this.timer) {
3720
+ clearTimeout(this.timer);
3721
+ this.timer = null;
3722
+ }
3723
+ }
3724
+ /** Whether the poller is currently running. */
3725
+ get isRunning() {
3726
+ return this.running;
3727
+ }
3728
+ // -----------------------------------------------------------------------
3729
+ // Poll scheduling (recursive setTimeout — no overlap)
3730
+ // -----------------------------------------------------------------------
3731
+ schedulePoll() {
3732
+ if (!this.running) return;
3733
+ this.timer = setTimeout(async () => {
3734
+ try {
3735
+ await this.poll();
3736
+ } catch {
3737
+ }
3738
+ this.schedulePoll();
3739
+ }, this.config.intervalMs ?? DEFAULT_INTERVAL_MS);
3740
+ }
3741
+ /** Execute a single poll cycle across all configured tables. */
3742
+ async poll() {
3743
+ const allDeltas = [];
3744
+ for (const table of this.config.tables) {
3745
+ const deltas = table.strategy.type === "cursor" ? await this.pollCursor(table) : await this.pollDiff(table);
3746
+ for (const d of deltas) {
3747
+ allDeltas.push(d);
3748
+ }
3749
+ }
3750
+ if (allDeltas.length === 0) return;
3751
+ const push = {
3752
+ clientId: this.clientId,
3753
+ deltas: allDeltas,
3754
+ lastSeenHlc: 0n
3755
+ };
3756
+ this.gateway.handlePush(push);
3757
+ }
3758
+ // -----------------------------------------------------------------------
3759
+ // Cursor strategy
3760
+ // -----------------------------------------------------------------------
3761
+ async pollCursor(tableConfig) {
3762
+ const strategy = tableConfig.strategy;
3763
+ if (strategy.type !== "cursor") return [];
3764
+ const rowIdCol = tableConfig.rowIdColumn ?? "id";
3765
+ const state = this.cursorStates.get(tableConfig.table);
3766
+ const lookbackMs = strategy.lookbackMs ?? DEFAULT_LOOKBACK_MS;
3767
+ let rows;
3768
+ if (state?.lastCursor != null) {
3769
+ let effectiveCursor = state.lastCursor;
3770
+ if (typeof effectiveCursor === "number") {
3771
+ effectiveCursor = effectiveCursor - lookbackMs;
3772
+ } else if (effectiveCursor instanceof Date) {
3773
+ effectiveCursor = new Date(effectiveCursor.getTime() - lookbackMs);
3774
+ } else if (typeof effectiveCursor === "string") {
3775
+ const parsed = Date.parse(effectiveCursor);
3776
+ if (!Number.isNaN(parsed)) {
3777
+ effectiveCursor = new Date(parsed - lookbackMs).toISOString();
3778
+ }
3779
+ }
3780
+ const sql = `SELECT * FROM (${tableConfig.query}) AS _src WHERE ${strategy.cursorColumn} > $1 ORDER BY ${strategy.cursorColumn} ASC`;
3781
+ rows = await this.config.queryFn(sql, [effectiveCursor]);
3782
+ } else {
3783
+ const sql = `SELECT * FROM (${tableConfig.query}) AS _src ORDER BY ${strategy.cursorColumn} ASC`;
3784
+ rows = await this.config.queryFn(sql);
3785
+ }
3786
+ if (rows.length === 0) return [];
3787
+ const lastRow = rows[rows.length - 1];
3788
+ const newCursor = lastRow[strategy.cursorColumn];
3789
+ this.cursorStates.set(tableConfig.table, { lastCursor: newCursor });
3790
+ const deltas = [];
3791
+ for (const row of rows) {
3792
+ const rowId = String(row[rowIdCol]);
3793
+ const after = { ...row };
3794
+ delete after[rowIdCol];
3795
+ const delta = await extractDelta(null, after, {
3796
+ table: tableConfig.table,
3797
+ rowId,
3798
+ clientId: this.clientId,
3799
+ hlc: this.hlc.now()
3800
+ });
3801
+ if (delta) {
3802
+ deltas.push(delta);
3803
+ }
3804
+ }
3805
+ return deltas;
3806
+ }
3807
+ // -----------------------------------------------------------------------
3808
+ // Diff strategy
3809
+ // -----------------------------------------------------------------------
3810
+ async pollDiff(tableConfig) {
3811
+ const rowIdCol = tableConfig.rowIdColumn ?? "id";
3812
+ const rows = await this.config.queryFn(tableConfig.query);
3813
+ const currentMap = /* @__PURE__ */ new Map();
3814
+ for (const row of rows) {
3815
+ const rowId = String(row[rowIdCol]);
3816
+ currentMap.set(rowId, row);
3817
+ }
3818
+ if (currentMap.size > LARGE_SNAPSHOT_WARN) {
3819
+ console.warn(
3820
+ `[lakesync:ingest] Diff snapshot for "${tableConfig.table}" has ${currentMap.size} rows (>50k). Consider using cursor strategy.`
3821
+ );
3822
+ }
3823
+ const state = this.diffStates.get(tableConfig.table);
3824
+ const previousMap = state?.snapshot ?? /* @__PURE__ */ new Map();
3825
+ const deltas = [];
3826
+ for (const [rowId, currentRow] of currentMap) {
3827
+ const previousRow = previousMap.get(rowId);
3828
+ const after = { ...currentRow };
3829
+ delete after[rowIdCol];
3830
+ let before = null;
3831
+ if (previousRow) {
3832
+ before = { ...previousRow };
3833
+ delete before[rowIdCol];
3834
+ }
3835
+ const delta = await extractDelta(before, after, {
3836
+ table: tableConfig.table,
3837
+ rowId,
3838
+ clientId: this.clientId,
3839
+ hlc: this.hlc.now()
3840
+ });
3841
+ if (delta) {
3842
+ deltas.push(delta);
3843
+ }
3844
+ }
3845
+ for (const [rowId, previousRow] of previousMap) {
3846
+ if (!currentMap.has(rowId)) {
3847
+ const before = { ...previousRow };
3848
+ delete before[rowIdCol];
3849
+ const delta = await extractDelta(before, null, {
3850
+ table: tableConfig.table,
3851
+ rowId,
3852
+ clientId: this.clientId,
3853
+ hlc: this.hlc.now()
3854
+ });
3855
+ if (delta) {
3856
+ deltas.push(delta);
3857
+ }
3858
+ }
3859
+ }
3860
+ this.diffStates.set(tableConfig.table, { snapshot: currentMap });
3861
+ return deltas;
3862
+ }
3863
+ };
3864
+
3865
+ // ../gateway-server/src/persistence.ts
3866
+ var MemoryPersistence = class {
3867
+ buffer = [];
3868
+ appendBatch(deltas) {
3869
+ this.buffer.push(...deltas);
3870
+ }
3871
+ loadAll() {
3872
+ return [...this.buffer];
3873
+ }
3874
+ clear() {
3875
+ this.buffer = [];
3876
+ }
3877
+ close() {
3878
+ this.buffer = [];
3879
+ }
3880
+ };
3881
+ var SqlitePersistence = class {
3882
+ db;
3883
+ constructor(path) {
3884
+ const Database = __require("better-sqlite3");
3885
+ this.db = new Database(path);
3886
+ this.db.pragma("journal_mode = WAL");
3887
+ this.db.exec(
3888
+ "CREATE TABLE IF NOT EXISTS unflushed_deltas (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)"
3889
+ );
3890
+ }
3891
+ appendBatch(deltas) {
3892
+ const stmt = this.db.prepare("INSERT INTO unflushed_deltas (data) VALUES (?)");
3893
+ const tx = this.db.transaction(() => {
3894
+ for (const delta of deltas) {
3895
+ stmt.run(JSON.stringify(delta, bigintReplacer));
3896
+ }
3897
+ });
3898
+ tx();
3899
+ }
3900
+ loadAll() {
3901
+ const rows = this.db.prepare("SELECT data FROM unflushed_deltas ORDER BY id").all();
3902
+ return rows.map((row) => JSON.parse(row.data, bigintReviver));
3903
+ }
3904
+ clear() {
3905
+ this.db.exec("DELETE FROM unflushed_deltas");
3906
+ }
3907
+ close() {
3908
+ this.db.close();
3909
+ }
3910
+ };
3911
+
3912
+ // ../gateway-server/src/server.ts
3913
+ import { createServer } from "http";
3914
+
3915
+ // ../../node_modules/.bun/ws@8.18.0/node_modules/ws/wrapper.mjs
3916
+ var import_stream = __toESM(require_stream(), 1);
3917
+ var import_receiver = __toESM(require_receiver(), 1);
3918
+ var import_sender = __toESM(require_sender(), 1);
3919
+ var import_websocket = __toESM(require_websocket(), 1);
3920
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3921
+
3922
+ // ../gateway-server/src/shared-buffer.ts
3923
+ var SharedBuffer = class {
3924
+ constructor(sharedAdapter) {
3925
+ this.sharedAdapter = sharedAdapter;
3926
+ }
3927
+ /**
3928
+ * Write-through push: write to shared adapter for cross-instance visibility.
3929
+ *
3930
+ * Gateway buffer handles fast reads; shared adapter handles
3931
+ * cross-instance visibility and durability.
3932
+ */
3933
+ async writeThroughPush(deltas) {
3934
+ try {
3935
+ await this.sharedAdapter.insertDeltas(deltas);
3936
+ } catch {
3937
+ }
3938
+ }
3939
+ /**
3940
+ * Merge pull: combine local buffer results with shared adapter results.
3941
+ *
3942
+ * Deduplicates by deltaId to avoid returning the same delta twice.
3943
+ */
3944
+ async mergePull(localResult, sinceHlc) {
3945
+ try {
3946
+ const adapterResult = await this.sharedAdapter.queryDeltasSince(sinceHlc);
3947
+ if (!adapterResult.ok) {
3948
+ return localResult;
3949
+ }
3950
+ const seenIds = new Set(localResult.deltas.map((d) => d.deltaId));
3951
+ const additional = adapterResult.value.filter((d) => !seenIds.has(d.deltaId));
3952
+ if (additional.length === 0) {
3953
+ return localResult;
3954
+ }
3955
+ const merged = [...localResult.deltas, ...additional];
3956
+ merged.sort((a, b) => a.hlc < b.hlc ? -1 : a.hlc > b.hlc ? 1 : 0);
3957
+ return {
3958
+ deltas: merged,
3959
+ serverHlc: localResult.serverHlc,
3960
+ hasMore: true
3961
+ };
3962
+ } catch {
3963
+ return localResult;
3964
+ }
3965
+ }
3966
+ };
3967
+
3968
+ // ../gateway-server/src/server.ts
3969
+ var DEFAULT_PORT = 3e3;
3970
+ var DEFAULT_FLUSH_INTERVAL_MS = 3e4;
3971
+ var ADMIN_ACTIONS = /* @__PURE__ */ new Set([
3972
+ "flush",
3973
+ "schema",
3974
+ "sync-rules",
3975
+ "register-connector",
3976
+ "unregister-connector",
3977
+ "list-connectors",
3978
+ "metrics"
3979
+ ]);
3980
+ var ROUTES = [
3981
+ ["POST", /^\/sync\/([^/]+)\/push$/, "push"],
3982
+ ["GET", /^\/sync\/([^/]+)\/pull$/, "pull"],
3983
+ ["POST", /^\/sync\/([^/]+)\/action$/, "action"],
3984
+ ["GET", /^\/sync\/([^/]+)\/actions$/, "describe-actions"],
3985
+ ["GET", /^\/sync\/([^/]+)\/ws$/, "ws"],
3986
+ ["POST", /^\/admin\/flush\/([^/]+)$/, "flush"],
3987
+ ["POST", /^\/admin\/schema\/([^/]+)$/, "schema"],
3988
+ ["POST", /^\/admin\/sync-rules\/([^/]+)$/, "sync-rules"],
3989
+ ["POST", /^\/admin\/connectors\/([^/]+)$/, "register-connector"],
3990
+ ["GET", /^\/admin\/connectors\/([^/]+)$/, "list-connectors"],
3991
+ ["DELETE", /^\/admin\/connectors\/([^/]+)\/([^/]+)$/, "unregister-connector", true],
3992
+ ["GET", /^\/admin\/metrics\/([^/]+)$/, "metrics"]
3993
+ ];
3994
+ function matchRoute(pathname, method) {
3995
+ for (const [m, pattern, action, hasConnector] of ROUTES) {
3996
+ if (method !== m) continue;
3997
+ const match = pathname.match(pattern);
3998
+ if (!match) continue;
3999
+ return {
4000
+ gatewayId: match[1],
4001
+ action,
4002
+ ...hasConnector ? { connectorName: match[2] } : {}
4003
+ };
4004
+ }
4005
+ return null;
4006
+ }
4007
+ function readBody(req) {
4008
+ return new Promise((resolve, reject) => {
4009
+ const chunks = [];
4010
+ req.on("data", (chunk) => chunks.push(chunk));
4011
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
4012
+ req.on("error", reject);
4013
+ });
4014
+ }
4015
+ function sendJson(res, body, status = 200, extraHeaders) {
4016
+ const json = JSON.stringify(body, bigintReplacer);
4017
+ res.writeHead(status, {
4018
+ "Content-Type": "application/json",
4019
+ ...extraHeaders
4020
+ });
4021
+ res.end(json);
4022
+ }
4023
+ function sendError(res, message, status, extraHeaders) {
4024
+ sendJson(res, { error: message }, status, extraHeaders);
4025
+ }
4026
+ function sendResult(res, result, corsH) {
4027
+ sendJson(res, result.body, result.status, corsH);
4028
+ }
4029
+ var GatewayServer = class {
4030
+ gateway;
4031
+ config;
4032
+ httpServer = null;
4033
+ flushTimer = null;
4034
+ configStore;
4035
+ persistence;
4036
+ resolvedPort = 0;
4037
+ wss = null;
4038
+ wsClients = /* @__PURE__ */ new Map();
4039
+ pollers = [];
4040
+ connectorAdapters = /* @__PURE__ */ new Map();
4041
+ connectorPollers = /* @__PURE__ */ new Map();
4042
+ sharedBuffer = null;
4043
+ constructor(config) {
4044
+ this.config = {
4045
+ port: config.port ?? DEFAULT_PORT,
4046
+ flushIntervalMs: config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
4047
+ ...config
4048
+ };
4049
+ this.gateway = new SyncGateway(
4050
+ {
4051
+ gatewayId: config.gatewayId,
4052
+ maxBufferBytes: config.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES,
4053
+ maxBufferAgeMs: config.maxBufferAgeMs ?? DEFAULT_MAX_BUFFER_AGE_MS
4054
+ },
4055
+ config.adapter
4056
+ );
4057
+ this.configStore = new MemoryConfigStore();
4058
+ this.persistence = config.persistence === "sqlite" ? new SqlitePersistence(config.sqlitePath ?? "./lakesync-buffer.sqlite") : new MemoryPersistence();
4059
+ if (config.cluster) {
4060
+ this.sharedBuffer = new SharedBuffer(config.cluster.sharedAdapter);
4061
+ }
4062
+ }
4063
+ /**
4064
+ * Start the HTTP server and periodic flush timer.
4065
+ *
4066
+ * Rehydrates unflushed deltas from the persistence layer before
4067
+ * accepting connections.
4068
+ */
4069
+ async start() {
4070
+ const persisted = this.persistence.loadAll();
4071
+ if (persisted.length > 0) {
4072
+ const push = {
4073
+ clientId: "__rehydrate__",
4074
+ deltas: persisted,
4075
+ lastSeenHlc: 0n
4076
+ };
4077
+ this.gateway.handlePush(push);
4078
+ this.persistence.clear();
4079
+ }
4080
+ this.httpServer = createServer((req, res) => {
4081
+ this.handleRequest(req, res);
4082
+ });
4083
+ await new Promise((resolve) => {
4084
+ this.httpServer.listen(this.config.port, () => {
4085
+ const addr = this.httpServer.address();
4086
+ if (addr && typeof addr === "object") {
4087
+ this.resolvedPort = addr.port;
4088
+ }
4089
+ resolve();
4090
+ });
4091
+ });
4092
+ this.wss = new import_websocket_server.default({ noServer: true });
4093
+ this.httpServer.on("upgrade", (req, socket, head) => {
4094
+ void this.handleUpgrade(req, socket, head);
4095
+ });
4096
+ this.flushTimer = setInterval(() => {
4097
+ this.periodicFlush();
4098
+ }, this.config.flushIntervalMs);
4099
+ if (this.config.ingestSources) {
4100
+ for (const source of this.config.ingestSources) {
4101
+ const poller = new SourcePoller(source, this.gateway);
4102
+ poller.start();
4103
+ this.pollers.push(poller);
4104
+ }
4105
+ }
4106
+ }
4107
+ /**
4108
+ * Handle HTTP -> WebSocket upgrade.
4109
+ *
4110
+ * Authenticates via Bearer token in Authorization header or `?token=` query param.
4111
+ */
4112
+ async handleUpgrade(req, socket, head) {
4113
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4114
+ let token = extractBearerToken(req);
4115
+ if (!token) {
4116
+ token = url.searchParams.get("token");
4117
+ }
4118
+ if (!token && this.config.jwtSecret) {
4119
+ socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
4120
+ socket.destroy();
4121
+ return;
4122
+ }
4123
+ let auth;
4124
+ if (this.config.jwtSecret && token) {
4125
+ const authResult = await verifyToken(token, this.config.jwtSecret);
4126
+ if (!authResult.ok) {
4127
+ socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
4128
+ socket.destroy();
4129
+ return;
4130
+ }
4131
+ auth = authResult.value;
4132
+ const gwMatch = url.pathname.match(/^\/sync\/([^/]+)\/ws$/);
4133
+ if (!gwMatch || gwMatch[1] !== auth.gatewayId) {
4134
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
4135
+ socket.destroy();
4136
+ return;
4137
+ }
4138
+ }
4139
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
4140
+ const clientId = auth?.clientId ?? `anon-${crypto.randomUUID()}`;
4141
+ const claims = auth?.customClaims ?? {};
4142
+ this.wsClients.set(ws, { clientId, claims });
4143
+ ws.on("message", (data) => {
4144
+ void this.handleWsMessage(ws, data, clientId, claims);
4145
+ });
4146
+ ws.on("close", () => {
4147
+ this.wsClients.delete(ws);
4148
+ });
4149
+ ws.on("error", () => {
4150
+ this.wsClients.delete(ws);
4151
+ });
4152
+ });
4153
+ }
4154
+ /**
4155
+ * Handle an incoming WebSocket message (binary protobuf).
4156
+ */
4157
+ async handleWsMessage(ws, data, clientId, claims) {
4158
+ const bytes = new Uint8Array(data);
4159
+ if (bytes.length < 2) {
4160
+ ws.close(1002, "Message too short");
4161
+ return;
4162
+ }
4163
+ const tag = bytes[0];
4164
+ const payload = bytes.subarray(1);
4165
+ if (tag === TAG_SYNC_PUSH) {
4166
+ const decoded = decodeSyncPush(payload);
4167
+ if (!decoded.ok) {
4168
+ ws.close(1008, decoded.error.message);
4169
+ return;
4170
+ }
4171
+ const result = this.gateway.handlePush(decoded.value);
4172
+ if (!result.ok) {
4173
+ ws.close(1008, result.error.message);
4174
+ return;
4175
+ }
4176
+ const response = encodeSyncResponse({
4177
+ deltas: [],
4178
+ serverHlc: result.value.serverHlc,
4179
+ hasMore: false
4180
+ });
4181
+ if (response.ok) {
4182
+ ws.send(response.value);
4183
+ }
4184
+ this.broadcastDeltas(result.value.deltas, result.value.serverHlc, clientId);
4185
+ } else if (tag === TAG_SYNC_PULL) {
4186
+ const decoded = decodeSyncPull(payload);
4187
+ if (!decoded.ok) {
4188
+ ws.close(1008, decoded.error.message);
4189
+ return;
4190
+ }
4191
+ const context = await this.buildWsSyncRulesContext(claims);
4192
+ const pullResult = this.gateway.handlePull(
4193
+ decoded.value,
4194
+ context
4195
+ );
4196
+ if (!pullResult.ok) {
4197
+ ws.close(1008, pullResult.error.message);
4198
+ return;
4199
+ }
4200
+ const response = encodeSyncResponse(pullResult.value);
4201
+ if (response.ok) {
4202
+ ws.send(response.value);
4203
+ }
4204
+ } else {
4205
+ ws.close(1002, `Unknown message tag: 0x${tag.toString(16).padStart(2, "0")}`);
4206
+ }
4207
+ }
4208
+ /**
4209
+ * Build sync rules context from WebSocket client claims.
4210
+ */
4211
+ async buildWsSyncRulesContext(claims) {
4212
+ const rules = await this.configStore.getSyncRules(this.config.gatewayId);
4213
+ if (!rules || rules.buckets.length === 0) {
4214
+ return void 0;
4215
+ }
4216
+ return { claims, rules };
4217
+ }
4218
+ /**
4219
+ * Broadcast ingested deltas to all connected WebSocket clients except the sender.
4220
+ */
4221
+ broadcastDeltas(deltas, serverHlc, excludeClientId) {
4222
+ if (deltas.length === 0) return;
4223
+ void this.broadcastDeltasAsync(deltas, serverHlc, excludeClientId);
4224
+ }
4225
+ async broadcastDeltasAsync(deltas, serverHlc, excludeClientId) {
4226
+ const rules = await this.configStore.getSyncRules(this.config.gatewayId);
4227
+ for (const [ws, meta] of this.wsClients) {
4228
+ if (meta.clientId === excludeClientId) continue;
4229
+ try {
4230
+ let filtered = deltas;
4231
+ if (rules && rules.buckets.length > 0) {
4232
+ const context = {
4233
+ claims: meta.claims,
4234
+ rules
4235
+ };
4236
+ filtered = filterDeltas(deltas, context);
4237
+ }
4238
+ if (filtered.length === 0) continue;
4239
+ const frame = encodeBroadcastFrame({
4240
+ deltas: filtered,
4241
+ serverHlc,
4242
+ hasMore: false
4243
+ });
4244
+ if (!frame.ok) continue;
4245
+ ws.send(frame.value);
4246
+ } catch {
4247
+ }
4248
+ }
4249
+ }
4250
+ /** Stop the server and clear the flush timer. */
4251
+ async stop() {
4252
+ for (const [, poller] of this.connectorPollers) {
4253
+ poller.stop();
4254
+ }
4255
+ this.connectorPollers.clear();
4256
+ for (const [, adapter] of this.connectorAdapters) {
4257
+ await adapter.close();
4258
+ }
4259
+ this.connectorAdapters.clear();
4260
+ for (const poller of this.pollers) {
4261
+ poller.stop();
4262
+ }
4263
+ this.pollers = [];
4264
+ if (this.flushTimer) {
4265
+ clearInterval(this.flushTimer);
4266
+ this.flushTimer = null;
4267
+ }
4268
+ if (this.wss) {
4269
+ for (const ws of this.wsClients.keys()) {
4270
+ try {
4271
+ ws.close(1001, "Server shutting down");
4272
+ } catch {
4273
+ }
4274
+ }
4275
+ this.wsClients.clear();
4276
+ this.wss.close();
4277
+ this.wss = null;
4278
+ }
4279
+ if (this.httpServer) {
4280
+ await new Promise((resolve) => {
4281
+ this.httpServer.close(() => resolve());
4282
+ });
4283
+ this.httpServer = null;
4284
+ }
4285
+ this.persistence.close();
4286
+ }
4287
+ /** The port the server is listening on (available after start). */
4288
+ get port() {
4289
+ return this.resolvedPort || this.config.port;
4290
+ }
4291
+ /** The underlying SyncGateway instance for direct access. */
4292
+ get gatewayInstance() {
4293
+ return this.gateway;
4294
+ }
4295
+ // -----------------------------------------------------------------------
4296
+ // Request handling
4297
+ // -----------------------------------------------------------------------
4298
+ async handleRequest(req, res) {
4299
+ const method = req.method ?? "GET";
4300
+ const rawUrl = req.url ?? "/";
4301
+ const url = new URL(rawUrl, `http://${req.headers.host ?? "localhost"}`);
4302
+ const pathname = url.pathname;
4303
+ const origin = req.headers.origin ?? null;
4304
+ const corsH = this.corsHeaders(origin);
4305
+ if (method === "OPTIONS") {
4306
+ res.writeHead(204, corsH);
4307
+ res.end();
4308
+ return;
4309
+ }
4310
+ if (pathname === "/health" && method === "GET") {
4311
+ sendJson(res, { status: "ok" }, 200, corsH);
4312
+ return;
4313
+ }
4314
+ const route = matchRoute(pathname, method);
4315
+ if (!route) {
4316
+ sendError(res, "Not found", 404, corsH);
4317
+ return;
4318
+ }
4319
+ if (route.gatewayId !== this.config.gatewayId) {
4320
+ sendError(res, "Gateway ID mismatch", 404, corsH);
4321
+ return;
4322
+ }
4323
+ let auth;
4324
+ if (this.config.jwtSecret) {
4325
+ const token = extractBearerToken(req);
4326
+ if (!token) {
4327
+ sendError(res, "Missing Bearer token", 401, corsH);
4328
+ return;
4329
+ }
4330
+ const authResult = await verifyToken(token, this.config.jwtSecret);
4331
+ if (!authResult.ok) {
4332
+ sendError(res, authResult.error.message, 401, corsH);
4333
+ return;
4334
+ }
4335
+ auth = authResult.value;
4336
+ if (auth.gatewayId !== route.gatewayId) {
4337
+ sendError(res, "Gateway ID mismatch: JWT authorises a different gateway", 403, corsH);
4338
+ return;
4339
+ }
4340
+ if (ADMIN_ACTIONS.has(route.action) && auth.role !== "admin") {
4341
+ sendError(res, "Admin role required", 403, corsH);
4342
+ return;
4343
+ }
4344
+ }
4345
+ switch (route.action) {
4346
+ case "push":
4347
+ await this.handlePush(req, res, corsH, auth);
4348
+ break;
4349
+ case "pull":
4350
+ await this.handlePull(url, res, corsH, auth);
4351
+ break;
4352
+ case "action":
4353
+ await this.handleAction(req, res, corsH, auth);
4354
+ break;
4355
+ case "describe-actions":
4356
+ this.handleDescribeActions(res, corsH);
4357
+ break;
4358
+ case "flush":
4359
+ await this.handleFlush(res, corsH);
4360
+ break;
4361
+ case "schema":
4362
+ await this.handleSaveSchemaRoute(req, res, corsH);
4363
+ break;
4364
+ case "sync-rules":
4365
+ await this.handleSaveSyncRulesRoute(req, res, corsH);
4366
+ break;
4367
+ case "register-connector":
4368
+ await this.handleRegisterConnector(req, res, corsH);
4369
+ break;
4370
+ case "unregister-connector":
4371
+ await this.handleUnregisterConnector(route.connectorName, res, corsH);
4372
+ break;
4373
+ case "list-connectors":
4374
+ await this.handleListConnectorsRoute(res, corsH);
4375
+ break;
4376
+ case "metrics":
4377
+ this.handleMetricsRoute(res, corsH);
4378
+ break;
4379
+ default:
4380
+ sendError(res, "Not found", 404, corsH);
4381
+ }
4382
+ }
4383
+ // -----------------------------------------------------------------------
4384
+ // Route handlers — thin wrappers around shared request handlers
4385
+ // -----------------------------------------------------------------------
4386
+ /**
4387
+ * Handle `POST /sync/:gatewayId/push` -- ingest client deltas.
4388
+ */
4389
+ async handlePush(req, res, corsH, auth) {
4390
+ const contentLength = Number(req.headers["content-length"] ?? "0");
4391
+ if (contentLength > MAX_PUSH_PAYLOAD_BYTES) {
4392
+ sendError(res, "Payload too large (max 1 MiB)", 413, corsH);
4393
+ return;
4394
+ }
4395
+ const raw = await readBody(req);
4396
+ const result = handlePushRequest(this.gateway, raw, auth?.clientId, {
4397
+ persistBatch: (deltas) => this.persistence.appendBatch(deltas),
4398
+ clearPersistence: () => this.persistence.clear(),
4399
+ broadcastFn: (deltas, serverHlc, excludeClientId) => this.broadcastDeltas(deltas, serverHlc, excludeClientId)
4400
+ });
4401
+ if (result.status === 200 && this.sharedBuffer) {
4402
+ const pushResult = result.body;
4403
+ if (pushResult.deltas.length > 0) {
4404
+ await this.sharedBuffer.writeThroughPush(pushResult.deltas);
4405
+ }
4406
+ }
4407
+ sendResult(res, result, corsH);
4408
+ }
4409
+ /**
4410
+ * Handle `GET /sync/:gatewayId/pull` -- retrieve deltas since a given HLC.
4411
+ */
4412
+ async handlePull(url, res, corsH, auth) {
4413
+ const syncRules = await this.configStore.getSyncRules(this.config.gatewayId);
4414
+ const result = await handlePullRequest(
4415
+ this.gateway,
4416
+ {
4417
+ since: url.searchParams.get("since"),
4418
+ clientId: url.searchParams.get("clientId"),
4419
+ limit: url.searchParams.get("limit"),
4420
+ source: url.searchParams.get("source")
4421
+ },
4422
+ auth?.customClaims,
4423
+ syncRules
4424
+ );
4425
+ let body = result.body;
4426
+ if (result.status === 200 && this.sharedBuffer) {
4427
+ const sinceParam = url.searchParams.get("since");
4428
+ if (sinceParam) {
4429
+ try {
4430
+ const sinceHlc = BigInt(sinceParam);
4431
+ body = await this.sharedBuffer.mergePull(body, sinceHlc);
4432
+ } catch {
4433
+ }
4434
+ }
4435
+ }
4436
+ sendJson(res, body, result.status, corsH);
4437
+ }
4438
+ /**
4439
+ * Handle `POST /sync/:gatewayId/action` -- execute imperative actions.
4440
+ */
4441
+ async handleAction(req, res, corsH, auth) {
4442
+ const raw = await readBody(req);
4443
+ const result = await handleActionRequest(this.gateway, raw, auth?.clientId, auth?.customClaims);
4444
+ sendResult(res, result, corsH);
4445
+ }
4446
+ /** Handle `GET /sync/:gatewayId/actions` -- describe available action handlers. */
4447
+ handleDescribeActions(res, corsH) {
4448
+ sendJson(res, this.gateway.describeActions(), 200, corsH);
4449
+ }
4450
+ /** Handle `POST /admin/flush/:gatewayId` -- manual flush. */
4451
+ async handleFlush(res, corsH) {
4452
+ const result = await handleFlushRequest(this.gateway, {
4453
+ clearPersistence: () => this.persistence.clear()
4454
+ });
4455
+ sendResult(res, result, corsH);
4456
+ }
4457
+ /** Handle `POST /admin/schema/:gatewayId` -- save table schema. */
4458
+ async handleSaveSchemaRoute(req, res, corsH) {
4459
+ const raw = await readBody(req);
4460
+ const result = await handleSaveSchema(raw, this.configStore, this.config.gatewayId);
4461
+ sendResult(res, result, corsH);
4462
+ }
4463
+ /** Handle `POST /admin/sync-rules/:gatewayId` -- save sync rules. */
4464
+ async handleSaveSyncRulesRoute(req, res, corsH) {
4465
+ const raw = await readBody(req);
4466
+ const result = await handleSaveSyncRules(raw, this.configStore, this.config.gatewayId);
4467
+ sendResult(res, result, corsH);
4468
+ }
4469
+ // -----------------------------------------------------------------------
4470
+ // Connector management
4471
+ // -----------------------------------------------------------------------
4472
+ /** Handle `POST /admin/connectors/:gatewayId` -- register a new connector. */
4473
+ async handleRegisterConnector(req, res, corsH) {
4474
+ const raw = await readBody(req);
4475
+ const result = await handleRegisterConnector(raw, this.configStore);
4476
+ if (result.status !== 200) {
4477
+ sendResult(res, result, corsH);
4478
+ return;
4479
+ }
4480
+ const connectors = await this.configStore.getConnectors();
4481
+ const registeredName = result.body.name;
4482
+ const config = connectors[registeredName];
4483
+ if (!config) {
4484
+ sendResult(res, result, corsH);
4485
+ return;
4486
+ }
4487
+ if (config.type === "jira" && config.jira) {
4488
+ try {
4489
+ const { JiraSourcePoller } = await import("./src-QU2YLPZY.js");
4490
+ const ingestConfig = config.ingest ? { intervalMs: config.ingest.intervalMs } : void 0;
4491
+ const poller = new JiraSourcePoller(config.jira, ingestConfig, config.name, this.gateway);
4492
+ poller.start();
4493
+ this.connectorPollers.set(config.name, poller);
4494
+ sendResult(res, result, corsH);
4495
+ } catch (err) {
4496
+ delete connectors[registeredName];
4497
+ await this.configStore.setConnectors(connectors);
4498
+ const message = err instanceof Error ? err.message : String(err);
4499
+ sendError(res, `Failed to load Jira connector: ${message}`, 500, corsH);
4500
+ }
4501
+ return;
4502
+ }
4503
+ if (config.type === "salesforce" && config.salesforce) {
4504
+ try {
4505
+ const { SalesforceSourcePoller } = await import("./src-WZNPHANQ.js");
4506
+ const ingestConfig = config.ingest ? { intervalMs: config.ingest.intervalMs } : void 0;
4507
+ const poller = new SalesforceSourcePoller(
4508
+ config.salesforce,
4509
+ ingestConfig,
4510
+ config.name,
4511
+ this.gateway
4512
+ );
4513
+ poller.start();
4514
+ this.connectorPollers.set(config.name, poller);
4515
+ sendResult(res, result, corsH);
4516
+ } catch (err) {
4517
+ delete connectors[registeredName];
4518
+ await this.configStore.setConnectors(connectors);
4519
+ const message = err instanceof Error ? err.message : String(err);
4520
+ sendError(res, `Failed to load Salesforce connector: ${message}`, 500, corsH);
4521
+ }
4522
+ return;
4523
+ }
4524
+ const adapterResult = createDatabaseAdapter(config);
4525
+ if (!adapterResult.ok) {
4526
+ delete connectors[registeredName];
4527
+ await this.configStore.setConnectors(connectors);
4528
+ sendError(res, adapterResult.error.message, 500, corsH);
4529
+ return;
4530
+ }
4531
+ const adapter = adapterResult.value;
4532
+ this.gateway.registerSource(config.name, adapter);
4533
+ this.connectorAdapters.set(config.name, adapter);
4534
+ if (isActionHandler(adapter)) {
4535
+ this.gateway.registerActionHandler(config.name, adapter);
4536
+ }
4537
+ if (config.ingest) {
4538
+ const queryFn = await createQueryFn(config);
4539
+ if (queryFn) {
4540
+ const pollerConfig = {
4541
+ name: config.name,
4542
+ queryFn,
4543
+ tables: config.ingest.tables.map((t) => ({
4544
+ table: t.table,
4545
+ query: t.query,
4546
+ rowIdColumn: t.rowIdColumn,
4547
+ strategy: t.strategy
4548
+ })),
4549
+ intervalMs: config.ingest.intervalMs
4550
+ };
4551
+ const poller = new SourcePoller(pollerConfig, this.gateway);
4552
+ poller.start();
4553
+ this.connectorPollers.set(config.name, poller);
4554
+ }
4555
+ }
4556
+ sendResult(res, result, corsH);
4557
+ }
4558
+ /** Handle `DELETE /admin/connectors/:gatewayId/:name` -- unregister a connector. */
4559
+ async handleUnregisterConnector(name, res, corsH) {
4560
+ const result = await handleUnregisterConnector(name, this.configStore);
4561
+ if (result.status !== 200) {
4562
+ sendResult(res, result, corsH);
4563
+ return;
4564
+ }
4565
+ const poller = this.connectorPollers.get(name);
4566
+ if (poller) {
4567
+ poller.stop();
4568
+ this.connectorPollers.delete(name);
4569
+ }
4570
+ const adapter = this.connectorAdapters.get(name);
4571
+ if (adapter) {
4572
+ await adapter.close();
4573
+ this.connectorAdapters.delete(name);
4574
+ }
4575
+ this.gateway.unregisterSource(name);
4576
+ this.gateway.unregisterActionHandler(name);
4577
+ sendResult(res, result, corsH);
4578
+ }
4579
+ /** Handle `GET /admin/connectors/:gatewayId` -- list registered connectors. */
4580
+ async handleListConnectorsRoute(res, corsH) {
4581
+ const result = await handleListConnectors(this.configStore);
4582
+ if (result.status !== 200) {
4583
+ sendResult(res, result, corsH);
4584
+ return;
4585
+ }
4586
+ const list = result.body;
4587
+ const augmented = list.map((c) => ({
4588
+ ...c,
4589
+ isPolling: this.connectorPollers.get(c.name)?.isRunning ?? false
4590
+ }));
4591
+ sendJson(res, augmented, 200, corsH);
4592
+ }
4593
+ /** Handle `GET /admin/metrics/:gatewayId` -- return buffer stats and process memory. */
4594
+ handleMetricsRoute(res, corsH) {
4595
+ const result = handleMetrics(this.gateway, { process: process.memoryUsage() });
4596
+ sendResult(res, result, corsH);
4597
+ }
4598
+ // -----------------------------------------------------------------------
4599
+ // Periodic flush
4600
+ // -----------------------------------------------------------------------
4601
+ async periodicFlush() {
4602
+ if (this.gateway.bufferStats.logSize === 0) {
4603
+ return;
4604
+ }
4605
+ const lock = this.config.cluster?.lock;
4606
+ const lockKey = `flush:${this.config.gatewayId}`;
4607
+ if (lock) {
4608
+ const acquired = await lock.acquire(lockKey, 3e4);
4609
+ if (!acquired) {
4610
+ return;
4611
+ }
4612
+ }
4613
+ try {
4614
+ const result = await this.gateway.flush();
4615
+ if (result.ok) {
4616
+ this.persistence.clear();
4617
+ }
4618
+ } finally {
4619
+ if (lock) {
4620
+ await lock.release(lockKey);
4621
+ }
4622
+ }
4623
+ }
4624
+ // -----------------------------------------------------------------------
4625
+ // CORS
4626
+ // -----------------------------------------------------------------------
4627
+ corsHeaders(origin) {
4628
+ const allowedOrigins = this.config.allowedOrigins;
4629
+ let allowOrigin = "*";
4630
+ if (allowedOrigins && allowedOrigins.length > 0) {
4631
+ if (origin && allowedOrigins.includes(origin)) {
4632
+ allowOrigin = origin;
4633
+ } else {
4634
+ return {};
4635
+ }
4636
+ } else if (origin) {
4637
+ allowOrigin = origin;
4638
+ }
4639
+ return {
4640
+ "Access-Control-Allow-Origin": allowOrigin,
4641
+ "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
4642
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
4643
+ "Access-Control-Max-Age": "86400"
4644
+ };
4645
+ }
4646
+ };
4647
+ function extractBearerToken(req) {
4648
+ const header = req.headers.authorization;
4649
+ if (!header) return null;
4650
+ const match = header.match(/^Bearer\s+(\S+)$/);
4651
+ return match?.[1] ?? null;
4652
+ }
4653
+ export {
4654
+ AdapterBasedLock,
4655
+ AuthError,
4656
+ GatewayServer,
4657
+ MemoryPersistence,
4658
+ SharedBuffer,
4659
+ SourcePoller,
4660
+ SqlitePersistence,
4661
+ verifyToken
4662
+ };
4663
+ //# sourceMappingURL=gateway-server.js.map