feat(patcher): build a loopback client copy with TypeScript

Add the shared BLK, VROMFS, executable patch, and build packages. Preserve
typed fields and shared name tables when reading BLK data. Rewrite the
service endpoints in place so the original environment names remain
available to the client, then build the client copy.
This commit is contained in:
N0VAN0M4LY committed 2026-11-24 00:35:13 +08:00
1 parent 89aa5198c3
commit c3914ec0d6
44 files changed
+1986 -1

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
/** Sequential little-endian reader over a byte array, with the format's variable-length integers. */
import { BlkFormatError } from '../errors.ts';
export class ByteReader {
readonly bytes: Uint8Array;
offset = 0;
constructor(bytes: Uint8Array) {
this.bytes = bytes;
}
get remaining(): number {
return this.bytes.length - this.offset;
}
u8(): number {
this.require(1);
return this.bytes[this.offset++]!;
}
take(length: number): Uint8Array {
this.require(length);
const slice = this.bytes.subarray(this.offset, this.offset + length);
this.offset += length;
return slice;
}
/** Unsigned LEB128: 7 bits per byte, least significant group first, high bit = more bytes follow. */
varUint(): number {
let value = 0;
for (let shift = 0; shift < 35; shift += 7) {
const byte = this.u8();
value += (byte & 0x7f) * 2 ** shift;
if ((byte & 0x80) === 0) return value;
}
throw new BlkFormatError(`variable-length integer at offset ${this.offset} is too long`);
}
private require(length: number): void {
if (length > this.remaining) {
throw new BlkFormatError(`unexpected end of data: need ${length} bytes at offset ${this.offset}, have ${this.remaining}`);
}
}
}
+55
View File
@@ -0,0 +1,55 @@
/** Growable little-endian byte buffer, with the format's variable-length integers. */
export class ByteWriter {
private buffer = new Uint8Array(256);
private view = new DataView(this.buffer.buffer);
length = 0;
u8(value: number): void {
this.reserve(1);
this.buffer[this.length++] = value;
}
u32(value: number): void {
this.reserve(4);
this.view.setUint32(this.length, value >>> 0, true);
this.length += 4;
}
bytes(data: Uint8Array): void {
this.reserve(data.length);
this.buffer.set(data, this.length);
this.length += data.length;
}
/** Unsigned LEB128, see ByteReader.varUint. */
varUint(value: number): void {
if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) {
throw new RangeError(`cannot encode ${value} as an unsigned 32-bit integer`);
}
let rest = value;
do {
const group = rest % 0x80;
rest = Math.floor(rest / 0x80);
this.u8(rest > 0 ? group | 0x80 : group);
} while (rest > 0);
}
/** Pad with zero bytes until the length is a multiple of `alignment`. */
align(alignment: number): void {
while (this.length % alignment !== 0) this.u8(0);
}
toBytes(): Uint8Array {
return this.buffer.slice(0, this.length);
}
private reserve(extra: number): void {
if (this.length + extra <= this.buffer.length) return;
let capacity = this.buffer.length * 2;
while (capacity < this.length + extra) capacity *= 2;
const grown = new Uint8Array(capacity);
grown.set(this.buffer.subarray(0, this.length));
this.buffer = grown;
this.view = new DataView(grown.buffer);
}
}
+108
View File
@@ -0,0 +1,108 @@
/**
* Decode the body of a binary BLK (after the format label) into a block tree.
*
* Layout (DagorEngine blk_serialize.cpp, DataBlock::loadFromBinDump):
* name table this document's own names (name-table.ts)
* varUint block count
* varUint parameter count
* varUint complex-data size
* complex data strings and values too large to store inline
* parameter records 8 bytes each, every block's parameters in block order
* block records, one per block in breadth-first order (block 0 is the root):
* varUint name index + 1 0 for the root
* varUint parameter count
* varUint sub-block count
* varUint first sub-block only when the sub-block count is not 0
* varUint first parameter only in the deduplicated variant, and only with parameters
*
* Name indices count the shared name map (if any) first, then this document's own names.
*/
import type { BlkBlock, BlkParam } from '../model.ts';
import { BlkFormatError } from '../errors.ts';
import type { ByteReader } from './byte-reader.ts';
import { readNameTable } from './name-table.ts';
import { decodeValue, type DecodeContext } from './param-values.ts';
const PARAM_RECORD_SIZE = 8;
export interface DumpLayout {
/** Names from the data pack's shared name map; empty for a self-contained document. */
readonly sharedNames: readonly string[];
/** Block records carry an explicit first-parameter index. */
readonly deduplicated: boolean;
}
interface BlockRecord {
readonly nameIndex: number | null;
readonly firstParam: number;
readonly paramCount: number;
readonly firstBlock: number;
readonly blockCount: number;
}
export function decodeDump(reader: ByteReader, layout: DumpLayout): BlkBlock {
const names = [...layout.sharedNames, ...readNameTable(reader)];
const blockCount = reader.varUint();
const paramCount = reader.varUint();
const complexSize = reader.varUint();
if (blockCount === 0) throw new BlkFormatError('a BLK document has at least the root block');
const complex = reader.take(complexSize);
const params = decodeParams(reader.take(paramCount * PARAM_RECORD_SIZE), { names, complex });
const records = readBlockRecords(reader, blockCount, params.length, names.length, layout.deduplicated);
return assembleTree(records, params, names);
}
function decodeParams(records: Uint8Array, context: DecodeContext): BlkParam[] {
const view = new DataView(records.buffer, records.byteOffset, records.byteLength);
const params: BlkParam[] = [];
for (let offset = 0; offset < records.length; offset += PARAM_RECORD_SIZE) {
const header = view.getUint32(offset, true);
const nameIndex = header & 0xff_ffff;
const name = context.names[nameIndex];
if (name === undefined) {
throw new BlkFormatError(`parameter ${offset / PARAM_RECORD_SIZE} refers to name ${nameIndex}, table has ${context.names.length}`);
}
params.push({ name, value: decodeValue(header >>> 24, view.getUint32(offset + 4, true), context) });
}
return params;
}
function readBlockRecords(reader: ByteReader, blockCount: number, paramCount: number, nameCount: number,
deduplicated: boolean): BlockRecord[] {
const records: BlockRecord[] = [];
let nextFirstBlock = 1;
let nextParam = 0;
for (let index = 0; index < blockCount; index++) {
const nameIndexPlusOne = reader.varUint();
const ownParams = reader.varUint();
const ownBlocks = reader.varUint();
const firstBlock = ownBlocks ? reader.varUint() : 0;
const firstParam = deduplicated ? (ownParams ? reader.varUint() : 0) : nextParam;
if (nameIndexPlusOne > nameCount) throw new BlkFormatError(`block ${index} refers to name ${nameIndexPlusOne - 1}, table has ${nameCount}`);
if (ownBlocks && (firstBlock !== nextFirstBlock || firstBlock + ownBlocks > blockCount)) {
throw new BlkFormatError(`block ${index} has an inconsistent sub-block range`);
}
if (firstParam + ownParams > paramCount) throw new BlkFormatError(`block ${index} has an inconsistent parameter range`);
records.push({ nameIndex: nameIndexPlusOne ? nameIndexPlusOne - 1 : null, firstParam, paramCount: ownParams, firstBlock, blockCount: ownBlocks });
nextFirstBlock += ownBlocks;
if (!deduplicated) nextParam += ownParams;
}
if (nextFirstBlock !== blockCount) throw new BlkFormatError(`${blockCount - nextFirstBlock} block(s) are unreachable from the root`);
return records;
}
function assembleTree(records: readonly BlockRecord[], params: readonly BlkParam[], names: readonly string[]): BlkBlock {
const blocks: BlkBlock[] = records.map((record) => ({
name: record.nameIndex === null ? '' : names[record.nameIndex]!,
// copied so that blocks sharing a parameter run (deduplicated variant) can be edited independently
params: params.slice(record.firstParam, record.firstParam + record.paramCount).map((param) => ({ ...param })),
blocks: [],
}));
records.forEach((record, index) => {
blocks[index]!.blocks = blocks.slice(record.firstBlock, record.firstBlock + record.blockCount);
});
return blocks[0]!;
}
+104
View File
@@ -0,0 +1,104 @@
/**
* Encode a block tree as the body of a self-contained binary BLK (no shared name map,
* no deduplication). The layout is the one dump-decoder.ts reads; the order of work follows
* DagorEngine's DataBlock::saveToBinStreamWithoutNames: strings go into the complex-data
* area first, then, after aligning to 4 bytes, the other values too large to store inline.
*
* Every string value is stored in the complex-data area; the format also allows pointing
* at an equal entry of the name table, but nothing requires it.
*/
import type { BlkBlock, BlkParam } from '../model.ts';
import { BlkFormatError } from '../errors.ts';
import { typeByName } from '../param-types.ts';
import { ByteWriter } from './byte-writer.ts';
import { writeNameTable } from './name-table.ts';
import { appendComplex, appendString, encodeInline, storesInline } from './param-values.ts';
const MAX_NAMES = 0xff_ffff;
const MAX_CHILDREN = 0xffff;
export function encodeDump(writer: ByteWriter, root: BlkBlock): void {
const order = breadthFirst(root);
const params = order.flatMap((block) => block.params);
const names = collectNames(order, root);
const complex = new ByteWriter();
const values = encodeValues(params, complex);
writeNameTable(writer, names.list);
writer.varUint(order.length);
writer.varUint(params.length);
writer.varUint(complex.length);
writer.bytes(complex.toBytes());
params.forEach((param, index) => {
writer.u32(names.indexOf(param.name) + typeByName(param.value.type).id * 0x100_0000);
writer.u32(values[index]!);
});
let nextFirstBlock = 1;
for (const block of order) {
if (block.params.length > MAX_CHILDREN || block.blocks.length > MAX_CHILDREN) {
throw new BlkFormatError(`block "${block.name}" has more than ${MAX_CHILDREN} parameters or sub-blocks`);
}
writer.varUint(block === root ? 0 : names.indexOf(block.name) + 1);
writer.varUint(block.params.length);
writer.varUint(block.blocks.length);
if (block.blocks.length) {
writer.varUint(nextFirstBlock);
nextFirstBlock += block.blocks.length;
}
}
}
function breadthFirst(root: BlkBlock): BlkBlock[] {
const order = [root];
for (let index = 0; index < order.length; index++) order.push(...order[index]!.blocks);
return order;
}
function encodeValues(params: readonly BlkParam[], complex: ByteWriter): number[] {
const values = new Array<number>(params.length);
params.forEach((param, index) => {
if (param.value.type === 'string') values[index] = appendString(complex, param.value.value);
});
let aligned = false;
params.forEach((param, index) => {
if (param.value.type === 'string') return;
if (storesInline(param.value)) {
values[index] = encodeInline(param.value) >>> 0;
return;
}
if (!aligned) {
complex.align(4);
aligned = true;
}
values[index] = appendComplex(complex, param.value);
});
return values;
}
class NameIndex {
readonly list: string[] = [];
private readonly indices = new Map<string, number>();
add(name: string): void {
if (this.indices.has(name)) return;
if (this.list.length >= MAX_NAMES) throw new BlkFormatError(`more than ${MAX_NAMES} distinct names`);
this.indices.set(name, this.list.length);
this.list.push(name);
}
indexOf(name: string): number {
const index = this.indices.get(name);
if (index === undefined) throw new BlkFormatError(`name "${name}" was not collected`);
return index;
}
}
function collectNames(order: readonly BlkBlock[], root: BlkBlock): NameIndex {
const names = new NameIndex();
for (const block of order) {
if (block !== root) names.add(block.name);
for (const param of block.params) names.add(param.name);
}
return names;
}
+88
View File
@@ -0,0 +1,88 @@
/**
* The one-byte format label at the start of a binary BLK, and what follows it.
*
* Source: DagorEngine prog/engine/ioSys/dataBlock/blk_shared.h (dblk::BBF_*) and
* blk_parser.cpp (DataBlock::loadFromStream). Any other first byte means a text BLK,
* which this module does not read.
*/
import { zstdDecompressSync } from 'node:zlib';
import type { BlkBlock } from '../model.ts';
import { BlkFormatError } from '../errors.ts';
import { ByteReader } from './byte-reader.ts';
import { ByteWriter } from './byte-writer.ts';
import { decodeDump } from './dump-decoder.ts';
import { encodeDump } from './dump-encoder.ts';
export const BlkLabel = {
/** Self-contained: own name table, body follows uncompressed. */
SelfContained: 1,
/** 3-byte compressed size, then zstd of a SelfContained document (label included). */
SelfContainedZstd: 2,
/** Names come from the data pack's shared name map; body follows uncompressed. */
SharedNames: 3,
/** As SharedNames, body is zstd-compressed to the end of the file. */
SharedNamesZstd: 4,
/** As SharedNamesZstd, compressed with the data pack's zstd dictionary. */
SharedNamesZstdDictionary: 5,
/** As SelfContained, block records carry explicit parameter offsets. */
SelfContainedDeduplicated: 6,
} as const;
/** What a document stored with a shared name map needs from its data pack. */
export interface SharedNameContext {
readonly names: readonly string[];
/** The pack's zstd dictionary, needed only for SharedNamesZstdDictionary documents. */
readonly dictionary?: Uint8Array | undefined;
}
export function decodeBlk(bytes: Uint8Array, shared?: SharedNameContext): BlkBlock {
const reader = new ByteReader(bytes);
const label = reader.u8();
switch (label) {
case BlkLabel.SelfContained:
return decodeDump(reader, { sharedNames: [], deduplicated: false });
case BlkLabel.SelfContainedDeduplicated:
return decodeDump(reader, { sharedNames: [], deduplicated: true });
case BlkLabel.SelfContainedZstd: {
const size = reader.u8() | (reader.u8() << 8) | (reader.u8() << 16);
const inner = decompress(reader.take(size));
if (inner[0] !== BlkLabel.SelfContained) throw new BlkFormatError('compressed BLK does not contain a self-contained document');
return decodeBlk(inner);
}
case BlkLabel.SharedNames:
return decodeDump(reader, { sharedNames: requireShared(shared).names, deduplicated: false });
case BlkLabel.SharedNamesZstd: {
const names = requireShared(shared).names;
return decodeDump(new ByteReader(decompress(reader.take(reader.remaining))), { sharedNames: names, deduplicated: false });
}
case BlkLabel.SharedNamesZstdDictionary: {
const context = requireShared(shared);
if (!context.dictionary) throw new BlkFormatError('this BLK needs the data pack\'s zstd dictionary');
const body = decompress(reader.take(reader.remaining), context.dictionary);
return decodeDump(new ByteReader(body), { sharedNames: context.names, deduplicated: false });
}
default:
throw new BlkFormatError(`format label ${label} is not a binary BLK (text BLK is not supported)`);
}
}
/** Encode as a self-contained binary BLK, which the game accepts in every loading mode. */
export function encodeBlk(root: BlkBlock): Uint8Array {
const writer = new ByteWriter();
writer.u8(BlkLabel.SelfContained);
encodeDump(writer, root);
return writer.toBytes();
}
export function decompress(data: Uint8Array, dictionary?: Uint8Array): Uint8Array {
try {
return dictionary ? zstdDecompressSync(data, { dictionary }) : zstdDecompressSync(data);
} catch (error) {
throw new BlkFormatError(`zstd decompression failed: ${(error as Error).message}`);
}
}
function requireShared(shared: SharedNameContext | undefined): SharedNameContext {
if (!shared) throw new BlkFormatError('this BLK uses the data pack\'s shared name map, which was not supplied');
return shared;
}
+44
View File
@@ -0,0 +1,44 @@
/**
* The name table: every block and parameter name of a document, referenced by index.
*
* Layout (DagorEngine blk_serialize.cpp, dblk::write_names_base / read_names_base):
* varUint count
* varUint total byte size of the names (only when count > 0)
* names, each UTF-8 and NUL-terminated
*/
import { BlkFormatError } from '../errors.ts';
import type { ByteReader } from './byte-reader.ts';
import type { ByteWriter } from './byte-writer.ts';
const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
const utf8Encoder = new TextEncoder();
export function readNameTable(reader: ByteReader): string[] {
const count = reader.varUint();
if (count === 0) return [];
const size = reader.varUint();
if (count > size) throw new BlkFormatError(`name table claims ${count} names in ${size} bytes`);
const blob = reader.take(size);
const names: string[] = [];
let start = 0;
while (names.length < count) {
const end = blob.indexOf(0, start);
if (end < 0) throw new BlkFormatError(`name table ends after ${names.length} of ${count} names`);
names.push(utf8Decoder.decode(blob.subarray(start, end)));
start = end + 1;
}
return names;
}
export function writeNameTable(writer: ByteWriter, names: readonly string[]): void {
writer.varUint(names.length);
if (names.length === 0) return;
const encoded = names.map((name) => utf8Encoder.encode(name));
writer.varUint(encoded.reduce((total, bytes) => total + bytes.length + 1, 0));
for (const bytes of encoded) {
if (bytes.includes(0)) throw new BlkFormatError('a name cannot contain a NUL character');
writer.bytes(bytes);
writer.u8(0);
}
}
+126
View File
@@ -0,0 +1,126 @@
/**
* Turning a parameter record's 32-bit value field into a typed value, and back.
*
* A parameter record is 8 bytes: u32 (name index in the low 24 bits, type id in the high
* 8 bits) and u32 `v`. For values of at most INLINE_SIZE bytes, `v` holds the value. For a
* string, `v` is either a name-table index with the top bit set, or an offset of a
* NUL-terminated UTF-8 string in the complex-data area. For any other larger value, `v` is
* an offset in the complex-data area.
*/
import type { BlkValue } from '../model.ts';
import { BlkFormatError } from '../errors.ts';
import { isInline, typeById, typeByName } from '../param-types.ts';
import type { ByteWriter } from './byte-writer.ts';
export const NAME_TABLE_STRING_FLAG = 0x8000_0000;
const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
const utf8Encoder = new TextEncoder();
const bits = new DataView(new ArrayBuffer(4));
export interface DecodeContext {
readonly names: readonly string[];
readonly complex: Uint8Array;
}
export function decodeValue(typeId: number, v: number, context: DecodeContext): BlkValue {
const info = typeById(typeId);
if (info.type === 'string') return { type: 'string', value: decodeString(v, context) };
if (isInline(info)) return decodeInline(info.type, v);
const { complex } = context;
if (v + info.size > complex.length) {
throw new BlkFormatError(`${info.type} value at complex offset ${v} runs past the end (${complex.length} bytes)`);
}
const view = new DataView(complex.buffer, complex.byteOffset + v, info.size);
const floats = (count: number) => Array.from({ length: count }, (_, i) => view.getFloat32(i * 4, true));
const ints = (count: number) => Array.from({ length: count }, (_, i) => view.getInt32(i * 4, true));
switch (info.type) {
case 'point2': return { type: 'point2', value: floats(2) as [number, number] };
case 'point3': return { type: 'point3', value: floats(3) as [number, number, number] };
case 'point4': return { type: 'point4', value: floats(4) as [number, number, number, number] };
case 'ipoint2': return { type: 'ipoint2', value: ints(2) as [number, number] };
case 'ipoint3': return { type: 'ipoint3', value: ints(3) as [number, number, number] };
case 'ipoint4': return { type: 'ipoint4', value: ints(4) as [number, number, number, number] };
case 'matrix': return { type: 'matrix', value: floats(12) };
case 'int64': return { type: 'int64', value: view.getBigInt64(0, true) };
default: throw new BlkFormatError(`no complex-data decoding for ${info.type}`);
}
}
/** The value field for an inline value. */
export function encodeInline(value: BlkValue): number {
switch (value.type) {
case 'int': return value.value | 0;
case 'bool': return value.value ? 1 : 0;
case 'color': return value.value >>> 0;
case 'real':
bits.setFloat32(0, value.value, true);
return bits.getUint32(0, true);
default: throw new BlkFormatError(`${value.type} is not stored inline`);
}
}
export function storesInline(value: BlkValue): boolean {
return isInline(typeByName(value.type));
}
/** Append a string to the complex-data area; returns its offset. */
export function appendString(complex: ByteWriter, text: string): number {
const encoded = utf8Encoder.encode(text);
if (encoded.includes(0)) throw new BlkFormatError('a string value cannot contain a NUL character');
const offset = complex.length;
complex.bytes(encoded);
complex.u8(0);
return offset;
}
/** Append a non-string, non-inline value to the complex-data area; returns its offset. */
export function appendComplex(complex: ByteWriter, value: BlkValue): number {
const offset = complex.length;
const size = typeByName(value.type).size;
const view = new DataView(new ArrayBuffer(size));
switch (value.type) {
case 'point2': case 'point3': case 'point4': case 'matrix':
value.value.forEach((item, i) => view.setFloat32(i * 4, item, true));
break;
case 'ipoint2': case 'ipoint3': case 'ipoint4':
value.value.forEach((item, i) => view.setInt32(i * 4, item, true));
break;
case 'int64':
view.setBigInt64(0, value.value, true);
break;
default:
throw new BlkFormatError(`${value.type} is not stored in the complex-data area`);
}
if (value.type === 'matrix' && value.value.length !== 12) {
throw new BlkFormatError(`a matrix has 12 numbers, got ${value.value.length}`);
}
complex.bytes(new Uint8Array(view.buffer));
return offset;
}
function decodeString(v: number, { names, complex }: DecodeContext): string {
if (v & NAME_TABLE_STRING_FLAG) {
const index = v & ~NAME_TABLE_STRING_FLAG;
const name = names[index];
if (name === undefined) throw new BlkFormatError(`string refers to name ${index}, table has ${names.length}`);
return name;
}
const end = complex.indexOf(0, v);
if (v >= complex.length || end < 0) throw new BlkFormatError(`string at complex offset ${v} is not terminated`);
return utf8Decoder.decode(complex.subarray(v, end));
}
function decodeInline(type: BlkValue['type'], v: number): BlkValue {
switch (type) {
case 'int': return { type: 'int', value: v | 0 };
case 'bool': return { type: 'bool', value: (v & 0xff) !== 0 };
case 'color': return { type: 'color', value: v >>> 0 };
case 'real':
bits.setUint32(0, v, true);
return { type: 'real', value: bits.getFloat32(0, true) };
default: throw new BlkFormatError(`${type} is not stored inline`);
}
}