// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later import { assert, assertEquals } from "@std/assert"; import { copy_dir, menu_data, menu_items, opened_menu, sent_block, test_game } from "./helpers.ts"; import type { WorldSave } from "$/server/game/saves.ts"; // a mod that uses every part of the server api worth testing, and writes down what happened in its storage const SERVER_SCRIPT = ` import type { BlockRef, ServerContext } from "bworld/server"; export function setup(ctx: ServerContext) { const log = (key: string, value: unknown = 1) => { const all = ctx.storage.get>("log") ?? {}; (all[key] ??= []).push(value); ctx.storage.set("log", all); }; ctx.components.register_block("testmod:ticker", { on_create(block) { block.data = { name: "ticker" }; }, on_tick(block, _params, dt) { log("tick_" + block.x, dt); }, on_second(block, _params, dt) { log("second_" + block.x, dt); }, }); ctx.components.register_block("testmod:lazy", { on_tick() { log("lazy_tick"); }, }); ctx.components.register_block("testmod:broken", { on_create(block) { block.data = {}; }, on_tick() { throw new Error("broken on purpose"); }, on_click(block, _params, player) { log("click", [block.id, player.name]); }, }); // a box that only takes coal, counts how often it's opened, and gives up its items when broken const coal_box = ctx.menus.register("testmod:coal_box", (menu, block) => { const container = ctx.containers.get(block.data.container)!; menu.title = "Coal Box"; menu.add_slot(container, 0, { x: 7, y: 17, filter: (item) => item.id === "bworld:coal" }); menu.add_slot(container, 1, { x: 25, y: 17 }); menu.add_player_inventory(7, 49); menu.add_data("opened", () => block.data.opened); menu.on_button((player, id) => log("button", [player.name, id])); menu.still_valid_near(block); }); ctx.components.register_block("testmod:coal_box", { on_interact(block, _params, player) { block.data ??= { container: ctx.containers.create(2).id, opened: 0 }; block.data.opened += 1; const menu = coal_box.open(player, block); menu.on_close(() => log("closed", menu.open)); return true; }, on_break(block) { const container = ctx.containers.get(block.data.container)!; for (let slot = 0; slot < container.size; slot++) { const item = container.get(slot); if (item) ctx.world.drop_item(block.x, block.y, block.z, item); } ctx.containers.delete(container.id); }, }); ctx.components.register_item("testmod:wand", { on_use(item, params: { power: number }, player) { log("use", [item.id, params.power, player.name]); }, }); ctx.net.on("testmod:ping", () => log("ping")); ctx.system.run_timeout(() => log("timeout", ctx.system.current_tick), 5); const interval = ctx.system.run_interval(() => { log("interval", ctx.system.current_tick); if (ctx.system.current_tick >= 30) ctx.system.clear_run(interval); }, 10); ctx.events.after.tick.subscribe(() => log("tick_event")); ctx.events.after.player_join.subscribe(({ player }) => { player.inventory.on_change((slot) => log("inventory", slot)); }); ctx.commands.register("state", { description: "", usage: "", run([x, y, z, name, value], player) { const [bx, by, bz] = [Number(x), Number(y), Number(z)]; try { if (value !== undefined) ctx.world.set_state(bx, by, bz, name, Number(value)); player.send_message("state " + ctx.world.get_state(bx, by, bz, name)); } catch (e) { player.send_message("error " + (e as Error).message); } }, }); // brigadier's way, like neoforge's const { literal, argument, types } = ctx.commands; ctx.commands.register( literal("shout") .describe("Says something to someone") .requires((source) => source.player.name !== "bob") .then( argument("who", types.player()).then( argument("mode", types.choice(["loud", "quiet"])).then( argument("text", types.greedy_string()).executes((context) => { const who = context.get<{ name: string }>("who").name; context.source.send_message(\`\${who} \${context.get("mode")}: \${context.get("text")}\`); }), ), ), ), ); ctx.commands.register(literal("boom").executes(() => { throw new Error("kaboom"); })); } `; const block = (id: string, extra: Record = {}) => JSON.stringify({ format_version: 1, block: { id, textures: "bworld:stone", mining: { toughness: 1 }, ...extra } }); function test_mods() { const dir = Deno.makeTempDirSync({ prefix: "bworld_scripts_" }); copy_dir("mods/bworld", `${dir}/bworld`); const mod = `${dir}/testmod`; Deno.mkdirSync(`${mod}/blocks`, { recursive: true }); Deno.mkdirSync(`${mod}/items`); Deno.mkdirSync(`${mod}/scripts`); Deno.writeTextFileSync( `${mod}/manifest.json`, JSON.stringify({ format_version: 1, id: "testmod", name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], scripts: { server: "scripts/server.ts" }, }), ); Deno.writeTextFileSync( `${mod}/blocks/ticker.json`, block("testmod:ticker", { components: { "testmod:ticker": {} } }), ); Deno.writeTextFileSync(`${mod}/blocks/lazy.json`, block("testmod:lazy", { components: { "testmod:lazy": {} } })); Deno.writeTextFileSync( `${mod}/blocks/broken.json`, block("testmod:broken", { components: { "testmod:broken": {} } }), ); Deno.writeTextFileSync( `${mod}/blocks/coal_box.json`, block("testmod:coal_box", { interactive: true, components: { "testmod:coal_box": {} } }), ); Deno.writeTextFileSync( `${mod}/blocks/lamp.json`, block("testmod:lamp", { states: [{ name: "power", bits: 3, default: 2 }, { name: "lit", bits: 1, default: 0 }], }), ); Deno.writeTextFileSync( `${mod}/items/wand.json`, JSON.stringify({ format_version: 1, item: { id: "testmod:wand", texture: "bworld:stone", places: "bworld:stone", components: { "testmod:wand": { power: 7 } }, }, }), ); Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT); return dir; } async function setup(save?: WorldSave) { const dir = test_mods(); const game = await test_game(dir, save); game.join(1, "alice"); game.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); game.take(1); const log = () => (game.game.mods.storage.testmod?.log ?? {}) as Record; return { ...game, dir, log }; } Deno.test("components tick 20 times a second and on_second once, only with block data and near players", async () => { const { game, log, dir } = await setup(); const error = console.error; console.error = () => {}; try { game.set_block(2, 100, 2, "testmod:ticker"); game.set_block(3, 100, 2, "testmod:lazy"); game.set_block(4, 100, 2, "testmod:broken"); // 20 chunks away from the only player game.set_block(16 * 20, 100, 0, "testmod:ticker"); for (let i = 0; i < 40; i++) game.tick(); } finally { console.error = error; } assertEquals(log()["tick_2"]?.length, 40); assert(log()["tick_2"].every((dt) => dt === 1 / 20)); assertEquals(log()["second_2"], [1, 1]); assertEquals(log()["lazy_tick"], undefined, "blocks without data don't tick"); assertEquals(log()[`tick_${16 * 20}`], undefined, "blocks far from every player don't tick"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("timers and the tick event run on the game loop's ticks", async () => { const { game, log, dir } = await setup(); for (let i = 0; i < 50; i++) game.tick(); assertEquals(log()["timeout"], [5]); assertEquals(log()["interval"], [10, 20, 30]); assertEquals(log()["tick_event"]?.length, 50); Deno.removeSync(dir, { recursive: true }); }); Deno.test("hitting a block runs on_click, using an item runs on_use instead of placing it", async () => { const { game, send, take, log, dir } = await setup(); game.set_block(1, 99, 1, "testmod:broken"); send(1, { type: "hit_block", x: 1, y: 99, z: 1 }); assertEquals(log()["click"], [["testmod:broken", "alice"]]); send(1, { type: "chat", text: "/give testmod:wand" }); const inventory = take(1).filter((m) => m.container === "inventory").at(-1).items; send(1, { type: "select_slot", slot: inventory.findIndex((i: { id: string } | null) => i?.id === "testmod:wand") }); send(1, { type: "use_item" }); assertEquals(log()["use"], [["testmod:wand", 7, "alice"]]); // on a block: used, not placed (even though it can place stone) send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "top" }); assertEquals(log()["use"]?.length, 2); assertEquals(game.world.get_block_id(1, 100, 1), "bworld:air"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("block states start at their defaults, can be changed, and are synced and saved", async () => { const { game, send, take, dir } = await setup(); const state = (args: string) => { send(1, { type: "chat", text: `/state ${args}` }); return take(1).filter((m) => m.type === "chat").map((m) => m.text).at(-1); }; // alice gets the chunks around her, and from then on changes to them game.tick(); game.set_block(5, 100, 5, "testmod:lamp"); take(1); assertEquals(state("5 100 5 power"), "state 2"); assertEquals(state("5 100 5 lit"), "state 0"); send(1, { type: "chat", text: "/state 5 100 5 power 5" }); const change = take(1).find((m) => m.type === "set_block"); assertEquals(change.id, "testmod:lamp"); assertEquals(change.state, 5, "other clients get the new state"); assertEquals(state("5 100 5 lit 1"), "state 1"); assertEquals(state("5 100 5 power"), "state 5"); assert(state("5 100 5 power 8").startsWith('error testmod:lamp state "power" has 3 bits')); assert(state("5 100 5 color").startsWith('error testmod:lamp has no state "color"')); // saved and loaded, and new players get it in the chunk const saved = game.save(); Deno.removeSync(dir, { recursive: true }); const again = await setup(saved); assertEquals(again.game.world.get_block_value(5, 100, 5) >>> 16, 5 | (1 << 3)); const joined = again.join(2, "bob"); again.send(2, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); again.game.tick(); assertEquals(sent_block(again.take(2), joined, 5, 100, 5), ["testmod:lamp", 5 | (1 << 3)]); Deno.removeSync(again.dir, { recursive: true }); }); Deno.test("inventory on_change fires for the slots that changed", async () => { const { game, send, log, dir } = await setup(); send(1, { type: "chat", text: "/give bworld:stone 3" }); send(1, { type: "chat", text: "/give bworld:dirt" }); game.tick(); assertEquals(log()["inventory"], [0, 1]); game.tick(); assertEquals(log()["inventory"], [0, 1], "nothing changed since"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("/tps reports the loop, and mods can't take engine commands", async () => { const { send, take, dir } = await setup(); send(1, { type: "chat", text: "/tps" }); assertEquals(take(1).at(-1).text, "The game loop isn't running"); Deno.removeSync(dir, { recursive: true }); const clash = test_mods(); Deno.writeTextFileSync( `${clash}/testmod/scripts/server.ts`, SERVER_SCRIPT.replace('ctx.commands.register("state"', 'ctx.commands.register("tps"'), ); let error = ""; try { await test_game(clash); } catch (e) { error = (e as Error).message; } assert(error.includes("/tps belongs to the engine"), error); Deno.removeSync(clash, { recursive: true }); }); Deno.test("mods build commands brigadier's way, like neoforge's: typed arguments, suggestions, requirements and aliases", async () => { const { join, send, take, dir } = await setup(); join(2, "bob"); take(1); const suggest = (id: number, text: string) => { send(id, { type: "suggest", id: 7, text }); return take(id).find((m) => m.type === "suggestions"); }; send(1, { type: "chat", text: "/shout bob loud hi there" }); assertEquals(take(1).at(-1).text, "bob loud: hi there"); send(1, { type: "chat", text: "/testmod:shout alice quiet hey" }); assertEquals(take(1).at(-1).text, "alice quiet: hey"); send(1, { type: "chat", text: "/shout nobody loud hi" }); assertEquals(take(1).at(-1).text, "nobody isn't online"); send(1, { type: "chat", text: "/shout bob" }); assertEquals(take(1).at(-1).text, "Not enough: /shout "); assertEquals(suggest(1, "/shout b"), { type: "suggestions", id: 7, start: 7, suggestions: [{ text: "bob" }] }); assertEquals(suggest(1, "/shout bob ").suggestions.map((s: { text: string }) => s.text), ["loud", "quiet"]); assertEquals(suggest(1, "/sh").suggestions.map((s: { text: string }) => s.text), ["shout"]); // bob can't, so it isn't suggested to him either assertEquals(suggest(2, "/sh").suggestions, []); send(2, { type: "chat", text: "/shout alice loud hi" }); assertEquals(take(2).at(-1).text, "Unknown command /shout"); // a mod's bug isn't the player's fault const error = console.error; const logged: unknown[][] = []; console.error = (...args: unknown[]) => logged.push(args); send(1, { type: "chat", text: "/boom" }); console.error = error; assertEquals(take(1).at(-1).text, "Something went wrong running /boom"); assert(String(logged[0]?.[0]).includes("[testmod]"), String(logged[0])); // /help lists it with its usage send(1, { type: "chat", text: "/help shout" }); assertEquals(take(1).at(-1).text, "/shout - Says something to someone"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("menus: filters, data, buttons, closing, saving, and dropping what's inside", async () => { const { game, send, take, log, dir } = await setup(); game.set_block(1, 100, 0, "testmod:coal_box"); send(1, { type: "chat", text: "/give bworld:coal 3" }); send(1, { type: "chat", text: "/give bworld:stone 1" }); take(1); send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); let messages = take(1); const opened = opened_menu(messages); assertEquals(opened.menu_type, "testmod:coal_box"); assertEquals(opened.title, "Coal Box"); assertEquals(opened.slots.slice(0, 2), [{ x: 7, y: 17 }, { x: 25, y: 17 }]); // the hotbar's first slot, under the rest of the inventory assertEquals(opened.slots[2], { x: 7, y: 49 + 58 }); assertEquals(opened.data, { opened: 1 }); // stone doesn't go into the coal slot, but does into the other one. coal goes in. the inventory's slots come after // the box's 2 const click = (slot: number, menu = opened.id) => send(1, { type: "click", menu, slot, button: 0 }); click(2 + 1); click(0); click(1); click(2 + 0); click(0); messages = take(1); assertEquals(menu_items(messages).slice(0, 2), [{ id: "bworld:coal", count: 3 }, { id: "bworld:stone", count: 1 }]); // clicks and buttons for a menu that isn't open are ignored click(0, opened.id + 1); assertEquals(take(1).filter((m) => m.type === "cursor"), []); send(1, { type: "menu_button", menu: opened.id + 1, button: 7 }); send(1, { type: "menu_button", menu: opened.id, button: 3 }); assertEquals(log().button, [["alice", 3]]); send(1, { type: "close_menu", menu: opened.id }); assertEquals(log().closed, [false]); // walking away closes it send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); game.teleport(game.players()[0], 20.5, 100, 0.5); game.tick(); assert(take(1).some((m) => m.type === "close_menu")); assertEquals(log().closed, [false, false]); // the items and the block's data are saved const loaded = await test_game(dir, game.save()); loaded.join(1, "alice"); loaded.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); loaded.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); messages = loaded.take(1); assertEquals(menu_items(messages).slice(0, 2), [{ id: "bworld:coal", count: 3 }, { id: "bworld:stone", count: 1 }]); assertEquals(opened_menu(messages).data, { opened: 3 }); loaded.game.tick(); assertEquals(menu_data(loaded.take(1)), undefined, "data is only sent again when it changes"); // breaking it closes the menu, runs on_close, and drops what was inside const containers = loaded.game.containers.size; loaded.send(1, { type: "break_block", x: 1, y: 100, z: 0 }); assert(loaded.take(1).some((m) => m.type === "close_menu")); const logged = loaded.game.mods.storage.testmod.log as Record; assertEquals(logged.closed, [false, false, false]); const dropped = loaded.game.item_entities().map((e) => e.item.to_data().id).sort(); assertEquals(dropped, ["bworld:coal", "bworld:stone"]); assertEquals(loaded.game.containers.size, containers - 1, "its container is gone"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("mod messages that are too big or too many are dropped", async () => { const { send, log, dir } = await setup(); send(1, { type: "mod", channel: "testmod:ping", data: "x".repeat(20_000) }); assertEquals(log().ping, undefined); for (let i = 0; i < 100; i++) send(1, { type: "mod", channel: "testmod:ping", data: {} }); // 60 a second, counting the big one, and this could be split over two seconds assert(log().ping.length > 0 && log().ping.length < 100); Deno.removeSync(dir, { recursive: true }); });