Files
bworld/server/load_bmods.ts
T
2026-10-25 14:05:57 -03:00

197 lines
7.1 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the server's mods: every .bmod in server_mods/, checked, with the server's changes to their config, sorted so
// dependencies load first, and with the copy players download (the same mod without its server script) ready to serve
import { join } from "@std/path";
import { type Bmod, BMOD_EXTENSION, client_copy, read_bmod, write_bmod } from "$/common/bmod.ts";
import { check_references, load_order, type LoadedMod } from "$/common/mod_check.ts";
import type { ModListing } from "$/common/mod_loader.ts";
import { data_file, FORMAT_VERSION } from "$/common/mod_data.ts";
import { is_object, json_object } from "$/common/schema.ts";
import { sha256 } from "$/common/utils.ts";
export interface ServerMod {
bmod: Bmod;
listing: ModListing;
// what's served at listing.file
client_bytes: Uint8Array<ArrayBuffer>;
}
export class ModsError extends Error {
constructor(problems: string[]) {
super(`Mods have errors:\n${problems.map((p) => ` ${p}`).join("\n")}`);
this.name = "ModsError";
}
}
// engine_textures are the engine: texture ids, for checking the textures mods use. config_dir has the server's
// <mod id>.json files that change mods' config. a mod with problems stops the whole server from starting, the game
// never runs with some mods missing
export async function load_bmods(
dir: string,
engine_textures: Iterable<string>,
config_dir?: string,
): Promise<ServerMod[]> {
let files: string[];
try {
files = [...Deno.readDirSync(dir)]
.filter((entry) => entry.isFile && entry.name.endsWith(BMOD_EXTENSION))
.map((entry) => entry.name)
.sort();
} catch (e) {
if (e instanceof Deno.errors.NotFound) return [];
throw e;
}
const problems: string[] = [];
const by_id = new Map<string, { file: string; bmod: Bmod }>();
for (const file of files) {
try {
const bmod = read_bmod(Deno.readFileSync(join(dir, file)), file);
const other = by_id.get(bmod.manifest.id);
if (other) {
problems.push(`${file} and ${other.file} are both the mod "${bmod.manifest.id}"`);
continue;
}
by_id.set(bmod.manifest.id, { file, bmod });
} catch (e) {
problems.push((e as Error).message);
}
}
if (config_dir) {
for (const { bmod } of by_id.values()) change_config(bmod, config_dir, problems);
}
// the same checks check-mods runs on mod folders
const loaded = [...by_id.values()].map(({ file, bmod }) => as_loaded_mod(file, bmod));
check_references(loaded, engine_textures);
for (const mod of loaded) {
const dependencies = (mod.manifest?.dependencies ?? []) as { id: string }[];
for (const { id } of dependencies) {
if (!by_id.has(id)) mod.report.errors.push(`depends on "${id}", which isn't in ${dir}`);
}
problems.push(...mod.report.errors.map((error) => `${mod.dir}: ${error}`));
for (const warning of mod.report.warnings) console.warn(`${mod.dir}: ${warning}`);
}
let ordered: LoadedMod[] = [];
try {
ordered = load_order(loaded);
} catch (e) {
problems.push((e as Error).message);
}
if (problems.length > 0) throw new ModsError(problems);
return await Promise.all(ordered.map(async (mod) => {
const bmod = by_id.get(mod.id)!.bmod;
const client_bytes = write_bmod(client_copy(bmod));
const hash = await sha256(client_bytes);
return {
bmod,
client_bytes,
listing: {
id: bmod.manifest.id,
name: bmod.manifest.name,
version: bmod.manifest.version,
sha256: hash,
file: `mods/${hash}${BMOD_EXTENSION}`,
size: client_bytes.length,
...(bmod.manifest.engine_access ? { engine_access: true } : {}),
},
};
}));
}
// applies config_dir/<mod id>.json to the mod's config, when the server has one
function change_config(bmod: Bmod, config_dir: string, problems: string[]) {
const file = join(config_dir, `${bmod.manifest.id}.json`);
let text: string;
try {
text = Deno.readTextFileSync(file);
} catch (e) {
if (e instanceof Deno.errors.NotFound) return;
throw e;
}
let json: unknown;
try {
json = JSON.parse(text);
} catch (e) {
problems.push(`${file}: isn't valid json: ${(e as Error).message}`);
return;
}
const config_file = data_file("config", json_object).safeParse(json);
if (!config_file.success) {
problems.push(`${file}: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`);
return;
}
const changed = apply_config(bmod.data.config ?? {}, config_file.data.config as Record<string, unknown>);
problems.push(...changed.problems.map((problem) => `${file}: ${problem}`));
bmod.data.config = changed.config;
}
// a mod's config with changes made to it, like a server's config/<mod id>.json makes: objects are changed setting by
// setting, anything else is replaced. a change has to be to a setting the mod has, and the same kind of json value,
// so a misspelled one doesn't go unnoticed
export function apply_config(
config: Record<string, unknown>,
changes: Record<string, unknown>,
): { config: Record<string, unknown>; problems: string[] } {
const problems: string[] = [];
const apply = (settings: Record<string, unknown>, changes: Record<string, unknown>, path: string) => {
const result = { ...settings };
for (const [key, value] of Object.entries(changes)) {
const name = `${path}${key}`;
if (!Object.hasOwn(settings, key)) {
problems.push(`${name} isn't one of the mod's settings`);
} else if (json_kind(value) !== json_kind(settings[key])) {
problems.push(`${name} must be ${json_kind(settings[key])}`);
} else {
result[key] = is_object(value)
? apply(settings[key] as Record<string, unknown>, value, `${name}.`)
: value;
}
}
return result;
};
return { config: apply(config, changes, ""), problems };
}
function json_kind(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "a list";
return is_object(value) ? "an object" : `a ${typeof value}`;
}
// in the shape the checks in common/mod_check.ts take
function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
const entries = <T>(list: T[]) => list.map((json) => ({ file: `${file} data.json`, json }));
return {
id: bmod.manifest.id,
dir: file,
report: { id: bmod.manifest.id, errors: [], warnings: [] },
manifest: bmod.manifest as unknown as Record<string, unknown>,
blocks: entries(bmod.data.blocks),
models: entries(bmod.data.models),
items: entries(bmod.data.items),
recipes: entries(bmod.data.recipes),
ores: entries(bmod.data.ores),
spawns: entries(bmod.data.spawns),
entities: entries(bmod.data.entities),
entity_models: entries(bmod.data.entity_models),
effects: entries(bmod.data.effects),
fluids: entries(bmod.data.fluids),
tags: entries(bmod.data.tags),
loot_tables: entries(bmod.data.loot_tables ?? []),
biomes: entries(bmod.data.biomes ?? []),
noises: entries(bmod.data.noises ?? []),
density_functions: entries(bmod.data.density_functions ?? []),
noise_settings: entries(bmod.data.noise_settings ?? []),
biome_sources: entries(bmod.data.biome_sources ?? []),
features: entries(bmod.data.features ?? []),
config: bmod.data.config,
textures: [...bmod.textures.keys()],
texture_files: new Map(),
texture_json: new Map(bmod.texture_json),
};
}