@granular-software/sdk 0.2.1 → 0.3.1

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