@cloudflare/containers-shared 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { spawn, execFileSync, execFile } from 'node:child_process';
2
3
  import crypto2, { randomUUID, createHash } from 'node:crypto';
3
4
  import { existsSync, readFileSync } from 'node:fs';
@@ -7,16 +8,3792 @@ import { UserError, FatalError } from '@cloudflare/workers-utils/errors';
7
8
  import { isDirectory } from '@cloudflare/workers-utils/fs-helpers';
8
9
  import { COMPLIANCE_REGION_CONFIG_UNKNOWN, getComplianceRegionSubdomain } from '@cloudflare/workers-utils/compliance';
9
10
  import { release } from 'node:os';
10
- import { writeContainerConfig, cleanBuildOutputDir } from '@cloudflare/build-output-utils';
11
+ import { writeContainerConfig, cleanBuildOutputDir, normalizeDirectoryName } from '@cloudflare/build-output-utils';
11
12
  import assert from 'node:assert';
12
- import { setTimeout } from 'node:timers/promises';
13
- import { log, startSection, newline, endSection, updateStatus, success, shapes } from '@cloudflare/cli-shared-helpers';
13
+ import { setTimeout as setTimeout$1 } from 'node:timers/promises';
14
+ import { log, startSection, newline, endSection, updateStatus, success, shapes, showCursor } from '@cloudflare/cli-shared-helpers';
14
15
  import { green, red, dim, brandColor, bold } from '@cloudflare/cli-shared-helpers/colors';
15
16
  import { getResolvedDurableObjectContainerApps, isDurableObjectContainerApp, resolveContainerClassName, isDockerfile, formatConfigSnippet } from '@cloudflare/workers-utils';
16
17
  import { spinner } from '@cloudflare/cli-shared-helpers/interactive';
18
+ import { once } from 'node:events';
19
+ import { createServer } from 'node:net';
17
20
 
21
+ const require$1 = createRequire(typeof __filename === "string" ? __filename : import.meta.url);
22
+ var __create = Object.create;
18
23
  var __defProp = Object.defineProperty;
24
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
25
+ var __getOwnPropNames = Object.getOwnPropertyNames;
26
+ var __getProtoOf = Object.getPrototypeOf;
27
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
19
28
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
+ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
30
+ get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
31
+ }) : x)(function(x) {
32
+ if (typeof require$1 !== "undefined") return require$1.apply(this, arguments);
33
+ throw Error('Dynamic require of "' + x + '" is not supported');
34
+ });
35
+ var __commonJS = (cb, mod) => function __require2() {
36
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
37
+ };
38
+ var __copyProps = (to, from, except, desc) => {
39
+ if (from && typeof from === "object" || typeof from === "function") {
40
+ for (let key of __getOwnPropNames(from))
41
+ if (!__hasOwnProp.call(to, key) && key !== except)
42
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
43
+ }
44
+ return to;
45
+ };
46
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
47
+ // If the importer is in node compatibility mode or this is not an ESM
48
+ // file that has been converted to a CommonJS file using a Babel-
49
+ // compatible transform (i.e. "__esModule" has not been set), then set
50
+ // "default" to the CommonJS "module.exports" for node compatibility.
51
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
52
+ mod
53
+ ));
54
+
55
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js
56
+ var require_constants = __commonJS({
57
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js"(exports$1, module) {
58
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
59
+ var hasBlob = typeof Blob !== "undefined";
60
+ if (hasBlob) BINARY_TYPES.push("blob");
61
+ module.exports = {
62
+ BINARY_TYPES,
63
+ CLOSE_TIMEOUT: 3e4,
64
+ EMPTY_BUFFER: Buffer.alloc(0),
65
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
66
+ hasBlob,
67
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
68
+ kListener: Symbol("kListener"),
69
+ kStatusCode: Symbol("status-code"),
70
+ kWebSocket: Symbol("websocket"),
71
+ NOOP: /* @__PURE__ */ __name(() => {
72
+ }, "NOOP")
73
+ };
74
+ }
75
+ });
76
+
77
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js
78
+ var require_buffer_util = __commonJS({
79
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js"(exports$1, module) {
80
+ var { EMPTY_BUFFER } = require_constants();
81
+ var FastBuffer = Buffer[Symbol.species];
82
+ function concat(list, totalLength) {
83
+ if (list.length === 0) return EMPTY_BUFFER;
84
+ if (list.length === 1) return list[0];
85
+ const target = Buffer.allocUnsafe(totalLength);
86
+ let offset = 0;
87
+ for (let i = 0; i < list.length; i++) {
88
+ const buf = list[i];
89
+ target.set(buf, offset);
90
+ offset += buf.length;
91
+ }
92
+ if (offset < totalLength) {
93
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
94
+ }
95
+ return target;
96
+ }
97
+ __name(concat, "concat");
98
+ function _mask(source, mask, output, offset, length) {
99
+ for (let i = 0; i < length; i++) {
100
+ output[offset + i] = source[i] ^ mask[i & 3];
101
+ }
102
+ }
103
+ __name(_mask, "_mask");
104
+ function _unmask(buffer, mask) {
105
+ for (let i = 0; i < buffer.length; i++) {
106
+ buffer[i] ^= mask[i & 3];
107
+ }
108
+ }
109
+ __name(_unmask, "_unmask");
110
+ function toArrayBuffer(buf) {
111
+ if (buf.length === buf.buffer.byteLength) {
112
+ return buf.buffer;
113
+ }
114
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
115
+ }
116
+ __name(toArrayBuffer, "toArrayBuffer");
117
+ function toBuffer(data) {
118
+ toBuffer.readOnly = true;
119
+ if (Buffer.isBuffer(data)) return data;
120
+ let buf;
121
+ if (data instanceof ArrayBuffer) {
122
+ buf = new FastBuffer(data);
123
+ } else if (ArrayBuffer.isView(data)) {
124
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
125
+ } else {
126
+ buf = Buffer.from(data);
127
+ toBuffer.readOnly = false;
128
+ }
129
+ return buf;
130
+ }
131
+ __name(toBuffer, "toBuffer");
132
+ module.exports = {
133
+ concat,
134
+ mask: _mask,
135
+ toArrayBuffer,
136
+ toBuffer,
137
+ unmask: _unmask
138
+ };
139
+ if (!process.env.WS_NO_BUFFER_UTIL) {
140
+ try {
141
+ const bufferUtil = __require("bufferutil");
142
+ module.exports.mask = function(source, mask, output, offset, length) {
143
+ if (length < 48) _mask(source, mask, output, offset, length);
144
+ else bufferUtil.mask(source, mask, output, offset, length);
145
+ };
146
+ module.exports.unmask = function(buffer, mask) {
147
+ if (buffer.length < 32) _unmask(buffer, mask);
148
+ else bufferUtil.unmask(buffer, mask);
149
+ };
150
+ } catch (e) {
151
+ }
152
+ }
153
+ }
154
+ });
155
+
156
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js
157
+ var require_limiter = __commonJS({
158
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js"(exports$1, module) {
159
+ var kDone = Symbol("kDone");
160
+ var kRun = Symbol("kRun");
161
+ var Limiter = class {
162
+ static {
163
+ __name(this, "Limiter");
164
+ }
165
+ /**
166
+ * Creates a new `Limiter`.
167
+ *
168
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
169
+ * to run concurrently
170
+ */
171
+ constructor(concurrency) {
172
+ this[kDone] = () => {
173
+ this.pending--;
174
+ this[kRun]();
175
+ };
176
+ this.concurrency = concurrency || Infinity;
177
+ this.jobs = [];
178
+ this.pending = 0;
179
+ }
180
+ /**
181
+ * Adds a job to the queue.
182
+ *
183
+ * @param {Function} job The job to run
184
+ * @public
185
+ */
186
+ add(job) {
187
+ this.jobs.push(job);
188
+ this[kRun]();
189
+ }
190
+ /**
191
+ * Removes a job from the queue and runs it if possible.
192
+ *
193
+ * @private
194
+ */
195
+ [kRun]() {
196
+ if (this.pending === this.concurrency) return;
197
+ if (this.jobs.length) {
198
+ const job = this.jobs.shift();
199
+ this.pending++;
200
+ job(this[kDone]);
201
+ }
202
+ }
203
+ };
204
+ module.exports = Limiter;
205
+ }
206
+ });
207
+
208
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js
209
+ var require_permessage_deflate = __commonJS({
210
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js"(exports$1, module) {
211
+ var zlib = __require("zlib");
212
+ var bufferUtil = require_buffer_util();
213
+ var Limiter = require_limiter();
214
+ var { kStatusCode } = require_constants();
215
+ var FastBuffer = Buffer[Symbol.species];
216
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
217
+ var kPerMessageDeflate = Symbol("permessage-deflate");
218
+ var kTotalLength = Symbol("total-length");
219
+ var kCallback = Symbol("callback");
220
+ var kBuffers = Symbol("buffers");
221
+ var kError = Symbol("error");
222
+ var zlibLimiter;
223
+ var PerMessageDeflate2 = class {
224
+ static {
225
+ __name(this, "PerMessageDeflate");
226
+ }
227
+ /**
228
+ * Creates a PerMessageDeflate instance.
229
+ *
230
+ * @param {Object} [options] Configuration options
231
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
232
+ * for, or request, a custom client window size
233
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
234
+ * acknowledge disabling of client context takeover
235
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
236
+ * calls to zlib
237
+ * @param {Boolean} [options.isServer=false] Create the instance in either
238
+ * server or client mode
239
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
240
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
241
+ * use of a custom server window size
242
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
243
+ * disabling of server context takeover
244
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
245
+ * messages should not be compressed if context takeover is disabled
246
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
247
+ * deflate
248
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
249
+ * inflate
250
+ */
251
+ constructor(options) {
252
+ this._options = options || {};
253
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
254
+ this._maxPayload = this._options.maxPayload | 0;
255
+ this._isServer = !!this._options.isServer;
256
+ this._deflate = null;
257
+ this._inflate = null;
258
+ this.params = null;
259
+ if (!zlibLimiter) {
260
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
261
+ zlibLimiter = new Limiter(concurrency);
262
+ }
263
+ }
264
+ /**
265
+ * @type {String}
266
+ */
267
+ static get extensionName() {
268
+ return "permessage-deflate";
269
+ }
270
+ /**
271
+ * Create an extension negotiation offer.
272
+ *
273
+ * @return {Object} Extension parameters
274
+ * @public
275
+ */
276
+ offer() {
277
+ const params = {};
278
+ if (this._options.serverNoContextTakeover) {
279
+ params.server_no_context_takeover = true;
280
+ }
281
+ if (this._options.clientNoContextTakeover) {
282
+ params.client_no_context_takeover = true;
283
+ }
284
+ if (this._options.serverMaxWindowBits) {
285
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
286
+ }
287
+ if (this._options.clientMaxWindowBits) {
288
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
289
+ } else if (this._options.clientMaxWindowBits == null) {
290
+ params.client_max_window_bits = true;
291
+ }
292
+ return params;
293
+ }
294
+ /**
295
+ * Accept an extension negotiation offer/response.
296
+ *
297
+ * @param {Array} configurations The extension negotiation offers/reponse
298
+ * @return {Object} Accepted configuration
299
+ * @public
300
+ */
301
+ accept(configurations) {
302
+ configurations = this.normalizeParams(configurations);
303
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
304
+ return this.params;
305
+ }
306
+ /**
307
+ * Releases all resources used by the extension.
308
+ *
309
+ * @public
310
+ */
311
+ cleanup() {
312
+ if (this._inflate) {
313
+ this._inflate.close();
314
+ this._inflate = null;
315
+ }
316
+ if (this._deflate) {
317
+ const callback = this._deflate[kCallback];
318
+ this._deflate.close();
319
+ this._deflate = null;
320
+ if (callback) {
321
+ callback(
322
+ new Error(
323
+ "The deflate stream was closed while data was being processed"
324
+ )
325
+ );
326
+ }
327
+ }
328
+ }
329
+ /**
330
+ * Accept an extension negotiation offer.
331
+ *
332
+ * @param {Array} offers The extension negotiation offers
333
+ * @return {Object} Accepted configuration
334
+ * @private
335
+ */
336
+ acceptAsServer(offers) {
337
+ const opts = this._options;
338
+ const accepted = offers.find((params) => {
339
+ 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) {
340
+ return false;
341
+ }
342
+ return true;
343
+ });
344
+ if (!accepted) {
345
+ throw new Error("None of the extension offers can be accepted");
346
+ }
347
+ if (opts.serverNoContextTakeover) {
348
+ accepted.server_no_context_takeover = true;
349
+ }
350
+ if (opts.clientNoContextTakeover) {
351
+ accepted.client_no_context_takeover = true;
352
+ }
353
+ if (typeof opts.serverMaxWindowBits === "number") {
354
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
355
+ }
356
+ if (typeof opts.clientMaxWindowBits === "number") {
357
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
358
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
359
+ delete accepted.client_max_window_bits;
360
+ }
361
+ return accepted;
362
+ }
363
+ /**
364
+ * Accept the extension negotiation response.
365
+ *
366
+ * @param {Array} response The extension negotiation response
367
+ * @return {Object} Accepted configuration
368
+ * @private
369
+ */
370
+ acceptAsClient(response) {
371
+ const params = response[0];
372
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
373
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
374
+ }
375
+ if (!params.client_max_window_bits) {
376
+ if (typeof this._options.clientMaxWindowBits === "number") {
377
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
378
+ }
379
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
380
+ throw new Error(
381
+ 'Unexpected or invalid parameter "client_max_window_bits"'
382
+ );
383
+ }
384
+ return params;
385
+ }
386
+ /**
387
+ * Normalize parameters.
388
+ *
389
+ * @param {Array} configurations The extension negotiation offers/reponse
390
+ * @return {Array} The offers/response with normalized parameters
391
+ * @private
392
+ */
393
+ normalizeParams(configurations) {
394
+ configurations.forEach((params) => {
395
+ Object.keys(params).forEach((key) => {
396
+ let value = params[key];
397
+ if (value.length > 1) {
398
+ throw new Error(`Parameter "${key}" must have only a single value`);
399
+ }
400
+ value = value[0];
401
+ if (key === "client_max_window_bits") {
402
+ if (value !== true) {
403
+ const num = +value;
404
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
405
+ throw new TypeError(
406
+ `Invalid value for parameter "${key}": ${value}`
407
+ );
408
+ }
409
+ value = num;
410
+ } else if (!this._isServer) {
411
+ throw new TypeError(
412
+ `Invalid value for parameter "${key}": ${value}`
413
+ );
414
+ }
415
+ } else if (key === "server_max_window_bits") {
416
+ const num = +value;
417
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
418
+ throw new TypeError(
419
+ `Invalid value for parameter "${key}": ${value}`
420
+ );
421
+ }
422
+ value = num;
423
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
424
+ if (value !== true) {
425
+ throw new TypeError(
426
+ `Invalid value for parameter "${key}": ${value}`
427
+ );
428
+ }
429
+ } else {
430
+ throw new Error(`Unknown parameter "${key}"`);
431
+ }
432
+ params[key] = value;
433
+ });
434
+ });
435
+ return configurations;
436
+ }
437
+ /**
438
+ * Decompress data. Concurrency limited.
439
+ *
440
+ * @param {Buffer} data Compressed data
441
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
442
+ * @param {Function} callback Callback
443
+ * @public
444
+ */
445
+ decompress(data, fin, callback) {
446
+ zlibLimiter.add((done) => {
447
+ this._decompress(data, fin, (err, result) => {
448
+ done();
449
+ callback(err, result);
450
+ });
451
+ });
452
+ }
453
+ /**
454
+ * Compress data. Concurrency limited.
455
+ *
456
+ * @param {(Buffer|String)} data Data to compress
457
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
458
+ * @param {Function} callback Callback
459
+ * @public
460
+ */
461
+ compress(data, fin, callback) {
462
+ zlibLimiter.add((done) => {
463
+ this._compress(data, fin, (err, result) => {
464
+ done();
465
+ callback(err, result);
466
+ });
467
+ });
468
+ }
469
+ /**
470
+ * Decompress data.
471
+ *
472
+ * @param {Buffer} data Compressed data
473
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
474
+ * @param {Function} callback Callback
475
+ * @private
476
+ */
477
+ _decompress(data, fin, callback) {
478
+ const endpoint = this._isServer ? "client" : "server";
479
+ if (!this._inflate) {
480
+ const key = `${endpoint}_max_window_bits`;
481
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
482
+ this._inflate = zlib.createInflateRaw({
483
+ ...this._options.zlibInflateOptions,
484
+ windowBits
485
+ });
486
+ this._inflate[kPerMessageDeflate] = this;
487
+ this._inflate[kTotalLength] = 0;
488
+ this._inflate[kBuffers] = [];
489
+ this._inflate.on("error", inflateOnError);
490
+ this._inflate.on("data", inflateOnData);
491
+ }
492
+ this._inflate[kCallback] = callback;
493
+ this._inflate.write(data);
494
+ if (fin) this._inflate.write(TRAILER);
495
+ this._inflate.flush(() => {
496
+ const err = this._inflate[kError];
497
+ if (err) {
498
+ this._inflate.close();
499
+ this._inflate = null;
500
+ callback(err);
501
+ return;
502
+ }
503
+ const data2 = bufferUtil.concat(
504
+ this._inflate[kBuffers],
505
+ this._inflate[kTotalLength]
506
+ );
507
+ if (this._inflate._readableState.endEmitted) {
508
+ this._inflate.close();
509
+ this._inflate = null;
510
+ } else {
511
+ this._inflate[kTotalLength] = 0;
512
+ this._inflate[kBuffers] = [];
513
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
514
+ this._inflate.reset();
515
+ }
516
+ }
517
+ callback(null, data2);
518
+ });
519
+ }
520
+ /**
521
+ * Compress data.
522
+ *
523
+ * @param {(Buffer|String)} data Data to compress
524
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
525
+ * @param {Function} callback Callback
526
+ * @private
527
+ */
528
+ _compress(data, fin, callback) {
529
+ const endpoint = this._isServer ? "server" : "client";
530
+ if (!this._deflate) {
531
+ const key = `${endpoint}_max_window_bits`;
532
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
533
+ this._deflate = zlib.createDeflateRaw({
534
+ ...this._options.zlibDeflateOptions,
535
+ windowBits
536
+ });
537
+ this._deflate[kTotalLength] = 0;
538
+ this._deflate[kBuffers] = [];
539
+ this._deflate.on("data", deflateOnData);
540
+ }
541
+ this._deflate[kCallback] = callback;
542
+ this._deflate.write(data);
543
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
544
+ if (!this._deflate) {
545
+ return;
546
+ }
547
+ let data2 = bufferUtil.concat(
548
+ this._deflate[kBuffers],
549
+ this._deflate[kTotalLength]
550
+ );
551
+ if (fin) {
552
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
553
+ }
554
+ this._deflate[kCallback] = null;
555
+ this._deflate[kTotalLength] = 0;
556
+ this._deflate[kBuffers] = [];
557
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
558
+ this._deflate.reset();
559
+ }
560
+ callback(null, data2);
561
+ });
562
+ }
563
+ };
564
+ module.exports = PerMessageDeflate2;
565
+ function deflateOnData(chunk) {
566
+ this[kBuffers].push(chunk);
567
+ this[kTotalLength] += chunk.length;
568
+ }
569
+ __name(deflateOnData, "deflateOnData");
570
+ function inflateOnData(chunk) {
571
+ this[kTotalLength] += chunk.length;
572
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
573
+ this[kBuffers].push(chunk);
574
+ return;
575
+ }
576
+ this[kError] = new RangeError("Max payload size exceeded");
577
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
578
+ this[kError][kStatusCode] = 1009;
579
+ this.removeListener("data", inflateOnData);
580
+ this.reset();
581
+ }
582
+ __name(inflateOnData, "inflateOnData");
583
+ function inflateOnError(err) {
584
+ this[kPerMessageDeflate]._inflate = null;
585
+ if (this[kError]) {
586
+ this[kCallback](this[kError]);
587
+ return;
588
+ }
589
+ err[kStatusCode] = 1007;
590
+ this[kCallback](err);
591
+ }
592
+ __name(inflateOnError, "inflateOnError");
593
+ }
594
+ });
595
+
596
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js
597
+ var require_validation = __commonJS({
598
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js"(exports$1, module) {
599
+ var { isUtf8 } = __require("buffer");
600
+ var { hasBlob } = require_constants();
601
+ var tokenChars = [
602
+ 0,
603
+ 0,
604
+ 0,
605
+ 0,
606
+ 0,
607
+ 0,
608
+ 0,
609
+ 0,
610
+ 0,
611
+ 0,
612
+ 0,
613
+ 0,
614
+ 0,
615
+ 0,
616
+ 0,
617
+ 0,
618
+ // 0 - 15
619
+ 0,
620
+ 0,
621
+ 0,
622
+ 0,
623
+ 0,
624
+ 0,
625
+ 0,
626
+ 0,
627
+ 0,
628
+ 0,
629
+ 0,
630
+ 0,
631
+ 0,
632
+ 0,
633
+ 0,
634
+ 0,
635
+ // 16 - 31
636
+ 0,
637
+ 1,
638
+ 0,
639
+ 1,
640
+ 1,
641
+ 1,
642
+ 1,
643
+ 1,
644
+ 0,
645
+ 0,
646
+ 1,
647
+ 1,
648
+ 0,
649
+ 1,
650
+ 1,
651
+ 0,
652
+ // 32 - 47
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 0,
664
+ 0,
665
+ 0,
666
+ 0,
667
+ 0,
668
+ 0,
669
+ // 48 - 63
670
+ 0,
671
+ 1,
672
+ 1,
673
+ 1,
674
+ 1,
675
+ 1,
676
+ 1,
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ // 64 - 79
687
+ 1,
688
+ 1,
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ 1,
694
+ 1,
695
+ 1,
696
+ 1,
697
+ 1,
698
+ 0,
699
+ 0,
700
+ 0,
701
+ 1,
702
+ 1,
703
+ // 80 - 95
704
+ 1,
705
+ 1,
706
+ 1,
707
+ 1,
708
+ 1,
709
+ 1,
710
+ 1,
711
+ 1,
712
+ 1,
713
+ 1,
714
+ 1,
715
+ 1,
716
+ 1,
717
+ 1,
718
+ 1,
719
+ 1,
720
+ // 96 - 111
721
+ 1,
722
+ 1,
723
+ 1,
724
+ 1,
725
+ 1,
726
+ 1,
727
+ 1,
728
+ 1,
729
+ 1,
730
+ 1,
731
+ 1,
732
+ 0,
733
+ 1,
734
+ 0,
735
+ 1,
736
+ 0
737
+ // 112 - 127
738
+ ];
739
+ function isValidStatusCode(code) {
740
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
741
+ }
742
+ __name(isValidStatusCode, "isValidStatusCode");
743
+ function _isValidUTF8(buf) {
744
+ const len = buf.length;
745
+ let i = 0;
746
+ while (i < len) {
747
+ if ((buf[i] & 128) === 0) {
748
+ i++;
749
+ } else if ((buf[i] & 224) === 192) {
750
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
751
+ return false;
752
+ }
753
+ i += 2;
754
+ } else if ((buf[i] & 240) === 224) {
755
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
756
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
757
+ return false;
758
+ }
759
+ i += 3;
760
+ } else if ((buf[i] & 248) === 240) {
761
+ 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
762
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
763
+ return false;
764
+ }
765
+ i += 4;
766
+ } else {
767
+ return false;
768
+ }
769
+ }
770
+ return true;
771
+ }
772
+ __name(_isValidUTF8, "_isValidUTF8");
773
+ function isBlob2(value) {
774
+ 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");
775
+ }
776
+ __name(isBlob2, "isBlob");
777
+ module.exports = {
778
+ isBlob: isBlob2,
779
+ isValidStatusCode,
780
+ isValidUTF8: _isValidUTF8,
781
+ tokenChars
782
+ };
783
+ if (isUtf8) {
784
+ module.exports.isValidUTF8 = function(buf) {
785
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
786
+ };
787
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
788
+ try {
789
+ const isValidUTF8 = __require("utf-8-validate");
790
+ module.exports.isValidUTF8 = function(buf) {
791
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
792
+ };
793
+ } catch (e) {
794
+ }
795
+ }
796
+ }
797
+ });
798
+
799
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js
800
+ var require_receiver = __commonJS({
801
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js"(exports$1, module) {
802
+ var { Writable } = __require("stream");
803
+ var PerMessageDeflate2 = require_permessage_deflate();
804
+ var {
805
+ BINARY_TYPES,
806
+ EMPTY_BUFFER,
807
+ kStatusCode,
808
+ kWebSocket
809
+ } = require_constants();
810
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
811
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
812
+ var FastBuffer = Buffer[Symbol.species];
813
+ var GET_INFO = 0;
814
+ var GET_PAYLOAD_LENGTH_16 = 1;
815
+ var GET_PAYLOAD_LENGTH_64 = 2;
816
+ var GET_MASK = 3;
817
+ var GET_DATA = 4;
818
+ var INFLATING = 5;
819
+ var DEFER_EVENT = 6;
820
+ var Receiver2 = class extends Writable {
821
+ static {
822
+ __name(this, "Receiver");
823
+ }
824
+ /**
825
+ * Creates a Receiver instance.
826
+ *
827
+ * @param {Object} [options] Options object
828
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
829
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
830
+ * multiple times in the same tick
831
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
832
+ * @param {Object} [options.extensions] An object containing the negotiated
833
+ * extensions
834
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
835
+ * client or server mode
836
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
837
+ * buffered data chunks
838
+ * @param {Number} [options.maxFragments=0] The maximum number of message
839
+ * fragments
840
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
841
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
842
+ * not to skip UTF-8 validation for text and close messages
843
+ */
844
+ constructor(options = {}) {
845
+ super();
846
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
847
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
848
+ this._extensions = options.extensions || {};
849
+ this._isServer = !!options.isServer;
850
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
851
+ this._maxFragments = options.maxFragments | 0;
852
+ this._maxPayload = options.maxPayload | 0;
853
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
854
+ this[kWebSocket] = void 0;
855
+ this._bufferedBytes = 0;
856
+ this._buffers = [];
857
+ this._compressed = false;
858
+ this._payloadLength = 0;
859
+ this._mask = void 0;
860
+ this._fragmented = 0;
861
+ this._masked = false;
862
+ this._fin = false;
863
+ this._opcode = 0;
864
+ this._totalPayloadLength = 0;
865
+ this._messageLength = 0;
866
+ this._fragments = [];
867
+ this._errored = false;
868
+ this._loop = false;
869
+ this._state = GET_INFO;
870
+ }
871
+ /**
872
+ * Implements `Writable.prototype._write()`.
873
+ *
874
+ * @param {Buffer} chunk The chunk of data to write
875
+ * @param {String} encoding The character encoding of `chunk`
876
+ * @param {Function} cb Callback
877
+ * @private
878
+ */
879
+ _write(chunk, encoding, cb) {
880
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
881
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
882
+ cb(
883
+ this.createError(
884
+ RangeError,
885
+ "Too many buffered chunks",
886
+ false,
887
+ 1008,
888
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
889
+ )
890
+ );
891
+ return;
892
+ }
893
+ this._bufferedBytes += chunk.length;
894
+ this._buffers.push(chunk);
895
+ this.startLoop(cb);
896
+ }
897
+ /**
898
+ * Consumes `n` bytes from the buffered data.
899
+ *
900
+ * @param {Number} n The number of bytes to consume
901
+ * @return {Buffer} The consumed bytes
902
+ * @private
903
+ */
904
+ consume(n) {
905
+ this._bufferedBytes -= n;
906
+ if (n === this._buffers[0].length) return this._buffers.shift();
907
+ if (n < this._buffers[0].length) {
908
+ const buf = this._buffers[0];
909
+ this._buffers[0] = new FastBuffer(
910
+ buf.buffer,
911
+ buf.byteOffset + n,
912
+ buf.length - n
913
+ );
914
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
915
+ }
916
+ const dst = Buffer.allocUnsafe(n);
917
+ do {
918
+ const buf = this._buffers[0];
919
+ const offset = dst.length - n;
920
+ if (n >= buf.length) {
921
+ dst.set(this._buffers.shift(), offset);
922
+ } else {
923
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
924
+ this._buffers[0] = new FastBuffer(
925
+ buf.buffer,
926
+ buf.byteOffset + n,
927
+ buf.length - n
928
+ );
929
+ }
930
+ n -= buf.length;
931
+ } while (n > 0);
932
+ return dst;
933
+ }
934
+ /**
935
+ * Starts the parsing loop.
936
+ *
937
+ * @param {Function} cb Callback
938
+ * @private
939
+ */
940
+ startLoop(cb) {
941
+ this._loop = true;
942
+ do {
943
+ switch (this._state) {
944
+ case GET_INFO:
945
+ this.getInfo(cb);
946
+ break;
947
+ case GET_PAYLOAD_LENGTH_16:
948
+ this.getPayloadLength16(cb);
949
+ break;
950
+ case GET_PAYLOAD_LENGTH_64:
951
+ this.getPayloadLength64(cb);
952
+ break;
953
+ case GET_MASK:
954
+ this.getMask();
955
+ break;
956
+ case GET_DATA:
957
+ this.getData(cb);
958
+ break;
959
+ case INFLATING:
960
+ case DEFER_EVENT:
961
+ this._loop = false;
962
+ return;
963
+ }
964
+ } while (this._loop);
965
+ if (!this._errored) cb();
966
+ }
967
+ /**
968
+ * Reads the first two bytes of a frame.
969
+ *
970
+ * @param {Function} cb Callback
971
+ * @private
972
+ */
973
+ getInfo(cb) {
974
+ if (this._bufferedBytes < 2) {
975
+ this._loop = false;
976
+ return;
977
+ }
978
+ const buf = this.consume(2);
979
+ if ((buf[0] & 48) !== 0) {
980
+ const error = this.createError(
981
+ RangeError,
982
+ "RSV2 and RSV3 must be clear",
983
+ true,
984
+ 1002,
985
+ "WS_ERR_UNEXPECTED_RSV_2_3"
986
+ );
987
+ cb(error);
988
+ return;
989
+ }
990
+ const compressed = (buf[0] & 64) === 64;
991
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
992
+ const error = this.createError(
993
+ RangeError,
994
+ "RSV1 must be clear",
995
+ true,
996
+ 1002,
997
+ "WS_ERR_UNEXPECTED_RSV_1"
998
+ );
999
+ cb(error);
1000
+ return;
1001
+ }
1002
+ this._fin = (buf[0] & 128) === 128;
1003
+ this._opcode = buf[0] & 15;
1004
+ this._payloadLength = buf[1] & 127;
1005
+ if (this._opcode === 0) {
1006
+ if (compressed) {
1007
+ const error = this.createError(
1008
+ RangeError,
1009
+ "RSV1 must be clear",
1010
+ true,
1011
+ 1002,
1012
+ "WS_ERR_UNEXPECTED_RSV_1"
1013
+ );
1014
+ cb(error);
1015
+ return;
1016
+ }
1017
+ if (!this._fragmented) {
1018
+ const error = this.createError(
1019
+ RangeError,
1020
+ "invalid opcode 0",
1021
+ true,
1022
+ 1002,
1023
+ "WS_ERR_INVALID_OPCODE"
1024
+ );
1025
+ cb(error);
1026
+ return;
1027
+ }
1028
+ this._opcode = this._fragmented;
1029
+ } else if (this._opcode === 1 || this._opcode === 2) {
1030
+ if (this._fragmented) {
1031
+ const error = this.createError(
1032
+ RangeError,
1033
+ `invalid opcode ${this._opcode}`,
1034
+ true,
1035
+ 1002,
1036
+ "WS_ERR_INVALID_OPCODE"
1037
+ );
1038
+ cb(error);
1039
+ return;
1040
+ }
1041
+ this._compressed = compressed;
1042
+ } else if (this._opcode > 7 && this._opcode < 11) {
1043
+ if (!this._fin) {
1044
+ const error = this.createError(
1045
+ RangeError,
1046
+ "FIN must be set",
1047
+ true,
1048
+ 1002,
1049
+ "WS_ERR_EXPECTED_FIN"
1050
+ );
1051
+ cb(error);
1052
+ return;
1053
+ }
1054
+ if (compressed) {
1055
+ const error = this.createError(
1056
+ RangeError,
1057
+ "RSV1 must be clear",
1058
+ true,
1059
+ 1002,
1060
+ "WS_ERR_UNEXPECTED_RSV_1"
1061
+ );
1062
+ cb(error);
1063
+ return;
1064
+ }
1065
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1066
+ const error = this.createError(
1067
+ RangeError,
1068
+ `invalid payload length ${this._payloadLength}`,
1069
+ true,
1070
+ 1002,
1071
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1072
+ );
1073
+ cb(error);
1074
+ return;
1075
+ }
1076
+ } else {
1077
+ const error = this.createError(
1078
+ RangeError,
1079
+ `invalid opcode ${this._opcode}`,
1080
+ true,
1081
+ 1002,
1082
+ "WS_ERR_INVALID_OPCODE"
1083
+ );
1084
+ cb(error);
1085
+ return;
1086
+ }
1087
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1088
+ this._masked = (buf[1] & 128) === 128;
1089
+ if (this._isServer) {
1090
+ if (!this._masked) {
1091
+ const error = this.createError(
1092
+ RangeError,
1093
+ "MASK must be set",
1094
+ true,
1095
+ 1002,
1096
+ "WS_ERR_EXPECTED_MASK"
1097
+ );
1098
+ cb(error);
1099
+ return;
1100
+ }
1101
+ } else if (this._masked) {
1102
+ const error = this.createError(
1103
+ RangeError,
1104
+ "MASK must be clear",
1105
+ true,
1106
+ 1002,
1107
+ "WS_ERR_UNEXPECTED_MASK"
1108
+ );
1109
+ cb(error);
1110
+ return;
1111
+ }
1112
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1113
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1114
+ else this.haveLength(cb);
1115
+ }
1116
+ /**
1117
+ * Gets extended payload length (7+16).
1118
+ *
1119
+ * @param {Function} cb Callback
1120
+ * @private
1121
+ */
1122
+ getPayloadLength16(cb) {
1123
+ if (this._bufferedBytes < 2) {
1124
+ this._loop = false;
1125
+ return;
1126
+ }
1127
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1128
+ this.haveLength(cb);
1129
+ }
1130
+ /**
1131
+ * Gets extended payload length (7+64).
1132
+ *
1133
+ * @param {Function} cb Callback
1134
+ * @private
1135
+ */
1136
+ getPayloadLength64(cb) {
1137
+ if (this._bufferedBytes < 8) {
1138
+ this._loop = false;
1139
+ return;
1140
+ }
1141
+ const buf = this.consume(8);
1142
+ const num = buf.readUInt32BE(0);
1143
+ if (num > Math.pow(2, 53 - 32) - 1) {
1144
+ const error = this.createError(
1145
+ RangeError,
1146
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1147
+ false,
1148
+ 1009,
1149
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1150
+ );
1151
+ cb(error);
1152
+ return;
1153
+ }
1154
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1155
+ this.haveLength(cb);
1156
+ }
1157
+ /**
1158
+ * Payload length has been read.
1159
+ *
1160
+ * @param {Function} cb Callback
1161
+ * @private
1162
+ */
1163
+ haveLength(cb) {
1164
+ if (this._payloadLength && this._opcode < 8) {
1165
+ this._totalPayloadLength += this._payloadLength;
1166
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1167
+ const error = this.createError(
1168
+ RangeError,
1169
+ "Max payload size exceeded",
1170
+ false,
1171
+ 1009,
1172
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1173
+ );
1174
+ cb(error);
1175
+ return;
1176
+ }
1177
+ }
1178
+ if (this._masked) this._state = GET_MASK;
1179
+ else this._state = GET_DATA;
1180
+ }
1181
+ /**
1182
+ * Reads mask bytes.
1183
+ *
1184
+ * @private
1185
+ */
1186
+ getMask() {
1187
+ if (this._bufferedBytes < 4) {
1188
+ this._loop = false;
1189
+ return;
1190
+ }
1191
+ this._mask = this.consume(4);
1192
+ this._state = GET_DATA;
1193
+ }
1194
+ /**
1195
+ * Reads data bytes.
1196
+ *
1197
+ * @param {Function} cb Callback
1198
+ * @private
1199
+ */
1200
+ getData(cb) {
1201
+ let data = EMPTY_BUFFER;
1202
+ if (this._payloadLength) {
1203
+ if (this._bufferedBytes < this._payloadLength) {
1204
+ this._loop = false;
1205
+ return;
1206
+ }
1207
+ data = this.consume(this._payloadLength);
1208
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1209
+ unmask(data, this._mask);
1210
+ }
1211
+ }
1212
+ if (this._opcode > 7) {
1213
+ this.controlMessage(data, cb);
1214
+ return;
1215
+ }
1216
+ if (this._compressed) {
1217
+ this._state = INFLATING;
1218
+ this.decompress(data, cb);
1219
+ return;
1220
+ }
1221
+ if (data.length) {
1222
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1223
+ const error = this.createError(
1224
+ RangeError,
1225
+ "Too many message fragments",
1226
+ false,
1227
+ 1008,
1228
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1229
+ );
1230
+ cb(error);
1231
+ return;
1232
+ }
1233
+ this._messageLength = this._totalPayloadLength;
1234
+ this._fragments.push(data);
1235
+ }
1236
+ this.dataMessage(cb);
1237
+ }
1238
+ /**
1239
+ * Decompresses data.
1240
+ *
1241
+ * @param {Buffer} data Compressed data
1242
+ * @param {Function} cb Callback
1243
+ * @private
1244
+ */
1245
+ decompress(data, cb) {
1246
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1247
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1248
+ if (err) return cb(err);
1249
+ if (buf.length) {
1250
+ this._messageLength += buf.length;
1251
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1252
+ const error = this.createError(
1253
+ RangeError,
1254
+ "Max payload size exceeded",
1255
+ false,
1256
+ 1009,
1257
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1258
+ );
1259
+ cb(error);
1260
+ return;
1261
+ }
1262
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1263
+ const error = this.createError(
1264
+ RangeError,
1265
+ "Too many message fragments",
1266
+ false,
1267
+ 1008,
1268
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1269
+ );
1270
+ cb(error);
1271
+ return;
1272
+ }
1273
+ this._fragments.push(buf);
1274
+ }
1275
+ this.dataMessage(cb);
1276
+ if (this._state === GET_INFO) this.startLoop(cb);
1277
+ });
1278
+ }
1279
+ /**
1280
+ * Handles a data message.
1281
+ *
1282
+ * @param {Function} cb Callback
1283
+ * @private
1284
+ */
1285
+ dataMessage(cb) {
1286
+ if (!this._fin) {
1287
+ this._state = GET_INFO;
1288
+ return;
1289
+ }
1290
+ const messageLength = this._messageLength;
1291
+ const fragments = this._fragments;
1292
+ this._totalPayloadLength = 0;
1293
+ this._messageLength = 0;
1294
+ this._fragmented = 0;
1295
+ this._fragments = [];
1296
+ if (this._opcode === 2) {
1297
+ let data;
1298
+ if (this._binaryType === "nodebuffer") {
1299
+ data = concat(fragments, messageLength);
1300
+ } else if (this._binaryType === "arraybuffer") {
1301
+ data = toArrayBuffer(concat(fragments, messageLength));
1302
+ } else if (this._binaryType === "blob") {
1303
+ data = new Blob(fragments);
1304
+ } else {
1305
+ data = fragments;
1306
+ }
1307
+ if (this._allowSynchronousEvents) {
1308
+ this.emit("message", data, true);
1309
+ this._state = GET_INFO;
1310
+ } else {
1311
+ this._state = DEFER_EVENT;
1312
+ setImmediate(() => {
1313
+ this.emit("message", data, true);
1314
+ this._state = GET_INFO;
1315
+ this.startLoop(cb);
1316
+ });
1317
+ }
1318
+ } else {
1319
+ const buf = concat(fragments, messageLength);
1320
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1321
+ const error = this.createError(
1322
+ Error,
1323
+ "invalid UTF-8 sequence",
1324
+ true,
1325
+ 1007,
1326
+ "WS_ERR_INVALID_UTF8"
1327
+ );
1328
+ cb(error);
1329
+ return;
1330
+ }
1331
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1332
+ this.emit("message", buf, false);
1333
+ this._state = GET_INFO;
1334
+ } else {
1335
+ this._state = DEFER_EVENT;
1336
+ setImmediate(() => {
1337
+ this.emit("message", buf, false);
1338
+ this._state = GET_INFO;
1339
+ this.startLoop(cb);
1340
+ });
1341
+ }
1342
+ }
1343
+ }
1344
+ /**
1345
+ * Handles a control message.
1346
+ *
1347
+ * @param {Buffer} data Data to handle
1348
+ * @return {(Error|RangeError|undefined)} A possible error
1349
+ * @private
1350
+ */
1351
+ controlMessage(data, cb) {
1352
+ if (this._opcode === 8) {
1353
+ if (data.length === 0) {
1354
+ this._loop = false;
1355
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1356
+ this.end();
1357
+ } else {
1358
+ const code = data.readUInt16BE(0);
1359
+ if (!isValidStatusCode(code)) {
1360
+ const error = this.createError(
1361
+ RangeError,
1362
+ `invalid status code ${code}`,
1363
+ true,
1364
+ 1002,
1365
+ "WS_ERR_INVALID_CLOSE_CODE"
1366
+ );
1367
+ cb(error);
1368
+ return;
1369
+ }
1370
+ const buf = new FastBuffer(
1371
+ data.buffer,
1372
+ data.byteOffset + 2,
1373
+ data.length - 2
1374
+ );
1375
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1376
+ const error = this.createError(
1377
+ Error,
1378
+ "invalid UTF-8 sequence",
1379
+ true,
1380
+ 1007,
1381
+ "WS_ERR_INVALID_UTF8"
1382
+ );
1383
+ cb(error);
1384
+ return;
1385
+ }
1386
+ this._loop = false;
1387
+ this.emit("conclude", code, buf);
1388
+ this.end();
1389
+ }
1390
+ this._state = GET_INFO;
1391
+ return;
1392
+ }
1393
+ if (this._allowSynchronousEvents) {
1394
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1395
+ this._state = GET_INFO;
1396
+ } else {
1397
+ this._state = DEFER_EVENT;
1398
+ setImmediate(() => {
1399
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1400
+ this._state = GET_INFO;
1401
+ this.startLoop(cb);
1402
+ });
1403
+ }
1404
+ }
1405
+ /**
1406
+ * Builds an error object.
1407
+ *
1408
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1409
+ * @param {String} message The error message
1410
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1411
+ * `message`
1412
+ * @param {Number} statusCode The status code
1413
+ * @param {String} errorCode The exposed error code
1414
+ * @return {(Error|RangeError)} The error
1415
+ * @private
1416
+ */
1417
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1418
+ this._loop = false;
1419
+ this._errored = true;
1420
+ const err = new ErrorCtor(
1421
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1422
+ );
1423
+ Error.captureStackTrace(err, this.createError);
1424
+ err.code = errorCode;
1425
+ err[kStatusCode] = statusCode;
1426
+ return err;
1427
+ }
1428
+ };
1429
+ module.exports = Receiver2;
1430
+ }
1431
+ });
1432
+
1433
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js
1434
+ var require_sender = __commonJS({
1435
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js"(exports$1, module) {
1436
+ var { Duplex } = __require("stream");
1437
+ var { randomFillSync } = __require("crypto");
1438
+ var {
1439
+ types: { isUint8Array }
1440
+ } = __require("util");
1441
+ var PerMessageDeflate2 = require_permessage_deflate();
1442
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1443
+ var { isBlob: isBlob2, isValidStatusCode } = require_validation();
1444
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1445
+ var kByteLength = Symbol("kByteLength");
1446
+ var maskBuffer = Buffer.alloc(4);
1447
+ var RANDOM_POOL_SIZE = 8 * 1024;
1448
+ var randomPool;
1449
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1450
+ var DEFAULT = 0;
1451
+ var DEFLATING = 1;
1452
+ var GET_BLOB_DATA = 2;
1453
+ var Sender2 = class _Sender {
1454
+ static {
1455
+ __name(this, "Sender");
1456
+ }
1457
+ /**
1458
+ * Creates a Sender instance.
1459
+ *
1460
+ * @param {Duplex} socket The connection socket
1461
+ * @param {Object} [extensions] An object containing the negotiated extensions
1462
+ * @param {Function} [generateMask] The function used to generate the masking
1463
+ * key
1464
+ */
1465
+ constructor(socket, extensions, generateMask) {
1466
+ this._extensions = extensions || {};
1467
+ if (generateMask) {
1468
+ this._generateMask = generateMask;
1469
+ this._maskBuffer = Buffer.alloc(4);
1470
+ }
1471
+ this._socket = socket;
1472
+ this._firstFragment = true;
1473
+ this._compress = false;
1474
+ this._bufferedBytes = 0;
1475
+ this._queue = [];
1476
+ this._state = DEFAULT;
1477
+ this.onerror = NOOP;
1478
+ this[kWebSocket] = void 0;
1479
+ }
1480
+ /**
1481
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1482
+ *
1483
+ * @param {(Buffer|String)} data The data to frame
1484
+ * @param {Object} options Options object
1485
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1486
+ * FIN bit
1487
+ * @param {Function} [options.generateMask] The function used to generate the
1488
+ * masking key
1489
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1490
+ * `data`
1491
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1492
+ * key
1493
+ * @param {Number} options.opcode The opcode
1494
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1495
+ * modified
1496
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1497
+ * RSV1 bit
1498
+ * @return {(Buffer|String)[]} The framed data
1499
+ * @public
1500
+ */
1501
+ static frame(data, options) {
1502
+ let mask;
1503
+ let merge = false;
1504
+ let offset = 2;
1505
+ let skipMasking = false;
1506
+ if (options.mask) {
1507
+ mask = options.maskBuffer || maskBuffer;
1508
+ if (options.generateMask) {
1509
+ options.generateMask(mask);
1510
+ } else {
1511
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1512
+ if (randomPool === void 0) {
1513
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1514
+ }
1515
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1516
+ randomPoolPointer = 0;
1517
+ }
1518
+ mask[0] = randomPool[randomPoolPointer++];
1519
+ mask[1] = randomPool[randomPoolPointer++];
1520
+ mask[2] = randomPool[randomPoolPointer++];
1521
+ mask[3] = randomPool[randomPoolPointer++];
1522
+ }
1523
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1524
+ offset = 6;
1525
+ }
1526
+ let dataLength;
1527
+ if (typeof data === "string") {
1528
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1529
+ dataLength = options[kByteLength];
1530
+ } else {
1531
+ data = Buffer.from(data);
1532
+ dataLength = data.length;
1533
+ }
1534
+ } else {
1535
+ dataLength = data.length;
1536
+ merge = options.mask && options.readOnly && !skipMasking;
1537
+ }
1538
+ let payloadLength = dataLength;
1539
+ if (dataLength >= 65536) {
1540
+ offset += 8;
1541
+ payloadLength = 127;
1542
+ } else if (dataLength > 125) {
1543
+ offset += 2;
1544
+ payloadLength = 126;
1545
+ }
1546
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1547
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1548
+ if (options.rsv1) target[0] |= 64;
1549
+ target[1] = payloadLength;
1550
+ if (payloadLength === 126) {
1551
+ target.writeUInt16BE(dataLength, 2);
1552
+ } else if (payloadLength === 127) {
1553
+ target[2] = target[3] = 0;
1554
+ target.writeUIntBE(dataLength, 4, 6);
1555
+ }
1556
+ if (!options.mask) return [target, data];
1557
+ target[1] |= 128;
1558
+ target[offset - 4] = mask[0];
1559
+ target[offset - 3] = mask[1];
1560
+ target[offset - 2] = mask[2];
1561
+ target[offset - 1] = mask[3];
1562
+ if (skipMasking) return [target, data];
1563
+ if (merge) {
1564
+ applyMask(data, mask, target, offset, dataLength);
1565
+ return [target];
1566
+ }
1567
+ applyMask(data, mask, data, 0, dataLength);
1568
+ return [target, data];
1569
+ }
1570
+ /**
1571
+ * Sends a close message to the other peer.
1572
+ *
1573
+ * @param {Number} [code] The status code component of the body
1574
+ * @param {(String|Buffer)} [data] The message component of the body
1575
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1576
+ * @param {Function} [cb] Callback
1577
+ * @public
1578
+ */
1579
+ close(code, data, mask, cb) {
1580
+ let buf;
1581
+ if (code === void 0) {
1582
+ buf = EMPTY_BUFFER;
1583
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1584
+ throw new TypeError("First argument must be a valid error code number");
1585
+ } else if (data === void 0 || !data.length) {
1586
+ buf = Buffer.allocUnsafe(2);
1587
+ buf.writeUInt16BE(code, 0);
1588
+ } else {
1589
+ const length = Buffer.byteLength(data);
1590
+ if (length > 123) {
1591
+ throw new RangeError("The message must not be greater than 123 bytes");
1592
+ }
1593
+ buf = Buffer.allocUnsafe(2 + length);
1594
+ buf.writeUInt16BE(code, 0);
1595
+ if (typeof data === "string") {
1596
+ buf.write(data, 2);
1597
+ } else if (isUint8Array(data)) {
1598
+ buf.set(data, 2);
1599
+ } else {
1600
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1601
+ }
1602
+ }
1603
+ const options = {
1604
+ [kByteLength]: buf.length,
1605
+ fin: true,
1606
+ generateMask: this._generateMask,
1607
+ mask,
1608
+ maskBuffer: this._maskBuffer,
1609
+ opcode: 8,
1610
+ readOnly: false,
1611
+ rsv1: false
1612
+ };
1613
+ if (this._state !== DEFAULT) {
1614
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1615
+ } else {
1616
+ this.sendFrame(_Sender.frame(buf, options), cb);
1617
+ }
1618
+ }
1619
+ /**
1620
+ * Sends a ping message to the other peer.
1621
+ *
1622
+ * @param {*} data The message to send
1623
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1624
+ * @param {Function} [cb] Callback
1625
+ * @public
1626
+ */
1627
+ ping(data, mask, cb) {
1628
+ let byteLength;
1629
+ let readOnly;
1630
+ if (typeof data === "string") {
1631
+ byteLength = Buffer.byteLength(data);
1632
+ readOnly = false;
1633
+ } else if (isBlob2(data)) {
1634
+ byteLength = data.size;
1635
+ readOnly = false;
1636
+ } else {
1637
+ data = toBuffer(data);
1638
+ byteLength = data.length;
1639
+ readOnly = toBuffer.readOnly;
1640
+ }
1641
+ if (byteLength > 125) {
1642
+ throw new RangeError("The data size must not be greater than 125 bytes");
1643
+ }
1644
+ const options = {
1645
+ [kByteLength]: byteLength,
1646
+ fin: true,
1647
+ generateMask: this._generateMask,
1648
+ mask,
1649
+ maskBuffer: this._maskBuffer,
1650
+ opcode: 9,
1651
+ readOnly,
1652
+ rsv1: false
1653
+ };
1654
+ if (isBlob2(data)) {
1655
+ if (this._state !== DEFAULT) {
1656
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1657
+ } else {
1658
+ this.getBlobData(data, false, options, cb);
1659
+ }
1660
+ } else if (this._state !== DEFAULT) {
1661
+ this.enqueue([this.dispatch, data, false, options, cb]);
1662
+ } else {
1663
+ this.sendFrame(_Sender.frame(data, options), cb);
1664
+ }
1665
+ }
1666
+ /**
1667
+ * Sends a pong message to the other peer.
1668
+ *
1669
+ * @param {*} data The message to send
1670
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1671
+ * @param {Function} [cb] Callback
1672
+ * @public
1673
+ */
1674
+ pong(data, mask, cb) {
1675
+ let byteLength;
1676
+ let readOnly;
1677
+ if (typeof data === "string") {
1678
+ byteLength = Buffer.byteLength(data);
1679
+ readOnly = false;
1680
+ } else if (isBlob2(data)) {
1681
+ byteLength = data.size;
1682
+ readOnly = false;
1683
+ } else {
1684
+ data = toBuffer(data);
1685
+ byteLength = data.length;
1686
+ readOnly = toBuffer.readOnly;
1687
+ }
1688
+ if (byteLength > 125) {
1689
+ throw new RangeError("The data size must not be greater than 125 bytes");
1690
+ }
1691
+ const options = {
1692
+ [kByteLength]: byteLength,
1693
+ fin: true,
1694
+ generateMask: this._generateMask,
1695
+ mask,
1696
+ maskBuffer: this._maskBuffer,
1697
+ opcode: 10,
1698
+ readOnly,
1699
+ rsv1: false
1700
+ };
1701
+ if (isBlob2(data)) {
1702
+ if (this._state !== DEFAULT) {
1703
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1704
+ } else {
1705
+ this.getBlobData(data, false, options, cb);
1706
+ }
1707
+ } else if (this._state !== DEFAULT) {
1708
+ this.enqueue([this.dispatch, data, false, options, cb]);
1709
+ } else {
1710
+ this.sendFrame(_Sender.frame(data, options), cb);
1711
+ }
1712
+ }
1713
+ /**
1714
+ * Sends a data message to the other peer.
1715
+ *
1716
+ * @param {*} data The message to send
1717
+ * @param {Object} options Options object
1718
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1719
+ * or text
1720
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1721
+ * compress `data`
1722
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1723
+ * last one
1724
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1725
+ * `data`
1726
+ * @param {Function} [cb] Callback
1727
+ * @public
1728
+ */
1729
+ send(data, options, cb) {
1730
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1731
+ let opcode = options.binary ? 2 : 1;
1732
+ let rsv1 = options.compress;
1733
+ let byteLength;
1734
+ let readOnly;
1735
+ if (typeof data === "string") {
1736
+ byteLength = Buffer.byteLength(data);
1737
+ readOnly = false;
1738
+ } else if (isBlob2(data)) {
1739
+ byteLength = data.size;
1740
+ readOnly = false;
1741
+ } else {
1742
+ data = toBuffer(data);
1743
+ byteLength = data.length;
1744
+ readOnly = toBuffer.readOnly;
1745
+ }
1746
+ if (this._firstFragment) {
1747
+ this._firstFragment = false;
1748
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1749
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1750
+ }
1751
+ this._compress = rsv1;
1752
+ } else {
1753
+ rsv1 = false;
1754
+ opcode = 0;
1755
+ }
1756
+ if (options.fin) this._firstFragment = true;
1757
+ const opts = {
1758
+ [kByteLength]: byteLength,
1759
+ fin: options.fin,
1760
+ generateMask: this._generateMask,
1761
+ mask: options.mask,
1762
+ maskBuffer: this._maskBuffer,
1763
+ opcode,
1764
+ readOnly,
1765
+ rsv1
1766
+ };
1767
+ if (isBlob2(data)) {
1768
+ if (this._state !== DEFAULT) {
1769
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1770
+ } else {
1771
+ this.getBlobData(data, this._compress, opts, cb);
1772
+ }
1773
+ } else if (this._state !== DEFAULT) {
1774
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1775
+ } else {
1776
+ this.dispatch(data, this._compress, opts, cb);
1777
+ }
1778
+ }
1779
+ /**
1780
+ * Gets the contents of a blob as binary data.
1781
+ *
1782
+ * @param {Blob} blob The blob
1783
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1784
+ * the data
1785
+ * @param {Object} options Options object
1786
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1787
+ * FIN bit
1788
+ * @param {Function} [options.generateMask] The function used to generate the
1789
+ * masking key
1790
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1791
+ * `data`
1792
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1793
+ * key
1794
+ * @param {Number} options.opcode The opcode
1795
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1796
+ * modified
1797
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1798
+ * RSV1 bit
1799
+ * @param {Function} [cb] Callback
1800
+ * @private
1801
+ */
1802
+ getBlobData(blob, compress, options, cb) {
1803
+ this._bufferedBytes += options[kByteLength];
1804
+ this._state = GET_BLOB_DATA;
1805
+ blob.arrayBuffer().then((arrayBuffer) => {
1806
+ if (this._socket.destroyed) {
1807
+ const err = new Error(
1808
+ "The socket was closed while the blob was being read"
1809
+ );
1810
+ process.nextTick(callCallbacks, this, err, cb);
1811
+ return;
1812
+ }
1813
+ this._bufferedBytes -= options[kByteLength];
1814
+ const data = toBuffer(arrayBuffer);
1815
+ if (!compress) {
1816
+ this._state = DEFAULT;
1817
+ this.sendFrame(_Sender.frame(data, options), cb);
1818
+ this.dequeue();
1819
+ } else {
1820
+ this.dispatch(data, compress, options, cb);
1821
+ }
1822
+ }).catch((err) => {
1823
+ process.nextTick(onError, this, err, cb);
1824
+ });
1825
+ }
1826
+ /**
1827
+ * Dispatches a message.
1828
+ *
1829
+ * @param {(Buffer|String)} data The message to send
1830
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1831
+ * `data`
1832
+ * @param {Object} options Options object
1833
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1834
+ * FIN bit
1835
+ * @param {Function} [options.generateMask] The function used to generate the
1836
+ * masking key
1837
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1838
+ * `data`
1839
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1840
+ * key
1841
+ * @param {Number} options.opcode The opcode
1842
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1843
+ * modified
1844
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1845
+ * RSV1 bit
1846
+ * @param {Function} [cb] Callback
1847
+ * @private
1848
+ */
1849
+ dispatch(data, compress, options, cb) {
1850
+ if (!compress) {
1851
+ this.sendFrame(_Sender.frame(data, options), cb);
1852
+ return;
1853
+ }
1854
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1855
+ this._bufferedBytes += options[kByteLength];
1856
+ this._state = DEFLATING;
1857
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1858
+ if (this._socket.destroyed) {
1859
+ const err = new Error(
1860
+ "The socket was closed while data was being compressed"
1861
+ );
1862
+ callCallbacks(this, err, cb);
1863
+ return;
1864
+ }
1865
+ this._bufferedBytes -= options[kByteLength];
1866
+ this._state = DEFAULT;
1867
+ options.readOnly = false;
1868
+ this.sendFrame(_Sender.frame(buf, options), cb);
1869
+ this.dequeue();
1870
+ });
1871
+ }
1872
+ /**
1873
+ * Executes queued send operations.
1874
+ *
1875
+ * @private
1876
+ */
1877
+ dequeue() {
1878
+ while (this._state === DEFAULT && this._queue.length) {
1879
+ const params = this._queue.shift();
1880
+ this._bufferedBytes -= params[3][kByteLength];
1881
+ Reflect.apply(params[0], this, params.slice(1));
1882
+ }
1883
+ }
1884
+ /**
1885
+ * Enqueues a send operation.
1886
+ *
1887
+ * @param {Array} params Send operation parameters.
1888
+ * @private
1889
+ */
1890
+ enqueue(params) {
1891
+ this._bufferedBytes += params[3][kByteLength];
1892
+ this._queue.push(params);
1893
+ }
1894
+ /**
1895
+ * Sends a frame.
1896
+ *
1897
+ * @param {(Buffer | String)[]} list The frame to send
1898
+ * @param {Function} [cb] Callback
1899
+ * @private
1900
+ */
1901
+ sendFrame(list, cb) {
1902
+ if (list.length === 2) {
1903
+ this._socket.cork();
1904
+ this._socket.write(list[0]);
1905
+ this._socket.write(list[1], cb);
1906
+ this._socket.uncork();
1907
+ } else {
1908
+ this._socket.write(list[0], cb);
1909
+ }
1910
+ }
1911
+ };
1912
+ module.exports = Sender2;
1913
+ function callCallbacks(sender, err, cb) {
1914
+ if (typeof cb === "function") cb(err);
1915
+ for (let i = 0; i < sender._queue.length; i++) {
1916
+ const params = sender._queue[i];
1917
+ const callback = params[params.length - 1];
1918
+ if (typeof callback === "function") callback(err);
1919
+ }
1920
+ }
1921
+ __name(callCallbacks, "callCallbacks");
1922
+ function onError(sender, err, cb) {
1923
+ callCallbacks(sender, err, cb);
1924
+ sender.onerror(err);
1925
+ }
1926
+ __name(onError, "onError");
1927
+ }
1928
+ });
1929
+
1930
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js
1931
+ var require_event_target = __commonJS({
1932
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js"(exports$1, module) {
1933
+ var { kForOnEventAttribute, kListener } = require_constants();
1934
+ var kCode = Symbol("kCode");
1935
+ var kData = Symbol("kData");
1936
+ var kError = Symbol("kError");
1937
+ var kMessage = Symbol("kMessage");
1938
+ var kReason = Symbol("kReason");
1939
+ var kTarget = Symbol("kTarget");
1940
+ var kType = Symbol("kType");
1941
+ var kWasClean = Symbol("kWasClean");
1942
+ var Event = class {
1943
+ static {
1944
+ __name(this, "Event");
1945
+ }
1946
+ /**
1947
+ * Create a new `Event`.
1948
+ *
1949
+ * @param {String} type The name of the event
1950
+ * @throws {TypeError} If the `type` argument is not specified
1951
+ */
1952
+ constructor(type) {
1953
+ this[kTarget] = null;
1954
+ this[kType] = type;
1955
+ }
1956
+ /**
1957
+ * @type {*}
1958
+ */
1959
+ get target() {
1960
+ return this[kTarget];
1961
+ }
1962
+ /**
1963
+ * @type {String}
1964
+ */
1965
+ get type() {
1966
+ return this[kType];
1967
+ }
1968
+ };
1969
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1970
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1971
+ var CloseEvent = class extends Event {
1972
+ static {
1973
+ __name(this, "CloseEvent");
1974
+ }
1975
+ /**
1976
+ * Create a new `CloseEvent`.
1977
+ *
1978
+ * @param {String} type The name of the event
1979
+ * @param {Object} [options] A dictionary object that allows for setting
1980
+ * attributes via object members of the same name
1981
+ * @param {Number} [options.code=0] The status code explaining why the
1982
+ * connection was closed
1983
+ * @param {String} [options.reason=''] A human-readable string explaining why
1984
+ * the connection was closed
1985
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1986
+ * connection was cleanly closed
1987
+ */
1988
+ constructor(type, options = {}) {
1989
+ super(type);
1990
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1991
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1992
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1993
+ }
1994
+ /**
1995
+ * @type {Number}
1996
+ */
1997
+ get code() {
1998
+ return this[kCode];
1999
+ }
2000
+ /**
2001
+ * @type {String}
2002
+ */
2003
+ get reason() {
2004
+ return this[kReason];
2005
+ }
2006
+ /**
2007
+ * @type {Boolean}
2008
+ */
2009
+ get wasClean() {
2010
+ return this[kWasClean];
2011
+ }
2012
+ };
2013
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
2014
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
2015
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
2016
+ var ErrorEvent = class extends Event {
2017
+ static {
2018
+ __name(this, "ErrorEvent");
2019
+ }
2020
+ /**
2021
+ * Create a new `ErrorEvent`.
2022
+ *
2023
+ * @param {String} type The name of the event
2024
+ * @param {Object} [options] A dictionary object that allows for setting
2025
+ * attributes via object members of the same name
2026
+ * @param {*} [options.error=null] The error that generated this event
2027
+ * @param {String} [options.message=''] The error message
2028
+ */
2029
+ constructor(type, options = {}) {
2030
+ super(type);
2031
+ this[kError] = options.error === void 0 ? null : options.error;
2032
+ this[kMessage] = options.message === void 0 ? "" : options.message;
2033
+ }
2034
+ /**
2035
+ * @type {*}
2036
+ */
2037
+ get error() {
2038
+ return this[kError];
2039
+ }
2040
+ /**
2041
+ * @type {String}
2042
+ */
2043
+ get message() {
2044
+ return this[kMessage];
2045
+ }
2046
+ };
2047
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2048
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2049
+ var MessageEvent = class extends Event {
2050
+ static {
2051
+ __name(this, "MessageEvent");
2052
+ }
2053
+ /**
2054
+ * Create a new `MessageEvent`.
2055
+ *
2056
+ * @param {String} type The name of the event
2057
+ * @param {Object} [options] A dictionary object that allows for setting
2058
+ * attributes via object members of the same name
2059
+ * @param {*} [options.data=null] The message content
2060
+ */
2061
+ constructor(type, options = {}) {
2062
+ super(type);
2063
+ this[kData] = options.data === void 0 ? null : options.data;
2064
+ }
2065
+ /**
2066
+ * @type {*}
2067
+ */
2068
+ get data() {
2069
+ return this[kData];
2070
+ }
2071
+ };
2072
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2073
+ var EventTarget = {
2074
+ /**
2075
+ * Register an event listener.
2076
+ *
2077
+ * @param {String} type A string representing the event type to listen for
2078
+ * @param {(Function|Object)} handler The listener to add
2079
+ * @param {Object} [options] An options object specifies characteristics about
2080
+ * the event listener
2081
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2082
+ * listener should be invoked at most once after being added. If `true`,
2083
+ * the listener would be automatically removed when invoked.
2084
+ * @public
2085
+ */
2086
+ addEventListener(type, handler, options = {}) {
2087
+ for (const listener of this.listeners(type)) {
2088
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2089
+ return;
2090
+ }
2091
+ }
2092
+ let wrapper;
2093
+ if (type === "message") {
2094
+ wrapper = /* @__PURE__ */ __name(function onMessage(data, isBinary) {
2095
+ const event = new MessageEvent("message", {
2096
+ data: isBinary ? data : data.toString()
2097
+ });
2098
+ event[kTarget] = this;
2099
+ callListener(handler, this, event);
2100
+ }, "onMessage");
2101
+ } else if (type === "close") {
2102
+ wrapper = /* @__PURE__ */ __name(function onClose(code, message) {
2103
+ const event = new CloseEvent("close", {
2104
+ code,
2105
+ reason: message.toString(),
2106
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2107
+ });
2108
+ event[kTarget] = this;
2109
+ callListener(handler, this, event);
2110
+ }, "onClose");
2111
+ } else if (type === "error") {
2112
+ wrapper = /* @__PURE__ */ __name(function onError(error) {
2113
+ const event = new ErrorEvent("error", {
2114
+ error,
2115
+ message: error.message
2116
+ });
2117
+ event[kTarget] = this;
2118
+ callListener(handler, this, event);
2119
+ }, "onError");
2120
+ } else if (type === "open") {
2121
+ wrapper = /* @__PURE__ */ __name(function onOpen() {
2122
+ const event = new Event("open");
2123
+ event[kTarget] = this;
2124
+ callListener(handler, this, event);
2125
+ }, "onOpen");
2126
+ } else {
2127
+ return;
2128
+ }
2129
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2130
+ wrapper[kListener] = handler;
2131
+ if (options.once) {
2132
+ this.once(type, wrapper);
2133
+ } else {
2134
+ this.on(type, wrapper);
2135
+ }
2136
+ },
2137
+ /**
2138
+ * Remove an event listener.
2139
+ *
2140
+ * @param {String} type A string representing the event type to remove
2141
+ * @param {(Function|Object)} handler The listener to remove
2142
+ * @public
2143
+ */
2144
+ removeEventListener(type, handler) {
2145
+ for (const listener of this.listeners(type)) {
2146
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2147
+ this.removeListener(type, listener);
2148
+ break;
2149
+ }
2150
+ }
2151
+ }
2152
+ };
2153
+ module.exports = {
2154
+ CloseEvent,
2155
+ ErrorEvent,
2156
+ Event,
2157
+ EventTarget,
2158
+ MessageEvent
2159
+ };
2160
+ function callListener(listener, thisArg, event) {
2161
+ if (typeof listener === "object" && listener.handleEvent) {
2162
+ listener.handleEvent.call(listener, event);
2163
+ } else {
2164
+ listener.call(thisArg, event);
2165
+ }
2166
+ }
2167
+ __name(callListener, "callListener");
2168
+ }
2169
+ });
2170
+
2171
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js
2172
+ var require_extension = __commonJS({
2173
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js"(exports$1, module) {
2174
+ var { tokenChars } = require_validation();
2175
+ function push(dest, name, elem) {
2176
+ if (dest[name] === void 0) dest[name] = [elem];
2177
+ else dest[name].push(elem);
2178
+ }
2179
+ __name(push, "push");
2180
+ function parse(header) {
2181
+ const offers = /* @__PURE__ */ Object.create(null);
2182
+ let params = /* @__PURE__ */ Object.create(null);
2183
+ let mustUnescape = false;
2184
+ let isEscaping = false;
2185
+ let inQuotes = false;
2186
+ let extensionName;
2187
+ let paramName;
2188
+ let start = -1;
2189
+ let code = -1;
2190
+ let end = -1;
2191
+ let i = 0;
2192
+ for (; i < header.length; i++) {
2193
+ code = header.charCodeAt(i);
2194
+ if (extensionName === void 0) {
2195
+ if (end === -1 && tokenChars[code] === 1) {
2196
+ if (start === -1) start = i;
2197
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2198
+ if (end === -1 && start !== -1) end = i;
2199
+ } else if (code === 59 || code === 44) {
2200
+ if (start === -1) {
2201
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2202
+ }
2203
+ if (end === -1) end = i;
2204
+ const name = header.slice(start, end);
2205
+ if (code === 44) {
2206
+ push(offers, name, params);
2207
+ params = /* @__PURE__ */ Object.create(null);
2208
+ } else {
2209
+ extensionName = name;
2210
+ }
2211
+ start = end = -1;
2212
+ } else {
2213
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2214
+ }
2215
+ } else if (paramName === void 0) {
2216
+ if (end === -1 && tokenChars[code] === 1) {
2217
+ if (start === -1) start = i;
2218
+ } else if (code === 32 || code === 9) {
2219
+ if (end === -1 && start !== -1) end = i;
2220
+ } else if (code === 59 || code === 44) {
2221
+ if (start === -1) {
2222
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2223
+ }
2224
+ if (end === -1) end = i;
2225
+ push(params, header.slice(start, end), true);
2226
+ if (code === 44) {
2227
+ push(offers, extensionName, params);
2228
+ params = /* @__PURE__ */ Object.create(null);
2229
+ extensionName = void 0;
2230
+ }
2231
+ start = end = -1;
2232
+ } else if (code === 61 && start !== -1 && end === -1) {
2233
+ paramName = header.slice(start, i);
2234
+ start = end = -1;
2235
+ } else {
2236
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2237
+ }
2238
+ } else {
2239
+ if (isEscaping) {
2240
+ if (tokenChars[code] !== 1) {
2241
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2242
+ }
2243
+ if (start === -1) start = i;
2244
+ else if (!mustUnescape) mustUnescape = true;
2245
+ isEscaping = false;
2246
+ } else if (inQuotes) {
2247
+ if (tokenChars[code] === 1) {
2248
+ if (start === -1) start = i;
2249
+ } else if (code === 34 && start !== -1) {
2250
+ inQuotes = false;
2251
+ end = i;
2252
+ } else if (code === 92) {
2253
+ isEscaping = true;
2254
+ } else {
2255
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2256
+ }
2257
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2258
+ inQuotes = true;
2259
+ } else if (end === -1 && tokenChars[code] === 1) {
2260
+ if (start === -1) start = i;
2261
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2262
+ if (end === -1) end = i;
2263
+ } else if (code === 59 || code === 44) {
2264
+ if (start === -1) {
2265
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2266
+ }
2267
+ if (end === -1) end = i;
2268
+ let value = header.slice(start, end);
2269
+ if (mustUnescape) {
2270
+ value = value.replace(/\\/g, "");
2271
+ mustUnescape = false;
2272
+ }
2273
+ push(params, paramName, value);
2274
+ if (code === 44) {
2275
+ push(offers, extensionName, params);
2276
+ params = /* @__PURE__ */ Object.create(null);
2277
+ extensionName = void 0;
2278
+ }
2279
+ paramName = void 0;
2280
+ start = end = -1;
2281
+ } else {
2282
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2283
+ }
2284
+ }
2285
+ }
2286
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2287
+ throw new SyntaxError("Unexpected end of input");
2288
+ }
2289
+ if (end === -1) end = i;
2290
+ const token = header.slice(start, end);
2291
+ if (extensionName === void 0) {
2292
+ push(offers, token, params);
2293
+ } else {
2294
+ if (paramName === void 0) {
2295
+ push(params, token, true);
2296
+ } else if (mustUnescape) {
2297
+ push(params, paramName, token.replace(/\\/g, ""));
2298
+ } else {
2299
+ push(params, paramName, token);
2300
+ }
2301
+ push(offers, extensionName, params);
2302
+ }
2303
+ return offers;
2304
+ }
2305
+ __name(parse, "parse");
2306
+ function format(extensions) {
2307
+ return Object.keys(extensions).map((extension2) => {
2308
+ let configurations = extensions[extension2];
2309
+ if (!Array.isArray(configurations)) configurations = [configurations];
2310
+ return configurations.map((params) => {
2311
+ return [extension2].concat(
2312
+ Object.keys(params).map((k) => {
2313
+ let values = params[k];
2314
+ if (!Array.isArray(values)) values = [values];
2315
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2316
+ })
2317
+ ).join("; ");
2318
+ }).join(", ");
2319
+ }).join(", ");
2320
+ }
2321
+ __name(format, "format");
2322
+ module.exports = { format, parse };
2323
+ }
2324
+ });
2325
+
2326
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js
2327
+ var require_websocket = __commonJS({
2328
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js"(exports$1, module) {
2329
+ var EventEmitter = __require("events");
2330
+ var https = __require("https");
2331
+ var http = __require("http");
2332
+ var net = __require("net");
2333
+ var tls = __require("tls");
2334
+ var { randomBytes, createHash: createHash2 } = __require("crypto");
2335
+ var { Duplex, Readable } = __require("stream");
2336
+ var { URL: URL2 } = __require("url");
2337
+ var PerMessageDeflate2 = require_permessage_deflate();
2338
+ var Receiver2 = require_receiver();
2339
+ var Sender2 = require_sender();
2340
+ var { isBlob: isBlob2 } = require_validation();
2341
+ var {
2342
+ BINARY_TYPES,
2343
+ CLOSE_TIMEOUT,
2344
+ EMPTY_BUFFER,
2345
+ GUID,
2346
+ kForOnEventAttribute,
2347
+ kListener,
2348
+ kStatusCode,
2349
+ kWebSocket,
2350
+ NOOP
2351
+ } = require_constants();
2352
+ var {
2353
+ EventTarget: { addEventListener, removeEventListener }
2354
+ } = require_event_target();
2355
+ var { format, parse } = require_extension();
2356
+ var { toBuffer } = require_buffer_util();
2357
+ var kAborted = Symbol("kAborted");
2358
+ var protocolVersions = [8, 13];
2359
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2360
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2361
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2362
+ static {
2363
+ __name(this, "WebSocket");
2364
+ }
2365
+ /**
2366
+ * Create a new `WebSocket`.
2367
+ *
2368
+ * @param {(String|URL)} address The URL to which to connect
2369
+ * @param {(String|String[])} [protocols] The subprotocols
2370
+ * @param {Object} [options] Connection options
2371
+ */
2372
+ constructor(address, protocols, options) {
2373
+ super();
2374
+ this._binaryType = BINARY_TYPES[0];
2375
+ this._closeCode = 1006;
2376
+ this._closeFrameReceived = false;
2377
+ this._closeFrameSent = false;
2378
+ this._closeMessage = EMPTY_BUFFER;
2379
+ this._closeTimer = null;
2380
+ this._errorEmitted = false;
2381
+ this._extensions = {};
2382
+ this._paused = false;
2383
+ this._protocol = "";
2384
+ this._readyState = _WebSocket.CONNECTING;
2385
+ this._receiver = null;
2386
+ this._sender = null;
2387
+ this._socket = null;
2388
+ if (address !== null) {
2389
+ this._bufferedAmount = 0;
2390
+ this._isServer = false;
2391
+ this._redirects = 0;
2392
+ if (protocols === void 0) {
2393
+ protocols = [];
2394
+ } else if (!Array.isArray(protocols)) {
2395
+ if (typeof protocols === "object" && protocols !== null) {
2396
+ options = protocols;
2397
+ protocols = [];
2398
+ } else {
2399
+ protocols = [protocols];
2400
+ }
2401
+ }
2402
+ initAsClient(this, address, protocols, options);
2403
+ } else {
2404
+ this._autoPong = options.autoPong;
2405
+ this._closeTimeout = options.closeTimeout;
2406
+ this._isServer = true;
2407
+ }
2408
+ }
2409
+ /**
2410
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2411
+ * instead of "blob".
2412
+ *
2413
+ * @type {String}
2414
+ */
2415
+ get binaryType() {
2416
+ return this._binaryType;
2417
+ }
2418
+ set binaryType(type) {
2419
+ if (!BINARY_TYPES.includes(type)) return;
2420
+ this._binaryType = type;
2421
+ if (this._receiver) this._receiver._binaryType = type;
2422
+ }
2423
+ /**
2424
+ * @type {Number}
2425
+ */
2426
+ get bufferedAmount() {
2427
+ if (!this._socket) return this._bufferedAmount;
2428
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2429
+ }
2430
+ /**
2431
+ * @type {String}
2432
+ */
2433
+ get extensions() {
2434
+ return Object.keys(this._extensions).join();
2435
+ }
2436
+ /**
2437
+ * @type {Boolean}
2438
+ */
2439
+ get isPaused() {
2440
+ return this._paused;
2441
+ }
2442
+ /**
2443
+ * @type {Function}
2444
+ */
2445
+ /* istanbul ignore next */
2446
+ get onclose() {
2447
+ return null;
2448
+ }
2449
+ /**
2450
+ * @type {Function}
2451
+ */
2452
+ /* istanbul ignore next */
2453
+ get onerror() {
2454
+ return null;
2455
+ }
2456
+ /**
2457
+ * @type {Function}
2458
+ */
2459
+ /* istanbul ignore next */
2460
+ get onopen() {
2461
+ return null;
2462
+ }
2463
+ /**
2464
+ * @type {Function}
2465
+ */
2466
+ /* istanbul ignore next */
2467
+ get onmessage() {
2468
+ return null;
2469
+ }
2470
+ /**
2471
+ * @type {String}
2472
+ */
2473
+ get protocol() {
2474
+ return this._protocol;
2475
+ }
2476
+ /**
2477
+ * @type {Number}
2478
+ */
2479
+ get readyState() {
2480
+ return this._readyState;
2481
+ }
2482
+ /**
2483
+ * @type {String}
2484
+ */
2485
+ get url() {
2486
+ return this._url;
2487
+ }
2488
+ /**
2489
+ * Set up the socket and the internal resources.
2490
+ *
2491
+ * @param {Duplex} socket The network socket between the server and client
2492
+ * @param {Buffer} head The first packet of the upgraded stream
2493
+ * @param {Object} options Options object
2494
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2495
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2496
+ * multiple times in the same tick
2497
+ * @param {Function} [options.generateMask] The function used to generate the
2498
+ * masking key
2499
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2500
+ * buffered data chunks
2501
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2502
+ * fragments
2503
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2504
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2505
+ * not to skip UTF-8 validation for text and close messages
2506
+ * @private
2507
+ */
2508
+ setSocket(socket, head, options) {
2509
+ const receiver = new Receiver2({
2510
+ allowSynchronousEvents: options.allowSynchronousEvents,
2511
+ binaryType: this.binaryType,
2512
+ extensions: this._extensions,
2513
+ isServer: this._isServer,
2514
+ maxBufferedChunks: options.maxBufferedChunks,
2515
+ maxFragments: options.maxFragments,
2516
+ maxPayload: options.maxPayload,
2517
+ skipUTF8Validation: options.skipUTF8Validation
2518
+ });
2519
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2520
+ this._receiver = receiver;
2521
+ this._sender = sender;
2522
+ this._socket = socket;
2523
+ receiver[kWebSocket] = this;
2524
+ sender[kWebSocket] = this;
2525
+ socket[kWebSocket] = this;
2526
+ receiver.on("conclude", receiverOnConclude);
2527
+ receiver.on("drain", receiverOnDrain);
2528
+ receiver.on("error", receiverOnError);
2529
+ receiver.on("message", receiverOnMessage);
2530
+ receiver.on("ping", receiverOnPing);
2531
+ receiver.on("pong", receiverOnPong);
2532
+ sender.onerror = senderOnError;
2533
+ if (socket.setTimeout) socket.setTimeout(0);
2534
+ if (socket.setNoDelay) socket.setNoDelay();
2535
+ if (head.length > 0) socket.unshift(head);
2536
+ socket.on("close", socketOnClose);
2537
+ socket.on("data", socketOnData);
2538
+ socket.on("end", socketOnEnd);
2539
+ socket.on("error", socketOnError);
2540
+ this._readyState = _WebSocket.OPEN;
2541
+ this.emit("open");
2542
+ }
2543
+ /**
2544
+ * Emit the `'close'` event.
2545
+ *
2546
+ * @private
2547
+ */
2548
+ emitClose() {
2549
+ if (!this._socket) {
2550
+ this._readyState = _WebSocket.CLOSED;
2551
+ this.emit("close", this._closeCode, this._closeMessage);
2552
+ return;
2553
+ }
2554
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2555
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2556
+ }
2557
+ this._receiver.removeAllListeners();
2558
+ this._readyState = _WebSocket.CLOSED;
2559
+ this.emit("close", this._closeCode, this._closeMessage);
2560
+ }
2561
+ /**
2562
+ * Start a closing handshake.
2563
+ *
2564
+ * +----------+ +-----------+ +----------+
2565
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2566
+ * | +----------+ +-----------+ +----------+ |
2567
+ * +----------+ +-----------+ |
2568
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2569
+ * +----------+ +-----------+ |
2570
+ * | | | +---+ |
2571
+ * +------------------------+-->|fin| - - - -
2572
+ * | +---+ | +---+
2573
+ * - - - - -|fin|<---------------------+
2574
+ * +---+
2575
+ *
2576
+ * @param {Number} [code] Status code explaining why the connection is closing
2577
+ * @param {(String|Buffer)} [data] The reason why the connection is
2578
+ * closing
2579
+ * @public
2580
+ */
2581
+ close(code, data) {
2582
+ if (this.readyState === _WebSocket.CLOSED) return;
2583
+ if (this.readyState === _WebSocket.CONNECTING) {
2584
+ const msg = "WebSocket was closed before the connection was established";
2585
+ abortHandshake(this, this._req, msg);
2586
+ return;
2587
+ }
2588
+ if (this.readyState === _WebSocket.CLOSING) {
2589
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2590
+ this._socket.end();
2591
+ }
2592
+ return;
2593
+ }
2594
+ this._readyState = _WebSocket.CLOSING;
2595
+ this._sender.close(code, data, !this._isServer, (err) => {
2596
+ if (err) return;
2597
+ this._closeFrameSent = true;
2598
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2599
+ this._socket.end();
2600
+ }
2601
+ });
2602
+ setCloseTimer(this);
2603
+ }
2604
+ /**
2605
+ * Pause the socket.
2606
+ *
2607
+ * @public
2608
+ */
2609
+ pause() {
2610
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2611
+ return;
2612
+ }
2613
+ this._paused = true;
2614
+ this._socket.pause();
2615
+ }
2616
+ /**
2617
+ * Send a ping.
2618
+ *
2619
+ * @param {*} [data] The data to send
2620
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2621
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2622
+ * @public
2623
+ */
2624
+ ping(data, mask, cb) {
2625
+ if (this.readyState === _WebSocket.CONNECTING) {
2626
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2627
+ }
2628
+ if (typeof data === "function") {
2629
+ cb = data;
2630
+ data = mask = void 0;
2631
+ } else if (typeof mask === "function") {
2632
+ cb = mask;
2633
+ mask = void 0;
2634
+ }
2635
+ if (typeof data === "number") data = data.toString();
2636
+ if (this.readyState !== _WebSocket.OPEN) {
2637
+ sendAfterClose(this, data, cb);
2638
+ return;
2639
+ }
2640
+ if (mask === void 0) mask = !this._isServer;
2641
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2642
+ }
2643
+ /**
2644
+ * Send a pong.
2645
+ *
2646
+ * @param {*} [data] The data to send
2647
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2648
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2649
+ * @public
2650
+ */
2651
+ pong(data, mask, cb) {
2652
+ if (this.readyState === _WebSocket.CONNECTING) {
2653
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2654
+ }
2655
+ if (typeof data === "function") {
2656
+ cb = data;
2657
+ data = mask = void 0;
2658
+ } else if (typeof mask === "function") {
2659
+ cb = mask;
2660
+ mask = void 0;
2661
+ }
2662
+ if (typeof data === "number") data = data.toString();
2663
+ if (this.readyState !== _WebSocket.OPEN) {
2664
+ sendAfterClose(this, data, cb);
2665
+ return;
2666
+ }
2667
+ if (mask === void 0) mask = !this._isServer;
2668
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2669
+ }
2670
+ /**
2671
+ * Resume the socket.
2672
+ *
2673
+ * @public
2674
+ */
2675
+ resume() {
2676
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2677
+ return;
2678
+ }
2679
+ this._paused = false;
2680
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2681
+ }
2682
+ /**
2683
+ * Send a data message.
2684
+ *
2685
+ * @param {*} data The message to send
2686
+ * @param {Object} [options] Options object
2687
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2688
+ * text
2689
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2690
+ * `data`
2691
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2692
+ * last one
2693
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2694
+ * @param {Function} [cb] Callback which is executed when data is written out
2695
+ * @public
2696
+ */
2697
+ send(data, options, cb) {
2698
+ if (this.readyState === _WebSocket.CONNECTING) {
2699
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2700
+ }
2701
+ if (typeof options === "function") {
2702
+ cb = options;
2703
+ options = {};
2704
+ }
2705
+ if (typeof data === "number") data = data.toString();
2706
+ if (this.readyState !== _WebSocket.OPEN) {
2707
+ sendAfterClose(this, data, cb);
2708
+ return;
2709
+ }
2710
+ const opts = {
2711
+ binary: typeof data !== "string",
2712
+ mask: !this._isServer,
2713
+ compress: true,
2714
+ fin: true,
2715
+ ...options
2716
+ };
2717
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2718
+ opts.compress = false;
2719
+ }
2720
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2721
+ }
2722
+ /**
2723
+ * Forcibly close the connection.
2724
+ *
2725
+ * @public
2726
+ */
2727
+ terminate() {
2728
+ if (this.readyState === _WebSocket.CLOSED) return;
2729
+ if (this.readyState === _WebSocket.CONNECTING) {
2730
+ const msg = "WebSocket was closed before the connection was established";
2731
+ abortHandshake(this, this._req, msg);
2732
+ return;
2733
+ }
2734
+ if (this._socket) {
2735
+ this._readyState = _WebSocket.CLOSING;
2736
+ this._socket.destroy();
2737
+ }
2738
+ }
2739
+ };
2740
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2741
+ enumerable: true,
2742
+ value: readyStates.indexOf("CONNECTING")
2743
+ });
2744
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2745
+ enumerable: true,
2746
+ value: readyStates.indexOf("CONNECTING")
2747
+ });
2748
+ Object.defineProperty(WebSocket2, "OPEN", {
2749
+ enumerable: true,
2750
+ value: readyStates.indexOf("OPEN")
2751
+ });
2752
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2753
+ enumerable: true,
2754
+ value: readyStates.indexOf("OPEN")
2755
+ });
2756
+ Object.defineProperty(WebSocket2, "CLOSING", {
2757
+ enumerable: true,
2758
+ value: readyStates.indexOf("CLOSING")
2759
+ });
2760
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2761
+ enumerable: true,
2762
+ value: readyStates.indexOf("CLOSING")
2763
+ });
2764
+ Object.defineProperty(WebSocket2, "CLOSED", {
2765
+ enumerable: true,
2766
+ value: readyStates.indexOf("CLOSED")
2767
+ });
2768
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2769
+ enumerable: true,
2770
+ value: readyStates.indexOf("CLOSED")
2771
+ });
2772
+ [
2773
+ "binaryType",
2774
+ "bufferedAmount",
2775
+ "extensions",
2776
+ "isPaused",
2777
+ "protocol",
2778
+ "readyState",
2779
+ "url"
2780
+ ].forEach((property) => {
2781
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2782
+ });
2783
+ ["open", "error", "close", "message"].forEach((method) => {
2784
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2785
+ enumerable: true,
2786
+ get() {
2787
+ for (const listener of this.listeners(method)) {
2788
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2789
+ }
2790
+ return null;
2791
+ },
2792
+ set(handler) {
2793
+ for (const listener of this.listeners(method)) {
2794
+ if (listener[kForOnEventAttribute]) {
2795
+ this.removeListener(method, listener);
2796
+ break;
2797
+ }
2798
+ }
2799
+ if (typeof handler !== "function") return;
2800
+ this.addEventListener(method, handler, {
2801
+ [kForOnEventAttribute]: true
2802
+ });
2803
+ }
2804
+ });
2805
+ });
2806
+ WebSocket2.prototype.addEventListener = addEventListener;
2807
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2808
+ module.exports = WebSocket2;
2809
+ function initAsClient(websocket, address, protocols, options) {
2810
+ const opts = {
2811
+ allowSynchronousEvents: true,
2812
+ autoPong: true,
2813
+ closeTimeout: CLOSE_TIMEOUT,
2814
+ protocolVersion: protocolVersions[1],
2815
+ maxBufferedChunks: 1024 * 1024,
2816
+ maxFragments: 128 * 1024,
2817
+ maxPayload: 100 * 1024 * 1024,
2818
+ skipUTF8Validation: false,
2819
+ perMessageDeflate: true,
2820
+ followRedirects: false,
2821
+ maxRedirects: 10,
2822
+ ...options,
2823
+ socketPath: void 0,
2824
+ hostname: void 0,
2825
+ protocol: void 0,
2826
+ timeout: void 0,
2827
+ method: "GET",
2828
+ host: void 0,
2829
+ path: void 0,
2830
+ port: void 0
2831
+ };
2832
+ websocket._autoPong = opts.autoPong;
2833
+ websocket._closeTimeout = opts.closeTimeout;
2834
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2835
+ throw new RangeError(
2836
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2837
+ );
2838
+ }
2839
+ let parsedUrl;
2840
+ if (address instanceof URL2) {
2841
+ parsedUrl = address;
2842
+ } else {
2843
+ try {
2844
+ parsedUrl = new URL2(address);
2845
+ } catch {
2846
+ throw new SyntaxError(`Invalid URL: ${address}`);
2847
+ }
2848
+ }
2849
+ if (parsedUrl.protocol === "http:") {
2850
+ parsedUrl.protocol = "ws:";
2851
+ } else if (parsedUrl.protocol === "https:") {
2852
+ parsedUrl.protocol = "wss:";
2853
+ }
2854
+ websocket._url = parsedUrl.href;
2855
+ const isSecure = parsedUrl.protocol === "wss:";
2856
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2857
+ let invalidUrlMessage;
2858
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2859
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2860
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2861
+ invalidUrlMessage = "The URL's pathname is empty";
2862
+ } else if (parsedUrl.hash) {
2863
+ invalidUrlMessage = "The URL contains a fragment identifier";
2864
+ }
2865
+ if (invalidUrlMessage) {
2866
+ const err = new SyntaxError(invalidUrlMessage);
2867
+ if (websocket._redirects === 0) {
2868
+ throw err;
2869
+ } else {
2870
+ emitErrorAndClose(websocket, err);
2871
+ return;
2872
+ }
2873
+ }
2874
+ const defaultPort = isSecure ? 443 : 80;
2875
+ const key = randomBytes(16).toString("base64");
2876
+ const request2 = isSecure ? https.request : http.request;
2877
+ const protocolSet = /* @__PURE__ */ new Set();
2878
+ let perMessageDeflate;
2879
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2880
+ opts.defaultPort = opts.defaultPort || defaultPort;
2881
+ opts.port = parsedUrl.port || defaultPort;
2882
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2883
+ opts.headers = {
2884
+ ...opts.headers,
2885
+ "Sec-WebSocket-Version": opts.protocolVersion,
2886
+ "Sec-WebSocket-Key": key,
2887
+ Connection: "Upgrade",
2888
+ Upgrade: "websocket"
2889
+ };
2890
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2891
+ opts.timeout = opts.handshakeTimeout;
2892
+ if (opts.perMessageDeflate) {
2893
+ perMessageDeflate = new PerMessageDeflate2({
2894
+ ...opts.perMessageDeflate,
2895
+ isServer: false,
2896
+ maxPayload: opts.maxPayload
2897
+ });
2898
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2899
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2900
+ });
2901
+ }
2902
+ if (protocols.length) {
2903
+ for (const protocol of protocols) {
2904
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2905
+ throw new SyntaxError(
2906
+ "An invalid or duplicated subprotocol was specified"
2907
+ );
2908
+ }
2909
+ protocolSet.add(protocol);
2910
+ }
2911
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2912
+ }
2913
+ if (opts.origin) {
2914
+ if (opts.protocolVersion < 13) {
2915
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2916
+ } else {
2917
+ opts.headers.Origin = opts.origin;
2918
+ }
2919
+ }
2920
+ if (parsedUrl.username || parsedUrl.password) {
2921
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2922
+ }
2923
+ if (isIpcUrl) {
2924
+ const parts = opts.path.split(":");
2925
+ opts.socketPath = parts[0];
2926
+ opts.path = parts[1];
2927
+ }
2928
+ let req;
2929
+ if (opts.followRedirects) {
2930
+ if (websocket._redirects === 0) {
2931
+ websocket._originalIpc = isIpcUrl;
2932
+ websocket._originalSecure = isSecure;
2933
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2934
+ const headers = options && options.headers;
2935
+ options = { ...options, headers: {} };
2936
+ if (headers) {
2937
+ for (const [key2, value] of Object.entries(headers)) {
2938
+ options.headers[key2.toLowerCase()] = value;
2939
+ }
2940
+ }
2941
+ } else if (websocket.listenerCount("redirect") === 0) {
2942
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2943
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2944
+ delete opts.headers.authorization;
2945
+ delete opts.headers.cookie;
2946
+ if (!isSameHost) delete opts.headers.host;
2947
+ opts.auth = void 0;
2948
+ }
2949
+ }
2950
+ if (opts.auth && !options.headers.authorization) {
2951
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2952
+ }
2953
+ req = websocket._req = request2(opts);
2954
+ if (websocket._redirects) {
2955
+ websocket.emit("redirect", websocket.url, req);
2956
+ }
2957
+ } else {
2958
+ req = websocket._req = request2(opts);
2959
+ }
2960
+ if (opts.timeout) {
2961
+ req.on("timeout", () => {
2962
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2963
+ });
2964
+ }
2965
+ req.on("error", (err) => {
2966
+ if (req === null || req[kAborted]) return;
2967
+ req = websocket._req = null;
2968
+ emitErrorAndClose(websocket, err);
2969
+ });
2970
+ req.on("response", (res) => {
2971
+ const location = res.headers.location;
2972
+ const statusCode = res.statusCode;
2973
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2974
+ if (++websocket._redirects > opts.maxRedirects) {
2975
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2976
+ return;
2977
+ }
2978
+ req.abort();
2979
+ let addr;
2980
+ try {
2981
+ addr = new URL2(location, address);
2982
+ } catch (e) {
2983
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2984
+ emitErrorAndClose(websocket, err);
2985
+ return;
2986
+ }
2987
+ initAsClient(websocket, addr, protocols, options);
2988
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2989
+ abortHandshake(
2990
+ websocket,
2991
+ req,
2992
+ `Unexpected server response: ${res.statusCode}`
2993
+ );
2994
+ }
2995
+ });
2996
+ req.on("upgrade", (res, socket, head) => {
2997
+ websocket.emit("upgrade", res);
2998
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2999
+ req = websocket._req = null;
3000
+ const upgrade = res.headers.upgrade;
3001
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3002
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
3003
+ return;
3004
+ }
3005
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
3006
+ if (res.headers["sec-websocket-accept"] !== digest) {
3007
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3008
+ return;
3009
+ }
3010
+ const serverProt = res.headers["sec-websocket-protocol"];
3011
+ let protError;
3012
+ if (serverProt !== void 0) {
3013
+ if (!protocolSet.size) {
3014
+ protError = "Server sent a subprotocol but none was requested";
3015
+ } else if (!protocolSet.has(serverProt)) {
3016
+ protError = "Server sent an invalid subprotocol";
3017
+ }
3018
+ } else if (protocolSet.size) {
3019
+ protError = "Server sent no subprotocol";
3020
+ }
3021
+ if (protError) {
3022
+ abortHandshake(websocket, socket, protError);
3023
+ return;
3024
+ }
3025
+ if (serverProt) websocket._protocol = serverProt;
3026
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
3027
+ if (secWebSocketExtensions !== void 0) {
3028
+ if (!perMessageDeflate) {
3029
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
3030
+ abortHandshake(websocket, socket, message);
3031
+ return;
3032
+ }
3033
+ let extensions;
3034
+ try {
3035
+ extensions = parse(secWebSocketExtensions);
3036
+ } catch (err) {
3037
+ const message = "Invalid Sec-WebSocket-Extensions header";
3038
+ abortHandshake(websocket, socket, message);
3039
+ return;
3040
+ }
3041
+ const extensionNames = Object.keys(extensions);
3042
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
3043
+ const message = "Server indicated an extension that was not requested";
3044
+ abortHandshake(websocket, socket, message);
3045
+ return;
3046
+ }
3047
+ try {
3048
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
3049
+ } catch (err) {
3050
+ const message = "Invalid Sec-WebSocket-Extensions header";
3051
+ abortHandshake(websocket, socket, message);
3052
+ return;
3053
+ }
3054
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3055
+ }
3056
+ websocket.setSocket(socket, head, {
3057
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3058
+ generateMask: opts.generateMask,
3059
+ maxBufferedChunks: opts.maxBufferedChunks,
3060
+ maxFragments: opts.maxFragments,
3061
+ maxPayload: opts.maxPayload,
3062
+ skipUTF8Validation: opts.skipUTF8Validation
3063
+ });
3064
+ });
3065
+ if (opts.finishRequest) {
3066
+ opts.finishRequest(req, websocket);
3067
+ } else {
3068
+ req.end();
3069
+ }
3070
+ }
3071
+ __name(initAsClient, "initAsClient");
3072
+ function emitErrorAndClose(websocket, err) {
3073
+ websocket._readyState = WebSocket2.CLOSING;
3074
+ websocket._errorEmitted = true;
3075
+ websocket.emit("error", err);
3076
+ websocket.emitClose();
3077
+ }
3078
+ __name(emitErrorAndClose, "emitErrorAndClose");
3079
+ function netConnect(options) {
3080
+ options.path = options.socketPath;
3081
+ return net.connect(options);
3082
+ }
3083
+ __name(netConnect, "netConnect");
3084
+ function tlsConnect(options) {
3085
+ options.path = void 0;
3086
+ if (!options.servername && options.servername !== "") {
3087
+ options.servername = net.isIP(options.host) ? "" : options.host;
3088
+ }
3089
+ return tls.connect(options);
3090
+ }
3091
+ __name(tlsConnect, "tlsConnect");
3092
+ function abortHandshake(websocket, stream, message) {
3093
+ websocket._readyState = WebSocket2.CLOSING;
3094
+ const err = new Error(message);
3095
+ Error.captureStackTrace(err, abortHandshake);
3096
+ if (stream.setHeader) {
3097
+ stream[kAborted] = true;
3098
+ stream.abort();
3099
+ if (stream.socket && !stream.socket.destroyed) {
3100
+ stream.socket.destroy();
3101
+ }
3102
+ process.nextTick(emitErrorAndClose, websocket, err);
3103
+ } else {
3104
+ stream.destroy(err);
3105
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3106
+ stream.once("close", websocket.emitClose.bind(websocket));
3107
+ }
3108
+ }
3109
+ __name(abortHandshake, "abortHandshake");
3110
+ function sendAfterClose(websocket, data, cb) {
3111
+ if (data) {
3112
+ const length = isBlob2(data) ? data.size : toBuffer(data).length;
3113
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3114
+ else websocket._bufferedAmount += length;
3115
+ }
3116
+ if (cb) {
3117
+ const err = new Error(
3118
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3119
+ );
3120
+ process.nextTick(cb, err);
3121
+ }
3122
+ }
3123
+ __name(sendAfterClose, "sendAfterClose");
3124
+ function receiverOnConclude(code, reason) {
3125
+ const websocket = this[kWebSocket];
3126
+ websocket._closeFrameReceived = true;
3127
+ websocket._closeMessage = reason;
3128
+ websocket._closeCode = code;
3129
+ if (websocket._socket[kWebSocket] === void 0) return;
3130
+ websocket._socket.removeListener("data", socketOnData);
3131
+ process.nextTick(resume, websocket._socket);
3132
+ if (code === 1005) websocket.close();
3133
+ else websocket.close(code, reason);
3134
+ }
3135
+ __name(receiverOnConclude, "receiverOnConclude");
3136
+ function receiverOnDrain() {
3137
+ const websocket = this[kWebSocket];
3138
+ if (!websocket.isPaused) websocket._socket.resume();
3139
+ }
3140
+ __name(receiverOnDrain, "receiverOnDrain");
3141
+ function receiverOnError(err) {
3142
+ const websocket = this[kWebSocket];
3143
+ if (websocket._socket[kWebSocket] !== void 0) {
3144
+ websocket._socket.removeListener("data", socketOnData);
3145
+ process.nextTick(resume, websocket._socket);
3146
+ websocket.close(err[kStatusCode]);
3147
+ }
3148
+ if (!websocket._errorEmitted) {
3149
+ websocket._errorEmitted = true;
3150
+ websocket.emit("error", err);
3151
+ }
3152
+ }
3153
+ __name(receiverOnError, "receiverOnError");
3154
+ function receiverOnFinish() {
3155
+ this[kWebSocket].emitClose();
3156
+ }
3157
+ __name(receiverOnFinish, "receiverOnFinish");
3158
+ function receiverOnMessage(data, isBinary) {
3159
+ this[kWebSocket].emit("message", data, isBinary);
3160
+ }
3161
+ __name(receiverOnMessage, "receiverOnMessage");
3162
+ function receiverOnPing(data) {
3163
+ const websocket = this[kWebSocket];
3164
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3165
+ websocket.emit("ping", data);
3166
+ }
3167
+ __name(receiverOnPing, "receiverOnPing");
3168
+ function receiverOnPong(data) {
3169
+ this[kWebSocket].emit("pong", data);
3170
+ }
3171
+ __name(receiverOnPong, "receiverOnPong");
3172
+ function resume(stream) {
3173
+ stream.resume();
3174
+ }
3175
+ __name(resume, "resume");
3176
+ function senderOnError(err) {
3177
+ const websocket = this[kWebSocket];
3178
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3179
+ if (websocket.readyState === WebSocket2.OPEN) {
3180
+ websocket._readyState = WebSocket2.CLOSING;
3181
+ setCloseTimer(websocket);
3182
+ }
3183
+ this._socket.end();
3184
+ if (!websocket._errorEmitted) {
3185
+ websocket._errorEmitted = true;
3186
+ websocket.emit("error", err);
3187
+ }
3188
+ }
3189
+ __name(senderOnError, "senderOnError");
3190
+ function setCloseTimer(websocket) {
3191
+ websocket._closeTimer = setTimeout(
3192
+ websocket._socket.destroy.bind(websocket._socket),
3193
+ websocket._closeTimeout
3194
+ );
3195
+ }
3196
+ __name(setCloseTimer, "setCloseTimer");
3197
+ function socketOnClose() {
3198
+ const websocket = this[kWebSocket];
3199
+ this.removeListener("close", socketOnClose);
3200
+ this.removeListener("data", socketOnData);
3201
+ this.removeListener("end", socketOnEnd);
3202
+ websocket._readyState = WebSocket2.CLOSING;
3203
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3204
+ const chunk = this.read(this._readableState.length);
3205
+ websocket._receiver.write(chunk);
3206
+ }
3207
+ websocket._receiver.end();
3208
+ this[kWebSocket] = void 0;
3209
+ clearTimeout(websocket._closeTimer);
3210
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3211
+ websocket.emitClose();
3212
+ } else {
3213
+ websocket._receiver.on("error", receiverOnFinish);
3214
+ websocket._receiver.on("finish", receiverOnFinish);
3215
+ }
3216
+ }
3217
+ __name(socketOnClose, "socketOnClose");
3218
+ function socketOnData(chunk) {
3219
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3220
+ this.pause();
3221
+ }
3222
+ }
3223
+ __name(socketOnData, "socketOnData");
3224
+ function socketOnEnd() {
3225
+ const websocket = this[kWebSocket];
3226
+ websocket._readyState = WebSocket2.CLOSING;
3227
+ websocket._receiver.end();
3228
+ this.end();
3229
+ }
3230
+ __name(socketOnEnd, "socketOnEnd");
3231
+ function socketOnError() {
3232
+ const websocket = this[kWebSocket];
3233
+ this.removeListener("error", socketOnError);
3234
+ this.on("error", NOOP);
3235
+ if (websocket) {
3236
+ websocket._readyState = WebSocket2.CLOSING;
3237
+ this.destroy();
3238
+ }
3239
+ }
3240
+ __name(socketOnError, "socketOnError");
3241
+ }
3242
+ });
3243
+
3244
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js
3245
+ var require_stream = __commonJS({
3246
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js"(exports$1, module) {
3247
+ require_websocket();
3248
+ var { Duplex } = __require("stream");
3249
+ function emitClose(stream) {
3250
+ stream.emit("close");
3251
+ }
3252
+ __name(emitClose, "emitClose");
3253
+ function duplexOnEnd() {
3254
+ if (!this.destroyed && this._writableState.finished) {
3255
+ this.destroy();
3256
+ }
3257
+ }
3258
+ __name(duplexOnEnd, "duplexOnEnd");
3259
+ function duplexOnError(err) {
3260
+ this.removeListener("error", duplexOnError);
3261
+ this.destroy();
3262
+ if (this.listenerCount("error") === 0) {
3263
+ this.emit("error", err);
3264
+ }
3265
+ }
3266
+ __name(duplexOnError, "duplexOnError");
3267
+ function createWebSocketStream2(ws, options) {
3268
+ let terminateOnDestroy = true;
3269
+ const duplex = new Duplex({
3270
+ ...options,
3271
+ autoDestroy: false,
3272
+ emitClose: false,
3273
+ objectMode: false,
3274
+ writableObjectMode: false
3275
+ });
3276
+ ws.on("message", /* @__PURE__ */ __name(function message(msg, isBinary) {
3277
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3278
+ if (!duplex.push(data)) ws.pause();
3279
+ }, "message"));
3280
+ ws.once("error", /* @__PURE__ */ __name(function error(err) {
3281
+ if (duplex.destroyed) return;
3282
+ terminateOnDestroy = false;
3283
+ duplex.destroy(err);
3284
+ }, "error"));
3285
+ ws.once("close", /* @__PURE__ */ __name(function close() {
3286
+ if (duplex.destroyed) return;
3287
+ duplex.push(null);
3288
+ }, "close"));
3289
+ duplex._destroy = function(err, callback) {
3290
+ if (ws.readyState === ws.CLOSED) {
3291
+ callback(err);
3292
+ process.nextTick(emitClose, duplex);
3293
+ return;
3294
+ }
3295
+ let called = false;
3296
+ ws.once("error", /* @__PURE__ */ __name(function error(err2) {
3297
+ called = true;
3298
+ callback(err2);
3299
+ }, "error"));
3300
+ ws.once("close", /* @__PURE__ */ __name(function close() {
3301
+ if (!called) callback(err);
3302
+ process.nextTick(emitClose, duplex);
3303
+ }, "close"));
3304
+ if (terminateOnDestroy) ws.terminate();
3305
+ };
3306
+ duplex._final = function(callback) {
3307
+ if (ws.readyState === ws.CONNECTING) {
3308
+ ws.once("open", /* @__PURE__ */ __name(function open() {
3309
+ duplex._final(callback);
3310
+ }, "open"));
3311
+ return;
3312
+ }
3313
+ if (ws._socket === null) return;
3314
+ if (ws._socket._writableState.finished) {
3315
+ callback();
3316
+ if (duplex._readableState.endEmitted) duplex.destroy();
3317
+ } else {
3318
+ ws._socket.once("finish", /* @__PURE__ */ __name(function finish() {
3319
+ callback();
3320
+ }, "finish"));
3321
+ ws.close();
3322
+ }
3323
+ };
3324
+ duplex._read = function() {
3325
+ if (ws.isPaused) ws.resume();
3326
+ };
3327
+ duplex._write = function(chunk, encoding, callback) {
3328
+ if (ws.readyState === ws.CONNECTING) {
3329
+ ws.once("open", /* @__PURE__ */ __name(function open() {
3330
+ duplex._write(chunk, encoding, callback);
3331
+ }, "open"));
3332
+ return;
3333
+ }
3334
+ ws.send(chunk, callback);
3335
+ };
3336
+ duplex.on("end", duplexOnEnd);
3337
+ duplex.on("error", duplexOnError);
3338
+ return duplex;
3339
+ }
3340
+ __name(createWebSocketStream2, "createWebSocketStream");
3341
+ module.exports = createWebSocketStream2;
3342
+ }
3343
+ });
3344
+
3345
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js
3346
+ var require_subprotocol = __commonJS({
3347
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js"(exports$1, module) {
3348
+ var { tokenChars } = require_validation();
3349
+ function parse(header) {
3350
+ const protocols = /* @__PURE__ */ new Set();
3351
+ let start = -1;
3352
+ let end = -1;
3353
+ let i = 0;
3354
+ for (i; i < header.length; i++) {
3355
+ const code = header.charCodeAt(i);
3356
+ if (end === -1 && tokenChars[code] === 1) {
3357
+ if (start === -1) start = i;
3358
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3359
+ if (end === -1 && start !== -1) end = i;
3360
+ } else if (code === 44) {
3361
+ if (start === -1) {
3362
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3363
+ }
3364
+ if (end === -1) end = i;
3365
+ const protocol2 = header.slice(start, end);
3366
+ if (protocols.has(protocol2)) {
3367
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3368
+ }
3369
+ protocols.add(protocol2);
3370
+ start = end = -1;
3371
+ } else {
3372
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3373
+ }
3374
+ }
3375
+ if (start === -1 || end !== -1) {
3376
+ throw new SyntaxError("Unexpected end of input");
3377
+ }
3378
+ const protocol = header.slice(start, i);
3379
+ if (protocols.has(protocol)) {
3380
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3381
+ }
3382
+ protocols.add(protocol);
3383
+ return protocols;
3384
+ }
3385
+ __name(parse, "parse");
3386
+ module.exports = { parse };
3387
+ }
3388
+ });
3389
+
3390
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js
3391
+ var require_websocket_server = __commonJS({
3392
+ "../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js"(exports$1, module) {
3393
+ var EventEmitter = __require("events");
3394
+ var http = __require("http");
3395
+ var { Duplex } = __require("stream");
3396
+ var { createHash: createHash2 } = __require("crypto");
3397
+ var extension2 = require_extension();
3398
+ var PerMessageDeflate2 = require_permessage_deflate();
3399
+ var subprotocol2 = require_subprotocol();
3400
+ var WebSocket2 = require_websocket();
3401
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3402
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3403
+ var RUNNING = 0;
3404
+ var CLOSING = 1;
3405
+ var CLOSED = 2;
3406
+ var WebSocketServer2 = class extends EventEmitter {
3407
+ static {
3408
+ __name(this, "WebSocketServer");
3409
+ }
3410
+ /**
3411
+ * Create a `WebSocketServer` instance.
3412
+ *
3413
+ * @param {Object} options Configuration options
3414
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3415
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3416
+ * multiple times in the same tick
3417
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3418
+ * automatically send a pong in response to a ping
3419
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3420
+ * pending connections
3421
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3422
+ * track clients
3423
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3424
+ * wait for the closing handshake to finish after `websocket.close()` is
3425
+ * called
3426
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3427
+ * @param {String} [options.host] The hostname where to bind the server
3428
+ * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
3429
+ * buffered data chunks
3430
+ * @param {Number} [options.maxFragments=131072] The maximum number of message
3431
+ * fragments
3432
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3433
+ * size
3434
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3435
+ * @param {String} [options.path] Accept only connections matching this path
3436
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3437
+ * permessage-deflate
3438
+ * @param {Number} [options.port] The port where to bind the server
3439
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3440
+ * server to use
3441
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3442
+ * not to skip UTF-8 validation for text and close messages
3443
+ * @param {Function} [options.verifyClient] A hook to reject connections
3444
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3445
+ * class to use. It must be the `WebSocket` class or class that extends it
3446
+ * @param {Function} [callback] A listener for the `listening` event
3447
+ */
3448
+ constructor(options, callback) {
3449
+ super();
3450
+ options = {
3451
+ allowSynchronousEvents: true,
3452
+ autoPong: true,
3453
+ maxBufferedChunks: 1024 * 1024,
3454
+ maxFragments: 128 * 1024,
3455
+ maxPayload: 100 * 1024 * 1024,
3456
+ skipUTF8Validation: false,
3457
+ perMessageDeflate: false,
3458
+ handleProtocols: null,
3459
+ clientTracking: true,
3460
+ closeTimeout: CLOSE_TIMEOUT,
3461
+ verifyClient: null,
3462
+ noServer: false,
3463
+ backlog: null,
3464
+ // use default (511 as implemented in net.js)
3465
+ server: null,
3466
+ host: null,
3467
+ path: null,
3468
+ port: null,
3469
+ WebSocket: WebSocket2,
3470
+ ...options
3471
+ };
3472
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3473
+ throw new TypeError(
3474
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3475
+ );
3476
+ }
3477
+ if (options.port != null) {
3478
+ this._server = http.createServer((req, res) => {
3479
+ const body = http.STATUS_CODES[426];
3480
+ res.writeHead(426, {
3481
+ "Content-Length": body.length,
3482
+ "Content-Type": "text/plain"
3483
+ });
3484
+ res.end(body);
3485
+ });
3486
+ this._server.listen(
3487
+ options.port,
3488
+ options.host,
3489
+ options.backlog,
3490
+ callback
3491
+ );
3492
+ } else if (options.server) {
3493
+ this._server = options.server;
3494
+ }
3495
+ if (this._server) {
3496
+ const emitConnection = this.emit.bind(this, "connection");
3497
+ this._removeListeners = addListeners(this._server, {
3498
+ listening: this.emit.bind(this, "listening"),
3499
+ error: this.emit.bind(this, "error"),
3500
+ upgrade: /* @__PURE__ */ __name((req, socket, head) => {
3501
+ this.handleUpgrade(req, socket, head, emitConnection);
3502
+ }, "upgrade")
3503
+ });
3504
+ }
3505
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3506
+ if (options.clientTracking) {
3507
+ this.clients = /* @__PURE__ */ new Set();
3508
+ this._shouldEmitClose = false;
3509
+ }
3510
+ this.options = options;
3511
+ this._state = RUNNING;
3512
+ }
3513
+ /**
3514
+ * Returns the bound address, the address family name, and port of the server
3515
+ * as reported by the operating system if listening on an IP socket.
3516
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3517
+ * returned as a string.
3518
+ *
3519
+ * @return {(Object|String|null)} The address of the server
3520
+ * @public
3521
+ */
3522
+ address() {
3523
+ if (this.options.noServer) {
3524
+ throw new Error('The server is operating in "noServer" mode');
3525
+ }
3526
+ if (!this._server) return null;
3527
+ return this._server.address();
3528
+ }
3529
+ /**
3530
+ * Stop the server from accepting new connections and emit the `'close'` event
3531
+ * when all existing connections are closed.
3532
+ *
3533
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3534
+ * @public
3535
+ */
3536
+ close(cb) {
3537
+ if (this._state === CLOSED) {
3538
+ if (cb) {
3539
+ this.once("close", () => {
3540
+ cb(new Error("The server is not running"));
3541
+ });
3542
+ }
3543
+ process.nextTick(emitClose, this);
3544
+ return;
3545
+ }
3546
+ if (cb) this.once("close", cb);
3547
+ if (this._state === CLOSING) return;
3548
+ this._state = CLOSING;
3549
+ if (this.options.noServer || this.options.server) {
3550
+ if (this._server) {
3551
+ this._removeListeners();
3552
+ this._removeListeners = this._server = null;
3553
+ }
3554
+ if (this.clients) {
3555
+ if (!this.clients.size) {
3556
+ process.nextTick(emitClose, this);
3557
+ } else {
3558
+ this._shouldEmitClose = true;
3559
+ }
3560
+ } else {
3561
+ process.nextTick(emitClose, this);
3562
+ }
3563
+ } else {
3564
+ const server = this._server;
3565
+ this._removeListeners();
3566
+ this._removeListeners = this._server = null;
3567
+ server.close(() => {
3568
+ emitClose(this);
3569
+ });
3570
+ }
3571
+ }
3572
+ /**
3573
+ * See if a given request should be handled by this server instance.
3574
+ *
3575
+ * @param {http.IncomingMessage} req Request object to inspect
3576
+ * @return {Boolean} `true` if the request is valid, else `false`
3577
+ * @public
3578
+ */
3579
+ shouldHandle(req) {
3580
+ if (this.options.path) {
3581
+ const index = req.url.indexOf("?");
3582
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3583
+ if (pathname !== this.options.path) return false;
3584
+ }
3585
+ return true;
3586
+ }
3587
+ /**
3588
+ * Handle a HTTP Upgrade request.
3589
+ *
3590
+ * @param {http.IncomingMessage} req The request object
3591
+ * @param {Duplex} socket The network socket between the server and client
3592
+ * @param {Buffer} head The first packet of the upgraded stream
3593
+ * @param {Function} cb Callback
3594
+ * @public
3595
+ */
3596
+ handleUpgrade(req, socket, head, cb) {
3597
+ socket.on("error", socketOnError);
3598
+ const key = req.headers["sec-websocket-key"];
3599
+ const upgrade = req.headers.upgrade;
3600
+ const version = +req.headers["sec-websocket-version"];
3601
+ if (req.method !== "GET") {
3602
+ const message = "Invalid HTTP method";
3603
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3604
+ return;
3605
+ }
3606
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3607
+ const message = "Invalid Upgrade header";
3608
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3609
+ return;
3610
+ }
3611
+ if (key === void 0 || !keyRegex.test(key)) {
3612
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3613
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3614
+ return;
3615
+ }
3616
+ if (version !== 13 && version !== 8) {
3617
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3618
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3619
+ "Sec-WebSocket-Version": "13, 8"
3620
+ });
3621
+ return;
3622
+ }
3623
+ if (!this.shouldHandle(req)) {
3624
+ abortHandshake(socket, 400);
3625
+ return;
3626
+ }
3627
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3628
+ let protocols = /* @__PURE__ */ new Set();
3629
+ if (secWebSocketProtocol !== void 0) {
3630
+ try {
3631
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3632
+ } catch (err) {
3633
+ const message = "Invalid Sec-WebSocket-Protocol header";
3634
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3635
+ return;
3636
+ }
3637
+ }
3638
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3639
+ const extensions = {};
3640
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3641
+ const perMessageDeflate = new PerMessageDeflate2({
3642
+ ...this.options.perMessageDeflate,
3643
+ isServer: true,
3644
+ maxPayload: this.options.maxPayload
3645
+ });
3646
+ try {
3647
+ const offers = extension2.parse(secWebSocketExtensions);
3648
+ if (offers[PerMessageDeflate2.extensionName]) {
3649
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3650
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3651
+ }
3652
+ } catch (err) {
3653
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3654
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3655
+ return;
3656
+ }
3657
+ }
3658
+ if (this.options.verifyClient) {
3659
+ const info = {
3660
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3661
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3662
+ req
3663
+ };
3664
+ if (this.options.verifyClient.length === 2) {
3665
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3666
+ if (!verified) {
3667
+ return abortHandshake(socket, code || 401, message, headers);
3668
+ }
3669
+ this.completeUpgrade(
3670
+ extensions,
3671
+ key,
3672
+ protocols,
3673
+ req,
3674
+ socket,
3675
+ head,
3676
+ cb
3677
+ );
3678
+ });
3679
+ return;
3680
+ }
3681
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3682
+ }
3683
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3684
+ }
3685
+ /**
3686
+ * Upgrade the connection to WebSocket.
3687
+ *
3688
+ * @param {Object} extensions The accepted extensions
3689
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3690
+ * @param {Set} protocols The subprotocols
3691
+ * @param {http.IncomingMessage} req The request object
3692
+ * @param {Duplex} socket The network socket between the server and client
3693
+ * @param {Buffer} head The first packet of the upgraded stream
3694
+ * @param {Function} cb Callback
3695
+ * @throws {Error} If called more than once with the same socket
3696
+ * @private
3697
+ */
3698
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3699
+ if (!socket.readable || !socket.writable) return socket.destroy();
3700
+ if (socket[kWebSocket]) {
3701
+ throw new Error(
3702
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3703
+ );
3704
+ }
3705
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3706
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
3707
+ const headers = [
3708
+ "HTTP/1.1 101 Switching Protocols",
3709
+ "Upgrade: websocket",
3710
+ "Connection: Upgrade",
3711
+ `Sec-WebSocket-Accept: ${digest}`
3712
+ ];
3713
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3714
+ if (protocols.size) {
3715
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3716
+ if (protocol) {
3717
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3718
+ ws._protocol = protocol;
3719
+ }
3720
+ }
3721
+ if (extensions[PerMessageDeflate2.extensionName]) {
3722
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3723
+ const value = extension2.format({
3724
+ [PerMessageDeflate2.extensionName]: [params]
3725
+ });
3726
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3727
+ ws._extensions = extensions;
3728
+ }
3729
+ this.emit("headers", headers, req);
3730
+ socket.write(headers.concat("\r\n").join("\r\n"));
3731
+ socket.removeListener("error", socketOnError);
3732
+ ws.setSocket(socket, head, {
3733
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3734
+ maxBufferedChunks: this.options.maxBufferedChunks,
3735
+ maxFragments: this.options.maxFragments,
3736
+ maxPayload: this.options.maxPayload,
3737
+ skipUTF8Validation: this.options.skipUTF8Validation
3738
+ });
3739
+ if (this.clients) {
3740
+ this.clients.add(ws);
3741
+ ws.on("close", () => {
3742
+ this.clients.delete(ws);
3743
+ if (this._shouldEmitClose && !this.clients.size) {
3744
+ process.nextTick(emitClose, this);
3745
+ }
3746
+ });
3747
+ }
3748
+ cb(ws, req);
3749
+ }
3750
+ };
3751
+ module.exports = WebSocketServer2;
3752
+ function addListeners(server, map) {
3753
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3754
+ return /* @__PURE__ */ __name(function removeListeners() {
3755
+ for (const event of Object.keys(map)) {
3756
+ server.removeListener(event, map[event]);
3757
+ }
3758
+ }, "removeListeners");
3759
+ }
3760
+ __name(addListeners, "addListeners");
3761
+ function emitClose(server) {
3762
+ server._state = CLOSED;
3763
+ server.emit("close");
3764
+ }
3765
+ __name(emitClose, "emitClose");
3766
+ function socketOnError() {
3767
+ this.destroy();
3768
+ }
3769
+ __name(socketOnError, "socketOnError");
3770
+ function abortHandshake(socket, code, message, headers) {
3771
+ message = message || http.STATUS_CODES[code];
3772
+ headers = {
3773
+ Connection: "close",
3774
+ "Content-Type": "text/html",
3775
+ "Content-Length": Buffer.byteLength(message),
3776
+ ...headers
3777
+ };
3778
+ socket.once("finish", socket.destroy);
3779
+ socket.end(
3780
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3781
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3782
+ );
3783
+ }
3784
+ __name(abortHandshake, "abortHandshake");
3785
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3786
+ if (server.listenerCount("wsClientError")) {
3787
+ const err = new Error(message);
3788
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3789
+ server.emit("wsClientError", err, socket, req);
3790
+ } else {
3791
+ abortHandshake(socket, code, message, headers);
3792
+ }
3793
+ }
3794
+ __name(abortHandshakeOrEmitwsClientError, "abortHandshakeOrEmitwsClientError");
3795
+ }
3796
+ });
20
3797
 
21
3798
  // src/client/core/ApiError.ts
22
3799
  var ApiError = class extends Error {
@@ -2513,35 +6290,6 @@ async function dockerLoginImageRegistry(pathToDocker, domain) {
2513
6290
  });
2514
6291
  }
2515
6292
  __name(dockerLoginImageRegistry, "dockerLoginImageRegistry");
2516
- async function dockerImageInspect(dockerPath, options) {
2517
- return new Promise((resolve2, reject) => {
2518
- const proc = spawn(
2519
- dockerPath,
2520
- ["image", "inspect", options.imageTag, "--format", options.formatString],
2521
- {
2522
- stdio: ["ignore", "pipe", "pipe"]
2523
- }
2524
- );
2525
- let stdout = "";
2526
- let stderr = "";
2527
- proc.stdout.on("data", (chunk) => stdout += chunk);
2528
- proc.stderr.on("data", (chunk) => stderr += chunk);
2529
- proc.on("close", (code) => {
2530
- if (code !== 0) {
2531
- return reject(
2532
- new UserError(`failed inspecting image locally: ${stderr.trim()}`, {
2533
- telemetryMessage: false
2534
- })
2535
- );
2536
- }
2537
- resolve2(stdout.trim());
2538
- });
2539
- proc.on("error", (err) => reject(err));
2540
- });
2541
- }
2542
- __name(dockerImageInspect, "dockerImageInspect");
2543
-
2544
- // src/utils.ts
2545
6293
  var runDockerCmd = /* @__PURE__ */ __name((dockerPath, args, stdio) => {
2546
6294
  let aborted = false;
2547
6295
  let resolve2;
@@ -2757,22 +6505,6 @@ var getContainerIdsFromImage = /* @__PURE__ */ __name((dockerPath, ancestorImage
2757
6505
  ]);
2758
6506
  return output.split("\n").filter((line) => line.trim());
2759
6507
  }, "getContainerIdsFromImage");
2760
- async function checkExposedPorts(dockerPath, options) {
2761
- const output = await dockerImageInspect(dockerPath, {
2762
- imageTag: options.image_tag,
2763
- formatString: "{{ len .Config.ExposedPorts }}"
2764
- });
2765
- if (output === "0") {
2766
- const containerName = options.image_name === void 0 ? options.class_name : `${options.class_name}.${options.image_name}`;
2767
- throw new UserError(
2768
- `The container "${containerName}" does not expose any ports. In your Dockerfile, please expose any ports you intend to connect to.
2769
- For additional information please see: https://developers.cloudflare.com/containers/local-dev/#exposing-ports.
2770
- `,
2771
- { telemetryMessage: false }
2772
- );
2773
- }
2774
- }
2775
- __name(checkExposedPorts, "checkExposedPorts");
2776
6508
  function generateContainerBuildId() {
2777
6509
  return randomUUID().slice(0, 8);
2778
6510
  }
@@ -2940,7 +6672,6 @@ async function prepareContainerImagesForDev(args) {
2940
6672
  if (aborted) {
2941
6673
  break;
2942
6674
  }
2943
- await checkExposedPorts(dockerPath, options);
2944
6675
  }
2945
6676
  if (!aborted) {
2946
6677
  await pullEgressInterceptorImage(dockerPath);
@@ -3152,6 +6883,33 @@ function validateAndEncodeGarKey(rawKey, expectedEmail) {
3152
6883
  return base64Key;
3153
6884
  }
3154
6885
  __name(validateAndEncodeGarKey, "validateAndEncodeGarKey");
6886
+ async function dockerImageInspect(dockerPath, options) {
6887
+ return new Promise((resolve2, reject) => {
6888
+ const proc = spawn(
6889
+ dockerPath,
6890
+ ["image", "inspect", options.imageTag, "--format", options.formatString],
6891
+ {
6892
+ stdio: ["ignore", "pipe", "pipe"]
6893
+ }
6894
+ );
6895
+ let stdout = "";
6896
+ let stderr = "";
6897
+ proc.stdout.on("data", (chunk) => stdout += chunk);
6898
+ proc.stderr.on("data", (chunk) => stderr += chunk);
6899
+ proc.on("close", (code) => {
6900
+ if (code !== 0) {
6901
+ return reject(
6902
+ new UserError(`failed inspecting image locally: ${stderr.trim()}`, {
6903
+ telemetryMessage: false
6904
+ })
6905
+ );
6906
+ }
6907
+ resolve2(stdout.trim());
6908
+ });
6909
+ proc.on("error", (err) => reject(err));
6910
+ });
6911
+ }
6912
+ __name(dockerImageInspect, "dockerImageInspect");
3155
6913
  var MB = 1e3 * 1e3;
3156
6914
  var MiB = 1024 * 1024;
3157
6915
  var instanceTypes = {
@@ -3879,15 +7637,15 @@ __name(dockerBuild, "dockerBuild");
3879
7637
  var BUILD_OUTPUT_IMAGE_NAMESPACE = "cloudflare-build";
3880
7638
  var DOCKER_REPOSITORY_NAME_LENGTH = 255;
3881
7639
  async function buildAndWriteContainerOutput(options) {
3882
- const containers = Object.entries(options.containers);
3883
- await cleanupPreviousBuildOutputImageTags({
3884
- root: options.root,
3885
- pathToDocker: options.pathToDocker
3886
- });
3887
- const buildId = createBuildId();
3888
7640
  const localTags = /* @__PURE__ */ new Set();
3889
7641
  try {
3890
- const dockerfileCount = countDockerfiles(containers);
7642
+ const containers = resolveContainerDirectories(options.containers);
7643
+ await cleanupPreviousBuildOutputImageTags({
7644
+ root: options.root,
7645
+ pathToDocker: options.pathToDocker
7646
+ });
7647
+ const buildId = createBuildId();
7648
+ const dockerfileCount = countDockerfiles(options.containers);
3891
7649
  if (dockerfileCount > 0) {
3892
7650
  await verifyDockerInstalled({
3893
7651
  dockerPath: options.pathToDocker,
@@ -3897,7 +7655,7 @@ async function buildAndWriteContainerOutput(options) {
3897
7655
  }
3898
7656
  const outputConfigs = [];
3899
7657
  try {
3900
- for (const [directoryName, config] of containers) {
7658
+ for (const { config, directoryName } of containers) {
3901
7659
  outputConfigs.push({
3902
7660
  root: options.root,
3903
7661
  directoryName,
@@ -3928,6 +7686,22 @@ async function buildAndWriteContainerOutput(options) {
3928
7686
  }
3929
7687
  }
3930
7688
  __name(buildAndWriteContainerOutput, "buildAndWriteContainerOutput");
7689
+ function resolveContainerDirectories(containers) {
7690
+ const containerNameByDirectory = /* @__PURE__ */ new Map();
7691
+ return containers.map((config) => {
7692
+ const directoryName = normalizeDirectoryName(config.name);
7693
+ const conflictingName = containerNameByDirectory.get(directoryName);
7694
+ if (conflictingName !== void 0) {
7695
+ throw new UserError(
7696
+ `Container names ${JSON.stringify(conflictingName)} and ${JSON.stringify(config.name)} resolve to the same Build Output directory ${JSON.stringify(directoryName)}. Rename one of the Containers.`,
7697
+ { telemetryMessage: "container build output directory name conflict" }
7698
+ );
7699
+ }
7700
+ containerNameByDirectory.set(directoryName, config.name);
7701
+ return { config, directoryName };
7702
+ });
7703
+ }
7704
+ __name(resolveContainerDirectories, "resolveContainerDirectories");
3931
7705
  async function buildContainerOutputConfig(options) {
3932
7706
  if (options.config.schedulingPolicy === "durable-object") {
3933
7707
  if (options.config.images === void 0) {
@@ -4036,7 +7810,7 @@ function createBuildId() {
4036
7810
  __name(createBuildId, "createBuildId");
4037
7811
  function countDockerfiles(containers) {
4038
7812
  let count = 0;
4039
- for (const [, config] of containers) {
7813
+ for (const config of containers) {
4040
7814
  if (config.schedulingPolicy === "durable-object") {
4041
7815
  count += Object.values(config.images ?? {}).filter(
4042
7816
  (image) => "dockerfile" in image
@@ -4526,7 +8300,7 @@ async function fetchUploadedVersion(config, accountId, scriptName, versionId) {
4526
8300
  if (!isUploadedVersionNotReadyError(error) || attempt === 4) {
4527
8301
  throw error;
4528
8302
  }
4529
- await setTimeout(500);
8303
+ await setTimeout$1(500);
4530
8304
  }
4531
8305
  }
4532
8306
  throw new Error("Unable to fetch uploaded Worker version");
@@ -5272,4 +9046,536 @@ function createContainerDevPlan(options) {
5272
9046
  }
5273
9047
  __name(createContainerDevPlan, "createContainerDevPlan");
5274
9048
 
5275
- export { AccountService, ApiError, ApplicationAffinityColocation, ApplicationAffinityHardwareGeneration, ApplicationMutationError, ApplicationRollout, ApplicationsService, AssignIPv4, AssignIPv6, BadRequestWithCodeError, CancelError, CancelablePromise, ContainerImagePreparationStatus, ContainerImagePreparationsService, ContainerNetworkMode, CreateApplicationRolloutRequest, DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE, DeploymentCheckKind, DeploymentCheckType, DeploymentMutationError, DeploymentNotFoundError, DeploymentPlacementState, DeploymentQueuedReason, DeploymentSchedulingState, DeploymentType, DeploymentsService, Diff, DurableObjectStatusHealth, EventName, EventType, ExternalRegistryKind, FUSE_CONTAINER_PRIVILEGES, HTTPMethod, IPType, IPsService, ImageRegistriesService, ImageRegistryAlreadyExistsError, ImageRegistryIsPublic, ImageRegistryNotAllowedError, ImageRegistryNotFoundError, ImageRegistryPermissions, ImageRegistryProtocolAlreadyExists, ImageRegistryProtocolIsReferencedError, ImageRegistryProtocolNotFound, InstanceType, JobStatusHealth, JobsService, MF_DEV_CONTAINER_PREFIX, NetworkMode, NodeGroup, OpenAPI, PlacementStatusHealth, PlacementsService, ProvisionerConfiguration, RolloutStep, RolloutsService, SSHPublicKeyNotFoundError, SchedulingPolicy, SecretAccessType, SecretNameAlreadyExists, SecretNotFound, SecretsService, SshPublicKeysService, UpdateApplicationRolloutRequest, apply, buildAndMaybePush, buildAndWriteContainerOutput, buildCommand, buildContainerImages, checkExposedPorts, cleanApplicationFromAPI, cleanForInstanceType, cleanupBuiltImages, cleanupContainers, configRolloutStepsToAPI, configureOpenAPIForContainerPull, containerPrivilegesAllowed, createContainerDevPlan, createDurableObjectNamespaceResolver, deployContainers, dockerBuild, dockerImageInspect, dockerLoginImageRegistry, ensureContainerLimits, ensureImageFitsLimits, fetchPagedListResult, fetchResult, formatError, generateContainerBuildId, getAndValidateRegistryType, getCloudflareContainerRegistry, getCloudflareRegistryWithAccountNamespace, getContainerAccount, getContainerIdsByImageTags, getContainerIdsFromImage, getContainerImageTag, getDevContainerImageName, getDockerHostFromEnv, getDockerSocketFromContext, getEgressInterceptorImage, getEgressInterceptorPlatform, getInstanceTypeUsage, inferInstanceType, initContainersSharedContext, isCloudflareRegistryImage, isDockerRunning, isDockerfileContainerConfig, listDurableObjects, logger, normalizeContainerImageRepositoryName, prepareContainerImagesForDev, promiseSpinner, pullEgressInterceptorImage, pullImage, pushBuiltContainerImage, pushCommand, pushImageIfChanged, request, requestPaginated, resolveDockerHost, resolveImageName, runDockerCmd, runDockerCmdWithOutput, sortObjectRecursive, startContainerBuild, stripUndefined, validateAndEncodeGarKey, verifyDockerInstalled };
9049
+ // ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/wrapper.mjs
9050
+ __toESM(require_stream());
9051
+ __toESM(require_extension());
9052
+ __toESM(require_permessage_deflate());
9053
+ __toESM(require_receiver());
9054
+ __toESM(require_sender());
9055
+ __toESM(require_subprotocol());
9056
+ var import_websocket = __toESM(require_websocket());
9057
+ __toESM(require_websocket_server());
9058
+
9059
+ // src/ssh.ts
9060
+ var containersSshOptions = {
9061
+ cipher: {
9062
+ describe: "Sets `ssh -c`: Select the cipher specification for encrypting the session",
9063
+ type: "string",
9064
+ hidden: true,
9065
+ deprecated: true
9066
+ },
9067
+ "log-file": {
9068
+ describe: "Sets `ssh -E`: Append debug logs to log_file instead of standard error",
9069
+ type: "string",
9070
+ hidden: true,
9071
+ deprecated: true
9072
+ },
9073
+ "escape-char": {
9074
+ describe: "Sets `ssh -e`: Set the escape character for sessions with a pty (default: '~')",
9075
+ type: "string",
9076
+ hidden: true,
9077
+ deprecated: true
9078
+ },
9079
+ "config-file": {
9080
+ alias: "F",
9081
+ describe: "Sets `ssh -F`: Specify an alternative per-user ssh configuration file",
9082
+ type: "string",
9083
+ hidden: true,
9084
+ deprecated: true
9085
+ },
9086
+ pkcs11: {
9087
+ describe: "Sets `ssh -I`: Specify the PKCS#11 shared library ssh should use to communicate with a PKCS#11 token providing keys for user authentication",
9088
+ type: "string",
9089
+ hidden: true,
9090
+ deprecated: true
9091
+ },
9092
+ "identity-file": {
9093
+ alias: "i",
9094
+ describe: "Sets `ssh -i`: Select a file from which the identity (private key) for public key authentication is read",
9095
+ type: "string",
9096
+ hidden: true,
9097
+ deprecated: true
9098
+ },
9099
+ "mac-spec": {
9100
+ describe: "Sets `ssh -m`: A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference",
9101
+ type: "string",
9102
+ hidden: true,
9103
+ deprecated: true
9104
+ },
9105
+ option: {
9106
+ alias: "o",
9107
+ describe: "Sets `ssh -o`: Set options in the format used in the ssh configuration file. May be repeated",
9108
+ type: "string",
9109
+ hidden: true,
9110
+ deprecated: true
9111
+ },
9112
+ tag: {
9113
+ describe: "Sets `ssh -P`: Specify a tag name that may be used to select configuration in ssh_config",
9114
+ type: "string",
9115
+ hidden: true,
9116
+ deprecated: true
9117
+ },
9118
+ stdio: {
9119
+ describe: "Proxy SSH traffic over stdin/stdout",
9120
+ type: "boolean"
9121
+ }
9122
+ };
9123
+ async function sshCommand(sshArgs) {
9124
+ const useStdio = shouldUseStdio(sshArgs);
9125
+ let sshResponse;
9126
+ try {
9127
+ const sshPromise = DeploymentsService.containerWranglerSsh(sshArgs.id);
9128
+ sshResponse = useStdio ? await sshPromise : await promiseSpinner(sshPromise, { message: "Authenticating" });
9129
+ } catch (e) {
9130
+ if (e instanceof ApiError) {
9131
+ if (e.status === 404) {
9132
+ throw new Error(`Instance ${sshArgs.id} not found`);
9133
+ }
9134
+ let msg = `Error verifying SSH access`;
9135
+ if (e.body.error !== void 0) {
9136
+ msg += `: ${e.body.error}`;
9137
+ }
9138
+ throw new Error(msg);
9139
+ }
9140
+ throw e;
9141
+ }
9142
+ const ws = new import_websocket.default(sshResponse.url, {
9143
+ headers: {
9144
+ authorization: `Bearer ${sshResponse.token}`,
9145
+ "user-agent": "wrangler"
9146
+ }
9147
+ });
9148
+ ws.binaryType = "arraybuffer";
9149
+ if (useStdio) {
9150
+ await stdioProxy(ws);
9151
+ return;
9152
+ }
9153
+ const proxy = tcpProxy(ws);
9154
+ const proxyController = new AbortController();
9155
+ try {
9156
+ proxy.listen({
9157
+ port: 0,
9158
+ host: "127.0.0.1",
9159
+ signal: proxyController.signal
9160
+ });
9161
+ await once(proxy, "listening");
9162
+ const proxyAddress = proxy.address();
9163
+ if (proxyAddress === null || typeof proxyAddress !== "object") {
9164
+ throw new Error("Couldn't get local SSH TCP proxy address");
9165
+ }
9166
+ await verifySshInstalled("ssh");
9167
+ const child = spawn(
9168
+ "ssh",
9169
+ [
9170
+ "cloudchamber@127.0.0.1",
9171
+ "-p",
9172
+ `${proxyAddress.port}`,
9173
+ ...buildContainerSshArgs(sshArgs),
9174
+ "--",
9175
+ ...sshArgs.command ?? []
9176
+ ],
9177
+ {
9178
+ stdio: ["inherit", "inherit", "inherit"],
9179
+ detached: true,
9180
+ signal: proxyController.signal
9181
+ }
9182
+ );
9183
+ const childKilled = new Promise((resolve2, reject) => {
9184
+ child.on("close", () => {
9185
+ resolve2(void 0);
9186
+ });
9187
+ child.on("error", reject);
9188
+ child.on("exit", (code) => {
9189
+ if (code !== 255) {
9190
+ resolve2(void 0);
9191
+ } else {
9192
+ reject(
9193
+ new Error(
9194
+ [
9195
+ "SSH exited unsuccessfully. Is the container running?",
9196
+ `${bold("NOTE:")} SSH does not automatically wake a container or count as activity to keep a container alive`
9197
+ ].join("\n")
9198
+ )
9199
+ );
9200
+ }
9201
+ });
9202
+ });
9203
+ showCursor(true);
9204
+ await childKilled;
9205
+ } finally {
9206
+ showCursor(true);
9207
+ proxyController.abort();
9208
+ if (ws.readyState === import_websocket.default.CONNECTING) {
9209
+ ws.terminate();
9210
+ } else {
9211
+ ws.close();
9212
+ }
9213
+ }
9214
+ }
9215
+ __name(sshCommand, "sshCommand");
9216
+ function verifySshInstalled(sshPath) {
9217
+ return new Promise((resolve2, reject) => {
9218
+ const child = spawn(sshPath, ["-V"]);
9219
+ let errorHandled = false;
9220
+ child.on("close", (code) => {
9221
+ if (code === 0) {
9222
+ resolve2(void 0);
9223
+ } else if (!errorHandled) {
9224
+ errorHandled = true;
9225
+ reject(new Error(`ssh exited with status code: ${code}`));
9226
+ }
9227
+ });
9228
+ child.on("error", (err) => {
9229
+ if (!errorHandled) {
9230
+ errorHandled = true;
9231
+ reject(new Error(`Verifying SSH installation failed: ${err.message}`));
9232
+ }
9233
+ });
9234
+ });
9235
+ }
9236
+ __name(verifySshInstalled, "verifySshInstalled");
9237
+ function tcpProxy(ws) {
9238
+ let inbound;
9239
+ const pending = [];
9240
+ const proxy = createServer((socket) => {
9241
+ if (inbound !== void 0) {
9242
+ socket.end();
9243
+ return;
9244
+ }
9245
+ inbound = socket;
9246
+ socket.on("error", (err) => logger.error("Proxy error: ", err));
9247
+ socket.on("close", () => {
9248
+ ws.close();
9249
+ proxy.close();
9250
+ });
9251
+ const start = /* @__PURE__ */ __name(() => socket.on("data", (data) => ws.send(data)), "start");
9252
+ if (ws.readyState === import_websocket.default.OPEN) {
9253
+ start();
9254
+ } else if (ws.readyState === import_websocket.default.CONNECTING) {
9255
+ ws.once("open", start);
9256
+ } else {
9257
+ socket.end();
9258
+ }
9259
+ for (const data of pending) {
9260
+ socket.write(data);
9261
+ }
9262
+ pending.length = 0;
9263
+ });
9264
+ ws.on("message", (data) => {
9265
+ const bytes = new Uint8Array(data);
9266
+ if (inbound === void 0) {
9267
+ pending.push(bytes);
9268
+ } else {
9269
+ inbound.write(bytes);
9270
+ }
9271
+ });
9272
+ ws.on("error", (err) => {
9273
+ logger.error("Web socket error:", err.message);
9274
+ inbound?.end();
9275
+ proxy.close();
9276
+ });
9277
+ ws.on("close", () => {
9278
+ inbound?.end();
9279
+ proxy.close();
9280
+ });
9281
+ return proxy;
9282
+ }
9283
+ __name(tcpProxy, "tcpProxy");
9284
+ function stdioProxy(ws) {
9285
+ return new Promise((resolve2, reject) => {
9286
+ const onData = /* @__PURE__ */ __name((data) => ws.send(data), "onData");
9287
+ const onEnd = /* @__PURE__ */ __name(() => ws.close(), "onEnd");
9288
+ const onError = /* @__PURE__ */ __name((err) => {
9289
+ ws.close();
9290
+ reject(err);
9291
+ }, "onError");
9292
+ const cleanup = /* @__PURE__ */ __name(() => {
9293
+ process.stdin.pause();
9294
+ process.stdin.off("data", onData);
9295
+ process.stdin.off("end", onEnd);
9296
+ process.stdin.off("error", onError);
9297
+ }, "cleanup");
9298
+ ws.addEventListener("error", (err) => {
9299
+ cleanup();
9300
+ reject(new Error(`Web socket error: ${err.message}`));
9301
+ });
9302
+ ws.addEventListener("open", () => {
9303
+ process.stdin.on("data", onData);
9304
+ process.stdin.on("end", onEnd);
9305
+ process.stdin.on("error", onError);
9306
+ process.stdin.resume();
9307
+ });
9308
+ ws.on("message", (data) => {
9309
+ process.stdout.write(formatWebSocketData(data));
9310
+ });
9311
+ ws.addEventListener("close", () => {
9312
+ cleanup();
9313
+ resolve2(void 0);
9314
+ });
9315
+ });
9316
+ }
9317
+ __name(stdioProxy, "stdioProxy");
9318
+ function formatWebSocketData(data) {
9319
+ if (Array.isArray(data)) {
9320
+ return Buffer.concat(data);
9321
+ }
9322
+ return data instanceof ArrayBuffer ? new Uint8Array(data) : data;
9323
+ }
9324
+ __name(formatWebSocketData, "formatWebSocketData");
9325
+ function shouldUseStdio(sshArgs) {
9326
+ return sshArgs.stdio === true || process.stdin.isTTY !== true && process.stdout.isTTY !== true;
9327
+ }
9328
+ __name(shouldUseStdio, "shouldUseStdio");
9329
+ function buildContainerSshArgs(sshArgs) {
9330
+ const flags = [
9331
+ // Never use a control socket.
9332
+ "-o",
9333
+ "ControlMaster=no",
9334
+ "-o",
9335
+ "ControlPersist=no",
9336
+ // Disable writing host keys to user known hosts file.
9337
+ "-o",
9338
+ "UserKnownHostsFile=/dev/null",
9339
+ // Do not perform strict host key checking: we use the same IP
9340
+ // address to connect to every container, all of which can have
9341
+ // separate host keys.
9342
+ "-o",
9343
+ "StrictHostKeyChecking=no"
9344
+ ];
9345
+ if (process.env.WRANGLER_LOG !== "debug") {
9346
+ flags.push("-o", "LogLevel=ERROR");
9347
+ }
9348
+ if (sshArgs.cipher !== void 0) {
9349
+ flags.push("-c", sshArgs.cipher);
9350
+ }
9351
+ if (sshArgs.logFile !== void 0) {
9352
+ flags.push("-E", sshArgs.logFile);
9353
+ }
9354
+ if (sshArgs.escapeChar !== void 0) {
9355
+ flags.push("-e", sshArgs.escapeChar);
9356
+ }
9357
+ if (sshArgs.configFile !== void 0) {
9358
+ flags.push("-F", sshArgs.configFile);
9359
+ }
9360
+ if (sshArgs.pkcs11 !== void 0) {
9361
+ flags.push("-I", sshArgs.pkcs11);
9362
+ }
9363
+ if (sshArgs.identityFile !== void 0) {
9364
+ flags.push("-i", sshArgs.identityFile);
9365
+ }
9366
+ if (sshArgs.macSpec !== void 0) {
9367
+ flags.push("-m", sshArgs.macSpec);
9368
+ }
9369
+ if (sshArgs.option !== void 0) {
9370
+ const options = Array.isArray(sshArgs.option) ? sshArgs.option : [sshArgs.option];
9371
+ options.forEach((o) => flags.push("-o", o));
9372
+ }
9373
+ if (sshArgs.tag !== void 0) {
9374
+ flags.push("-P", sshArgs.tag);
9375
+ }
9376
+ return flags;
9377
+ }
9378
+ __name(buildContainerSshArgs, "buildContainerSshArgs");
9379
+
9380
+ // src/registry-images.ts
9381
+ var MAX_REPOSITORY_LENGTH = 255;
9382
+ var REPOSITORY_COMPONENT_REGEXP = /^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/;
9383
+ var TAG_REGEXP = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;
9384
+ var IMAGE_TAG_REGEXP = /^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$/;
9385
+ async function listContainerImages({
9386
+ accountId,
9387
+ complianceConfig,
9388
+ filter
9389
+ }) {
9390
+ const pattern = new RegExp(filter ?? "");
9391
+ const creds = await getCreds(
9392
+ ["pull" /* PULL */],
9393
+ complianceConfig
9394
+ );
9395
+ const repositories = await listReposWithTags(creds, complianceConfig);
9396
+ const prefix = `${accountId}/`;
9397
+ return Object.entries(repositories).flatMap(([repo, tags]) => {
9398
+ const stripped = repo.replace(/^\/+/, "");
9399
+ if (!pattern.test(stripped)) {
9400
+ return [];
9401
+ }
9402
+ const visibleTags = tags.filter((tag) => isValidImageTag(tag));
9403
+ if (visibleTags.length === 0) {
9404
+ return [];
9405
+ }
9406
+ return [
9407
+ {
9408
+ name: stripped.startsWith(prefix) ? stripped.slice(prefix.length) : stripped,
9409
+ tags: visibleTags
9410
+ }
9411
+ ];
9412
+ });
9413
+ }
9414
+ __name(listContainerImages, "listContainerImages");
9415
+ function parseContainerImageTag(image) {
9416
+ const parts = image.split(":");
9417
+ const [repository, tag] = parts;
9418
+ if (parts.length !== 2 || !repository || !tag || repository.length > MAX_REPOSITORY_LENGTH || repository.split("/").some((part) => !REPOSITORY_COMPONENT_REGEXP.test(part)) || !TAG_REGEXP.test(tag)) {
9419
+ throw new Error("Invalid image format. Expected IMAGE:TAG");
9420
+ }
9421
+ return { repository, tag };
9422
+ }
9423
+ __name(parseContainerImageTag, "parseContainerImageTag");
9424
+ async function deleteContainerImage({
9425
+ accountId,
9426
+ complianceConfig,
9427
+ image
9428
+ }) {
9429
+ const { repository, tag } = parseContainerImageTag(image);
9430
+ const creds = await getCreds(
9431
+ ["pull" /* PULL */, "push" /* PUSH */],
9432
+ complianceConfig
9433
+ );
9434
+ const url = new URL(
9435
+ `https://${getCloudflareContainerRegistry(complianceConfig)}`
9436
+ );
9437
+ const baseUrl = `${url.protocol}//${url.host}`;
9438
+ const digest = await deleteTag(baseUrl, accountId, repository, tag, creds);
9439
+ try {
9440
+ const response = await fetch(`${baseUrl}/v2/gc/layers`, {
9441
+ method: "PUT",
9442
+ headers: {
9443
+ Authorization: `Basic ${creds}`,
9444
+ "Content-Type": "application/json"
9445
+ }
9446
+ });
9447
+ if (!response.ok) {
9448
+ throw new Error(`${response.status} ${response.statusText}`);
9449
+ }
9450
+ } catch (error) {
9451
+ const detail = error instanceof Error ? error.message : String(error);
9452
+ return {
9453
+ digest,
9454
+ warning: `Image ${image} was deleted, but the garbage-collection request failed: ${detail}`
9455
+ };
9456
+ }
9457
+ return { digest };
9458
+ }
9459
+ __name(deleteContainerImage, "deleteContainerImage");
9460
+ async function listReposWithTags(creds, complianceConfig) {
9461
+ const url = new URL(
9462
+ `https://${getCloudflareContainerRegistry(complianceConfig)}`
9463
+ );
9464
+ const catalogUrl = `${url.protocol}//${url.host}/v2/_catalog?tags=true`;
9465
+ const repositories = /* @__PURE__ */ new Map();
9466
+ const seenCursors = /* @__PURE__ */ new Set();
9467
+ let nextUrl = catalogUrl;
9468
+ while (true) {
9469
+ const response = await fetch(nextUrl, {
9470
+ method: "GET",
9471
+ headers: { Authorization: `Basic ${creds}` }
9472
+ });
9473
+ if (!response.ok) {
9474
+ throw new Error(
9475
+ `Failed to fetch repository catalog: ${response.status} ${response.statusText}`
9476
+ );
9477
+ }
9478
+ const data = await response.json();
9479
+ for (const [repository, tags] of Object.entries(data.repositories ?? {})) {
9480
+ const merged = repositories.get(repository) ?? /* @__PURE__ */ new Set();
9481
+ for (const tag of tags) {
9482
+ merged.add(tag);
9483
+ }
9484
+ repositories.set(repository, merged);
9485
+ }
9486
+ const cursor = nextCatalogCursor(response.headers.get("Link"), nextUrl);
9487
+ if (cursor === void 0) {
9488
+ break;
9489
+ }
9490
+ if (seenCursors.has(cursor)) {
9491
+ throw new Error("Registry catalog pagination repeated a cursor.");
9492
+ }
9493
+ seenCursors.add(cursor);
9494
+ const next = new URL(catalogUrl);
9495
+ next.searchParams.set("last", cursor);
9496
+ nextUrl = next.href;
9497
+ }
9498
+ return Object.fromEntries(
9499
+ [...repositories].map(([repository, tags]) => [repository, [...tags]])
9500
+ );
9501
+ }
9502
+ __name(listReposWithTags, "listReposWithTags");
9503
+ function nextCatalogCursor(header, baseUrl) {
9504
+ if (!header) {
9505
+ return void 0;
9506
+ }
9507
+ const links = header.matchAll(
9508
+ /(?:^|,)\s*(?:<([^>]+)>|([^;,\s]+))((?:;[^,]*)?)/g
9509
+ );
9510
+ for (const [, bracketed, bare, parameters] of links) {
9511
+ const relation = /;\s*rel\s*=\s*(?:"([^"]+)"|([^;\s]+))/i.exec(
9512
+ parameters ?? ""
9513
+ );
9514
+ if (!(relation?.[1] ?? relation?.[2] ?? "").split(/\s+/).includes("next")) {
9515
+ continue;
9516
+ }
9517
+ const target = bracketed ?? bare;
9518
+ if (!target) {
9519
+ throw new Error("Registry catalog next-page link is missing a URL.");
9520
+ }
9521
+ const cursor = new URL(target, baseUrl).searchParams.get("last");
9522
+ if (!cursor) {
9523
+ throw new Error("Registry catalog next-page link is missing a cursor.");
9524
+ }
9525
+ return cursor;
9526
+ }
9527
+ return void 0;
9528
+ }
9529
+ __name(nextCatalogCursor, "nextCatalogCursor");
9530
+ async function deleteTag(baseUrl, accountId, image, tag, creds) {
9531
+ const manifestAcceptHeader = "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json";
9532
+ const manifestUrl = `${baseUrl}/v2/${accountId}/${image}/manifests/${tag}`;
9533
+ const headResponse = await fetch(manifestUrl, {
9534
+ method: "HEAD",
9535
+ headers: {
9536
+ Authorization: `Basic ${creds}`,
9537
+ Accept: manifestAcceptHeader
9538
+ }
9539
+ });
9540
+ if (!headResponse.ok) {
9541
+ throw new Error(
9542
+ `Failed to retrieve info for ${image}:${tag}: ${headResponse.status} ${headResponse.statusText}`
9543
+ );
9544
+ }
9545
+ const digest = headResponse.headers.get("Docker-Content-Digest");
9546
+ if (!digest) {
9547
+ throw new Error(`Digest not found for ${image}:${tag}.`);
9548
+ }
9549
+ const deleteUrl = `${baseUrl}/v2/${accountId}/${image}/manifests/${tag}`;
9550
+ const deleteResponse = await fetch(deleteUrl, {
9551
+ method: "DELETE",
9552
+ headers: {
9553
+ Authorization: `Basic ${creds}`,
9554
+ Accept: manifestAcceptHeader
9555
+ }
9556
+ });
9557
+ if (!deleteResponse.ok) {
9558
+ throw new Error(
9559
+ `Failed to delete ${image}:${tag} (digest: ${digest}): ${deleteResponse.status} ${deleteResponse.statusText}`
9560
+ );
9561
+ }
9562
+ return digest;
9563
+ }
9564
+ __name(deleteTag, "deleteTag");
9565
+ async function getCreds(permissions, complianceConfig) {
9566
+ const credentials = await ImageRegistriesService.generateImageRegistryCredentials(
9567
+ getCloudflareContainerRegistry(complianceConfig),
9568
+ {
9569
+ expiration_minutes: 5,
9570
+ permissions
9571
+ }
9572
+ );
9573
+ return Buffer.from(`v1:${credentials.password}`).toString("base64");
9574
+ }
9575
+ __name(getCreds, "getCreds");
9576
+ function isValidImageTag(value) {
9577
+ return IMAGE_TAG_REGEXP.test(value);
9578
+ }
9579
+ __name(isValidImageTag, "isValidImageTag");
9580
+
9581
+ export { AccountService, ApiError, ApplicationAffinityColocation, ApplicationAffinityHardwareGeneration, ApplicationMutationError, ApplicationRollout, ApplicationsService, AssignIPv4, AssignIPv6, BadRequestWithCodeError, CancelError, CancelablePromise, ContainerImagePreparationStatus, ContainerImagePreparationsService, ContainerNetworkMode, CreateApplicationRolloutRequest, DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE, DeploymentCheckKind, DeploymentCheckType, DeploymentMutationError, DeploymentNotFoundError, DeploymentPlacementState, DeploymentQueuedReason, DeploymentSchedulingState, DeploymentType, DeploymentsService, Diff, DurableObjectStatusHealth, EventName, EventType, ExternalRegistryKind, FUSE_CONTAINER_PRIVILEGES, HTTPMethod, IPType, IPsService, ImageRegistriesService, ImageRegistryAlreadyExistsError, ImageRegistryIsPublic, ImageRegistryNotAllowedError, ImageRegistryNotFoundError, ImageRegistryPermissions, ImageRegistryProtocolAlreadyExists, ImageRegistryProtocolIsReferencedError, ImageRegistryProtocolNotFound, InstanceType, JobStatusHealth, JobsService, MF_DEV_CONTAINER_PREFIX, NetworkMode, NodeGroup, OpenAPI, PlacementStatusHealth, PlacementsService, ProvisionerConfiguration, RolloutStep, RolloutsService, SSHPublicKeyNotFoundError, SchedulingPolicy, SecretAccessType, SecretNameAlreadyExists, SecretNotFound, SecretsService, SshPublicKeysService, UpdateApplicationRolloutRequest, apply, buildAndMaybePush, buildAndWriteContainerOutput, buildCommand, buildContainerImages, cleanApplicationFromAPI, cleanForInstanceType, cleanupBuiltImages, cleanupContainers, configRolloutStepsToAPI, configureOpenAPIForContainerPull, containerPrivilegesAllowed, containersSshOptions, createContainerDevPlan, createDurableObjectNamespaceResolver, deleteContainerImage, deployContainers, dockerBuild, dockerImageInspect, dockerLoginImageRegistry, ensureContainerLimits, ensureImageFitsLimits, fetchPagedListResult, fetchResult, formatError, generateContainerBuildId, getAndValidateRegistryType, getCloudflareContainerRegistry, getCloudflareRegistryWithAccountNamespace, getContainerAccount, getContainerIdsByImageTags, getContainerIdsFromImage, getContainerImageTag, getDevContainerImageName, getDockerHostFromEnv, getDockerSocketFromContext, getEgressInterceptorImage, getEgressInterceptorPlatform, getInstanceTypeUsage, inferInstanceType, initContainersSharedContext, isCloudflareRegistryImage, isDockerRunning, isDockerfileContainerConfig, isValidImageTag, listContainerImages, listDurableObjects, logger, normalizeContainerImageRepositoryName, parseContainerImageTag, prepareContainerImagesForDev, promiseSpinner, pullEgressInterceptorImage, pullImage, pushBuiltContainerImage, pushCommand, pushImageIfChanged, request, requestPaginated, resolveDockerHost, resolveImageName, runDockerCmd, runDockerCmdWithOutput, shouldUseStdio, sortObjectRecursive, sshCommand, startContainerBuild, stripUndefined, validateAndEncodeGarKey, verifyDockerInstalled, verifySshInstalled };