Block registry api

This commit is contained in:
2026-11-12 20:41:13 -03:00
parent e7fe663746
commit 76802ed430
39 changed files with 499 additions and 100 deletions
+160
View File
@@ -0,0 +1,160 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// blocks a content script registers in code are the mod's data like its files': checked, registered on the server,
// sent to players and generated by worldgen workers. see common/mod_api/content.ts
import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { ID_MASK } from "@/common/constants.ts";
import { client_copy, read_mod } from "@/common/mod.ts";
import { to_flat } from "@/common/section.ts";
import { load_bundle } from "@/common/worldgen_bundle.ts";
import type { ContentContext } from "@/common/mod_api/content.ts";
import { load_client_mods } from "@/client/mods.ts";
import { load_mods } from "@/server/load_mods.ts";
import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts";
import { copy_dir, test_game } from "./helpers.ts";
// a block for every rock and its bricks, and one more where the script can't read files, like the server's worker
const CONTENT = `
import type { ContentContext } from "cubi/content";
export function setup(ctx: ContentContext) {
for (const rock of ["granite", "basalt"]) {
ctx.blocks.register({ id: \`rocks:\${rock}\`, textures: "cubi:missing", drops: \`rocks:\${rock}\` });
ctx.blocks.register({ id: \`rocks:\${rock}_bricks\`, textures: "cubi:missing" });
}
try {
Deno.readTextFileSync("deno.json");
} catch {
ctx.blocks.register({ id: "rocks:sandboxed", textures: "cubi:missing" });
}
(globalThis as any).rocks_ctx = ctx;
EXTRA
}
`;
const CODE_BLOCKS = ["rocks:granite", "rocks:granite_bricks", "rocks:basalt", "rocks:basalt_bricks"];
// the base game, and rocks: a block file, the content script above, and a tag and an ore that name its blocks
function rocks_mod(extra = "") {
const dir = Deno.makeTempDirSync({ prefix: "bworld_content_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const write = (path: string, content: unknown) => {
Deno.mkdirSync(`${dir}/rocks/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
Deno.writeTextFileSync(`${dir}/rocks/${path}`, typeof content === "string" ? content : JSON.stringify(content));
};
write("manifest.json", {
format_version: 1,
id: "rocks",
name: "Rocks",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { content: "scripts/content.ts" },
});
write("blocks/lamp.json", { format_version: 1, block: { id: "rocks:lamp", textures: "cubi:missing" } });
write("scripts/content.ts", CONTENT.replace("EXTRA", extra));
write("tags/blocks/rocks/rocks.json", { format_version: 1, tag: { values: ["rocks:granite", "rocks:basalt"] } });
write("worldgen/ores.json", {
format_version: 1,
ores: [{ id: "rocks:basalt", replaces: "bworld:stone", min_y: 5, max_y: 200, scale: 0.07, threshold: 0.3 }],
});
return dir;
}
Deno.test("check-mods runs a mod's content script, and its files can name the blocks it registers", async () => {
const dir = rocks_mod();
const rocks = (await load_and_check(dir)).find((mod) => mod.id === "rocks")!;
Deno.removeSync(dir, { recursive: true });
assertEquals(rocks.report.errors, []);
// after the files' blocks, in the order they were registered, listed under the script
assertEquals(rocks.blocks.map(({ json }) => json.id), ["rocks:lamp", ...CODE_BLOCKS]);
assertEquals(rocks.blocks.slice(1).map(({ file }) => file), CODE_BLOCKS.map(() => "scripts/content.ts"));
// only during setup
const ctx = (globalThis as unknown as { rocks_ctx: ContentContext }).rocks_ctx;
assertThrows(
() => ctx.blocks.register({ id: "rocks:late", textures: "cubi:missing" }),
Error,
"only be registered during setup",
);
});
Deno.test("the server registers a content script's blocks, and a worldgen worker numbers and generates them alike", async () => {
const dir = rocks_mod();
const { game } = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
for (const id of CODE_BLOCKS) {
assert(EverythingRegistry.get("blocks", id), `${id} is a block`);
assert(EverythingRegistry.get("items", id), `${id} has an item`);
}
const bundle = structuredClone(game.worldgen_bundle!);
const game_ids = { ...game.world.block_ids };
EverythingRegistry.clear();
const loaded = await load_bundle(bundle);
assertEquals(loaded.block_ids, game_ids, "blocks are numbered like the game numbers them");
const basalt = loaded.block_ids["rocks:basalt"];
const generated = to_flat(loaded.generate(0, 0).column.sections);
assert(generated.some((value) => (value & ID_MASK) === basalt), "the ore of a block made in code is generated");
});
Deno.test("a packed mod leaves its content script's blocks out, the server registers them without permissions, and players get them as data", async () => {
const sources = rocks_mod();
const folder = Deno.makeTempDirSync({ prefix: "bworld_content_mods_" });
for (const mod of await load_and_check(sources)) {
Deno.writeFileSync(`${folder}/${mod.id}.cubi`, await pack_mod(mod));
}
Deno.removeSync(sources, { recursive: true });
const packed = read_mod(Deno.readFileSync(`${folder}/rocks.cubi`), "rocks.cubi");
assertEquals(packed.data.blocks.map((block) => block.id), ["rocks:lamp"]);
assert(packed.scripts.content);
const rocks = (await load_mods(folder, ["cubi:missing"])).find((mod) => mod.listing.id === "rocks")!;
Deno.removeSync(folder, { recursive: true });
// its worker can't read files, unlike check-mods
const ids = ["rocks:lamp", ...CODE_BLOCKS, "rocks:sandboxed"];
assertEquals(rocks.mod.data.blocks.map((block) => block.id), ids);
const copy = read_mod(rocks.client_bytes, rocks.listing.file);
assertEquals(copy.scripts.content, undefined, "players don't run it, they get what it registered");
assertEquals(copy.data.blocks, client_copy(rocks.mod).data.blocks);
EverythingRegistry.clear();
await load_client_mods([rocks.listing], [copy]);
for (const id of ids) assert(EverythingRegistry.get("blocks", id), `${id} is a block on the client`);
});
Deno.test("a content script's mistakes stop its mod loading, naming the script", async () => {
const cases: [string, string][] = [
[
`ctx.blocks.register({ id: "bworld:granite", textures: "cubi:missing" });`,
`scripts/content.ts: block bworld:granite isn't in this mod's namespace "rocks"`,
],
[`ctx.blocks.register({ id: "rocks:broken" } as any);`, "scripts/content.ts: block rocks:broken: "],
[
`ctx.blocks.register({ id: "rocks:lamp", textures: "cubi:missing" });`,
"scripts/content.ts: block rocks:lamp is also defined by rocks",
],
[`throw new Error("no rocks today");`, "scripts/content.ts: no rocks today"],
];
for (const [extra, error] of cases) {
const dir = rocks_mod(extra);
const rocks = (await load_and_check(dir)).find((mod) => mod.id === "rocks")!;
Deno.removeSync(dir, { recursive: true });
assert(rocks.report.errors.some((e) => e.includes(error)), `${error} in ${rocks.report.errors.join("\n")}`);
}
// on the server too, from the .cubi
const sources = rocks_mod(`ctx.blocks.register({ id: "bworld:granite", textures: "cubi:missing" });`);
const folder = Deno.makeTempDirSync({ prefix: "bworld_content_mods_" });
for (const mod of await load_and_check(sources)) {
Deno.writeFileSync(`${folder}/${mod.id}.cubi`, await pack_mod(mod));
}
Deno.removeSync(sources, { recursive: true });
const rejected = await assertRejects(() => load_mods(folder, ["cubi:missing"]));
Deno.removeSync(folder, { recursive: true });
assertStringIncludes(
(rejected as Error).message,
`rocks.cubi: scripts/content.js: block bworld:granite isn't in this mod's namespace "rocks"`,
);
});
+5 -5
View File
@@ -205,19 +205,19 @@ Deno.test("in a dimension without sky light only blocks give light", async () =>
});
Deno.test("a dimension's min_y and max_y have to be whole sections, and fit its generator's cells", async () => {
const errors = (options: Parameters<typeof mods>[0]) => {
const errors = async (options: Parameters<typeof mods>[0]) => {
const dir = mods(options);
const report = load_and_check(dir).find((mod) => mod.id === "flat")!.report;
const report = (await load_and_check(dir)).find((mod) => mod.id === "flat")!.report;
Deno.removeSync(dir, { recursive: true });
return report.errors.filter((error) => error.includes("worldgen/dimension/flat.json"));
};
assertEquals(errors({ flat: true, bworld_default: false, shape: TALL }), []);
assertEquals(await errors({ flat: true, bworld_default: false, shape: TALL }), []);
for (const shape of [{ min_y: -8 }, { max_y: 0 }, { min_y: -4096 }, { max_y: 4096 }]) {
assertEquals(errors({ flat: true, bworld_default: false, shape }).length, 1, JSON.stringify(shape));
assertEquals((await errors({ flat: true, bworld_default: false, shape })).length, 1, JSON.stringify(shape));
}
// sections of 16, but the generator samples every 32 blocks
const shape = { min_y: -48, max_y: 320 };
assert(errors({ flat: true, bworld_default: false, shape, cell_height: 32 })[0].includes("cell_height 32"));
assert((await errors({ flat: true, bworld_default: false, shape, cell_height: 32 }))[0].includes("cell_height 32"));
const dir = mods({ flat: true, bworld_default: false, shape, cell_height: 32 });
await assertRejects(() => test_game(dir), Error, "flat.json: can't be generated by flat:flat");
+2 -2
View File
@@ -173,7 +173,7 @@ Deno.test("a client mod hooks LocalPlayer from its .cubi", async () => {
}`,
],
});
const mod = load_and_check(dir)[0];
const mod = (await load_and_check(dir))[0];
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "floaty.cubi");
const listing: ModListing = {
@@ -344,7 +344,7 @@ Deno.test("cubi/engine without engine_access is an error in check-mods and in a
console.log(engine.common.physics);
}`;
write_mod(dir, "sneaky", { server: ["server.ts", script] }, {});
const [mod] = load_and_check(dir);
const [mod] = await load_and_check(dir);
assertEquals(mod.report.errors, [
`scripts/server.ts imports cubi/engine, which needs "engine_access": true in manifest.json`,
]);
+4 -4
View File
@@ -42,7 +42,7 @@ Deno.test("a mod's fluids/ file registers a fluid, packed into its .cubi", async
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
const syrup = { id: "testfluids:syrup", name: "Maple Syrup", color: "#a0522d", texture: "testfluids:syrup_still" };
fluid_mod(dir, { "syrup.json": syrup });
const mods = load_and_check(dir);
const mods = await load_and_check(dir);
assertEquals(mods[0].report.errors, []);
// it has no textures
assertEquals(mods[0].report.warnings, [
@@ -55,10 +55,10 @@ Deno.test("a mod's fluids/ file registers a fluid, packed into its .cubi", async
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a fluid with a bad color fails loading", () => {
Deno.test("a fluid with a bad color fails loading", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
fluid_mod(dir, { "syrup.json": { id: "testfluids:syrup", color: "brown" } });
const errors = load_and_check(dir)[0].report.errors;
const errors = (await load_and_check(dir))[0].report.errors;
assert(errors.some((e) => e.startsWith("fluids/syrup.json:") && e.includes("color")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
});
@@ -86,7 +86,7 @@ async function both_sides(ask: (fluids: FluidApi) => unknown) {
const { game } = await test_game(dir);
const server = ask(game.mods.fluid_rules.api());
const mod = load_and_check(dir).find((m) => m.id === "testfluids")!;
const mod = (await load_and_check(dir)).find((m) => m.id === "testfluids")!;
const packed = read_mod(await pack_mod(mod), "testfluids.cubi");
Deno.removeSync(dir, { recursive: true });
const listing: ModListing = { id: "testfluids", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
+6 -6
View File
@@ -36,14 +36,14 @@ let repo_mods: ServerModSource[] | undefined;
// mods straight from their source folders, skipping the build: scripts are imported as typescript. each call gets its
// own copy, so a test that changes what it got can't change another test's
export function mod_sources(mods_dir: string): ServerModSource[] {
if (resolve(mods_dir) !== resolve("mods")) return read_mod_sources(mods_dir);
repo_mods ??= read_mod_sources(mods_dir);
export async function mod_sources(mods_dir: string): Promise<ServerModSource[]> {
if (resolve(mods_dir) !== resolve("mods")) return await read_mod_sources(mods_dir);
repo_mods ??= await read_mod_sources(mods_dir);
return structuredClone(repo_mods);
}
function read_mod_sources(mods_dir: string): ServerModSource[] {
const mods = load_and_check(mods_dir);
async function read_mod_sources(mods_dir: string): Promise<ServerModSource[]> {
const mods = await load_and_check(mods_dir);
const errors = mods.flatMap((mod) => mod.report.errors.map((e) => `${mod.id}: ${e}`));
if (errors.length) throw new Error(errors.join("\n"));
return load_order(mods).map((mod) => {
@@ -94,7 +94,7 @@ export async function test_game(
config: Record<string, Record<string, unknown>> = {},
) {
EverythingRegistry.clear();
const mods = mod_sources(mods_dir);
const mods = await mod_sources(mods_dir);
for (const mod of mods) {
if (!config[mod.listing.id]) continue;
const changed = apply_config(mod.data.config ?? {}, config[mod.listing.id]);
+6 -6
View File
@@ -487,9 +487,9 @@ function gears_mod(): string {
return mod;
}
Deno.test("tags keep their entries, renamed, and ones that don't exist here become optional", () => {
Deno.test("tags keep their entries, renamed, and ones that don't exist here become optional", async () => {
const mod = gears_mod();
const report = import_tags(
const report = await import_tags(
data({
"gears/tags/items/spinning": {
values: ["gears:gear", "minecraft:stone", "#forge:ingots/brass", { id: "other:cog", required: false }],
@@ -517,9 +517,9 @@ Deno.test("tags keep their entries, renamed, and ones that don't exist here beco
assertStringIncludes(report.warnings[0].warning, "bworld:stone");
});
Deno.test("create's pressing recipes keep their shape, with bworld's item choices, from 0.5's and 6.0's json", () => {
Deno.test("create's pressing recipes keep their shape, with bworld's item choices, from 0.5's and 6.0's json", async () => {
const mod = gears_mod();
const report = import_recipes(
const report = await import_recipes(
data({
// 0.5 named results' items "item", and an ingredient that's a list is one any of whose items fit
"gears/recipes/pressing/teeth": {
@@ -558,7 +558,7 @@ Deno.test("create's pressing recipes keep their shape, with bworld's item choice
assertEquals(report.skipped.map(({ location }) => location), ["gears:pressing/granite"]);
});
Deno.test("stonecutting recipes become bworld's, and ones it can't use are reported", () => {
Deno.test("stonecutting recipes become bworld's, and ones it can't use are reported", async () => {
const mod = gears_mod();
const cut = (ingredient: unknown, result: unknown, extra = {}) => ({
type: "minecraft:stonecutting",
@@ -566,7 +566,7 @@ Deno.test("stonecutting recipes become bworld's, and ones it can't use are repor
result,
...extra,
});
const report = import_recipes(
const report = await import_recipes(
data({
// before 1.20.5 the count is the recipe's, after it the result's. 1.21 renamed the folder
"gears/recipes/gear_from_teeth": cut({ tag: "gears:teeth" }, "gears:gear", { count: 2 }),
+2 -2
View File
@@ -49,10 +49,10 @@ Deno.test("an item with a model is drawn with it, in the model's own textures, p
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods reports an item's model that doesn't exist", () => {
Deno.test("check-mods reports an item's model that doesn't exist", async () => {
const dir = mods_with({ textures: { "0": "bworld:oak_planks" }, elements: [HANDLE] });
Deno.removeSync(`${dir}/copper_tools/models/wrench.json`);
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
const errors = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
assert(errors.includes("model copper_tools:wrench doesn't exist"), errors);
Deno.removeSync(dir, { recursive: true });
});
+3 -3
View File
@@ -259,11 +259,11 @@ async function setup() {
return { ...t, dir };
}
Deno.test("check-mods catches loot tables that point at nothing", () => {
Deno.test("check-mods catches loot tables that point at nothing", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_loot_check_" });
copy_dir("mods/bworld", `${dir}/bworld`);
loot_mod(dir);
const ok = load_and_check(dir).find((mod) => mod.id === "testloot")!;
const ok = (await load_and_check(dir)).find((mod) => mod.id === "testloot")!;
assertEquals(ok.report.errors, []);
assertEquals(ok.loot_tables.map((t) => t.json.id).sort(), [
"testloot:blocks/ore",
@@ -280,7 +280,7 @@ Deno.test("check-mods catches loot tables that point at nothing", () => {
},
}),
);
const errors = load_and_check(dir).find((mod) => mod.id === "testloot")!.report.errors;
const errors = (await load_and_check(dir)).find((mod) => mod.id === "testloot")!.report.errors;
assert(errors.some((e) => e.includes("item testloot:nothing doesn't exist")), errors.join("\n"));
assert(errors.some((e) => e.includes("loot table testloot:nowhere doesn't exist")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
+1 -1
View File
@@ -65,7 +65,7 @@ export function setup(ctx: ServerContext) {
await assertRejects(() => config_of({ copper_tools: { sped: 1 } }), Error, "sped");
Deno.writeTextFileSync(`${dir}/copper_tools/config.json`, config_file([16]));
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors;
const errors = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report.errors;
assert(errors.some((error) => error.startsWith("config.json")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
+2 -2
View File
@@ -26,7 +26,7 @@ async function packed_mods() {
const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_src_" });
copy_dir("mods/bworld", `${sources}/bworld`);
create_mod("copper_tools", "Copper Tools", sources);
const mods = load_and_check(sources);
const mods = await load_and_check(sources);
for (const mod of mods) assertEquals(mod.report.errors, [], mod.id);
const folder = Deno.makeTempDirSync({ prefix: "bworld_mod_" });
@@ -206,7 +206,7 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => {
`import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function setup(ctx: any) {\n\tctx.log(GREETING);\n}\n`,
);
const project = load_and_check(sources).find((m) => m.id === "project")!;
const project = (await load_and_check(sources)).find((m) => m.id === "project")!;
assertEquals(project.report.errors, []);
const packed = read_mod(await pack_mod(project), "project.cubi");
assertStringIncludes(packed.scripts.server!, "hello from a deno project");
+2 -2
View File
@@ -88,13 +88,13 @@ Deno.test("a mod's model can use the base game's templates as its parent", async
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods reports a parent that doesn't exist and parents that loop", () => {
Deno.test("check-mods reports a parent that doesn't exist and parents that loop", async () => {
const dir = mods_with({
orphan: { id: "copper_tools:orphan", parent: "copper_tools:nowhere" },
one: { id: "copper_tools:one", parent: "copper_tools:two" },
two: { id: "copper_tools:two", parent: "copper_tools:one" },
});
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
const errors = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
assert(errors.includes("model copper_tools:nowhere doesn't exist"), errors);
assert(errors.includes("copper_tools:one's parents loop"), errors);
Deno.removeSync(dir, { recursive: true });
+2 -2
View File
@@ -87,7 +87,7 @@ const seen = globalThis as unknown as Record<string, unknown>;
// packs testrecipes from dir, which it then removes, and loads it on a client like one joining would
async function load_client(dir: string) {
const mod = load_and_check(dir).find((m) => m.id === "testrecipes")!;
const mod = (await load_and_check(dir)).find((m) => m.id === "testrecipes")!;
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "testrecipes.cubi");
Deno.removeSync(dir, { recursive: true });
@@ -222,7 +222,7 @@ Deno.test("recipes can only be registered while shared scripts set up", async ()
});
Deno.test("every mod's recipe types are registered on a client too, so it loads them", async () => {
const mods = load_order(load_and_check("mods"));
const mods = load_order(await load_and_check("mods"));
const packed = await Promise.all(mods.map(async (mod) => read_mod(await pack_mod(mod), `${mod.id}.cubi`)));
const listings = mods.map((mod): ModListing => ({
id: mod.id,
+3 -3
View File
@@ -80,8 +80,8 @@ Deno.test("a texture's .json is checked, packed into the .cubi and read back", a
const json = { animation: { frametime: 3, interpolate: true } };
Deno.writeTextFileSync(`${textures}/lamps/goo.json`, JSON.stringify(json));
const lamps = () => load_and_check(sources).find((m) => m.id === "lava_lamps")!;
const mod = lamps();
const lamps = async () => (await load_and_check(sources)).find((m) => m.id === "lava_lamps")!;
const mod = await lamps();
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "lava_lamps.cubi");
assertEquals([...packed.texture_json!], [["lava_lamps:lamps_goo", json]]);
@@ -92,7 +92,7 @@ Deno.test("a texture's .json is checked, packed into the .cubi and read back", a
`${textures}/lamps/goo.json`,
JSON.stringify({ animation: { width: 5 } }),
);
const broken = lamps();
const broken = await lamps();
assertEquals(broken.report.errors, [
"textures/lamps/goo.json: the png is 16×64, which doesn't split into 5×16 frames",
"textures/stray.json: there's no stray.png for it to go with",
+1 -1
View File
@@ -47,7 +47,7 @@ async function load(client_script: string) {
}),
);
write("scripts/client.ts", client_script);
const mods = load_order(load_and_check(dir));
const mods = load_order(await load_and_check(dir));
const packed = await Promise.all(mods.map(async (mod) => read_mod(await pack_mod(mod), `${mod.id}.cubi`)));
Deno.removeSync(dir, { recursive: true });
const listings: ModListing[] = mods.map((mod) => ({
+1 -1
View File
@@ -477,7 +477,7 @@ Deno.test("client scripts register visuals during setup, for blocks that exist",
const load = async (script: string) => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
write_testmod(dir, script);
const mod = load_and_check(dir)[0];
const mod = (await load_and_check(dir))[0];
const packed = read_mod(await pack_mod(mod), "testmod.cubi");
Deno.removeSync(dir, { recursive: true });
const listing: ModListing = { id: "testmod", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };