@elizaos/plugin-minecraft 2.0.0-beta.1 → 2.0.11-beta.7

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