Improve commands

This commit is contained in:
2026-09-27 00:38:55 -03:00
parent 535bd36d91
commit 8c7ca92891
13 changed files with 1095 additions and 109 deletions
+162
View File
@@ -0,0 +1,162 @@
import { assert, assertEquals, assertThrows } from "@std/assert";
import {
argument,
boolean,
choice,
CommandDispatcher,
CommandError,
greedy_string,
integer,
literal,
word,
} from "$/common/commands.ts";
import { test_game } from "./helpers.ts";
interface Source {
admin: boolean;
said: string[];
}
function dispatcher() {
const commands = new CommandDispatcher<Source>();
commands.register(
literal<Source>("add").then(
argument<number, Source>("a", integer()).then(
argument<number, Source>("b", integer(0, 10))
.executes((c) => c.source.said.push(`${c.get<number>("a") + c.get<number>("b")}`)),
),
),
);
commands.register(
literal<Source>("say")
.executes((c) => c.source.said.push("..."))
.then(argument<string, Source>("text", greedy_string()).executes((c) => c.source.said.push(c.get("text")))),
);
commands.register(
literal<Source>("mode")
.then(literal<Source>("all").executes((c) => c.source.said.push("literal all")))
.then(argument<string, Source>("name", word()).executes((c) => c.source.said.push(`word ${c.get("name")}`)))
.then(
literal<Source>("flag").then(
argument<boolean, Source>("on", boolean()).executes((c) =>
c.source.said.push(`flag ${c.get("on")}`)
),
),
),
);
commands.register(
literal<Source>("secret").requires((s) => s.admin).executes((c) => c.source.said.push("secret")),
);
commands.register(
literal<Source>("color").then(
argument<string, Source>("color", choice(["red", "green", "blue"]))
.suggests((partial) => [{ text: `${partial}!`, tooltip: "custom" }])
.executes((c) => c.source.said.push(c.get("color"))),
),
);
return commands;
}
const run = (input: string, admin = false) => {
const source = { admin, said: [] as string[] };
dispatcher().execute(input, source);
return source.said;
};
const error = (input: string, admin = false) => assertThrows(() => run(input, admin), CommandError).message;
const suggest = (input: string, admin = false) => {
const { start, suggestions } = dispatcher().suggest(input, { admin, said: [] });
return { start, texts: suggestions.map((s) => s.text) };
};
Deno.test("commands run down the tree with typed arguments, words winning over arguments", () => {
assertEquals(run("add 2 3"), ["5"]);
assertEquals(run("add -2 3"), ["1"]);
assertEquals(run("say"), ["..."]);
assertEquals(run("say hello there, you"), ["hello there, you"]);
assertEquals(run("mode all"), ["literal all"]);
assertEquals(run("mode alls"), ["word alls"]);
assertEquals(run("mode flag true"), ["flag true"]);
assertEquals(run("secret", true), ["secret"]);
});
Deno.test("what went wrong is from the furthest the command got", () => {
assertEquals(error("nope"), "Unknown command /nope");
assertEquals(error(""), "Unknown command /");
assertEquals(error("add 2"), "Not enough: /add <a> <b>");
assertEquals(error("add 2 11"), "11 is too big, the most is 10");
assertEquals(error("add x 1"), `"x" isn't a whole number`);
assertEquals(error("add 1 2 3"), `Didn't expect "3": /add <a> <b>`);
assertEquals(error("mode flag maybe"), `"maybe" isn't true or false`);
assertEquals(error("color pink"), `"pink" isn't one of red, green, blue`);
// not allowed is the same as not there
assertEquals(error("secret"), "Unknown command /secret");
});
Deno.test("usage reads like brigadier's smart usage", () => {
const commands = dispatcher();
const source = { admin: false, said: [] };
assertEquals(commands.usage(commands.get("add")!, source), "add <a> <b>");
assertEquals(commands.usage(commands.get("say")!, source), "say [<text>]");
assertEquals(commands.usage(commands.get("mode")!, source), "mode (all|flag|<name>)");
assertThrows(() => commands.register(literal<Source>("add")), Error, "/add already exists");
});
Deno.test("suggestions are for the word being typed, from words, types and providers", () => {
assertEquals(suggest(""), { start: 0, texts: ["add", "color", "mode", "say"] });
assertEquals(suggest("", true).texts, ["add", "color", "mode", "say", "secret"]);
assertEquals(suggest("m"), { start: 0, texts: ["mode"] });
assertEquals(suggest("mode "), { start: 5, texts: ["all", "flag"] });
assertEquals(suggest("mode f"), { start: 5, texts: ["flag"] });
assertEquals(suggest("mode flag t"), { start: 10, texts: ["true"] });
assertEquals(suggest("color g").texts, ["g!"]);
// nothing fits after a bad argument, or in a greedy one
assertEquals(suggest("add x ").texts, []);
assertEquals(suggest("say a ").texts, []);
});
Deno.test("/give suggests items as they're typed, with their names", async () => {
const { join, take, send } = await test_game("mods");
join(1, "alice");
take(1);
const suggest = (text: string) => {
send(1, { type: "suggest", id: 3, text });
return take(1).find((m) => m.type === "suggestions");
};
const carrots = suggest("/give car");
assertEquals(carrots.id, 3);
assertEquals(carrots.start, 6);
assert(
carrots.suggestions.some((s: { text: string; tooltip: string }) =>
s.text === "bworld:carrot" && s.tooltip === "Carrot"
),
);
assert(carrots.suggestions.every((s: { text: string }) => s.text.split(":")[1].startsWith("car")));
// every item, but not air
const all = suggest("/give ").suggestions.map((s: { text: string }) => s.text);
assert(all.includes("bworld:stone") && all.includes("farmersdelight:cabbage"), String(all));
assert(!all.includes("bworld:air"));
assertEquals(suggest("/give farmersdelight:tom").suggestions.map((s: { text: string }) => s.text), [
"farmersdelight:tomato",
"farmersdelight:tomato_seeds",
]);
assertEquals(suggest("/gi").suggestions, [{ text: "give" }]);
assertEquals(suggest("/time set ").suggestions.map((s: { text: string }) => s.text), [
"day",
"midnight",
"night",
"noon",
"sunset",
]);
// only commands
assertEquals(suggest("hello"), undefined);
send(1, { type: "chat", text: "/give carrot 2" });
assertEquals(take(1).find((m) => m.type === "chat").text, "Gave 2 Carrot");
send(1, { type: "chat", text: "/give air" });
assertEquals(take(1).find((m) => m.type === "chat").text, "There's no item called air");
send(1, { type: "chat", text: "/give" });
assertEquals(take(1).find((m) => m.type === "chat").text, "Not enough: /give <item> [<count>]");
});
+60
View File
@@ -73,6 +73,25 @@ export function setup(ctx: ServerContext) {
}
},
});
// fabric's way
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"); }));
}
`;
@@ -254,6 +273,47 @@ Deno.test("/tps reports the loop, and mods can't take engine commands", async ()
Deno.removeSync(clash, { recursive: true });
});
Deno.test("mods build commands fabric's way: 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 <who> <mode> <text>");
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 <who> <mode> <text> - Says something to someone");
Deno.removeSync(dir, { recursive: true });
});
Deno.test("container screens: filters, properties, 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");
+1 -1
View File
@@ -49,7 +49,7 @@ Deno.test("the server keeps the time, tells players, saves it, and /time changes
assertEquals(game.world.time, CYCLE_TICKS + 100);
send(1, { type: "chat", text: "/time set nope" });
messages = take(1);
assert(messages.at(-1).text.startsWith("Usage: /time"));
assertEquals(messages.at(-1).text, `"nope" isn't one of day, noon, sunset, night, midnight`);
const loaded = await test_game("mods", game.save());
assertEquals(loaded.game.world.time, CYCLE_TICKS + 100);