feat(mods): add core mod manifest, resolver, BLK/CSV patchers, and server API types

This commit is contained in:
N0VAN0M4LY committed 2026-12-02 23:42:26 +08:00
1 parent f1ec034994
commit 8fbaeb4228
14 files changed
+2197 -1

No files matched your search

+12
View File
@@ -1934,6 +1934,10 @@
"resolved": "apps/launcher",
"link": true
},
"node_modules/@wto/mods": {
"resolved": "packages/mods",
"link": true
},
"node_modules/@wto/patcher": {
"resolved": "packages/patcher",
"link": true
@@ -6151,6 +6155,14 @@
"name": "@wto/jsonc",
"version": "0.1.0"
},
"packages/mods": {
"name": "@wto/mods",
"version": "0.1.0",
"dependencies": {
"@wto/blk": "*",
"@wto/jsonc": "*"
}
},
"packages/patcher": {
"name": "@wto/patcher",
"version": "0.1.0",
+2 -1
View File
@@ -10,6 +10,7 @@ export { emptyBlock } from './model.ts';
export { BlkFormatError } from './errors.ts';
export { BlkLabel, decodeBlk, encodeBlk, type SharedNameContext } from './binary/format.ts';
export { parseSharedNameMap, type SharedNameMap } from './shared-name-map.ts';
export { appendParam, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
export { appendParam, cloneBlock, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
export { formatBlkText } from './text/format-text.ts';
export { isBinaryBlk, parseBlkText } from './text/parse-text.ts';
export { singleVehiclePackId, stableGuid } from './stable-guid.ts';
+317
View File
@@ -0,0 +1,317 @@
/**
* Parse a BLK document in Dagor's text syntax back into the typed in-memory model.
*
* Syntax source: DagorEngine prog/engine/ioSys/dataBlock/blk_read.cpp (BSD-3).
* Supports C/C++ comments, quoted and bare identifiers, `~` string escapes, nested blocks,
* optional semicolons, and every typed parameter suffix emitted by `format-text.ts`.
*/
import { BlkFormatError } from '../errors.ts';
import { emptyBlock, type BlkBlock, type BlkValue } from '../model.ts';
export function isBinaryBlk(bytes: Uint8Array): boolean {
if (bytes.length === 0) return false;
const first = bytes[0]!;
// Binary BLK labels used by DagorEngine (see binary/format.ts BlkLabel: 0x00..0x06, zstd 0x28).
return first <= 0x06 || first === 0x28;
}
export function parseBlkText(source: string): BlkBlock {
const parser = new BlkTextParser(source);
const root = emptyBlock('');
parser.readBlockBody(root, false);
return root;
}
class BlkTextParser {
readonly #text: string;
#pos = 0;
constructor(text: string) {
// Strip UTF-8 BOM if present.
this.#text = text.startsWith('\uFEFF') ? text.slice(1) : text;
}
readBlockBody(target: BlkBlock, expectClosingBrace: boolean): void {
while (true) {
this.#skipIgnored();
if (this.#eof()) {
if (expectClosingBrace) this.#fail('unexpected end of BLK text inside block');
return;
}
if (this.#peek() === '}') {
if (!expectClosingBrace) this.#fail('unexpected closing brace "}" at root');
this.#pos += 1;
return;
}
const key = this.#readIdentifierOrString();
this.#skipIgnored();
const ch = this.#peek();
if (ch === '{') {
this.#pos += 1;
const child = emptyBlock(key);
this.readBlockBody(child, true);
target.blocks.push(child);
continue;
}
if (ch === ':') {
this.#pos += 1;
const suffix = this.#readTypeSuffix();
this.#skipHorizontalAndComments();
if (this.#peek() !== '=') this.#fail(`expected "=" after type suffix ":${suffix}"`);
this.#pos += 1;
const value = this.#readValue(suffix);
target.params.push({ name: key, value });
continue;
}
// Untyped `include "..."` directive or unknown syntax.
if (key === 'include' && (ch === '"' || ch === "'")) {
const included = this.#readQuotedString();
target.params.push({ name: 'include', value: { type: 'string', value: included } });
continue;
}
this.#fail(`expected "{" or ":" after "${key}"`);
}
}
#readIdentifierOrString(): string {
const ch = this.#peek();
if (ch === '"' || ch === "'") return this.#readQuotedString();
const start = this.#pos;
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ':' || c === '{' || c === '}' || c === '=' || c === ';' || /\s/.test(c)) break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
if (this.#pos === start) this.#fail(`unexpected character "${ch ?? ''}"`);
return this.#text.slice(start, this.#pos);
}
#readTypeSuffix(): string {
const start = this.#pos;
while (!this.#eof() && /[A-Za-z0-9]/.test(this.#text[this.#pos]!)) this.#pos += 1;
const suffix = this.#text.slice(start, this.#pos);
if (!suffix) this.#fail('missing BLK type suffix after ":"');
return suffix;
}
#readValue(suffix: string): BlkValue {
this.#skipHorizontalAndComments();
switch (suffix) {
case 't': return { type: 'string', value: this.#readStringValue() };
case 'i': return { type: 'int', value: this.#readInt() };
case 'i64': return { type: 'int64', value: this.#readBigInt() };
case 'r': return { type: 'real', value: this.#readReal() };
case 'b': return { type: 'bool', value: this.#readBool() };
case 'p2': return { type: 'point2', value: this.#readReals(2) as [number, number] };
case 'p3': return { type: 'point3', value: this.#readReals(3) as [number, number, number] };
case 'p4': return { type: 'point4', value: this.#readReals(4) as [number, number, number, number] };
case 'ip2': return { type: 'ipoint2', value: this.#readInts(2) as [number, number] };
case 'ip3': return { type: 'ipoint3', value: this.#readInts(3) as [number, number, number] };
case 'ip4': return { type: 'ipoint4', value: this.#readInts(4) as [number, number, number, number] };
case 'c': return { type: 'color', value: this.#readColor() };
case 'm': return { type: 'matrix', value: this.#readMatrix() };
default: this.#fail(`unsupported BLK type suffix ":${suffix}"`);
}
}
#readStringValue(): string {
const ch = this.#peek();
if (ch === '"' || ch === "'") return this.#readQuotedString();
// Unquoted single-line string terminated by newline, semicolon, brace, or comment.
const start = this.#pos;
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === '\r' || c === '\n' || c === ';' || c === '}') break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
return this.#text.slice(start, this.#pos).trim();
}
#readQuotedString(): string {
const quote = this.#text[this.#pos]!;
this.#pos += 1;
let out = '';
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
this.#pos += 1;
if (c === quote) return out;
if (c === '~' && !this.#eof()) {
const next = this.#text[this.#pos]!;
this.#pos += 1;
switch (next) {
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case '~': out += '~'; break;
case '"': out += '"'; break;
case "'": out += "'"; break;
default: out += next; break;
}
continue;
}
out += c;
}
this.#fail('unterminated string literal');
}
#readToken(): string {
this.#skipHorizontalAndComments();
const start = this.#pos;
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ',' || c === ';' || c === '}' || c === ']' || /\s/.test(c)) break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
if (this.#pos === start) this.#fail('expected value token');
return this.#text.slice(start, this.#pos);
}
#readInt(): number {
const raw = this.#readToken();
const parsed = raw.startsWith('0x') || raw.startsWith('0X') ? Number.parseInt(raw, 16) : Number(raw);
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) this.#fail(`invalid integer "${raw}"`);
return parsed | 0;
}
#readBigInt(): bigint {
const raw = this.#readToken();
try {
return BigInt(raw);
} catch {
this.#fail(`invalid int64 "${raw}"`);
}
}
#readReal(): number {
const raw = this.#readToken();
const parsed = Number(raw);
if (!Number.isFinite(parsed)) this.#fail(`invalid real "${raw}"`);
return parsed;
}
#readBool(): boolean {
const raw = this.#readToken().toLowerCase();
if (raw === 'yes' || raw === 'true' || raw === '1') return true;
if (raw === 'no' || raw === 'false' || raw === '0') return false;
this.#fail(`invalid bool "${raw}"`);
}
#readReals(count: number): number[] {
const values: number[] = [];
for (let i = 0; i < count; i += 1) {
if (i > 0) this.#expectComma();
values.push(this.#readReal());
}
return values;
}
#readInts(count: number): number[] {
const values: number[] = [];
for (let i = 0; i < count; i += 1) {
if (i > 0) this.#expectComma();
values.push(this.#readInt());
}
return values;
}
#readColor(): number {
const channels = this.#readInts(4);
const [r, g, b, a] = channels as [number, number, number, number];
return (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0;
}
#readMatrix(): number[] {
this.#expectChar('[');
const values: number[] = [];
for (let row = 0; row < 4; row += 1) {
this.#skipIgnored();
this.#expectChar('[');
for (let col = 0; col < 3; col += 1) {
if (col > 0) this.#expectComma();
values.push(this.#readReal());
}
this.#skipHorizontalAndComments();
this.#expectChar(']');
this.#skipHorizontalAndComments();
if (this.#peek() === ',') this.#pos += 1;
}
this.#skipIgnored();
this.#expectChar(']');
return values;
}
#expectComma(): void {
this.#skipHorizontalAndComments();
if (this.#peek() !== ',') this.#fail('expected "," between tuple components');
this.#pos += 1;
}
#expectChar(expected: string): void {
this.#skipHorizontalAndComments();
if (this.#peek() !== expected) this.#fail(`expected "${expected}"`);
this.#pos += 1;
}
#skipIgnored(): void {
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ';' || /\s/.test(c)) {
this.#pos += 1;
continue;
}
if (this.#skipComment()) continue;
break;
}
}
#skipHorizontalAndComments(): void {
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ' ' || c === '\t') {
this.#pos += 1;
continue;
}
if (this.#skipComment()) continue;
break;
}
}
#skipComment(): boolean {
if (this.#text[this.#pos] !== '/') return false;
const next = this.#text[this.#pos + 1];
if (next === '/') {
this.#pos += 2;
while (!this.#eof() && this.#text[this.#pos] !== '\n') this.#pos += 1;
return true;
}
if (next === '*') {
this.#pos += 2;
while (!this.#eof()) {
if (this.#text[this.#pos] === '*' && this.#text[this.#pos + 1] === '/') {
this.#pos += 2;
return true;
}
this.#pos += 1;
}
this.#fail('unterminated block comment');
}
return false;
}
#peek(): string | undefined {
return this.#text[this.#pos];
}
#eof(): boolean {
return this.#pos >= this.#text.length;
}
#fail(message: string): never {
const prefix = this.#text.slice(0, this.#pos);
const line = prefix.split('\n').length;
throw new BlkFormatError(`BLK text parse error on line ${line}: ${message}`);
}
}
+25
View File
@@ -34,6 +34,31 @@ export function appendParam(block: BlkBlock, name: string, value: BlkValue): voi
block.params.push({ name, value });
}
/** Deep-clone a BLK block tree, optionally under a new block name. */
export function cloneBlock(block: BlkBlock, newName = block.name): BlkBlock {
return {
name: newName,
params: block.params.map((param) => ({
name: param.name,
value: cloneValue(param.value),
})),
blocks: block.blocks.map((child) => cloneBlock(child)),
};
}
function cloneValue(value: BlkValue): BlkValue {
switch (value.type) {
case 'point2': return { type: 'point2', value: [...value.value] as [number, number] };
case 'point3': return { type: 'point3', value: [...value.value] as [number, number, number] };
case 'point4': return { type: 'point4', value: [...value.value] as [number, number, number, number] };
case 'ipoint2': return { type: 'ipoint2', value: [...value.value] as [number, number] };
case 'ipoint3': return { type: 'ipoint3', value: [...value.value] as [number, number, number] };
case 'ipoint4': return { type: 'ipoint4', value: [...value.value] as [number, number, number, number] };
case 'matrix': return { type: 'matrix', value: [...value.value] };
default: return { ...value };
}
}
/** Visit every parameter of the tree, depth first, with the path of block names leading to it. */
export function visitParams(block: BlkBlock, visit: (param: BlkParam, path: readonly string[]) => void,
path: readonly string[] = []): void {
+13
View File
@@ -0,0 +1,13 @@
{
"name": "@wto/mods",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
".": "./src/index.ts"
},
"dependencies": {
"@wto/blk": "*",
"@wto/jsonc": "*"
}
}
+450
View File
@@ -0,0 +1,450 @@
/**
* Structured, type-preserving incremental patches for BLK documents (`*.blk.patch.jsonc`).
*
* Allows multiple mods to add vehicles to config/shop.blk, adjust prices/BR in config/wpcost.blk,
* tweak weapon/FM parameters, or clone an existing vehicle block and customize it without
* shipping whole stock files.
*/
import {
appendParam,
cloneBlock,
emptyBlock,
ensureBlock,
findParam,
setParam,
type BlkBlock,
type BlkValue,
type BlkValueType,
} from '@wto/blk';
import { parseJsonc } from '@wto/jsonc';
export interface BlkPathStep {
readonly name: string;
/** Zero-based occurrence index when multiple sibling blocks share the same name (e.g. `range[2]`). */
readonly index?: number;
}
export type BlkPatchValueInput =
| string
| number
| boolean
| { readonly type: BlkValueType; readonly value: unknown };
export interface BlkBlockBlueprint {
readonly name?: string;
readonly params?: ReadonlyArray<{ readonly name: string; readonly value: BlkPatchValueInput }>;
readonly blocks?: readonly BlkBlockBlueprint[];
}
export type BlkPatchOp =
| {
readonly op: 'setParam';
readonly path: readonly string[];
readonly name: string;
readonly value: BlkPatchValueInput;
readonly createBlocks?: boolean;
}
| {
readonly op: 'addParam';
readonly path: readonly string[];
readonly name: string;
readonly value: BlkPatchValueInput;
readonly createBlocks?: boolean;
}
| {
readonly op: 'removeParam';
readonly path: readonly string[];
readonly name: string;
readonly value?: string | number | boolean;
}
| {
readonly op: 'upsertBlock';
readonly path: readonly string[];
readonly block?: BlkBlockBlueprint;
}
| {
readonly op: 'addBlock';
readonly path: readonly string[];
readonly name: string;
readonly block?: BlkBlockBlueprint;
readonly before?: string;
readonly after?: string;
readonly createBlocks?: boolean;
}
| {
readonly op: 'removeBlock';
readonly path: readonly string[];
}
| {
readonly op: 'cloneBlock';
readonly from: readonly string[];
readonly toParent: readonly string[];
readonly newName: string;
readonly replaceExisting?: boolean;
readonly before?: string;
readonly after?: string;
readonly ops?: readonly BlkPatchOp[];
};
export interface BlkPatchDocument {
readonly ops: readonly BlkPatchOp[];
}
export class BlkPatchError extends Error {
override name = 'BlkPatchError';
}
export function parseBlkPatchDocument(text: string, where = 'blk patch'): BlkPatchDocument {
let raw: unknown;
try {
raw = parseJsonc(text);
} catch (error) {
throw new BlkPatchError(`${where}: cannot parse JSONC: ${error instanceof Error ? error.message : String(error)}`);
}
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new BlkPatchError(`${where}: root must be an object with an "ops" array`);
}
const opsRaw = (raw as Record<string, unknown>).ops;
if (!Array.isArray(opsRaw)) {
throw new BlkPatchError(`${where}: missing "ops" array`);
}
return { ops: opsRaw.map((item, idx) => validateOp(item, `${where}.ops[${idx}]`)) };
}
export function applyBlkPatch(root: BlkBlock, patch: BlkPatchDocument, where = 'blk patch'): void {
for (let i = 0; i < patch.ops.length; i += 1) {
applyOp(root, patch.ops[i]!, `${where}.ops[${i}]`);
}
}
function applyOp(root: BlkBlock, op: BlkPatchOp, where: string): void {
switch (op.op) {
case 'setParam': {
const target = resolveBlock(root, op.path, op.createBlocks ?? false, where);
const existing = findParam(target, op.name);
const value = toBlkValue(op.value, existing?.value.type, where);
setParam(target, op.name, value);
return;
}
case 'addParam': {
const target = resolveBlock(root, op.path, op.createBlocks ?? false, where);
const existing = findParam(target, op.name);
const value = toBlkValue(op.value, existing?.value.type, where);
appendParam(target, op.name, value);
return;
}
case 'removeParam': {
const target = tryResolveBlock(root, op.path);
if (!target) return;
target.params = target.params.filter((param) => {
if (param.name !== op.name) return true;
if (op.value === undefined) return false;
return !paramValueMatchesPrimitive(param.value, op.value);
});
return;
}
case 'upsertBlock': {
const target = resolveBlock(root, op.path, true, where);
if (op.block) mergeBlockBlueprint(target, op.block, where);
return;
}
case 'addBlock': {
const parent = resolveBlock(root, op.path, op.createBlocks ?? false, where);
const created = emptyBlock(op.name);
if (op.block) mergeBlockBlueprint(created, op.block, where);
insertBlockPositioned(parent, created, op.before, op.after);
return;
}
case 'removeBlock': {
if (op.path.length === 0) throw new BlkPatchError(`${where}: cannot remove root block`);
const parent = tryResolveBlock(root, op.path.slice(0, -1));
if (!parent) return;
const step = parsePathStep(op.path[op.path.length - 1]!, where);
const index = findChildBlockIndex(parent, step);
if (index >= 0) parent.blocks.splice(index, 1);
return;
}
case 'cloneBlock': {
const source = resolveBlock(root, op.from, false, `${where}.from`);
const parent = resolveBlock(root, op.toParent, true, `${where}.toParent`);
const cloned = cloneBlock(source, op.newName);
if (op.ops) {
for (let i = 0; i < op.ops.length; i += 1) {
applyOp(cloned, op.ops[i]!, `${where}.ops[${i}]`);
}
}
if (op.replaceExisting) {
const existingIdx = parent.blocks.findIndex((child) => child.name === op.newName);
if (existingIdx >= 0) {
parent.blocks[existingIdx] = cloned;
return;
}
}
insertBlockPositioned(parent, cloned, op.before, op.after);
return;
}
}
}
function insertBlockPositioned(parent: BlkBlock, block: BlkBlock, before?: string, after?: string): void {
if (before !== undefined) {
const idx = parent.blocks.findIndex((child) => child.name === before);
if (idx >= 0) {
parent.blocks.splice(idx, 0, block);
return;
}
}
if (after !== undefined) {
const idx = parent.blocks.findIndex((child) => child.name === after);
if (idx >= 0) {
parent.blocks.splice(idx + 1, 0, block);
return;
}
}
parent.blocks.push(block);
}
function mergeBlockBlueprint(target: BlkBlock, blueprint: BlkBlockBlueprint, where: string): void {
if (blueprint.params) {
for (const [idx, param] of blueprint.params.entries()) {
const existing = findParam(target, param.name);
const value = toBlkValue(param.value, existing?.value.type, `${where}.params[${idx}]`);
appendParam(target, param.name, value);
}
}
if (blueprint.blocks) {
for (const [idx, childBlueprint] of blueprint.blocks.entries()) {
const name = childBlueprint.name;
if (!name) throw new BlkPatchError(`${where}.blocks[${idx}]: child block must have a "name"`);
const child = emptyBlock(name);
mergeBlockBlueprint(child, childBlueprint, `${where}.blocks[${idx}]`);
target.blocks.push(child);
}
}
}
function resolveBlock(root: BlkBlock, path: readonly string[], createMissing: boolean, where: string): BlkBlock {
let current = root;
for (const rawStep of path) {
const step = parsePathStep(rawStep, where);
const idx = findChildBlockIndex(current, step);
if (idx >= 0) {
current = current.blocks[idx]!;
} else if (createMissing && step.index === undefined) {
current = ensureBlock(current, step.name);
} else {
throw new BlkPatchError(`${where}: block "${rawStep}" not found along path [${path.join(' / ')}]`);
}
}
return current;
}
function tryResolveBlock(root: BlkBlock, path: readonly string[]): BlkBlock | undefined {
let current = root;
for (const rawStep of path) {
const step = parsePathStep(rawStep, 'path');
const idx = findChildBlockIndex(current, step);
if (idx < 0) return undefined;
current = current.blocks[idx]!;
}
return current;
}
function parsePathStep(raw: string, where: string): BlkPathStep {
const match = /^(.+)\[(\d+)\]$/.exec(raw);
if (!match) {
if (!raw) throw new BlkPatchError(`${where}: empty path segment`);
return { name: raw };
}
return { name: match[1]!, index: Number(match[2]!) };
}
function findChildBlockIndex(parent: BlkBlock, step: BlkPathStep): number {
const wanted = step.index ?? 0;
let seen = 0;
for (let i = 0; i < parent.blocks.length; i += 1) {
if (parent.blocks[i]!.name !== step.name) continue;
if (seen === wanted) return i;
seen += 1;
}
return -1;
}
function toBlkValue(input: BlkPatchValueInput, inferredType: BlkValueType | undefined, where: string): BlkValue {
if (typeof input === 'string') return { type: 'string', value: input };
if (typeof input === 'boolean') return { type: 'bool', value: input };
if (typeof input === 'number') {
if (inferredType === 'real') return { type: 'real', value: input };
if (inferredType === 'int') return { type: 'int', value: input | 0 };
if (inferredType === 'int64') return { type: 'int64', value: BigInt(Math.trunc(input)) };
return Number.isInteger(input) ? { type: 'int', value: input | 0 } : { type: 'real', value: input };
}
if (!input || typeof input !== 'object') {
throw new BlkPatchError(`${where}: invalid BLK value`);
}
const { type, value } = input;
switch (type) {
case 'string':
if (typeof value !== 'string') throw new BlkPatchError(`${where}: string value expected`);
return { type: 'string', value };
case 'bool':
if (typeof value !== 'boolean') throw new BlkPatchError(`${where}: bool value expected`);
return { type: 'bool', value };
case 'int':
if (typeof value !== 'number' || !Number.isInteger(value)) throw new BlkPatchError(`${where}: int value expected`);
return { type: 'int', value: value | 0 };
case 'real':
if (typeof value !== 'number' || !Number.isFinite(value)) throw new BlkPatchError(`${where}: real value expected`);
return { type: 'real', value };
case 'int64':
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
return { type: 'int64', value: BigInt(value) };
}
throw new BlkPatchError(`${where}: int64 value expected`);
case 'color':
if (typeof value === 'number' && Number.isInteger(value)) return { type: 'color', value: value >>> 0 };
if (Array.isArray(value) && value.length === 4 && value.every((n) => typeof n === 'number')) {
const [r, g, b, a] = value as [number, number, number, number];
return { type: 'color', value: (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0 };
}
throw new BlkPatchError(`${where}: color expects integer or [r,g,b,a]`);
case 'point2': return { type: 'point2', value: expectNumberTuple(value, 2, false, where) as [number, number] };
case 'point3': return { type: 'point3', value: expectNumberTuple(value, 3, false, where) as [number, number, number] };
case 'point4': return { type: 'point4', value: expectNumberTuple(value, 4, false, where) as [number, number, number, number] };
case 'ipoint2': return { type: 'ipoint2', value: expectNumberTuple(value, 2, true, where) as [number, number] };
case 'ipoint3': return { type: 'ipoint3', value: expectNumberTuple(value, 3, true, where) as [number, number, number] };
case 'ipoint4': return { type: 'ipoint4', value: expectNumberTuple(value, 4, true, where) as [number, number, number, number] };
case 'matrix': return { type: 'matrix', value: expectNumberTuple(value, 12, false, where) };
default:
throw new BlkPatchError(`${where}: unsupported BLK type "${String(type)}"`);
}
}
function expectNumberTuple(raw: unknown, length: number, integerOnly: boolean, where: string): number[] {
if (!Array.isArray(raw) || raw.length !== length) {
throw new BlkPatchError(`${where}: expected array of ${length} numbers`);
}
return raw.map((item) => {
if (typeof item !== 'number' || !Number.isFinite(item) || (integerOnly && !Number.isInteger(item))) {
throw new BlkPatchError(`${where}: invalid numeric element in tuple`);
}
return integerOnly ? (item | 0) : item;
});
}
function paramValueMatchesPrimitive(value: BlkValue, expected: string | number | boolean): boolean {
if (typeof expected === 'string') return value.type === 'string' && value.value === expected;
if (typeof expected === 'boolean') return value.type === 'bool' && value.value === expected;
return (value.type === 'int' || value.type === 'real') && value.value === expected;
}
function validateOp(raw: unknown, where: string): BlkPatchOp {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new BlkPatchError(`${where}: operation must be an object`);
}
const obj = raw as Record<string, unknown>;
const op = obj.op;
switch (op) {
case 'setParam':
case 'addParam':
return {
op,
path: expectStringArray(obj.path ?? [], `${where}.path`),
name: expectNonEmptyString(obj.name, `${where}.name`),
value: obj.value as BlkPatchValueInput,
...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}),
};
case 'removeParam':
return {
op,
path: expectStringArray(obj.path ?? [], `${where}.path`),
name: expectNonEmptyString(obj.name, `${where}.name`),
...(typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean'
? { value: obj.value }
: {}),
};
case 'upsertBlock':
return {
op,
path: expectStringArray(obj.path, `${where}.path`),
...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}),
};
case 'addBlock':
return {
op,
path: expectStringArray(obj.path ?? [], `${where}.path`),
name: expectNonEmptyString(obj.name, `${where}.name`),
...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}),
...(typeof obj.before === 'string' ? { before: obj.before } : {}),
...(typeof obj.after === 'string' ? { after: obj.after } : {}),
...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}),
};
case 'removeBlock':
return {
op,
path: expectStringArray(obj.path, `${where}.path`),
};
case 'cloneBlock':
return {
op,
from: expectStringArray(obj.from, `${where}.from`),
toParent: expectStringArray(obj.toParent ?? [], `${where}.toParent`),
newName: expectNonEmptyString(obj.newName, `${where}.newName`),
...(typeof obj.replaceExisting === 'boolean' ? { replaceExisting: obj.replaceExisting } : {}),
...(typeof obj.before === 'string' ? { before: obj.before } : {}),
...(typeof obj.after === 'string' ? { after: obj.after } : {}),
...(Array.isArray(obj.ops)
? { ops: obj.ops.map((nested, idx) => validateOp(nested, `${where}.ops[${idx}]`)) }
: {}),
};
default:
throw new BlkPatchError(`${where}: unsupported op "${String(op)}"`);
}
}
function validateBlueprint(raw: unknown, where: string): BlkBlockBlueprint {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
throw new BlkPatchError(`${where}: block blueprint must be an object`);
}
const obj = raw as Record<string, unknown>;
const name = obj.name === undefined ? undefined : expectNonEmptyString(obj.name, `${where}.name`);
const params = obj.params === undefined ? undefined : expectParamList(obj.params, `${where}.params`);
const blocks = obj.blocks === undefined
? undefined
: (Array.isArray(obj.blocks)
? obj.blocks.map((child, idx) => validateBlueprint(child, `${where}.blocks[${idx}]`))
: (() => { throw new BlkPatchError(`${where}.blocks: must be an array`); })());
return {
...(name !== undefined ? { name } : {}),
...(params !== undefined ? { params } : {}),
...(blocks !== undefined ? { blocks } : {}),
};
}
function expectParamList(raw: unknown, where: string): Array<{ readonly name: string; readonly value: BlkPatchValueInput }> {
if (!Array.isArray(raw)) throw new BlkPatchError(`${where}: must be an array`);
return raw.map((item, idx) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
throw new BlkPatchError(`${where}[${idx}]: expected { name, value }`);
}
const entry = item as Record<string, unknown>;
return {
name: expectNonEmptyString(entry.name, `${where}[${idx}].name`),
value: entry.value as BlkPatchValueInput,
};
});
}
function expectStringArray(raw: unknown, where: string): string[] {
if (!Array.isArray(raw) || raw.some((item) => typeof item !== 'string' || item.length === 0)) {
throw new BlkPatchError(`${where}: must be an array of non-empty strings`);
}
return raw as string[];
}
function expectNonEmptyString(raw: unknown, where: string): string {
if (typeof raw !== 'string' || raw.length === 0) {
throw new BlkPatchError(`${where}: must be a non-empty string`);
}
return raw;
}
+140
View File
@@ -0,0 +1,140 @@
/**
* Incremental semicolon-separated localization CSV merger for `lang.vromfs.bin` (`*.csv.patch.csv`).
*
* Keeps the stock file's column layout and quoting conventions while merging matching row keys
* (column 0) and appending new entries from each enabled mod in load order.
*/
export function mergeLocalizationCsv(baseCsv: string, patchCsv: string): string {
const hasBom = baseCsv.startsWith('\uFEFF');
const newline = baseCsv.includes('\r\n') ? '\r\n' : '\n';
const cleanBase = hasBom ? baseCsv.slice(1) : baseCsv;
const cleanPatch = patchCsv.startsWith('\uFEFF') ? patchCsv.slice(1) : patchCsv;
const baseLines = splitCsvLines(cleanBase);
const patchLines = splitCsvLines(cleanPatch);
if (baseLines.length === 0 || patchLines.length <= 1) return baseCsv;
const baseHeader = parseSemicolonRow(baseLines[0]!);
const patchHeader = parseSemicolonRow(patchLines[0]!);
const baseColIndex = new Map<string, number>();
baseHeader.forEach((name, idx) => baseColIndex.set(name.trim(), idx));
const colMapping: Array<{ readonly patchIdx: number; readonly baseIdx: number }> = [];
for (let pIdx = 1; pIdx < patchHeader.length; pIdx += 1) {
const colName = patchHeader[pIdx]!.trim();
const bIdx = baseColIndex.get(colName);
if (bIdx !== undefined) colMapping.push({ patchIdx: pIdx, baseIdx: bIdx });
}
if (colMapping.length === 0) return baseCsv;
// Map existing key -> line index in baseLines for fast in-place updates.
const rowIndexByKey = new Map<string, number>();
for (let i = 1; i < baseLines.length; i += 1) {
const line = baseLines[i]!;
if (!line.trim()) continue;
const key = firstField(line);
if (key) rowIndexByKey.set(key, i);
}
const outLines = [...baseLines];
const trailingBlank = outLines.length > 0 && outLines[outLines.length - 1] === '';
if (trailingBlank) outLines.pop();
for (let i = 1; i < patchLines.length; i += 1) {
const line = patchLines[i]!;
if (!line.trim()) continue;
const patchCols = parseSemicolonRow(line);
const key = patchCols[0] ?? '';
if (!key) continue;
const existingIdx = rowIndexByKey.get(key);
if (existingIdx !== undefined) {
const merged = parseSemicolonRow(outLines[existingIdx]!);
while (merged.length < baseHeader.length) merged.push('');
for (const { patchIdx, baseIdx } of colMapping) {
const replacement = patchCols[patchIdx];
if (replacement !== undefined && replacement !== '') merged[baseIdx] = replacement;
}
outLines[existingIdx] = formatSemicolonRow(merged);
} else {
const created = new Array<string>(baseHeader.length).fill('');
created[0] = key;
for (const { patchIdx, baseIdx } of colMapping) {
const val = patchCols[patchIdx];
if (val !== undefined) created[baseIdx] = val;
}
rowIndexByKey.set(key, outLines.length);
outLines.push(formatSemicolonRow(created));
}
}
const result = outLines.join(newline) + (trailingBlank ? newline : '');
return hasBom ? `\uFEFF${result}` : result;
}
function splitCsvLines(text: string): string[] {
// Handle quoted fields that may span multiple lines.
const lines: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < text.length; i += 1) {
const ch = text[i]!;
if (ch === '"') {
if (inQuotes && text[i + 1] === '"') {
current += '""';
i += 1;
} else {
inQuotes = !inQuotes;
current += ch;
}
continue;
}
if (!inQuotes && (ch === '\n' || (ch === '\r' && text[i + 1] === '\n'))) {
lines.push(current);
current = '';
if (ch === '\r') i += 1;
continue;
}
current += ch;
}
lines.push(current);
return lines;
}
function parseSemicolonRow(line: string): string[] {
const fields: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i]!;
if (ch === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
} else if (ch === ';' && !inQuotes) {
fields.push(current);
current = '';
} else {
current += ch;
}
}
fields.push(current);
return fields;
}
function firstField(line: string): string {
if (line.startsWith('"')) {
const cols = parseSemicolonRow(line);
return cols[0] ?? '';
}
const semi = line.indexOf(';');
return semi >= 0 ? line.slice(0, semi) : line;
}
function formatSemicolonRow(fields: readonly string[]): string {
return fields.map((field) => `"${field.replaceAll('"', '""')}"`).join(';');
}
+252
View File
@@ -0,0 +1,252 @@
/**
* Discover installed mods inside the global mods directory and inspect their capabilities
* (server tuning/script, client pack patches, GUI patches, declarative exe patches,
* 3D model addons, and optional companion files).
*/
import { existsSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { MOD_MANIFEST_FILE, readModManifest } from './manifest.ts';
import {
MODDABLE_CLIENT_PACKS,
type DiscoveredMod,
type ModContentSummary,
type ModDiscoveryError,
type ModDiscoveryResult,
type ModManifest,
type ModPackOperation,
type ModRiskBadge,
type ModdableClientPack,
} from './types.ts';
const DEFAULT_SERVER_ENTRIES = ['server/index.ts', 'server/index.mjs', 'server/index.js'] as const;
const DEFAULT_SERVER_TUNING_DIR = 'server/tuning';
const BLK_PATCH_SUFFIX = '.patch.jsonc';
const CSV_PATCH_SUFFIX = '.patch.csv';
const CONFIG_BLK_PATCH_PATH = 'client/config-blk.patch.jsonc';
export function discoverMods(modsRootDir: string): ModDiscoveryResult {
if (!existsSync(modsRootDir)) return { mods: [], errors: [] };
const mods: DiscoveredMod[] = [];
const errors: ModDiscoveryError[] = [];
const seenIds = new Map<string, string>();
let entries;
try {
entries = readdirSync(modsRootDir, { withFileTypes: true });
} catch (error) {
return {
mods: [],
errors: [{ folderName: '.', rootDir: modsRootDir, reason: error instanceof Error ? error.message : String(error) }],
};
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const rootDir = join(modsRootDir, entry.name);
if (!existsSync(join(rootDir, MOD_MANIFEST_FILE))) continue;
try {
const manifest = readModManifest(rootDir);
const duplicateFolder = seenIds.get(manifest.id);
if (duplicateFolder) {
errors.push({
folderName: entry.name,
rootDir,
reason: `duplicate mod id "${manifest.id}" (already provided by folder "${duplicateFolder}")`,
});
continue;
}
seenIds.set(manifest.id, entry.name);
const content = inspectModContent(rootDir, manifest);
mods.push({ folderName: entry.name, rootDir, manifest, content });
} catch (error) {
errors.push({
folderName: entry.name,
rootDir,
reason: error instanceof Error ? error.message : String(error),
});
}
}
mods.sort((left, right) => left.manifest.id.localeCompare(right.manifest.id));
errors.sort((left, right) => left.folderName.localeCompare(right.folderName));
return { mods, errors };
}
export function inspectModContent(rootDir: string, manifest: ModManifest): ModContentSummary {
const serverEntry = resolveServerEntry(rootDir, manifest);
const tuningDirRel = manifest.server?.tuning ?? DEFAULT_SERVER_TUNING_DIR;
const serverTuningFiles = listTuningFiles(rootDir, tuningDirRel);
const packOperations = scanClientPackOperations(rootDir);
const guiPatchDirs = scanPatchDirectories(rootDir, 'client/gui-patches');
const exePatchDirs = scanPatchDirectories(rootDir, 'client/exe-patches');
const addonDir = join(rootDir, 'client', 'addon');
const addonRelativeFiles = existsSync(addonDir) && isDirectory(addonDir)
? listRelativeFiles(addonDir)
: [];
const hasClientAddon = addonRelativeFiles.length > 0;
const addonHasGrpHdr = addonRelativeFiles.some((file) => file.toLowerCase() === 'res/grp_hdr.vromfs.bin');
const filesDir = join(rootDir, 'client', 'files');
const clientFiles = existsSync(filesDir) && isDirectory(filesDir)
? listRelativeFiles(filesDir)
: [];
const configBlkPatch = isFile(join(rootDir, ...CONFIG_BLK_PATCH_PATH.split('/')))
? CONFIG_BLK_PATCH_PATH
: undefined;
const badges = computeRiskBadges({
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined,
hasGui: guiPatchDirs.length > 0,
hasScript: serverEntry !== undefined,
hasExe: exePatchDirs.length > 0,
});
return {
...(serverEntry !== undefined ? { serverEntry } : {}),
serverTuningFiles,
packOperations,
guiPatchDirs,
exePatchDirs,
hasClientAddon,
addonHasGrpHdr,
addonRelativeFiles,
clientFiles,
...(configBlkPatch !== undefined ? { configBlkPatch } : {}),
badges,
};
}
function resolveServerEntry(rootDir: string, manifest: ModManifest): string | undefined {
if (manifest.server?.entry) {
const full = join(rootDir, ...manifest.server.entry.split('/'));
if (!isFile(full)) {
throw new Error(`declared server.entry "${manifest.server.entry}" does not exist`);
}
return manifest.server.entry;
}
for (const candidate of DEFAULT_SERVER_ENTRIES) {
if (isFile(join(rootDir, ...candidate.split('/')))) return candidate;
}
return undefined;
}
function listTuningFiles(rootDir: string, tuningDirRel: string): string[] {
const dir = join(rootDir, ...tuningDirRel.split('/'));
if (!isDirectory(dir)) return [];
return readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonc'))
.map((entry) => entry.name.slice(0, -'.jsonc'.length))
.sort();
}
function scanClientPackOperations(rootDir: string): ModPackOperation[] {
const packsRoot = join(rootDir, 'client', 'packs');
if (!isDirectory(packsRoot)) return [];
const ops: ModPackOperation[] = [];
for (const pack of MODDABLE_CLIENT_PACKS) {
const packDir = join(packsRoot, ...pack.split('/'));
if (!isDirectory(packDir)) continue;
for (const rel of listRelativeFiles(packDir)) {
const sourceRelativePath = `client/packs/${pack}/${rel}`;
if (rel.toLowerCase().endsWith(BLK_PATCH_SUFFIX)) {
ops.push({
pack,
targetPath: rel.slice(0, -BLK_PATCH_SUFFIX.length),
action: 'blk-patch',
sourceRelativePath,
});
} else if (rel.toLowerCase().endsWith(CSV_PATCH_SUFFIX)) {
ops.push({
pack,
targetPath: rel.slice(0, -CSV_PATCH_SUFFIX.length),
action: 'csv-patch',
sourceRelativePath,
});
} else {
ops.push({
pack,
targetPath: rel,
action: 'file',
sourceRelativePath,
});
}
}
}
return ops;
}
function scanPatchDirectories(rootDir: string, subPath: string): string[] {
const base = join(rootDir, ...subPath.split('/'));
if (!isDirectory(base)) return [];
const results: string[] = [];
const walk = (current: string) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const full = join(current, entry.name);
if (isFile(join(full, 'patch.jsonc'))) {
results.push(relative(rootDir, full).replaceAll('\\', '/'));
} else {
walk(full);
}
}
};
walk(base);
return results.sort();
}
function listRelativeFiles(dir: string): string[] {
const out: string[] = [];
const walk = (current: string) => {
for (const entry of readdirSync(current, { withFileTypes: true })) {
const full = join(current, entry.name);
if (entry.isDirectory()) walk(full);
else if (entry.isFile()) out.push(relative(dir, full).replaceAll('\\', '/'));
}
};
walk(dir);
return out.sort();
}
function computeRiskBadges(flags: {
readonly hasData: boolean;
readonly hasGui: boolean;
readonly hasScript: boolean;
readonly hasExe: boolean;
}): ModRiskBadge[] {
const badges: ModRiskBadge[] = [];
if (flags.hasData || (!flags.hasGui && !flags.hasScript && !flags.hasExe)) badges.push('data');
if (flags.hasGui) badges.push('gui');
if (flags.hasScript) badges.push('script');
if (flags.hasExe) badges.push('exe');
return badges;
}
function isFile(path: string): boolean {
try {
return statSync(path).isFile();
} catch {
return false;
}
}
function isDirectory(path: string): boolean {
try {
return statSync(path).isDirectory();
} catch {
return false;
}
}
export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClientPack[] {
const set = new Set<ModdableClientPack>();
for (const mod of mods) {
for (const op of mod.content.packOperations) set.add(op.pack);
if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin');
if (mod.content.hasClientAddon) set.add('aces.vromfs.bin');
}
return MODDABLE_CLIENT_PACKS.filter((pack) => set.has(pack));
}
+79
View File
@@ -0,0 +1,79 @@
/**
* Shared additive mod system core: manifest parsing, mod discovery, load-order & conflict
* resolution, type-preserving BLK incremental patching, localization CSV merging, multi-layer
* tuning `$listOps` merging, and experimental server mod contracts.
*/
export {
MOD_API_VERSION,
MOD_FORMAT_VERSION,
MODDABLE_CLIENT_PACKS,
resolveLocalizedText,
type ClientModsConfig,
type DiscoveredMod,
type LocalizedText,
type ModContentSummary,
type ModDiscoveryError,
type ModDiscoveryResult,
type ModIssue,
type ModIssueKind,
type ModIssueSeverity,
type ModManifest,
type ModPackOperation,
type ModPreset,
type ModRiskBadge,
type ModServerConfig,
type ModdableClientPack,
type PackFileAction,
type ResolvedModLoadOrder,
} from './types.ts';
export {
MOD_MANIFEST_FILE,
ModManifestError,
expectSafeRelativePath,
parseModManifest,
readModManifest,
} from './manifest.ts';
export { discoverMods, inspectModContent, touchedClientPacks } from './discovery.ts';
export {
computeAutoSortOrder,
emptyClientModsConfig,
matchesVersionPattern,
normalizeClientModsConfig,
resolveModLoadOrder,
} from './resolve.ts';
export {
BlkPatchError,
applyBlkPatch,
parseBlkPatchDocument,
type BlkBlockBlueprint,
type BlkPatchDocument,
type BlkPatchOp,
type BlkPatchValueInput,
type BlkPathStep,
} from './blk-patch.ts';
export { mergeLocalizationCsv } from './csv-patch.ts';
export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts';
export type {
BattleLiveFactContext,
BattleMatchmakeContext,
BattleSettlementContext,
ModCharHandler,
ModCharRequest,
ModCharResponse,
ModCharWrapper,
ModHttpHandler,
ModHttpRequest,
ModHttpResponse,
ModLogger,
ModMatchingHandler,
ModMatchingRequest,
ModMatchingWrapper,
ModPlayerStorage,
ModStorageApi,
ServerModCataloguesView,
ServerModDatasetsView,
ServerModHooksApi,
ServerModRoutesApi,
WtoServerMod,
WtoServerModContext,
} from './server-api.ts';
+159
View File
@@ -0,0 +1,159 @@
/**
* Parse and validate `mod.jsonc` manifests.
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc';
import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts';
export const MOD_MANIFEST_FILE = 'mod.jsonc';
const MOD_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const ALLOWED_ROOT_KEYS = new Set([
'format',
'id',
'name',
'version',
'author',
'description',
'api_version',
'game_versions',
'requires',
'conflicts',
'load_after',
'load_before',
'server',
]);
const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']);
export class ModManifestError extends Error {
override name = 'ModManifestError';
}
export function readModManifest(modDir: string): ModManifest {
const filePath = join(modDir, MOD_MANIFEST_FILE);
let raw: unknown;
try {
raw = parseJsonc(readFileSync(filePath, 'utf8'));
} catch (error) {
throw new ModManifestError(`cannot parse ${MOD_MANIFEST_FILE}: ${error instanceof Error ? error.message : String(error)}`);
}
return parseModManifest(raw, filePath);
}
export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModManifest {
const obj = expectObject(raw, where);
rejectUnknownKeys(obj, ALLOWED_ROOT_KEYS, where);
if (obj.format !== MOD_FORMAT_VERSION) {
throw new ModManifestError(`${where}: "format" must be ${MOD_FORMAT_VERSION}`);
}
const id = expectString(obj.id, `${where} "id"`);
if (!MOD_ID_PATTERN.test(id)) {
throw new ModManifestError(`${where}: "id" must match ${MOD_ID_PATTERN.source} (got "${id}")`);
}
const name = expectLocalizedText(obj.name, `${where} "name"`);
const version = expectString(obj.version, `${where} "version"`);
const author = expectString(obj.author, `${where} "author"`);
const description = obj.description === undefined ? undefined : expectLocalizedText(obj.description, `${where} "description"`);
const apiVersion = expectString(obj.api_version, `${where} "api_version"`);
const gameVersions = optionalStringList(obj.game_versions, `${where} "game_versions"`);
const requires = optionalIdList(obj.requires, `${where} "requires"`, id);
const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id);
const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id);
const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id);
const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`);
return {
format: MOD_FORMAT_VERSION,
id,
name,
version,
author,
...(description !== undefined ? { description } : {}),
apiVersion,
gameVersions,
requires,
conflicts,
loadAfter,
loadBefore,
...(server !== undefined ? { server } : {}),
};
}
function parseServerConfig(raw: unknown, where: string): ModServerConfig {
const obj = expectObject(raw, where);
rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where);
const entry = obj.entry === undefined ? undefined : expectSafeRelativePath(obj.entry, `${where} "entry"`);
const tuning = obj.tuning === undefined ? undefined : expectSafeRelativePath(obj.tuning, `${where} "tuning"`);
return {
...(entry !== undefined ? { entry } : {}),
...(tuning !== undefined ? { tuning } : {}),
};
}
export function expectSafeRelativePath(raw: unknown, where: string): string {
const text = expectString(raw, where).replaceAll('\\', '/');
if (text.startsWith('/') || /^[A-Za-z]:/.test(text)) {
throw new ModManifestError(`${where}: path must be relative to the mod folder (got "${text}")`);
}
const segments = text.split('/').filter((segment) => segment.length > 0);
if (segments.length === 0 || segments.some((segment) => segment === '.' || segment === '..')) {
throw new ModManifestError(`${where}: path must not contain "." or ".." segments (got "${text}")`);
}
return segments.join('/');
}
function expectObject(value: unknown, where: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new ModManifestError(`${where}: expected an object`);
}
return value as Record<string, unknown>;
}
function rejectUnknownKeys(obj: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
const unknown = Object.keys(obj).filter((key) => !allowed.has(key));
if (unknown.length > 0) {
throw new ModManifestError(`${where}: unknown field(s): ${unknown.join(', ')}`);
}
}
function expectString(value: unknown, where: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new ModManifestError(`${where}: must be a non-empty string`);
}
return value.trim();
}
function expectLocalizedText(value: unknown, where: string): LocalizedText {
if (typeof value === 'string') {
if (value.trim().length === 0) throw new ModManifestError(`${where}: must not be empty`);
return value.trim();
}
const obj = expectObject(value, where);
const entries = Object.entries(obj);
if (entries.length === 0) throw new ModManifestError(`${where}: localized map must not be empty`);
const out: Record<string, string> = {};
for (const [lang, text] of entries) {
out[lang] = expectString(text, `${where}.${lang}`);
}
return out;
}
function optionalStringList(value: unknown, where: string): readonly string[] {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new ModManifestError(`${where}: must be an array of strings`);
return value.map((item, index) => expectString(item, `${where}[${index}]`));
}
function optionalIdList(value: unknown, where: string, selfId: string): readonly string[] {
const ids = optionalStringList(value, where);
const seen = new Set<string>();
for (const id of ids) {
if (!MOD_ID_PATTERN.test(id)) throw new ModManifestError(`${where}: invalid mod id "${id}"`);
if (id === selfId) throw new ModManifestError(`${where}: mod cannot reference itself ("${id}")`);
if (seen.has(id)) throw new ModManifestError(`${where}: duplicate mod id "${id}"`);
seen.add(id);
}
return ids;
}
+333
View File
@@ -0,0 +1,333 @@
/**
* Resolve effective mod load order, check dependencies/conflicts/version compatibility,
* detect overlapping pack or companion file targets, and offer topological auto-sorting.
*/
import {
MOD_API_VERSION,
type ClientModsConfig,
type DiscoveredMod,
type ModIssue,
type ResolvedModLoadOrder,
} from './types.ts';
export function emptyClientModsConfig(): ClientModsConfig {
return {
format: 1,
order: [],
enabled: {},
activePresetId: null,
presets: [],
};
}
/**
* Reconcile a saved client config with the currently discovered mods:
* keep saved order for known mods, append newly discovered mods alphabetically (disabled by default),
* and drop removed mod ids from the active ordering without destroying saved presets.
*/
export function normalizeClientModsConfig(
config: ClientModsConfig,
discovered: readonly DiscoveredMod[],
): ClientModsConfig {
const knownIds = new Set(discovered.map((mod) => mod.manifest.id));
const seen = new Set<string>();
const order: string[] = [];
for (const id of config.order) {
if (knownIds.has(id) && !seen.has(id)) {
seen.add(id);
order.push(id);
}
}
for (const mod of discovered) {
if (!seen.has(mod.manifest.id)) {
seen.add(mod.manifest.id);
order.push(mod.manifest.id);
}
}
const enabled: Record<string, boolean> = {};
for (const id of order) {
enabled[id] = config.enabled[id] === true;
}
return {
format: 1,
order,
enabled,
activePresetId: config.activePresetId,
presets: config.presets,
};
}
export function resolveModLoadOrder(
discovered: readonly DiscoveredMod[],
config: Pick<ClientModsConfig, 'order' | 'enabled'>,
gameVersion?: string | null,
): ResolvedModLoadOrder {
const byId = new Map(discovered.map((mod) => [mod.manifest.id, mod]));
const orderedIds: string[] = [];
const seen = new Set<string>();
for (const id of config.order) {
if (byId.has(id) && !seen.has(id)) {
seen.add(id);
orderedIds.push(id);
}
}
for (const mod of discovered) {
if (!seen.has(mod.manifest.id)) {
seen.add(mod.manifest.id);
orderedIds.push(mod.manifest.id);
}
}
const enabledMods = orderedIds
.filter((id) => config.enabled[id] === true)
.map((id) => byId.get(id)!);
const enabledIndex = new Map(enabledMods.map((mod, index) => [mod.manifest.id, index]));
const issues: ModIssue[] = [];
for (const mod of enabledMods) {
const id = mod.manifest.id;
const pos = enabledIndex.get(id)!;
if (mod.manifest.apiVersion !== MOD_API_VERSION) {
issues.push({
severity: 'warning',
kind: 'api-version-mismatch',
modId: id,
detail: `mod targets api_version "${mod.manifest.apiVersion}", current experimental API is "${MOD_API_VERSION}"`,
});
}
if (gameVersion && mod.manifest.gameVersions.length > 0 && !matchesAnyVersionPattern(gameVersion, mod.manifest.gameVersions)) {
issues.push({
severity: 'warning',
kind: 'game-version-mismatch',
modId: id,
detail: `mod lists game_versions [${mod.manifest.gameVersions.join(', ')}], client is ${gameVersion}`,
});
}
for (const reqId of mod.manifest.requires) {
if (!byId.has(reqId)) {
issues.push({
severity: 'error',
kind: 'missing-dependency',
modId: id,
otherModId: reqId,
detail: `requires missing mod "${reqId}"`,
});
} else if (!enabledIndex.has(reqId)) {
issues.push({
severity: 'error',
kind: 'dependency-disabled',
modId: id,
otherModId: reqId,
detail: `requires disabled mod "${reqId}"`,
});
} else if (enabledIndex.get(reqId)! > pos) {
issues.push({
severity: 'warning',
kind: 'dependency-order',
modId: id,
otherModId: reqId,
detail: `loaded before required dependency "${reqId}"`,
});
}
}
for (const conflictId of mod.manifest.conflicts) {
if (enabledIndex.has(conflictId) && id < conflictId) {
issues.push({
severity: 'error',
kind: 'declared-conflict',
modId: id,
otherModId: conflictId,
detail: `declares incompatibility with "${conflictId}"`,
});
}
}
for (const afterId of mod.manifest.loadAfter) {
const otherPos = enabledIndex.get(afterId);
if (otherPos !== undefined && otherPos > pos) {
issues.push({
severity: 'warning',
kind: 'load-order-hint',
modId: id,
otherModId: afterId,
detail: `recommends loading after "${afterId}"`,
});
}
}
for (const beforeId of mod.manifest.loadBefore) {
const otherPos = enabledIndex.get(beforeId);
if (otherPos !== undefined && otherPos < pos) {
issues.push({
severity: 'warning',
kind: 'load-order-hint',
modId: id,
otherModId: beforeId,
detail: `recommends loading before "${beforeId}"`,
});
}
}
}
detectTargetOverlaps(enabledMods, issues);
return {
enabledMods,
issues,
hasBlockingErrors: issues.some((issue) => issue.severity === 'error'),
};
}
/**
* Topologically sort mods using `requires`, `load_after`, and `load_before` constraints.
* Falls back gracefully to existing relative order when cycles exist.
*/
export function computeAutoSortOrder(
discovered: readonly DiscoveredMod[],
currentOrder: readonly string[],
): string[] {
const rank = new Map<string, number>();
currentOrder.forEach((id, index) => rank.set(id, index));
const ids = discovered.map((mod) => mod.manifest.id);
const idSet = new Set(ids);
const edges = new Map<string, Set<string>>(ids.map((id) => [id, new Set()]));
const inDegree = new Map<string, number>(ids.map((id) => [id, 0]));
const addEdge = (before: string, after: string) => {
if (!idSet.has(before) || !idSet.has(after) || before === after) return;
const outgoing = edges.get(before)!;
if (!outgoing.has(after)) {
outgoing.add(after);
inDegree.set(after, (inDegree.get(after) ?? 0) + 1);
}
};
for (const mod of discovered) {
const id = mod.manifest.id;
for (const req of mod.manifest.requires) addEdge(req, id);
for (const after of mod.manifest.loadAfter) addEdge(after, id);
for (const before of mod.manifest.loadBefore) addEdge(id, before);
}
const comparePriority = (a: string, b: string) => {
const ra = rank.get(a) ?? Number.MAX_SAFE_INTEGER;
const rb = rank.get(b) ?? Number.MAX_SAFE_INTEGER;
return ra !== rb ? ra - rb : a.localeCompare(b);
};
const ready = ids.filter((id) => (inDegree.get(id) ?? 0) === 0).sort(comparePriority);
const result: string[] = [];
while (ready.length > 0) {
const next = ready.shift()!;
result.push(next);
for (const target of edges.get(next)!) {
const deg = (inDegree.get(target) ?? 1) - 1;
inDegree.set(target, deg);
if (deg === 0) {
ready.push(target);
ready.sort(comparePriority);
}
}
}
if (result.length < ids.length) {
const placed = new Set(result);
const remaining = ids.filter((id) => !placed.has(id)).sort(comparePriority);
result.push(...remaining);
}
return result;
}
function detectTargetOverlaps(enabledMods: readonly DiscoveredMod[], issues: ModIssue[]): void {
const packFiles = new Map<string, string>();
const packPatches = new Map<string, string>();
const companionFiles = new Map<string, string>();
const tuningFiles = new Map<string, string>();
for (const mod of enabledMods) {
const id = mod.manifest.id;
for (const op of mod.content.packOperations) {
const key = `${op.pack}:${op.targetPath.toLowerCase()}`;
if (op.action === 'file') {
const previous = packFiles.get(key) ?? packPatches.get(key);
if (previous && previous !== id) {
issues.push({
severity: 'warning',
kind: 'pack-file-override',
modId: id,
otherModId: previous,
detail: `replaces "${op.pack}/${op.targetPath}" already modified by "${previous}"`,
});
}
packFiles.set(key, id);
} else {
const previousFile = packFiles.get(key);
const previousPatch = packPatches.get(key);
if (previousFile && previousFile !== id) {
issues.push({
severity: 'info',
kind: 'pack-blk-shared-target',
modId: id,
otherModId: previousFile,
detail: `patches "${op.pack}/${op.targetPath}" after "${previousFile}"`,
});
} else if (previousPatch && previousPatch !== id) {
issues.push({
severity: 'info',
kind: 'pack-blk-shared-target',
modId: id,
otherModId: previousPatch,
detail: `merges into "${op.pack}/${op.targetPath}" after "${previousPatch}"`,
});
}
packPatches.set(key, id);
}
}
for (const file of mod.content.clientFiles) {
const key = file.toLowerCase();
const previous = companionFiles.get(key);
if (previous && previous !== id) {
issues.push({
severity: 'warning',
kind: 'client-file-conflict',
modId: id,
otherModId: previous,
detail: `companion file "${file}" overrides "${previous}"`,
});
}
companionFiles.set(key, id);
}
for (const tuning of mod.content.serverTuningFiles) {
const key = tuning.toLowerCase();
const previous = tuningFiles.get(key);
if (previous && previous !== id) {
issues.push({
severity: 'info',
kind: 'tuning-file-shared',
modId: id,
otherModId: previous,
detail: `merges server tuning "${tuning}.jsonc" after "${previous}"`,
});
}
tuningFiles.set(key, id);
}
}
}
export function matchesVersionPattern(version: string, pattern: string): boolean {
if (pattern === '*') return true;
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*');
return new RegExp(`^${escaped}$`).test(version);
}
function matchesAnyVersionPattern(version: string, patterns: readonly string[]): boolean {
return patterns.some((pattern) => matchesVersionPattern(version, pattern));
}
+184
View File
@@ -0,0 +1,184 @@
/**
* Public TypeScript contract for WTOffline server-side JS/TS mods.
*
* EXPERIMENTAL / UNSTABLE:
* WTOffline is in early development. Internal server types, dataset shapes, hook signatures,
* and route contracts may change without backwards compatibility across releases. Mod authors
* using server scripts should expect breaking changes and maintain compatibility with updates.
*/
import type { BlkBlock } from '@wto/blk';
import type { ModManifest } from './types.ts';
export interface ModLogger {
info(message: string): void;
warn(message: string): void;
error(message: string): void;
}
/** Per-account JSON storage isolated under `<dataFolder>/saves/<userId>/mods/<modId>.json`. */
export interface ModPlayerStorage {
read<T = unknown>(): T | undefined;
write(value: unknown): void;
remove(): void;
}
export interface ModStorageApi {
/** Storage scoped to one local player account (never mutates stock `profile.blk`). */
forPlayer(userId: string): ModPlayerStorage;
/** Shared mod storage under `<dataFolder>/mods-data/<modId>.json`. */
shared(): ModPlayerStorage;
}
/** Mutable snapshot of extracted static datasets exposed before domain catalogues are built. */
export interface ServerModDatasetsView {
readonly vehicles: unknown[];
readonly battleEconomy: Record<string, unknown>;
readonly battleSpawnRules: unknown;
readonly multiplayerMissions: unknown[];
readonly uiLabels: Record<string, unknown>;
readonly unitNames: Record<string, unknown>;
/** Escape hatch: read or replace any dataset object by its dataset id. */
get<T = unknown>(datasetId: string): T | undefined;
set(datasetId: string, value: unknown): void;
}
/** Exposed domain catalogues and services after server initialization. */
export interface ServerModCataloguesView {
readonly tuning: Readonly<Record<string, unknown>>;
readonly gameModes: unknown;
readonly profiles: unknown;
readonly accounts: unknown;
readonly research: unknown;
readonly equipment: unknown;
readonly repair: unknown;
readonly store: unknown;
readonly inventory: unknown;
readonly trophies: unknown;
readonly items: unknown;
readonly crew: unknown;
readonly decor: unknown;
readonly unlocks: unknown;
readonly clans: unknown;
readonly battleMatchmaker: unknown;
readonly battleEconomy: unknown;
readonly battleStreaks: unknown;
readonly notifyInventoryChanged: () => void;
readonly notifyUser: (userId: string, eventName: string, payload: Record<string, unknown>) => void;
}
export interface BattleMatchmakeContext {
readonly userId: string;
readonly eventName: string;
/** Mutable room / matchmake request parameters or generated launch plan. */
readonly request: Record<string, unknown>;
}
export interface BattleLiveFactContext {
readonly userId: string;
readonly roomId: string;
readonly fact: Record<string, unknown>;
}
export interface BattleSettlementContext {
readonly userId: string;
readonly roomId: string;
/** Mutable settlement payload before final rewards are committed to the profile. */
readonly summary: Record<string, unknown>;
}
export interface ModCharRequest {
readonly action: string;
readonly userId: string;
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: Buffer;
readonly query: Readonly<Record<string, string>>;
}
export interface ModCharResponse {
readonly status?: number;
readonly contentType?: string;
readonly headers?: Readonly<Record<string, string>>;
readonly body: Buffer | Uint8Array | string;
}
export type ModCharHandler = (request: ModCharRequest) => ModCharResponse | Promise<ModCharResponse>;
export type ModCharWrapper = (
request: ModCharRequest,
next: (request: ModCharRequest) => Promise<ModCharResponse>,
) => ModCharResponse | Promise<ModCharResponse>;
export interface ModMatchingRequest {
readonly method: string;
readonly params: Readonly<Record<string, unknown>>;
readonly userId: string | undefined;
}
export type ModMatchingHandler = (request: ModMatchingRequest) => Record<string, unknown>;
export type ModMatchingWrapper = (
request: ModMatchingRequest,
next: (request: ModMatchingRequest) => Record<string, unknown>,
) => Record<string, unknown>;
export interface ModHttpRequest {
readonly method: string;
readonly path: string;
readonly query: Readonly<Record<string, string>>;
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: Buffer;
}
export interface ModHttpResponse {
readonly status?: number;
readonly contentType?: string;
readonly headers?: Readonly<Record<string, string>>;
readonly body: Buffer | Uint8Array | string;
}
export type ModHttpHandler = (request: ModHttpRequest) => ModHttpResponse | Promise<ModHttpResponse>;
export interface ServerModHooksApi {
onDatasetsLoaded(handler: (datasets: ServerModDatasetsView) => void | Promise<void>): void;
onCataloguesReady(handler: (catalogues: ServerModCataloguesView) => void | Promise<void>): void;
onServerListening(handler: (info: { readonly port: number }) => void | Promise<void>): void;
onServerClosing(handler: () => void | Promise<void>): void;
readonly profile: {
onRefresh(handler: (profile: BlkBlock, userId: string) => void): void;
};
readonly battle: {
onBeforeMatchmake(handler: (ctx: BattleMatchmakeContext) => void): void;
onLiveFact(handler: (ctx: BattleLiveFactContext) => void): void;
onAfterSettle(handler: (ctx: BattleSettlementContext) => void): void;
};
}
export interface ServerModRoutesApi {
readonly char: {
register(action: string, handler: ModCharHandler): void;
wrap(action: string, wrapper: ModCharWrapper): void;
};
readonly matching: {
register(method: string, handler: ModMatchingHandler): void;
wrap(method: string, wrapper: ModMatchingWrapper): void;
};
readonly http: {
/** Register a route under `/mods/<modId>/...` (automatically namespaced to this mod). */
register(subPath: string, handler: ModHttpHandler): void;
};
}
export interface WtoServerModContext {
readonly apiVersion: string;
readonly manifest: ModManifest;
readonly modDir: string;
readonly gameFolder: string;
readonly dataFolder: string;
readonly port: number;
readonly logger: ModLogger;
readonly storage: ModStorageApi;
readonly hooks: ServerModHooksApi;
readonly routes: ServerModRoutesApi;
}
export interface WtoServerMod {
setup(ctx: WtoServerModContext): void | Promise<void>;
}
+77
View File
@@ -0,0 +1,77 @@
/**
* Multi-layer tuning merge helper with additive list operations (`$listOps`).
*
* Objects merge key-by-key. Plain arrays replace the base value (preserving existing player
* override behaviour). An object containing only `{ "$listOps": [...] }` applies incremental
* append/prepend/upsertBy/removeBy operations to the base array so multiple mods can add
* store packs, redeem codes, trophies, or preset clans without clobbering one another.
*/
export type TuningListOp =
| { readonly op: 'append'; readonly items: readonly unknown[] }
| { readonly op: 'prepend'; readonly items: readonly unknown[] }
| { readonly op: 'upsertBy'; readonly key: string; readonly item: Record<string, unknown> }
| { readonly op: 'removeBy'; readonly key: string; readonly value: unknown };
export function mergeTuningLayer(base: unknown, override: unknown): unknown {
if (isListOpsEnvelope(override)) {
const list = Array.isArray(base) ? [...base] : [];
return applyListOps(list, override.$listOps);
}
if (!isPlainObject(base) || !isPlainObject(override)) return override;
const merged: Record<string, unknown> = { ...base };
for (const [key, value] of Object.entries(override)) {
merged[key] = key in base ? mergeTuningLayer(base[key], value) : value;
}
return merged;
}
function applyListOps(base: unknown[], ops: readonly unknown[]): unknown[] {
const result = [...base];
for (const rawOp of ops) {
if (!isPlainObject(rawOp) || typeof rawOp.op !== 'string') {
throw new Error('invalid $listOps entry: expected object with string "op"');
}
switch (rawOp.op) {
case 'append':
if (!Array.isArray(rawOp.items)) throw new Error('$listOps append requires an "items" array');
result.push(...rawOp.items);
break;
case 'prepend':
if (!Array.isArray(rawOp.items)) throw new Error('$listOps prepend requires an "items" array');
result.unshift(...rawOp.items);
break;
case 'upsertBy': {
if (typeof rawOp.key !== 'string' || !isPlainObject(rawOp.item)) {
throw new Error('$listOps upsertBy requires string "key" and object "item"');
}
const matchValue = rawOp.item[rawOp.key];
const idx = result.findIndex((entry) => isPlainObject(entry) && entry[rawOp.key as string] === matchValue);
if (idx >= 0) result[idx] = mergeTuningLayer(result[idx], rawOp.item);
else result.push(rawOp.item);
break;
}
case 'removeBy': {
if (typeof rawOp.key !== 'string') throw new Error('$listOps removeBy requires string "key"');
for (let i = result.length - 1; i >= 0; i -= 1) {
const entry = result[i];
if (isPlainObject(entry) && entry[rawOp.key] === rawOp.value) result.splice(i, 1);
}
break;
}
default:
throw new Error(`unsupported $listOps operation "${rawOp.op}"`);
}
}
return result;
}
function isListOpsEnvelope(value: unknown): value is { readonly $listOps: readonly unknown[] } {
if (!isPlainObject(value)) return false;
const keys = Object.keys(value);
return keys.length === 1 && keys[0] === '$listOps' && Array.isArray(value.$listOps);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+154
View File
@@ -0,0 +1,154 @@
/**
* Shared types for the additive mod system.
*
* EXPERIMENTAL: Mod manifest fields, conflict structures, and runtime contracts are under active
* early development and may change without backwards compatibility.
*/
export const MOD_FORMAT_VERSION = 1;
export const MOD_API_VERSION = '0.1-experimental';
/** Supported client .vromfs.bin packs that mods may patch or add files to. */
export const MODDABLE_CLIENT_PACKS = [
'char.vromfs.bin',
'aces.vromfs.bin',
'gui.vromfs.bin',
'lang.vromfs.bin',
'mis.vromfs.bin',
'game.vromfs.bin',
'ui/atlases.vromfs.bin',
'ui/images.vromfs.bin',
] as const;
export type ModdableClientPack = (typeof MODDABLE_CLIENT_PACKS)[number];
export type LocalizedText = string | Readonly<Record<string, string>>;
export type ModRiskBadge = 'data' | 'gui' | 'script' | 'exe';
export interface ModServerConfig {
/** Relative path to the server script entry (.ts, .mjs, or .js), when present. */
readonly entry?: string;
/** Relative path to the server tuning override directory (defaults to "server/tuning"). */
readonly tuning?: string;
}
export interface ModManifest {
readonly format: 1;
readonly id: string;
readonly name: LocalizedText;
readonly version: string;
readonly author: string;
readonly description?: LocalizedText;
readonly apiVersion: string;
readonly gameVersions: readonly string[];
readonly requires: readonly string[];
readonly conflicts: readonly string[];
readonly loadAfter: readonly string[];
readonly loadBefore: readonly string[];
readonly server?: ModServerConfig;
}
export type PackFileAction = 'blk-patch' | 'csv-patch' | 'file';
export interface ModPackOperation {
readonly pack: ModdableClientPack;
/** Target path inside the pack (without .patch.jsonc / .patch.csv suffix). */
readonly targetPath: string;
readonly action: PackFileAction;
/** Path relative to the mod root folder. */
readonly sourceRelativePath: string;
}
export interface ModContentSummary {
readonly serverEntry?: string;
readonly serverTuningFiles: readonly string[];
readonly packOperations: readonly ModPackOperation[];
readonly guiPatchDirs: readonly string[];
readonly exePatchDirs: readonly string[];
readonly hasClientAddon: boolean;
/** True when client/addon includes a compiled res/grp_hdr.vromfs.bin index. */
readonly addonHasGrpHdr: boolean;
readonly addonRelativeFiles: readonly string[];
/** Relative paths under client/files (mapped into the game copy root). */
readonly clientFiles: readonly string[];
/** Optional relative path to client/config-blk.patch.jsonc. */
readonly configBlkPatch?: string;
readonly badges: readonly ModRiskBadge[];
}
export interface DiscoveredMod {
readonly folderName: string;
readonly rootDir: string;
readonly manifest: ModManifest;
readonly content: ModContentSummary;
}
export interface ModDiscoveryError {
readonly folderName: string;
readonly rootDir: string;
readonly reason: string;
}
export interface ModDiscoveryResult {
readonly mods: readonly DiscoveredMod[];
readonly errors: readonly ModDiscoveryError[];
}
export interface ModPreset {
readonly id: string;
readonly name: string;
readonly order: readonly string[];
readonly enabled: Readonly<Record<string, boolean>>;
readonly updatedAt: string;
}
export interface ClientModsConfig {
readonly format: 1;
readonly order: readonly string[];
readonly enabled: Readonly<Record<string, boolean>>;
readonly activePresetId: string | null;
readonly presets: readonly ModPreset[];
}
export type ModIssueSeverity = 'error' | 'warning' | 'info';
export type ModIssueKind =
| 'missing-dependency'
| 'dependency-disabled'
| 'dependency-order'
| 'declared-conflict'
| 'load-order-hint'
| 'game-version-mismatch'
| 'api-version-mismatch'
| 'pack-file-override'
| 'pack-blk-shared-target'
| 'client-file-conflict'
| 'tuning-file-shared';
export interface ModIssue {
readonly severity: ModIssueSeverity;
readonly kind: ModIssueKind;
readonly modId: string;
readonly otherModId?: string;
readonly detail: string;
}
export interface ResolvedModLoadOrder {
readonly enabledMods: readonly DiscoveredMod[];
readonly issues: readonly ModIssue[];
readonly hasBlockingErrors: boolean;
}
/** Pick the best localized display string for a mod field. */
export function resolveLocalizedText(value: LocalizedText, language: string): string {
if (typeof value === 'string') return value;
const exact = value[language];
if (exact) return exact;
const prefix = language.split('-')[0];
if (prefix) {
const partial = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
if (partial?.[1]) return partial[1];
}
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
}