From a69db0cd2ab0da68f2f06701416cbe06645a4fd9 Mon Sep 17 00:00:00 2001 From: Paula Date: Sat, 14 Nov 2026 13:49:21 -0300 Subject: [PATCH] sharing contexts --- client/mods.ts | 95 ++++++++----------------------- common/block_rules.ts | 2 +- common/content_scripts.ts | 15 +++-- common/fluids.ts | 8 ++- common/mod_loader.ts | 43 +++++++++++--- common/shared_context.ts | 67 ++++++++++++++++++++++ common/worldgen_loader.ts | 22 +++----- server/game/mod_runtime.ts | 105 +++++++++-------------------------- tests/content_script_test.ts | 8 +-- tests/features_test.ts | 2 +- tests/helpers.ts | 29 ++++------ tests/hud_test.ts | 2 +- tests/script_recipes_test.ts | 2 +- 13 files changed, 192 insertions(+), 208 deletions(-) create mode 100644 common/shared_context.ts diff --git a/client/mods.ts b/client/mods.ts index f0aca9a..6aaf80e 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -23,16 +23,17 @@ import { recipe_lookup, RecipeBook, register_mod_data, + registrar, run_phase, - shared_recipes_api, } from "@/common/mod_loader.ts"; +import { blocks_api, shared_context } from "@/common/shared_context.ts"; import { type Mod, read_mod } from "@/common/mod.ts"; import { get_state_value, set_state_value, shared_items_api } from "@/common/utils.ts"; import { BlockRules } from "@/common/block_rules.ts"; -import { fluid_exists, FluidRules, same_fluid } from "@/common/fluids.ts"; +import { FluidRules } from "@/common/fluids.ts"; import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts"; -import { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } from "@/common/block_shapes.ts"; -import type { SharedContext, SharedWorld } from "@/common/mod_api/shared.ts"; +import { covers_face, EMPTY_SHAPE, FULL_SHAPE } from "@/common/block_shapes.ts"; +import type { SharedWorld } from "@/common/mod_api/shared.ts"; import { tag_api } from "@/common/tags.ts"; import { AIR_ID } from "@/common/protocol.ts"; import type { Client } from "./client.ts"; @@ -227,7 +228,15 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) { block_rules = new BlockRules(run_mod, rules_world.get_block); set_fluid_rules(new FluidRules(run_mod)); rules_setup = true; - await run("shared", (i) => shared_context(listings[i])); + await run("shared", (i) => + shared_context({ id: listings[i].id, version: listings[i].version }, { + side: "client", + world: rules_world, + block_rules, + fluid_rules, + recipes: () => recipe_book, + running: () => rules_setup, + })); rules_setup = false; check_recipe_types(recipe_book); @@ -240,56 +249,6 @@ function script_url(code: string) { return code_url(new TextEncoder().encode(code)); } -// ctx.blocks, the same in shared and client phases -function blocks_api(mod: string): SharedContext["blocks"] { - return { - exists: (id) => EverythingRegistry.get("blocks", id) !== undefined, - components(id) { - const block = EverythingRegistry.get("blocks", id); - if (!block) throw new Error(`[${mod}] unknown block ${id}`); - return structuredClone(block.components ?? {}); - }, - solid(id) { - if (id === AIR_ID) return false; - const block = EverythingRegistry.get("blocks", id); - if (!block) throw new Error(`[${mod}] unknown block ${id}`); - return is_solid(block); - }, - }; -} - -function shared_context(listing: ModListing): SharedContext { - const mod = listing.id; - return { - mod: { id: mod, version: listing.version }, - side: "client", - tags: tag_api(), - blocks: blocks_api(mod), - items: shared_items_api(mod, fluid_rules), - fluids: { - exists: fluid_exists, - same: same_fluid, - register(id, rules) { - if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`); - fluid_rules.register(mod, id, rules); - }, - }, - recipes: shared_recipes_api(mod, () => recipe_book, () => rules_setup, (message) => { - throw new Error(`[${mod}] ${message}`); - }), - world: rules_world, - components: { - register_block(id, rules) { - if (!id.startsWith(`${mod}:`)) { - throw new Error(`[${mod}] component ${id} must be in the namespace "${mod}"`); - } - if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`); - block_rules.register(mod, id, rules); - }, - }, - }; -} - function client_context(listing: ModListing): ClientContext { const mod = listing.id; const not_yet = (name: string, where: string) => @@ -305,11 +264,7 @@ function client_context(listing: ModListing): ClientContext { return client; }; - const own = (id: string, what = "channel") => { - if (!id.startsWith(`${mod}:`)) { - throw new Error(`[${mod}] ${what} ${id} must be in the namespace "${mod}"`); - } - }; + const register = registrar(mod, "client", () => client_setup); const known_item = (id: string) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`[${mod}] unknown item ${id}`); @@ -320,8 +275,8 @@ function client_context(listing: ModListing): ClientContext { mod: { id: mod, version: listing.version }, ui: { register_menu_screen(type, create) { - own(type, "menu type"); - if (menu_screens.has(type)) throw new Error(`[${mod}] ${type} already has a screen`); + register.own("menu type", type); + if (menu_screens.has(type)) register.fail(`the screen of ${type} is registered twice`); menu_screens.set(type, { mod, create }); }, open(screen) { @@ -342,12 +297,8 @@ function client_context(listing: ModListing): ClientContext { }, hud: { register(id, layer) { - if (!client_setup) throw new Error(`[${mod}] hud layers can only be registered during setup`); - own(id, "hud layer"); + register.new_id("hud layer", id, hud_layers.some((other) => other.id === id)); if (typeof layer?.on_render !== "function") throw new Error(`[${mod}] a hud layer needs an on_render`); - if (hud_layers.some((other) => other.id === id)) { - throw new Error(`[${mod}] hud layer ${id} already exists`); - } hud_layers.push({ mod, id, layer }); }, on_overlay_message(fn) { @@ -359,13 +310,13 @@ function client_context(listing: ModListing): ClientContext { options: key_mappings(need_client), net: { on(channel, handler) { - own(channel); + register.own("channel", channel); const handlers = net_handlers.get(channel) ?? []; handlers.push({ mod, handler: handler as (data: unknown) => void }); net_handlers.set(channel, handlers); }, send(channel, data) { - own(channel); + register.own("channel", channel); need_client().connection.send({ type: "mod", channel, data }); }, }, @@ -451,7 +402,7 @@ function client_context(listing: ModListing): ClientContext { return mod_name(id); }, }, - blocks: blocks_api(mod), + blocks: blocks_api(), fluids: { ...fluid_rules.api(), mod(id) { @@ -470,12 +421,12 @@ function client_context(listing: ModListing): ClientContext { tags: tag_api(), render: { register_visual(block, create, options) { - if (!client_setup) throw new Error(`[${mod}] visuals can only be registered during setup`); + register.running("visual"); const nid = EverythingRegistry.get_id("blocks", block); if (nid === undefined) throw new Error(`[${mod}] unknown block ${block}`); if (typeof create !== "function") throw new Error(`[${mod}] a visual needs a function that makes it`); const other = block_visuals.get(nid); - if (other) throw new Error(`[${mod}] ${block} already has a visual, from ${other.mod}`); + if (other) register.fail(`${block} already has a visual, from ${other.mod}`); block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false }); }, }, diff --git a/common/block_rules.ts b/common/block_rules.ts index a052a5c..9d7683b 100644 --- a/common/block_rules.ts +++ b/common/block_rules.ts @@ -70,8 +70,8 @@ export class BlockRules { readonly told?: (x: number, y: number, z: number, from: Position) => void, ) {} + // checked by the shared context, see common/shared_context.ts register(mod: string, id: string, rules: Rules) { - if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of ${id} are registered twice`); this.#rules.set(id, { mod, rules }); } diff --git a/common/content_scripts.ts b/common/content_scripts.ts index a7751e7..607651f 100644 --- a/common/content_scripts.ts +++ b/common/content_scripts.ts @@ -6,7 +6,7 @@ // the mod's data before anything else reads it import { type BlockJson, validate_block } from "./mod_data.ts"; import type { ContentContext } from "./mod_api/content.ts"; -import { ModLoadError, run_phase } from "./mod_loader.ts"; +import { ModLoadError, registrar, run_phase } from "./mod_loader.ts"; import { expose_engine } from "./hooks.ts"; import { common_engine } from "./engine_modules.ts"; @@ -38,20 +38,19 @@ export async function run_content_script( // the whole script loads here, and one with engine access can import cubi/engine. only engine.common is here expose_engine({ common: common_engine() }); const blocks: BlockJson[] = []; - let setting_up = true; + let running = true; + const register = registrar(mod, "content", () => running); const ctx: ContentContext = { mod: { id: mod, version }, blocks: { register(block) { - if (!setting_up) throw new Error("blocks can only be registered during setup"); + register.running("block"); // what a file could hold, so the server, its players and its worldgen workers all get the same thing const json = JSON.parse(JSON.stringify(block ?? null)); const id = typeof json?.id === "string" ? json.id : "without an id"; const problems = validate_block(json); - if (problems.length > 0) throw new Error(`block ${id}: ${problems.join("; ")}`); - if (json.id.split(":")[0] !== mod) { - throw new Error(`block ${json.id} isn't in this mod's namespace "${mod}"`); - } + if (problems.length > 0) register.fail(`block ${id}: ${problems.join("; ")}`); + register.own("block", json.id); blocks.push(json); }, }, @@ -63,6 +62,6 @@ export async function run_content_script( const problem = e instanceof ModLoadError ? e.problem : e instanceof Error ? e.message : String(e); return { blocks, problems: [problem] }; } finally { - setting_up = false; + running = false; } } diff --git a/common/fluids.ts b/common/fluids.ts index 7c0fa6b..1798c5c 100644 --- a/common/fluids.ts +++ b/common/fluids.ts @@ -16,13 +16,15 @@ export class FluidRules { // run runs a mod's code, reporting what it throws instead of letting it take the game down constructor(readonly run: (mod: string, what: string, fn: () => T) => T | undefined) {} + // checked by the shared context, see common/shared_context.ts register(mod: string, id: string, rules: Rules) { - if (!id.startsWith(`${mod}:`)) throw new Error(`[${mod}] fluid ${id} must be in the namespace "${mod}"`); - if (!EverythingRegistry.get("fluids", id)) throw new Error(`[${mod}] unknown fluid ${id}`); - if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of fluid ${id} are registered twice`); this.#rules.set(id, { mod, rules }); } + has(id: string) { + return this.#rules.has(id); + } + name(fluid: FluidVariant): string { const json = known_fluid(fluid.id); const valid = (value: unknown): value is string => typeof value === "string" && value.length > 0; diff --git a/common/mod_loader.ts b/common/mod_loader.ts index 52dc122..85e4899 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -128,6 +128,35 @@ export class ModLoadError extends Error { export const PHASES = ["content", "shared", "server", "client", "worldgen"] as const; export type Phase = typeof PHASES[number]; +// the checks everything a mod registers from code goes through, the same on every side: only while the phase that +// registers it runs, in the mod's own namespace, and once. running says whether that phase is running. what names the +// kind of thing, like "component" +export function registrar(mod: string, phase: Phase, running: () => boolean) { + const fail = (message: string): never => { + throw new ModLoadError(mod, message); + }; + const checks = { + fail, + running(what: string) { + if (!running()) fail(`${what} can only be registered while the ${phase} phase runs`); + }, + own(what: string, id: string) { + if (typeof id !== "string" || !id.startsWith(`${mod}:`)) { + fail(`${what} ${id} must be in the namespace "${mod}"`); + } + }, + // all three, taken saying whether id is registered already + new_id(what: string, id: string, taken: boolean) { + checks.running(what); + checks.own(what, id); + if (taken) fail(`${what} ${id} is registered twice`); + }, + }; + return checks; +} + +export type Registrar = ReturnType; + // imports a mod's script and calls its export for phase, if it has one, with the context context makes. a realm // imports the same url once, so every phase there gets the same module and what it keeps at its top level export async function run_phase( @@ -329,18 +358,18 @@ export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup { } // ctx.recipes for shared phases, the same on the server and every client: a recipe registered there is in the book -// on every side without being sent, like one from the mod's recipes/. checked like a data file's. fail throws, as the -// side's error for the mod. list reads the book as it is, so a script sees the recipes of the ones before it +// on every side without being sent, like one from the mod's recipes/. checked like a data file's. list reads the book +// as it is, so a script sees the recipes of the ones before it export function shared_recipes_api( mod: string, recipes: () => RecipeBook, - setting_up: () => boolean, - fail: (message: string) => never, + register: Registrar, ): SharedContext["recipes"] { + const fail = register.fail; return { ...recipe_lookup(recipes), register(type, json) { - if (!setting_up()) fail("recipes can only be registered during setup"); + register.running("recipe"); const recipe = { ...structuredClone(json), type }; const problems = validate_recipe(recipe); if (problems.length > 0) fail(`recipe of type ${type}: ${problems.join(", ")}`); @@ -353,10 +382,8 @@ export function shared_recipes_api( list: (type) => structuredClone(type ? recipes().all.filter((recipe) => recipe.type === type) : recipes().all), // the recipes of the type there are so far are parsed now, and the ones registered after as they come register_type(type, rules) { - if (!setting_up()) fail("recipe types can only be registered during setup"); - if (!type.startsWith(`${mod}:`)) fail(`recipe type ${type} must be in the namespace "${mod}"`); const book = recipes(); - if (book.types.has(type)) fail(`recipe type ${type} is already registered`); + register.new_id("recipe type", type, book.types.has(type)); const type_rules = rules as RecipeType; try { book.parsed.set( diff --git a/common/shared_context.ts b/common/shared_context.ts new file mode 100644 index 0000000..2fd66cb --- /dev/null +++ b/common/shared_context.ts @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// what mods' shared phases get, built the same way on the server and every client so they register the same rules and +// recipes. each side gives it its own world, rules and recipe book +import type { ModInfo, SharedContext, SharedWorld } from "./mod_api/shared.ts"; +import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts"; +import { AIR_ID } from "./protocol.ts"; +import { is_solid } from "./block_shapes.ts"; +import type { BlockRules } from "./block_rules.ts"; +import { fluid_exists, type FluidRules, same_fluid } from "./fluids.ts"; +import { type RecipeBook, registrar, shared_recipes_api } from "./mod_loader.ts"; +import { tag_api } from "./tags.ts"; +import { shared_items_api } from "./utils.ts"; + +export interface SharedSide { + side: "server" | "client"; + // what the rules read and change: the real world on the server, what a client shows on a client + world: SharedWorld; + block_rules: BlockRules; + fluid_rules: FluidRules; + recipes: () => RecipeBook; + // whether the shared phases are running, the only time they can register + running: () => boolean; +} + +export function shared_context(mod: ModInfo, side: SharedSide): SharedContext { + const register = registrar(mod.id, "shared", side.running); + return { + mod, + side: side.side, + tags: tag_api(), + blocks: blocks_api(), + items: shared_items_api(mod.id, side.fluid_rules), + fluids: { + exists: fluid_exists, + same: same_fluid, + register(id, rules) { + register.new_id("fluid rules", id, side.fluid_rules.has(id)); + if (!fluid_exists(id)) register.fail(`unknown fluid ${id}`); + side.fluid_rules.register(mod.id, id, rules); + }, + }, + recipes: shared_recipes_api(mod.id, side.recipes, register), + world: side.world, + components: { + register_block(id, rules) { + register.new_id("component", id, side.block_rules.has(id)); + side.block_rules.register(mod.id, id, rules); + }, + }, + }; +} + +// ctx.blocks, the part every side has +export function blocks_api(): SharedContext["blocks"] { + const known = (id: string) => { + const block = EverythingRegistry.get("blocks", id); + if (!block) throw new Error(`unknown block ${id}`); + return block; + }; + return { + exists: (id) => EverythingRegistry.get("blocks", id) !== undefined, + components: (id) => structuredClone(known(id).components ?? {}), + solid: (id) => id !== AIR_ID && is_solid(known(id)), + }; +} diff --git a/common/worldgen_loader.ts b/common/worldgen_loader.ts index de1dece..641c835 100644 --- a/common/worldgen_loader.ts +++ b/common/worldgen_loader.ts @@ -7,7 +7,7 @@ import type { FeatureChunk, FeatureStep, WorldgenContext } from "@/common/mod_ap import type { OreJson } from "@/common/mod_data.ts"; import type { SetupFeature, WorldgenSetup } from "./generation.ts"; import { EverythingRegistry } from "./everything_registry.ts"; -import { ModLoadError, run_phase } from "./mod_loader.ts"; +import { ModLoadError, registrar, run_phase } from "./mod_loader.ts"; import { compile_generator } from "./worldgen/generator.ts"; import type { WorldShape } from "./world_shape.ts"; import { @@ -54,17 +54,12 @@ export async function load_worldgen(sources: WorldgenSources): Promise("features") ?? []).filter((f) => f); for (const { mod, url, engine_access } of sources.scripts) { - const own = (id: string, what: string) => { - if (!id.startsWith(`${mod}:`)) { - throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`); - } - }; + let running = true; + const register = registrar(mod, "worldgen", () => running); const ctx: WorldgenContext = { register_feature(id, generate, options = {}) { - own(id, "feature"); - if (pending.some((p) => p.feature.id === id) || data_features.some((f) => f.id === id)) { - throw new ModLoadError(mod, `feature ${id} is registered twice, as code or data`); - } + const taken = pending.some((p) => p.feature.id === id) || data_features.some((f) => f.id === id); + register.new_id("feature", id, taken); const step = options.step ?? DEFAULT_STEP; if (!FEATURE_STEPS.includes(step)) { throw new ModLoadError(mod, `feature ${id}: step must be one of ${FEATURE_STEPS.join(", ")}`); @@ -79,13 +74,11 @@ export async function load_worldgen(sources: WorldgenSources): Promise ctx); + running = false; } // data features last, so they can use the types and modifiers every script registered diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index f1cffe9..d9fc378 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -14,14 +14,15 @@ import { shared_items_api, } from "@/common/utils.ts"; import { LootTables } from "./loot.ts"; -import { collision_shape_at, covers_face, is_solid, raycast_blocks, type Shape } from "@/common/block_shapes.ts"; +import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "@/common/block_shapes.ts"; import { AIR, CHUNK_SIZE, faces, ID_MASK } from "@/common/constants.ts"; import { physics } from "@/common/physics.ts"; import { clock } from "@/common/time.ts"; import { BlockRules } from "@/common/block_rules.ts"; -import { fluid_exists, FluidRules, same_fluid } from "@/common/fluids.ts"; +import { FluidRules } from "@/common/fluids.ts"; import { interact, item_handler, tank_handler, transfer, use_container } from "./fluid_handlers.ts"; import type { SharedContext } from "@/common/mod_api/shared.ts"; +import { blocks_api, shared_context } from "@/common/shared_context.ts"; import { tag_api } from "@/common/tags.ts"; import type { BlockComponent, @@ -56,8 +57,8 @@ import { ModLoadError, type Phase, recipe_lookup, + registrar, run_phase, - shared_recipes_api, } from "@/common/mod_loader.ts"; import { argument, @@ -307,24 +308,9 @@ export class ModRuntime { } #shared_context({ mod, version, config }: ScriptSource): SharedContext { - const { world, blocks } = this.#context(mod, version, config); - return { - mod: { id: mod, version }, + const { world } = this.#context(mod, version, config); + return shared_context({ id: mod, version }, { side: "server", - tags: tag_api(), - blocks, - items: shared_items_api(mod, this.fluid_rules), - fluids: { - exists: fluid_exists, - same: same_fluid, - register: (id, rules) => { - if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup"); - this.fluid_rules.register(mod, id, rules); - }, - }, - recipes: shared_recipes_api(mod, () => this.game.recipes, () => this.#shared_setup, (message) => { - throw new ModLoadError(mod, message); - }), world: { get_block: world.get_block, get_state: world.get_state, @@ -333,16 +319,11 @@ export class ModRuntime { biome_at: world.biome_at, season_at: world.season_at, }, - components: { - register_block: (id, rules) => { - if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup"); - if (!id.startsWith(`${mod}:`)) { - throw new ModLoadError(mod, `component ${id} must be in the namespace "${mod}"`); - } - this.rules.register(mod, id, rules); - }, - }, - }; + block_rules: this.rules, + fluid_rules: this.fluid_rules, + recipes: () => this.game.recipes, + running: () => this.#shared_setup, + }); } // every effect mods define, from their json. they're made before scripts run, since the world loads first and @@ -694,16 +675,7 @@ export class ModRuntime { } #context(mod: string, version: string, config: Record): ServerContext { - const setup_only = (what: string) => { - if (!this.#setting_up) { - throw new Error(`[${mod}] ${what} can only be registered during setup`); - } - }; - const own = (id: string, what: string) => { - if (!id.startsWith(`${mod}:`)) { - throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`); - } - }; + const register = registrar(mod, "server", () => this.#setting_up); const game = () => this.game; const ctx: ServerContext = { @@ -711,36 +683,24 @@ export class ModRuntime { config, components: { register_block: (id, component) => { - setup_only("components"); - own(id, "component"); - if (this.block_components.has(id)) { - throw new ModLoadError(mod, `component ${id} is registered twice`); - } + register.new_id("component", id, this.block_components.has(id)); this.block_components.set(id, { mod, component: component as BlockComponent }); this.#components_of.clear(); this.#ticking_components_of.clear(); this.#components_with.clear(); }, register_item: (id, component) => { - setup_only("components"); - own(id, "component"); - if (this.item_components.has(id)) { - throw new ModLoadError(mod, `component ${id} is registered twice`); - } + register.new_id("component", id, this.item_components.has(id)); this.item_components.set(id, { mod, component: component as ItemComponent }); }, register_effect: (id, component) => { - setup_only("components"); - own(id, "component"); - if (this.effect_components.has(id)) { - throw new ModLoadError(mod, `component ${id} is registered twice`); - } + register.new_id("component", id, this.effect_components.has(id)); this.effect_components.set(id, { mod, component: component as EffectComponent }); }, }, commands: { register: (name_or_node: string | CommandNode, command?: Command) => { - setup_only("commands"); + register.running("command"); const node = typeof name_or_node === "string" ? simple_command(name_or_node, command!) : name_or_node as unknown as CommandNode; @@ -1011,23 +971,12 @@ export class ModRuntime { }, }, blocks: { - exists: (id) => EverythingRegistry.get("blocks", id) !== undefined, + ...blocks_api(), toughness: (id) => { const block = EverythingRegistry.get("blocks", id); if (!block) throw new Error(`unknown block ${id}`); return block.toughness ?? Infinity; }, - components: (id) => { - const block = EverythingRegistry.get("blocks", id); - if (!block) throw new Error(`unknown block ${id}`); - return structuredClone(block.components ?? {}); - }, - solid: (id) => { - if (id === AIR_ID) return false; - const block = EverythingRegistry.get("blocks", id); - if (!block) throw new Error(`unknown block ${id}`); - return is_solid(block); - }, }, fluids: { ...this.fluid_rules.api(), @@ -1062,19 +1011,19 @@ export class ModRuntime { return left; }, register_condition: (id, condition) => { - setup_only("loot conditions"); + register.running("loot condition"); this.loot.register_condition(mod, id, condition); }, register_function: (id, fn) => { - setup_only("loot functions"); + register.running("loot function"); this.loot.register_function(mod, id, fn); }, modify: (table, fn) => { - setup_only("loot modifiers"); + register.running("loot modifier"); this.loot.modify(mod, table, fn); }, register_table: (id, table) => { - setup_only("loot tables"); + register.running("loot table"); this.loot.register_table(mod, id, table); }, }, @@ -1094,12 +1043,12 @@ export class ModRuntime { }, menus: { extend_player_menu: (build) => { - setup_only("extend_player_menu"); + register.running("player menu slot"); this.#player_menu_builders.push({ mod, build }); }, register: (id: string, build: (menu: MenuBuilder, args: Args, player: Player) => void) => { - own(id, "menu type"); - if (this.#menu_types.has(id)) throw new Error(`[${mod}] menu type ${id} is already registered`); + register.own("menu type", id); + if (this.#menu_types.has(id)) register.fail(`menu type ${id} is registered twice`); this.#menu_types.add(id); const type: MenuType = { id, @@ -1115,13 +1064,13 @@ export class ModRuntime { }, net: { on: (channel, handler) => { - own(channel, "channel"); + register.own("channel", channel); const handlers = this.#net_handlers.get(channel) ?? []; handlers.push({ mod, handler: handler as (player: Player, data: unknown) => void }); this.#net_handlers.set(channel, handlers); }, send: (player, channel, data) => { - own(channel, "channel"); + register.own("channel", channel); const server_player = this.#server_players.get(player); if (!server_player || !game().players().includes(server_player)) { throw new Error(`${player.name} isn't online`); @@ -1129,7 +1078,7 @@ export class ModRuntime { game().send_mod_message(server_player, channel, data); }, broadcast: (channel, data) => { - own(channel, "channel"); + register.own("channel", channel); for (const player of game().players()) game().send_mod_message(player, channel, data); }, }, diff --git a/tests/content_script_test.ts b/tests/content_script_test.ts index cc61c2b..7d3f1e5 100644 --- a/tests/content_script_test.ts +++ b/tests/content_script_test.ts @@ -71,12 +71,12 @@ Deno.test("check-mods runs a mod's content phase, and its files can name the blo 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 + // only while the content phase runs 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", + "block can only be registered while the content phase runs", ); }); @@ -128,7 +128,7 @@ Deno.test("a content phase's mistakes stop its mod loading, naming the script", 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"`, + `scripts/content.ts: block bworld:granite must be in the namespace "rocks"`, ], [`ctx.blocks.register({ id: "rocks:broken" } as any);`, "scripts/content.ts: block rocks:broken: "], [ @@ -155,6 +155,6 @@ Deno.test("a content phase's mistakes stop its mod loading, naming the script", Deno.removeSync(folder, { recursive: true }); assertStringIncludes( (rejected as Error).message, - `rocks.cubi: script.js: block bworld:granite isn't in this mod's namespace "rocks"`, + `rocks.cubi: script.js: block bworld:granite must be in the namespace "rocks"`, ); }); diff --git a/tests/features_test.ts b/tests/features_test.ts index 40c1583..9249ba0 100644 --- a/tests/features_test.ts +++ b/tests/features_test.ts @@ -154,7 +154,7 @@ Deno.test("a feature can't be both code and data", async () => { await assertRejects( () => test_game(clash), Error, - "feature testmod:glass_pillar is registered twice, as code or data", + "feature testmod:glass_pillar is registered twice", ); } finally { Deno.removeSync(clash, { recursive: true }); diff --git a/tests/helpers.ts b/tests/helpers.ts index a24108f..24e2bfd 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -27,11 +27,12 @@ import type { ModelJson } from "@/common/block_models.ts"; import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts"; import { FluidRules } from "@/common/fluids.ts"; import { BlockRules } from "@/common/block_rules.ts"; -import { collision_shape_at, covers_face, is_solid } from "@/common/block_shapes.ts"; -import { tag_api } from "@/common/tags.ts"; -import { get_state_value, set_state_value, shared_items_api } from "@/common/utils.ts"; +import { collision_shape_at, covers_face } from "@/common/block_shapes.ts"; +import { get_state_value, set_state_value } from "@/common/utils.ts"; import type { Face, SharedWorld } from "@/common/mod_api/shared.ts"; import { shared as setup_shared } from "@/mods/bworld/scripts/shared.ts"; +import { shared_context } from "@/common/shared_context.ts"; +import { RecipeBook } from "@/common/mod_loader.ts"; // the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only // mods/ is kept, since tests change the temporary folders they make between games @@ -377,6 +378,7 @@ export function client_of(game: GameServer, area: Area) { const info = (id: string) => EverythingRegistry.get("blocks", id); const rules = new BlockRules((_mod, _what, fn) => fn(), (x, y, z) => at(x, y, z)?.[0]); + const recipes = new RecipeBook(); const world: SharedWorld = { get_block: (x, y, z) => at(x, y, z)?.[0], get_state(x, y, z, name) { @@ -403,22 +405,15 @@ export function client_of(game: GameServer, area: Area) { biome_at: () => undefined, season_at: () => undefined, }; - setup_shared({ - mod: { id: "bworld", version: "test" }, + setup_shared(shared_context({ id: "bworld", version: "test" }, { side: "client", - tags: tag_api(), - blocks: { - exists: (id) => info(id) !== undefined, - components: (id) => structuredClone(info(id)!.components ?? {}), - solid: (id) => id !== AIR_ID && is_solid(info(id)!), - }, - items: shared_items_api("bworld", new FluidRules((_mod, _what, fn) => fn())), - // only its blocks are looked at here - fluids: { exists: () => false, same: () => false, register() {} }, - recipes: { register() {}, list: () => [], register_type() {}, find: () => undefined, all: () => [] }, world, - components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) }, - }); + block_rules: rules, + fluid_rules: new FluidRules((_mod, _what, fn) => fn()), + // its recipes aren't looked at here + recipes: () => recipes, + running: () => true, + })); return { // what game_mode does when this client places held against face of x y z, at hit diff --git a/tests/hud_test.ts b/tests/hud_test.ts index 8225b9a..c0e3521 100644 --- a/tests/hud_test.ts +++ b/tests/hud_test.ts @@ -86,6 +86,6 @@ Deno.test("hud layers are in the mod's namespace, one to an id", async () => { ctx.hud.register("testmod:bar", ${layer}); }`), Error, - "hud layer testmod:bar already exists", + "hud layer testmod:bar is registered twice", ); }); diff --git a/tests/script_recipes_test.ts b/tests/script_recipes_test.ts index a684f87..6557204 100644 --- a/tests/script_recipes_test.ts +++ b/tests/script_recipes_test.ts @@ -217,7 +217,7 @@ Deno.test("recipes can only be registered while shared phases set up", async () `(globalThis as any).testrecipes_late = () => ctx.recipes.register("testrecipes:sifting", {});`, ); try { - await assertRejects(() => test_game(dir), Error, "recipes can only be registered during setup"); + await assertRejects(() => test_game(dir), Error, "recipe can only be registered while the shared phase runs"); } finally { delete (globalThis as Record).testrecipes_late; Deno.removeSync(dir, { recursive: true });