Files
WT-Offline/packages/patcher/src/pack-edit.ts
T

62 lines
2.7 KiB
TypeScript

/**
* Rebuild a data pack with some of its BLK documents edited and, optionally, new files added.
* Every other file of the pack is kept byte for byte. Edited documents are stored self-contained (they no longer depend on
* the pack's shared name map), which the game accepts in every loading mode.
*/
import { decodeBlk, encodeBlk, parseSharedNameMap, type BlkBlock } from '@wto/blk';
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
export interface PackEditResult<T> {
readonly pack: Uint8Array;
readonly report: T;
}
/** One BLK document of the pack and the change to make to it. */
export interface BlkEdit {
readonly path: string;
readonly edit: (root: BlkBlock) => void;
}
export function editPackBlk<T>(stockPack: Uint8Array, blkPath: string, edit: (root: BlkBlock) => T): PackEditResult<T> {
let report: T | undefined;
const pack = editPackBlks(stockPack, [{ path: blkPath, edit: (root) => { report = edit(root); } }]);
return { pack, report: report as T };
}
/** A file the stock pack does not have, stored as is. */
export interface AddedFile {
readonly path: string;
readonly content: Uint8Array;
}
export function editPackBlks(stockPack: Uint8Array, edits: readonly BlkEdit[], added: readonly AddedFile[] = []): Uint8Array {
const archive = readArchive(stockPack);
const dictionary = findDictionary(archive);
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
for (const { path, edit } of edits) {
const root = decodeBlk(getFile(archive, path), { names, dictionary });
edit(root);
putFile(archive, path, encodeBlk(root));
}
for (const file of added) {
if (archive.files.has(file.path)) throw new Error(`the data pack already has ${file.path}`);
putFile(archive, file.path, file.content);
}
return writeArchive(archive);
}
/** Read one BLK document of a pack without changing anything. */
export function readPackBlk(stockPack: Uint8Array, path: string): BlkBlock {
const archive = readArchive(stockPack);
const dictionary = findDictionary(archive);
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
return decodeBlk(getFile(archive, path), { names, dictionary });
}
/** The pack's zstd dictionary, if it has one. */
function findDictionary(archive: Archive): Uint8Array | undefined {
const dictionaries = [...archive.files.keys()].filter((path) => path.endsWith('.dict'));
if (dictionaries.length > 1) throw new Error(`the data pack has several zstd dictionaries: ${dictionaries.join(', ')}`);
return dictionaries.length ? archive.files.get(dictionaries[0]!) : undefined;
}