agents-city 0.4.0 → 0.5.2

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