@minecraftbot-com/plugin 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/AGENTS.md +177 -0
  2. package/README.md +45 -2
  3. package/dist/api.d.ts +351 -0
  4. package/dist/api.js +2 -0
  5. package/dist/cli/api.d.ts +26 -0
  6. package/dist/cli/api.js +61 -0
  7. package/dist/cli/build.d.ts +23 -0
  8. package/dist/cli/build.js +65 -0
  9. package/dist/cli/check.d.ts +10 -0
  10. package/dist/cli/check.js +98 -0
  11. package/dist/cli/config.d.ts +11 -0
  12. package/dist/cli/config.js +38 -0
  13. package/dist/cli/create.d.ts +2 -0
  14. package/dist/cli/create.js +39 -0
  15. package/dist/cli/dev-mcp.d.ts +36 -0
  16. package/dist/cli/dev-mcp.js +101 -0
  17. package/dist/cli/dev.d.ts +15 -0
  18. package/dist/cli/dev.js +261 -0
  19. package/dist/cli/fetch-guard.d.ts +7 -0
  20. package/dist/cli/fetch-guard.js +66 -0
  21. package/dist/cli/main.d.ts +2 -0
  22. package/dist/cli/main.js +112 -0
  23. package/dist/cli/mcp.d.ts +24 -0
  24. package/dist/cli/mcp.js +136 -0
  25. package/dist/cli/output.d.ts +11 -0
  26. package/dist/cli/output.js +25 -0
  27. package/dist/cli/test.d.ts +2 -0
  28. package/dist/cli/test.js +39 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/generated/block-states.d.ts +4087 -0
  32. package/dist/generated/block-states.js +2 -0
  33. package/dist/generated/blocks.d.ts +1289 -0
  34. package/dist/generated/blocks.js +1291 -0
  35. package/dist/generated/contracts.d.ts +304 -0
  36. package/dist/generated/contracts.js +327 -0
  37. package/dist/generated/effects.d.ts +43 -0
  38. package/dist/generated/effects.js +45 -0
  39. package/dist/generated/entities.d.ts +164 -0
  40. package/dist/generated/entities.js +166 -0
  41. package/dist/generated/items.d.ts +1661 -0
  42. package/dist/generated/items.js +1663 -0
  43. package/dist/generated/operations.d.ts +7 -0
  44. package/dist/generated/operations.js +65 -0
  45. package/dist/generated/permission-labels.d.ts +3 -0
  46. package/dist/generated/permission-labels.js +17 -0
  47. package/dist/generated/version.d.ts +2 -0
  48. package/dist/generated/version.js +3 -0
  49. package/dist/host/index.d.ts +7 -0
  50. package/dist/host/index.js +5 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +13 -0
  53. package/dist/permissions.d.ts +11 -0
  54. package/dist/permissions.js +18 -0
  55. package/dist/plugin.d.ts +86 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/protocol.d.ts +167 -0
  58. package/dist/protocol.js +4 -0
  59. package/dist/runtime/connection.d.ts +52 -0
  60. package/dist/runtime/connection.js +132 -0
  61. package/dist/runtime/handles.d.ts +95 -0
  62. package/dist/runtime/handles.js +289 -0
  63. package/dist/runtime/memory-transport.d.ts +6 -0
  64. package/dist/runtime/memory-transport.js +39 -0
  65. package/dist/runtime/runtime.d.ts +57 -0
  66. package/dist/runtime/runtime.js +265 -0
  67. package/dist/runtime/scope.d.ts +25 -0
  68. package/dist/runtime/scope.js +94 -0
  69. package/dist/runtime/storage-runtime.d.ts +10 -0
  70. package/dist/runtime/storage-runtime.js +131 -0
  71. package/dist/settings.d.ts +111 -0
  72. package/dist/settings.js +78 -0
  73. package/dist/storage.d.ts +78 -0
  74. package/dist/storage.js +24 -0
  75. package/dist/testing/fake-container.d.ts +175 -0
  76. package/dist/testing/fake-container.js +483 -0
  77. package/dist/testing/index.d.ts +37 -0
  78. package/dist/testing/index.js +54 -0
  79. package/dist/types.d.ts +65 -0
  80. package/dist/types.js +54 -0
  81. package/llms.txt +11 -0
  82. package/package.json +55 -4
  83. package/src/api.ts +334 -0
  84. package/src/cli/api.ts +79 -0
  85. package/src/cli/build.ts +76 -0
  86. package/src/cli/check.ts +103 -0
  87. package/src/cli/config.ts +48 -0
  88. package/src/cli/create.ts +38 -0
  89. package/src/cli/dev-mcp.ts +131 -0
  90. package/src/cli/dev.ts +272 -0
  91. package/src/cli/fetch-guard.ts +61 -0
  92. package/src/cli/main.ts +113 -0
  93. package/src/cli/mcp.ts +168 -0
  94. package/src/cli/output.ts +30 -0
  95. package/src/cli/test.ts +38 -0
  96. package/src/errors.ts +34 -0
  97. package/src/generated/block-states.ts +892 -0
  98. package/src/generated/blocks.ts +1291 -0
  99. package/src/generated/contracts.ts +329 -0
  100. package/src/generated/effects.ts +45 -0
  101. package/src/generated/entities.ts +166 -0
  102. package/src/generated/items.ts +1663 -0
  103. package/src/generated/operations.ts +69 -0
  104. package/src/generated/permission-labels.ts +19 -0
  105. package/src/generated/version.ts +3 -0
  106. package/src/host/index.ts +9 -0
  107. package/src/index.ts +34 -0
  108. package/src/permissions.ts +23 -0
  109. package/src/plugin.ts +105 -0
  110. package/src/protocol.ts +107 -0
  111. package/src/runtime/connection.ts +167 -0
  112. package/src/runtime/handles.ts +337 -0
  113. package/src/runtime/memory-transport.ts +41 -0
  114. package/src/runtime/runtime.ts +281 -0
  115. package/src/runtime/scope.ts +101 -0
  116. package/src/runtime/storage-runtime.ts +138 -0
  117. package/src/settings.ts +118 -0
  118. package/src/storage.ts +82 -0
  119. package/src/testing/fake-container.ts +571 -0
  120. package/src/testing/index.ts +70 -0
  121. package/src/types.ts +88 -0
  122. package/templates/basic/AGENTS.md +31 -0
  123. package/templates/basic/README.md +13 -0
  124. package/templates/basic/gitignore +3 -0
  125. package/templates/basic/package.json +18 -0
  126. package/templates/basic/src/index.ts +20 -0
  127. package/templates/basic/test/plugin.test.ts +14 -0
  128. package/templates/basic/tsconfig.json +14 -0
@@ -0,0 +1,483 @@
1
+ import { OPERATIONS, PROFILE_WIDE_OPERATIONS, EVENT_PERMISSIONS } from "../generated/operations.js";
2
+ import { BotEvent, ProfileEvent, StorageScope } from "../generated/contracts.js";
3
+ import { networkHost } from "../permissions.js";
4
+ const STACK = 64;
5
+ const INVENTORY_SLOTS = 36;
6
+ function countOf(items, item) {
7
+ return items.filter(s => s.item === item).reduce((n, s) => n + s.count, 0);
8
+ }
9
+ /** Takes up to `count` of an item out of a slot list; returns how many it took. */
10
+ function takeFrom(items, item, count) {
11
+ let taken = 0;
12
+ for (const s of items) {
13
+ if (s.item !== item || taken >= count)
14
+ continue;
15
+ const n = Math.min(s.count, count - taken);
16
+ s.count -= n;
17
+ taken += n;
18
+ }
19
+ for (let i = items.length - 1; i >= 0; i--)
20
+ if (items[i].count <= 0)
21
+ items.splice(i, 1);
22
+ return taken;
23
+ }
24
+ /** Puts up to `count` of an item into a slot list of `slots` slots, stacking to 64; returns how many fit. */
25
+ function putInto(items, slots, item, count) {
26
+ let put = 0;
27
+ for (const s of items) {
28
+ if (s.item !== item || s.count >= STACK || put >= count)
29
+ continue;
30
+ const n = Math.min(STACK - s.count, count - put);
31
+ s.count += n;
32
+ put += n;
33
+ }
34
+ while (put < count && items.length < slots) {
35
+ const used = new Set(items.map(s => s.slot));
36
+ let slot = 0;
37
+ while (used.has(slot))
38
+ slot++;
39
+ const n = Math.min(STACK, count - put);
40
+ items.push({ item, count: n, slot });
41
+ put += n;
42
+ }
43
+ return put;
44
+ }
45
+ const REACH = 4.5;
46
+ const LIMITS = { callsPerSecond: 50, concurrentCalls: 64, frameBytes: 131072, eventQueue: 256, storageBytes: 1_048_576, storageValueBytes: 65_536 };
47
+ function key(p) {
48
+ return `${p.x},${p.y},${p.z}`;
49
+ }
50
+ function distance(a, b) {
51
+ return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
52
+ }
53
+ /**
54
+ * An in-memory bot container for tests: a tiny world, inventories, chat, storage, and the same permission
55
+ * checks as the real one. It speaks the real protocol over a Transport, so the SDK is exercised end to end.
56
+ */
57
+ export class FakeContainer {
58
+ transport;
59
+ options;
60
+ calls = [];
61
+ said = [];
62
+ commands = [];
63
+ logs = [];
64
+ warnings = new Map();
65
+ stats = new Map();
66
+ errors = [];
67
+ blocks = new Map();
68
+ storage = new Map();
69
+ manifest = null;
70
+ bots = new Map();
71
+ subscriptions = new Set();
72
+ running = new Set();
73
+ granted = new Set();
74
+ entities;
75
+ players;
76
+ unreachable;
77
+ pendingFollows = new Map();
78
+ /** The fake world's containers by position, readable from tests. */
79
+ chests = new Map();
80
+ constructor(transport, options = {}) {
81
+ this.transport = transport;
82
+ this.options = options;
83
+ const bots = options.bots?.length ? options.bots : [{}];
84
+ bots.forEach((b, i) => {
85
+ const id = b.id ?? `bot-${i + 1}`;
86
+ this.bots.set(id, {
87
+ info: { id, name: b.name ?? `Bot${i + 1}`, uuid: b.uuid ?? `00000000-0000-0000-0000-${String(i + 1).padStart(12, "0")}`, connected: b.connected ?? true, enabled: b.enabled ?? true },
88
+ position: b.position ?? { x: 0, y: 64, z: 0 },
89
+ health: b.health ?? 20,
90
+ food: b.food ?? 20,
91
+ inventory: (b.inventory ?? []).map((it, slot) => ({ slot, ...it })),
92
+ version: b.version ?? "1.21.4",
93
+ open: null,
94
+ });
95
+ });
96
+ for (const b of options.blocks ?? [])
97
+ this.blocks.set(key(b.position), { ...b, state: b.state ?? {} });
98
+ for (const c of options.containers ?? []) {
99
+ const block = c.block ?? "minecraft:chest";
100
+ this.chests.set(key(c.position), { position: c.position, block, size: c.size ?? 27, items: (c.items ?? []).map((it, slot) => ({ slot, ...it })) });
101
+ this.blocks.set(key(c.position), { position: c.position, block, state: {} });
102
+ }
103
+ this.entities = [...(options.entities ?? [])];
104
+ this.players = (options.players ?? []).map(p => ({ ping: 20, ...p }));
105
+ this.unreachable = new Set((options.unreachable ?? []).map(key));
106
+ transport.onmessage = text => this.receive(text);
107
+ transport.onclose = () => { };
108
+ }
109
+ bot(id) {
110
+ const b = this.bots.get(id);
111
+ if (!b)
112
+ throw new Error(`No fake bot ${id}`);
113
+ return b;
114
+ }
115
+ /** Starts run(bot) on every enabled, connected bot (and runProfile), as the container does after welcome. */
116
+ startAll() {
117
+ if (this.manifest?.profile)
118
+ this.send({ type: "start", bot: null, settings: this.settingsFor("*") });
119
+ for (const b of this.bots.values())
120
+ if (b.info.enabled && b.info.connected)
121
+ this.startBot(b.info.id);
122
+ }
123
+ startBot(id) {
124
+ this.running.add(id);
125
+ this.send({ type: "start", bot: id, settings: this.settingsFor(id), version: this.bot(id).version });
126
+ }
127
+ stopBot(id, reason = "UserStopped") {
128
+ this.running.delete(id);
129
+ this.send({ type: "stop", bot: id, reason });
130
+ }
131
+ /** Sends a bot event if the plugin subscribed to it. Returns whether it was sent. */
132
+ emit(bot, event, data) {
133
+ if (!this.subscriptions.has(`${bot}|${event}`))
134
+ return false;
135
+ this.send({ type: "event", bot, event, data });
136
+ return true;
137
+ }
138
+ /** Sends a profile event (`botId` in data becomes a ProfileBot in the SDK). */
139
+ emitProfile(event, data) {
140
+ if (!this.subscriptions.has(`|${event}`))
141
+ return false;
142
+ this.send({ type: "event", bot: null, event, data });
143
+ return true;
144
+ }
145
+ /** A chat message from a player (or the server, without sender) to a bot. */
146
+ chat(bot, text, sender = "Steve") {
147
+ return this.emit(bot, BotEvent.Chat, { text, sender, senderUuid: null, system: sender === null });
148
+ }
149
+ disconnectBot(id, reason = "Kicked") {
150
+ const b = this.bot(id);
151
+ b.info.connected = false;
152
+ if (this.running.has(id))
153
+ this.stopBot(id, "BotDisconnected");
154
+ this.send({ type: "bots", bots: [...this.bots.values()].map(x => x.info) });
155
+ this.emitProfile(ProfileEvent.BotDisconnected, { botId: id, reason });
156
+ }
157
+ setEntities(entities) {
158
+ this.entities = [...entities];
159
+ }
160
+ close() {
161
+ this.transport.close(1000, "Test finished");
162
+ }
163
+ settingsFor(id) {
164
+ return { ...(this.options.settings?.["*"] ?? {}), ...(this.options.settings?.[id] ?? {}) };
165
+ }
166
+ send(frame) {
167
+ this.transport.send(JSON.stringify(frame));
168
+ }
169
+ receive(text) {
170
+ const frame = JSON.parse(text);
171
+ switch (frame.type) {
172
+ case "hello":
173
+ this.hello(frame);
174
+ break;
175
+ case "call":
176
+ this.call(frame);
177
+ break;
178
+ case "cancel": {
179
+ const resolve = this.pendingFollows.get(frame.id);
180
+ this.pendingFollows.delete(frame.id);
181
+ resolve?.();
182
+ break;
183
+ }
184
+ case "subscribe": {
185
+ const event = frame.event;
186
+ const needs = frame.bot === null ? null : EVENT_PERMISSIONS[event];
187
+ if (needs && !this.granted.has(needs)) {
188
+ this.errors.push({ op: `subscribe ${event}`, code: "PermissionDenied", message: `BotEvent.${event} needs Permission.${needs}` });
189
+ this.send({ type: "error", id: null, code: "PermissionDenied", message: `BotEvent.${event} needs Permission.${needs}` });
190
+ break;
191
+ }
192
+ this.subscriptions.add(`${frame.bot ?? ""}|${frame.event}`);
193
+ break;
194
+ }
195
+ case "unsubscribe":
196
+ this.subscriptions.delete(`${frame.bot ?? ""}|${frame.event}`);
197
+ break;
198
+ case "log":
199
+ this.logs.push({ bot: frame.bot, level: frame.level, message: frame.message });
200
+ break;
201
+ case "warning":
202
+ if (frame.message === null)
203
+ this.warnings.delete(`${frame.bot ?? ""}|${frame.key}`);
204
+ else
205
+ this.warnings.set(`${frame.bot ?? ""}|${frame.key}`, frame.message);
206
+ break;
207
+ case "stat":
208
+ this.stats.set(`${frame.bot ?? ""}|${frame.key}`, frame.value);
209
+ break;
210
+ case "done":
211
+ if (frame.bot)
212
+ this.running.delete(frame.bot);
213
+ break;
214
+ }
215
+ }
216
+ hello(frame) {
217
+ this.manifest = frame.manifest;
218
+ this.granted = new Set(this.options.granted ?? frame.manifest.permissions);
219
+ this.send({
220
+ type: "welcome",
221
+ installation: "test-installation",
222
+ mode: "Dev",
223
+ profile: this.options.profile ?? { id: "test-profile", name: "Test profile" },
224
+ bots: [...this.bots.values()].map(b => b.info),
225
+ granted: [...this.granted],
226
+ settings: this.settingsFor("*"),
227
+ limits: LIMITS,
228
+ });
229
+ }
230
+ fail(frame, failure, message) {
231
+ this.send({ type: "result", id: frame.id, ok: false, failure, message });
232
+ }
233
+ ok(frame, value = null) {
234
+ this.send({ type: "result", id: frame.id, ok: true, value });
235
+ }
236
+ error(frame, code, message) {
237
+ this.errors.push({ op: frame.op, code, message });
238
+ this.send({ type: "error", id: frame.id, code, message });
239
+ }
240
+ call(frame) {
241
+ this.calls.push({ bot: frame.bot, op: frame.op, args: frame.args });
242
+ if (!(frame.op in OPERATIONS))
243
+ return this.error(frame, "UnknownOperation", `Unknown operation ${frame.op}`);
244
+ const needs = OPERATIONS[frame.op];
245
+ if (needs && !this.granted.has(needs))
246
+ return this.error(frame, "PermissionDenied", `${frame.op} needs Permission.${needs}: add it to permissions in definePlugin`);
247
+ if (frame.bot !== null && !PROFILE_WIDE_OPERATIONS.has(frame.op) && !this.running.has(frame.bot)) {
248
+ return this.error(frame, "BotNotRunning", `The plugin isn't running on bot ${frame.bot}`);
249
+ }
250
+ const a = frame.args;
251
+ const b = frame.bot ? this.bots.get(frame.bot) : undefined;
252
+ if (frame.bot && !b)
253
+ return this.fail(frame, "UnknownBot", `No bot ${frame.bot}`);
254
+ switch (frame.op) {
255
+ case "bot.status":
256
+ return this.ok(frame, { health: b.health, food: b.food, saturation: 5, alive: b.health > 0, gameMode: "Survival", dimension: "minecraft:overworld", experienceLevel: 0 });
257
+ case "bot.position":
258
+ return this.ok(frame, b.position);
259
+ case "bot.supports":
260
+ return this.ok(frame, true);
261
+ case "bot.goto": {
262
+ const target = { x: a.x, y: a.y, z: a.z };
263
+ if (this.unreachable.has(key(target)))
264
+ return this.fail(frame, "NoPath", `No path to ${key(target)}`);
265
+ b.position = target;
266
+ return this.ok(frame);
267
+ }
268
+ case "bot.follow":
269
+ // Follows until cancelled: resolves when the plugin stops or cancels the call.
270
+ this.pendingFollows.set(frame.id, () => { });
271
+ return;
272
+ case "bot.stopMoving":
273
+ case "bot.lookAt":
274
+ case "bot.jump":
275
+ return this.ok(frame);
276
+ case "bot.dig": {
277
+ const at = { x: a.x, y: a.y, z: a.z };
278
+ if (distance(b.position, at) > REACH)
279
+ return this.fail(frame, "OutOfReach", "Too far away");
280
+ if (!this.blocks.delete(key(at)))
281
+ return this.fail(frame, "NothingThere", "No block there");
282
+ return this.ok(frame);
283
+ }
284
+ case "bot.place": {
285
+ const at = { x: a.x, y: a.y, z: a.z };
286
+ if (distance(b.position, at) > REACH)
287
+ return this.fail(frame, "OutOfReach", "Too far away");
288
+ if (this.blocks.has(key(at)))
289
+ return this.fail(frame, "Occupied", "Something is already there");
290
+ const stack = b.inventory.find(s => s.item === a.item && s.count > 0);
291
+ if (!stack)
292
+ return this.fail(frame, "NoItem", `No ${a.item} in the inventory`);
293
+ stack.count--;
294
+ this.blocks.set(key(at), { position: at, block: a.item, state: {} });
295
+ return this.ok(frame);
296
+ }
297
+ case "bot.activateBlock":
298
+ case "bot.useItem":
299
+ return this.ok(frame);
300
+ case "bot.attack": {
301
+ const target = this.entities.find(e => e.id === a.entity);
302
+ if (!target)
303
+ return this.fail(frame, "NotFound", "No such entity");
304
+ if (distance(b.position, target.position) > 3)
305
+ return this.fail(frame, "OutOfReach", "Too far away");
306
+ return this.ok(frame);
307
+ }
308
+ case "bot.say":
309
+ this.said.push({ bot: frame.bot, text: a.text });
310
+ return this.ok(frame);
311
+ case "bot.command":
312
+ this.commands.push({ bot: frame.bot, command: a.command });
313
+ return this.ok(frame);
314
+ case "bot.connect":
315
+ if (b.info.connected)
316
+ return this.fail(frame, "AlreadyConnected", "Already connected");
317
+ b.info.connected = true;
318
+ return this.ok(frame);
319
+ case "bot.disconnect":
320
+ if (!b.info.connected)
321
+ return this.fail(frame, "AlreadyDisconnected", "Already disconnected");
322
+ b.info.connected = false;
323
+ return this.ok(frame);
324
+ case "bot.reconnect":
325
+ return this.ok(frame);
326
+ case "world.block": {
327
+ const found = this.blocks.get(key(a));
328
+ return this.ok(frame, found ? { position: found.position, block: found.block, state: found.state ?? {} } : null);
329
+ }
330
+ case "world.findBlocks": {
331
+ const from = a.from ?? b.position;
332
+ const wanted = new Set(a.blocks);
333
+ const matches = [...this.blocks.values()]
334
+ .filter(x => wanted.has(x.block) && distance(from, x.position) <= a.radius)
335
+ .filter(x => Object.entries(a.state ?? {}).every(([k, v]) => String(x.state?.[k]) === String(v)))
336
+ .sort((p, q) => distance(from, p.position) - distance(from, q.position))
337
+ .slice(0, a.limit);
338
+ return this.ok(frame, matches.map(x => ({ position: x.position, block: x.block, state: x.state ?? {} })));
339
+ }
340
+ case "entities.nearby": {
341
+ const types = a.types ? new Set(a.types) : null;
342
+ const list = this.entities
343
+ .map(e => ({ ...e, distance: distance(b.position, e.position) }))
344
+ .filter(e => e.distance <= a.radius && (!types || types.has(e.type)))
345
+ .sort((p, q) => p.distance - q.distance)
346
+ .slice(0, a.limit)
347
+ .map(e => ({ id: e.id, type: e.type, uuid: e.uuid ?? null, name: e.name ?? null, position: e.position, distance: e.distance }));
348
+ return this.ok(frame, list);
349
+ }
350
+ case "entities.players":
351
+ return this.ok(frame, this.players.map(p => ({ ...p, gameMode: "Survival" })));
352
+ case "inventory.items":
353
+ return this.ok(frame, b.inventory.filter(s => s.count > 0).map(s => ({ item: s.item, count: s.count, slot: s.slot ?? 0, name: s.name ?? null })));
354
+ case "inventory.held": {
355
+ const s = b.inventory.find(x => x.count > 0);
356
+ return this.ok(frame, s ? { item: s.item, count: s.count, slot: s.slot ?? 0, name: s.name ?? null } : null);
357
+ }
358
+ case "inventory.equip":
359
+ return b.inventory.some(s => s.item === a.item && s.count > 0) ? this.ok(frame) : this.fail(frame, "NoItem", `No ${a.item}`);
360
+ case "inventory.drop": {
361
+ const s = b.inventory.find(x => x.item === a.item && x.count > 0);
362
+ if (!s)
363
+ return this.fail(frame, "NoItem", `No ${a.item}`);
364
+ s.count = a.count === null ? 0 : Math.max(0, s.count - a.count);
365
+ return this.ok(frame);
366
+ }
367
+ case "bot.recipes":
368
+ return this.ok(frame, (this.options.recipes ?? []).filter(r => r.result === a.item).map(r => ({
369
+ result: r.result, count: r.count ?? 1, table: r.table ?? false,
370
+ ingredients: Object.entries(r.ingredients).map(([item, count]) => ({ items: [item], count })),
371
+ })));
372
+ case "bot.craft":
373
+ return this.craft(frame, b, a);
374
+ case "container.open": {
375
+ const at = { x: a.x, y: a.y, z: a.z };
376
+ const chest = this.chests.get(key(at));
377
+ if (!chest)
378
+ return this.fail(frame, "NotAContainer", `${this.blocks.get(key(at))?.block ?? "Nothing"} at ${key(at)} isn't a container`);
379
+ if (distance(b.position, at) > REACH)
380
+ return this.fail(frame, "OutOfReach", "Too far away");
381
+ b.open = key(at);
382
+ return this.ok(frame, { position: chest.position, block: chest.block, size: chest.size, items: this.describe(chest.items) });
383
+ }
384
+ case "container.items": {
385
+ const chest = b.open ? this.chests.get(b.open) : undefined;
386
+ return chest ? this.ok(frame, this.describe(chest.items)) : this.fail(frame, "Closed", "No container is open");
387
+ }
388
+ case "container.deposit":
389
+ case "container.withdraw": {
390
+ const chest = b.open ? this.chests.get(b.open) : undefined;
391
+ if (!chest)
392
+ return this.fail(frame, "Closed", "No container is open");
393
+ const deposit = frame.op === "container.deposit";
394
+ const [from, to, toSlots] = deposit ? [b.inventory, chest.items, chest.size] : [chest.items, b.inventory, INVENTORY_SLOTS];
395
+ const wanted = Math.min(a.count ?? Infinity, countOf(from, a.item));
396
+ if (wanted === 0)
397
+ return this.fail(frame, "NoItem", `No ${a.item} to move`);
398
+ const moved = putInto(to, toSlots, a.item, wanted);
399
+ takeFrom(from, a.item, moved);
400
+ return moved > 0 ? this.ok(frame, { moved }) : this.fail(frame, "Full", "No room");
401
+ }
402
+ case "container.close":
403
+ b.open = null;
404
+ return this.ok(frame);
405
+ case "plugins.start":
406
+ case "plugins.stop":
407
+ return this.ok(frame);
408
+ case "storage.get":
409
+ case "storage.set":
410
+ case "storage.delete":
411
+ case "storage.entries":
412
+ return this.storageCall(frame, a);
413
+ }
414
+ return this.error(frame, "UnknownOperation", `The fake container doesn't implement ${frame.op}`);
415
+ }
416
+ describe(items) {
417
+ return items.filter(s => s.count > 0).map(s => ({ item: s.item, count: s.count, slot: s.slot ?? 0, name: s.name ?? null }));
418
+ }
419
+ /** Crafts as the real container does: whole crafts, ingredients from the inventory, a table within reach if needed. */
420
+ craft(frame, b, a) {
421
+ const recipe = (this.options.recipes ?? []).find(r => r.result === a.item);
422
+ if (!recipe)
423
+ return this.fail(frame, "NoRecipe", `No crafting recipe makes ${a.item}`);
424
+ const per = recipe.count ?? 1;
425
+ const crafts = Math.ceil((a.count ?? 1) / per);
426
+ const missing = Object.entries(recipe.ingredients).filter(([item, n]) => countOf(b.inventory, item) < n * crafts);
427
+ if (missing.length)
428
+ return this.fail(frame, "MissingIngredients", `Crafting ${a.item} needs ${missing.map(([item, n]) => `${n * crafts} ${item}`).join(", ")}`);
429
+ if (recipe.table) {
430
+ const tables = [...this.blocks.values()].filter(x => x.block === "minecraft:crafting_table" && distance(b.position, x.position) <= REACH);
431
+ const at = a.table ? tables.find(t => key(t.position) === key(a.table)) : tables[0];
432
+ if (!at)
433
+ return this.fail(frame, "NoCraftingTable", `${a.item} needs a crafting table and none is within reach`);
434
+ }
435
+ for (const [item, n] of Object.entries(recipe.ingredients))
436
+ takeFrom(b.inventory, item, n * crafts);
437
+ const made = putInto(b.inventory, INVENTORY_SLOTS, recipe.result, per * crafts);
438
+ if (made === 0)
439
+ return this.fail(frame, "InventoryFull", "No room in the inventory");
440
+ b.open = null;
441
+ return this.ok(frame, { crafted: made });
442
+ }
443
+ storageCall(frame, a) {
444
+ const declared = this.manifest?.storage[a.name];
445
+ if (!declared)
446
+ return this.error(frame, "BadArguments", `storage.${a.name} isn't declared in definePlugin's storage`);
447
+ if (declared.scope === StorageScope.Bot && !a.bot)
448
+ return this.error(frame, "BadArguments", `storage.${a.name} is bot-scoped: use storage.${a.name}.for(bot)`);
449
+ const base = `${a.name}|${declared.scope}|${a.bot ?? ""}`;
450
+ switch (frame.op) {
451
+ case "storage.get": {
452
+ const entry = this.storage.get(`${base}|${a.key ?? ""}`);
453
+ return this.ok(frame, { value: entry?.value ?? null, version: entry?.version ?? 0 });
454
+ }
455
+ case "storage.set": {
456
+ const k = `${base}|${a.key ?? ""}`;
457
+ const entry = this.storage.get(k);
458
+ const version = entry?.version ?? 0;
459
+ if (a.ifVersion !== null && a.ifVersion !== version)
460
+ return this.fail(frame, "Conflict", "Changed since it was read");
461
+ if (JSON.stringify(a.value).length > LIMITS.storageValueBytes)
462
+ return this.error(frame, "ValueTooLarge", "Values are limited to 64 KB");
463
+ this.storage.set(k, { value: JSON.parse(JSON.stringify(a.value)), version: version + 1 });
464
+ return this.ok(frame, { version: version + 1 });
465
+ }
466
+ case "storage.delete":
467
+ this.storage.delete(`${base}|${a.key ?? ""}`);
468
+ return this.ok(frame);
469
+ case "storage.entries": {
470
+ const prefix = `${base}|`;
471
+ const keys = [...this.storage.keys()].filter(k => k.startsWith(prefix) && k !== prefix).map(k => k.slice(prefix.length)).sort();
472
+ const start = a.after ? keys.findIndex(k => k > a.after) : 0;
473
+ const page = start < 0 ? [] : keys.slice(start, start + a.limit);
474
+ const next = start >= 0 && start + a.limit < keys.length ? page[page.length - 1] : null;
475
+ return this.ok(frame, { entries: page.map(k => [k, this.storage.get(prefix + k).value]), next });
476
+ }
477
+ }
478
+ }
479
+ }
480
+ /** Hosts a declared network permission covers, for tests of fetch rules. */
481
+ export function declaredHosts(manifest) {
482
+ return manifest.permissions.map(networkHost).filter((h) => h !== null);
483
+ }
@@ -0,0 +1,37 @@
1
+ import type { DefinedPlugin } from "../plugin.js";
2
+ import { PluginRuntime, type LogLevel } from "../runtime/runtime.js";
3
+ import { FakeContainer, type FakeContainerOptions } from "./fake-container.js";
4
+ export { FakeContainer } from "./fake-container.js";
5
+ export type { FakeBlock, FakeBotOptions, FakeChest, FakeContainerOptions, FakeEntity, FakeItem, FakeRecipe, RecordedCall } from "./fake-container.js";
6
+ export interface TestRun {
7
+ /** The fake bot container: its world, what the plugin said, stored data, and `emit`/`chat` to send events. */
8
+ readonly container: FakeContainer;
9
+ readonly runtime: PluginRuntime;
10
+ /** Lets pending calls, events and timers of 0 ms settle. Call it after triggering something. */
11
+ settle(ms?: number): Promise<void>;
12
+ /** Waits until `condition` holds (checked after each settle), or throws after `timeoutMs`. */
13
+ until(condition: () => boolean, timeoutMs?: number): Promise<void>;
14
+ /** Stops the plugin and closes the fake connection. */
15
+ stop(): Promise<void>;
16
+ }
17
+ /**
18
+ * Starts a plugin against a fake bot. Permissions are checked as on a real bot, so a missing permission
19
+ * fails here too.
20
+ *
21
+ * @example
22
+ * import { test } from "node:test";
23
+ * import assert from "node:assert/strict";
24
+ * import { testPlugin } from "@minecraftbot-com/plugin/testing";
25
+ * import plugin from "../src/index.js";
26
+ *
27
+ * test("answers !ping", async () => {
28
+ * const run = await testPlugin(plugin);
29
+ * run.container.chat("bot-1", "!ping");
30
+ * await run.until(() => run.container.said.length > 0);
31
+ * assert.equal(run.container.said[0].text, "pong");
32
+ * await run.stop();
33
+ * });
34
+ */
35
+ export declare function testPlugin(plugin: DefinedPlugin, options?: FakeContainerOptions & {
36
+ onLog?: (level: LogLevel, message: string) => void;
37
+ }): Promise<TestRun>;
@@ -0,0 +1,54 @@
1
+ // @minecraftbot-com/plugin/testing: run a plugin against a fake bot in unit tests, no server needed.
2
+ import { PluginRuntime } from "../runtime/runtime.js";
3
+ import { memoryTransportPair } from "../runtime/memory-transport.js";
4
+ import { FakeContainer } from "./fake-container.js";
5
+ export { FakeContainer } from "./fake-container.js";
6
+ /**
7
+ * Starts a plugin against a fake bot. Permissions are checked as on a real bot, so a missing permission
8
+ * fails here too.
9
+ *
10
+ * @example
11
+ * import { test } from "node:test";
12
+ * import assert from "node:assert/strict";
13
+ * import { testPlugin } from "@minecraftbot-com/plugin/testing";
14
+ * import plugin from "../src/index.js";
15
+ *
16
+ * test("answers !ping", async () => {
17
+ * const run = await testPlugin(plugin);
18
+ * run.container.chat("bot-1", "!ping");
19
+ * await run.until(() => run.container.said.length > 0);
20
+ * assert.equal(run.container.said[0].text, "pong");
21
+ * await run.stop();
22
+ * });
23
+ */
24
+ export async function testPlugin(plugin, options = {}) {
25
+ const [pluginSide, containerSide] = memoryTransportPair();
26
+ const container = new FakeContainer(containerSide, options);
27
+ const runtime = await PluginRuntime.connect(plugin, pluginSide, "test-token", "0.0.0-test", { onLog: options.onLog ? (l, m) => options.onLog(l, m) : undefined });
28
+ container.startAll();
29
+ const settle = async (ms = 0) => {
30
+ for (let i = 0; i < 20; i++)
31
+ await Promise.resolve();
32
+ await new Promise(r => setTimeout(r, ms));
33
+ for (let i = 0; i < 20; i++)
34
+ await Promise.resolve();
35
+ };
36
+ await settle();
37
+ return {
38
+ container,
39
+ runtime,
40
+ settle,
41
+ async until(condition, timeoutMs = 2000) {
42
+ const deadline = Date.now() + timeoutMs;
43
+ while (!condition()) {
44
+ if (Date.now() > deadline)
45
+ throw new Error(`Condition not met within ${timeoutMs} ms`);
46
+ await settle(5);
47
+ }
48
+ },
49
+ async stop() {
50
+ runtime.close();
51
+ await settle();
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,65 @@
1
+ /** A position or direction in the world. Block positions are whole numbers. */
2
+ export interface Vec3 {
3
+ readonly x: number;
4
+ readonly y: number;
5
+ readonly z: number;
6
+ }
7
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
8
+ [key: string]: JsonValue;
9
+ };
10
+ /**
11
+ * A length of time. Units are in the name so a number never means two things.
12
+ *
13
+ * @example { seconds: 5 } { ticks: 20 } { minutes: 1, seconds: 30 }
14
+ */
15
+ export interface Duration {
16
+ readonly ticks?: number;
17
+ readonly milliseconds?: number;
18
+ readonly seconds?: number;
19
+ readonly minutes?: number;
20
+ }
21
+ /** A Duration in milliseconds (one tick is 50 ms). */
22
+ export declare function toMilliseconds(d: Duration): number;
23
+ /**
24
+ * The outcome of an action that can fail for normal reasons (no path, out of reach). Check `ok`:
25
+ * failures are values, not exceptions.
26
+ *
27
+ * @example
28
+ * const moved = await bot.goto(target, { within: 2 });
29
+ * if (!moved.ok) log.warn(`Can't get there: ${moved.reason}`);
30
+ */
31
+ export type Result<F extends string, T = undefined> = ({
32
+ readonly ok: true;
33
+ } & (T extends undefined ? {} : {
34
+ readonly value: T;
35
+ })) | {
36
+ readonly ok: false;
37
+ readonly reason: F;
38
+ readonly message: string;
39
+ };
40
+ /**
41
+ * A position the SDK hands you. It prints as `x y z` in template strings and has a few helpers.
42
+ *
43
+ * @example
44
+ * log.info(`Going to ${chest}`); // "Going to 10 64 -3"
45
+ * const above = chest.offset(0, 1, 0);
46
+ */
47
+ export declare class Position implements Vec3 {
48
+ readonly x: number;
49
+ readonly y: number;
50
+ readonly z: number;
51
+ constructor(x: number, y: number, z: number);
52
+ /** A new position moved by the given amounts. */
53
+ offset(dx: number, dy: number, dz: number): Position;
54
+ /** Straight-line distance in blocks. */
55
+ distanceTo(other: Vec3): number;
56
+ /** The block this position is in (rounded down). */
57
+ floored(): Position;
58
+ equals(other: Vec3): boolean;
59
+ toString(): string;
60
+ toJSON(): Vec3;
61
+ }
62
+ /** Makes a position: `vec3(10, 64, -3)`. */
63
+ export declare function vec3(x: number, y: number, z: number): Position;
64
+ /** @internal Turns a position from a frame into a Position. */
65
+ export declare function toPosition(v: unknown): Position;