move to vfs package

This commit is contained in:
tresabhi committed 2026-11-23 20:27:55 -06:00
1 parent ff1aadb774
commit a89c75509e
49 files changed
+125 -96

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
export function Cache(disableInDev = false) {
const cache = new WeakMap<object, Map<string, Promise<unknown>>>();
return function <This, Arguments extends any[], Return>(
target: (this: This, ...args: Arguments) => Promise<Return>
// TODO: evaluate if we need context to make the error trace easier
// context: ClassMethodDecoratorContext<
// This,
// (this: This, ...args: Arguments) => Promise<Return>
// >,
) {
return async function replacementMethod(this: This, ...args: Arguments) {
const key = args.join("-");
let thisCache: Map<string, Promise<Return>>;
if (cache.has(this as object)) {
thisCache = cache.get(this as object) as Map<string, Promise<Return>>;
} else {
thisCache = new Map();
cache.set(this as object, thisCache);
}
const disabled = disableInDev && import.meta.env.DEV;
if (thisCache.has(key) && !disabled) {
return thisCache.get(key)!;
}
const promise = (async () => {
try {
return await target.apply(this, args);
} catch (error) {
thisCache!.delete(key);
throw error;
}
})();
thisCache.set(key, promise);
return promise;
};
};
}
+1 -1
View File
@@ -16,7 +16,7 @@ import { fetchPB } from "../../api";
import { fetchJSON } from "../../api/fetchJSON";
import { BlitzScripts } from "../../types/blitzScripts";
import { AbstractBlitzKitAPI } from "./abstract";
import { Cache } from "./server/0_base";
import { Cache } from "./cache";
export class ClientBlitzKitAPI extends AbstractBlitzKitAPI {
@Cache()
+3 -2
View File
@@ -1,11 +1,12 @@
import { AbstractBlitzKitAPI, AbstractVFS } from "@blitzkit/core";
import { AbstractBlitzKitAPI } from "@blitzkit/core";
import type { AbstractVFS } from "@blitzkit/vfs";
export async function createDynamicAPI(vfs: () => Promise<AbstractVFS>) {
let _api: AbstractBlitzKitAPI;
if (import.meta.env.SSR) {
const { ServerBlitzKitAPI } = await import(
"@blitzkit/core/src/blitzkit/api/server/index"
"@blitzkit/core/src/blitzkit/api/server"
);
_api = await new ServerBlitzKitAPI(await vfs()).init();
-1
View File
@@ -1,4 +1,3 @@
export * from "./abstract";
export * from "./client";
export * from "./dynamic";
export * from "./server";
@@ -17,7 +17,7 @@ import {
toUniqueId,
VehicleDefinitionList,
} from "@blitzkit/core";
import { AbstractVFS } from "@blitzkit/core/src/blitzkit/vfs/abstract";
import type { AbstractVFS } from "@blitzkit/vfs";
import locales from "@blitzkit/i18n/locales.json";
import {
ConsumableTankCategoryFilterCategory,
@@ -298,47 +298,3 @@ export abstract class ServerBlitzKitAPI0 extends AbstractBlitzKitAPI {
return { locales: collection } satisfies I18nString;
}
}
export function Cache(disableInDev = false) {
const cache = new WeakMap<object, Map<string, Promise<unknown>>>();
return function <This, Arguments extends any[], Return>(
target: (this: This, ...args: Arguments) => Promise<Return>
// TODO: evaluate if we need context to make the error trace easier
// context: ClassMethodDecoratorContext<
// This,
// (this: This, ...args: Arguments) => Promise<Return>
// >,
) {
return async function replacementMethod(this: This, ...args: Arguments) {
const key = args.join("-");
let thisCache: Map<string, Promise<Return>>;
if (cache.has(this as object)) {
thisCache = cache.get(this as object) as Map<string, Promise<Return>>;
} else {
thisCache = new Map();
cache.set(this as object, thisCache);
}
const disabled = disableInDev && import.meta.env.DEV;
if (thisCache.has(key) && !disabled) {
return thisCache.get(key)!;
}
const promise = (async () => {
try {
return await target.apply(this, args);
} catch (error) {
thisCache!.delete(key);
throw error;
}
})();
thisCache.set(key, promise);
return promise;
};
};
}
@@ -1,7 +1,7 @@
import { fetchGlossary } from "@blitzkit/core";
import locales from "@blitzkit/i18n/locales.json";
import { Avatar, Gallery } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI9 } from "./9_game";
export abstract class ServerBlitzKitAPI10 extends ServerBlitzKitAPI9 {
@@ -4,8 +4,8 @@ import type {
ConsumablesCommon,
OptionalDevices,
} from "../../../types";
import { AbstractVFS } from "../../vfs";
import { Cache } from "./0_base";
import type { AbstractVFS } from "@blitzkit/vfs";
import { Cache } from "../cache";
import { ServerBlitzKitAPI10 } from "./10_avatars";
export abstract class ServerBlitzKitAPI11 extends ServerBlitzKitAPI10 {
@@ -2,7 +2,7 @@ import { Strings } from "@blitzkit/i18n";
import locales from "@blitzkit/i18n/locales.json";
import { DeepPartial } from "@blitzkit/protos";
import { merge } from "lodash-es";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI11 } from "./11_scripts";
export abstract class ServerBlitzKitAPI12 extends ServerBlitzKitAPI11 {
@@ -46,7 +46,8 @@ import {
Unlock,
type VehicleAbility,
} from "@blitzkit/protos";
import { Cache, ServerBlitzKitAPI0 } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI0 } from "./0_base";
export abstract class ServerBlitzKitAPI1 extends ServerBlitzKitAPI0 {
// A gun the way a tank's turret or a vehicle ability builds it. `gun`
@@ -4,7 +4,7 @@ import {
type TankParameters,
} from "@blitzkit/core";
import { isEqual, times } from "lodash-es";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI1 } from "./1_tanks";
export abstract class ServerBlitzKitAPI2 extends ServerBlitzKitAPI1 {
@@ -18,7 +18,7 @@ import {
} from "@blitzkit/core";
import { Armor, Crew, ModelDefinitions, ProtoVector3 } from "@blitzkit/protos";
import { MathUtils, Vector3 as THREEVector3, Vector3Tuple } from "three";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI2 } from "./2_camouflages";
// The `front` and `back` tags hold "min max range" in degrees
@@ -1,5 +1,5 @@
import { MapDefinitions } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI3 } from "./3_models";
export abstract class ServerBlitzKitAPI4 extends ServerBlitzKitAPI3 {
@@ -1,5 +1,5 @@
import { EquipmentDefinitions, EquipmentSlot } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI4 } from "./4_maps";
export abstract class ServerBlitzKitAPI5 extends ServerBlitzKitAPI4 {
@@ -1,6 +1,6 @@
import { BlitzTankFilterDefinitionCategory } from "@blitzkit/core";
import { Consumable, ConsumableDefinitions } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI5 } from "./5_equipments";
export abstract class ServerBlitzKitAPI6 extends ServerBlitzKitAPI5 {
@@ -1,6 +1,6 @@
import { BlitzTankFilterDefinitionCategory } from "@blitzkit/core";
import { Provision, ProvisionDefinitions } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI6 } from "./6_consumables";
export abstract class ServerBlitzKitAPI7 extends ServerBlitzKitAPI6 {
@@ -1,7 +1,7 @@
import { BlitzTankClass } from "@blitzkit/core";
import { SkillDefinitions } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI7 } from "./7_provisions";
export abstract class ServerBlitzKitAPI8 extends ServerBlitzKitAPI7 {
@@ -1,7 +1,7 @@
import { AvailableNationsYaml } from "@blitzkit/core";
import { GameDefinitions } from "@blitzkit/protos";
import { Cache } from "./0_base";
import { Cache } from "../cache";
import { ServerBlitzKitAPI8 } from "./8_skills";
export abstract class ServerBlitzKitAPI9 extends ServerBlitzKitAPI8 {
@@ -1,60 +0,0 @@
import locales from "@blitzkit/i18n/locales.json";
import { XMLParser } from "fast-xml-parser";
import {
WGC_CLIENT_GUID,
WGC_CLIENT_URL,
WGC_METADATA_PROTOCOL_VERSION,
WGC_PATCHES_CHAIN_PROTOCOL_VERSION,
} from "../config/wgcClient";
import type { WGCClientMetadata, WGCPatchesChain } from "../types/wgcClient";
const parser = new XMLParser();
// Base url of the latest full client's 7z volumes, without the .001 suffix
export async function fetchWGCClientSource() {
const metadataUrl = new URL("api/v1/metadata", WGC_CLIENT_URL);
metadataUrl.searchParams.set("guid", WGC_CLIENT_GUID);
metadataUrl.searchParams.set("chain_id", "unknown");
metadataUrl.searchParams.set(
"protocol_version",
WGC_METADATA_PROTOCOL_VERSION
);
const metadata = await fetch(`${metadataUrl}`)
.then((response) => response.text())
.then((text) => parser.parse(text) as WGCClientMetadata);
const patchesChainUrl = new URL("api/v1/patches_chain", WGC_CLIENT_URL);
patchesChainUrl.searchParams.set(
"protocol_version",
WGC_PATCHES_CHAIN_PROTOCOL_VERSION
);
patchesChainUrl.searchParams.set("client_type", "full");
patchesChainUrl.searchParams.set("lang", locales.default);
patchesChainUrl.searchParams.set(
"metadata_version",
`${metadata.protocol.version}`
);
patchesChainUrl.searchParams.set(
"metadata_protocol_version",
WGC_METADATA_PROTOCOL_VERSION
);
patchesChainUrl.searchParams.set(
"chain_id",
metadata.protocol.predefined_section.chain_id
);
patchesChainUrl.searchParams.set("game_installation", "true");
patchesChainUrl.searchParams.set("game_id", WGC_CLIENT_GUID);
patchesChainUrl.searchParams.set("client_current_version", "0");
const patchesChain = await fetch(`${patchesChainUrl}`)
.then((response) => response.text())
.then((text) => parser.parse(text) as WGCPatchesChain);
const firstVolume = patchesChain.protocol.patches_chain.patch.files.file[0];
const url = new URL(firstVolume.name, patchesChain.protocol.web_seeds.url);
return `${url}`.replace(/\.001$/, "");
}
-2
View File
@@ -11,7 +11,6 @@ export * from "./discoveredIdDefinitions";
export * from "./emblemURL";
export * from "./environment";
export * from "./eventManager";
export * from "./fetchWGCClientSource";
export * from "./getTimeDaysAgo";
export * from "./isExplosive";
export * from "./metaSortTank";
@@ -33,6 +32,5 @@ export * from "./tankNames";
export * from "./unionBoundingBox";
export * from "./uniqueGuns";
export * from "./unwrapBlitzkitResponse";
export * from "./vfs";
export * from "./votes";
export * from "./youtubers";
-114
View File
@@ -1,114 +0,0 @@
import { readDVPL } from "@blitzkit/core";
import { Options, parse as parseCSV } from "csv-parse/browser/esm/sync";
import { XMLParser } from "fast-xml-parser";
import type { normalize } from "node:path/posix";
import { parse as parseYaml } from "yaml";
// Tags of an upgrade progression that are lists even with a single child
const UPGRADE_PROGRESSION_LIST_TAGS = new Set([
"node",
"attribute",
"alternativeMechanicGroup",
]);
export abstract class AbstractVFS {
textDecoder = new TextDecoder();
private xmlParser = new XMLParser();
private attributeXmlParser = new XMLParser({
ignoreAttributes: false,
// A lone child would otherwise parse to an object instead of a list
isArray: (name) => UPGRADE_PROGRESSION_LIST_TAGS.has(name),
});
protected normalizePath?: typeof normalize;
async init() {
const path = await import("node:path/posix");
this.normalizePath = path.normalize;
return await this._init();
}
protected abstract _init(): Promise<typeof this>;
abstract dispose(): void;
abstract has(path: string): Promise<boolean>;
abstract raw(path: string): Promise<Uint8Array<ArrayBuffer>>;
async resolve(path: string) {
const normalized = this.normalizePath!(path);
if (await this.has(normalized)) return normalized;
const dvplPath = `${normalized}.dvpl`;
if (await this.has(dvplPath)) return dvplPath;
return null;
}
async assert(path: string) {
const resolved = await this.resolve(path);
if (resolved === null) throw new Error(`File not found: ${path}`);
return resolved;
}
async file(file: string) {
const resolved = await this.assert(file);
const raw = await this.raw(resolved);
let buffer = raw;
if (resolved.endsWith(".dvpl")) {
buffer = new Uint8Array(readDVPL(Buffer.from(raw)));
}
return buffer;
}
protected abstract _dir(path: string): Promise<string[]>;
async dir(path: string) {
const files = await this._dir(path);
return files.map((file) =>
file.endsWith(".dvpl") ? file.slice(0, -5) : file,
);
}
async text(path: string) {
const file = await this.file(path);
return this.textDecoder.decode(file);
}
async yaml<Type>(path: string) {
const file = await this.text(path);
return parseYaml(file) as Type;
}
async xml<Type>(path: string) {
const file = await this.text(path);
return this.xmlParser.parse(file) as Type;
}
// Keeps attributes as `@_name` and lists as arrays, which `xml` drops
async xmlWithAttributes<Type>(path: string) {
const file = await this.text(path);
return this.attributeXmlParser.parse(file) as Type;
}
protected async _csv(text: string, options: Options = {}) {
const parsed = parseCSV(text, options);
return parsed;
}
async csv(path: string, options: Options = {}) {
const text = await this.text(path);
return await this._csv(text, options);
}
[Symbol.dispose]() {
this.dispose();
}
}
-33
View File
@@ -1,33 +0,0 @@
import { assertSecret } from "@blitzkit/core";
import { fetchWGCClientSource } from "../fetchWGCClientSource";
import { AbstractVFS } from "./abstract";
import { LocalVFS } from "./local";
import { MixedVFS } from "./mixed";
import { SevenZipVFS } from "./sevenZip";
import { ZipVFS } from "./zip";
export async function createClientVFS() {
const provider = import.meta.env.CLIENT_PROVIDER;
let vfs: AbstractVFS;
if (provider === "zip") {
vfs = new ZipVFS(assertSecret(import.meta.env.CLIENT_SOURCE));
} else if (provider === "7z") {
vfs = new SevenZipVFS(assertSecret(import.meta.env.CLIENT_SOURCE));
} else if (provider === "wgc") {
vfs = new SevenZipVFS(await fetchWGCClientSource());
} else if (provider === "local") {
vfs = new LocalVFS(assertSecret(import.meta.env.CLIENT_DIR));
} else {
throw new Error(`Unknown client provider: ${provider}`);
}
// smart dlc patches take precedence over the client
const smartDlcDir = import.meta.env.SMART_DLC_DIR;
if (smartDlcDir) {
vfs = new MixedVFS([new LocalVFS(smartDlcDir), vfs]);
}
return await vfs.init();
}
-6
View File
@@ -1,6 +0,0 @@
export * from "./abstract";
export * from "./local";
export * from "./mixed";
export * from "./sevenZip";
export * from "./steam";
export * from "./zip";
-43
View File
@@ -1,43 +0,0 @@
import type { readdir } from "node:fs/promises";
import { AbstractVFS } from "./abstract";
export class LocalVFS extends AbstractVFS {
protected readdir?: typeof readdir;
constructor(private base: string) {
super();
}
async _init() {
const path = await import("node:path/posix");
const fs = await import("node:fs/promises");
this.normalizePath = path.normalize;
this.readdir = fs.readdir;
return this;
}
async has(path: string) {
const file = Bun.file(`${this.base}/${path}`);
return await file.exists();
}
async raw(path: string) {
const file = Bun.file(`${this.base}/${path}`);
const buffer = await file.arrayBuffer();
const array = new Uint8Array(buffer);
return array;
}
async _dir(path: string) {
try {
return await this.readdir!(`${this.base}/${path}`);
} catch (_) {
return [];
}
}
dispose() {}
}
-49
View File
@@ -1,49 +0,0 @@
import { AbstractVFS } from "./abstract";
export class MixedVFS extends AbstractVFS {
constructor(private vfses: AbstractVFS[]) {
super();
}
async _init() {
for (const vfs of this.vfses) {
await vfs.init();
}
return this;
}
dispose() {
for (const vfs of this.vfses) {
vfs.dispose();
}
}
async has(path: string) {
for (const vfs of this.vfses) {
if (await vfs.has(path)) return true;
}
return false;
}
async raw(path: string) {
for (const vfs of this.vfses) {
if (await vfs.has(path)) return await vfs.raw(path);
}
throw new Error(`File not found: ${path}`);
}
async _dir(path: string) {
const files = new Set<string>();
for (const vfs of this.vfses) {
for (const file of await vfs.dir(path)) {
files.add(file);
}
}
return Array.from(files);
}
}
@@ -1,228 +0,0 @@
import type { lzma, lzma2 } from "@napi-rs/lzma";
import type { crc32 } from "node:zlib";
import {
SEVEN_ZIP_SIGNATURE_HEADER_SIZE,
SevenZipReadStream,
type SevenZipCoder,
type SevenZipFileInfo,
type SevenZipStreamsInfo,
} from "../../../streams/sevenZip";
import type { HTTPMultiRangeReader } from "./rangeReader";
const enum Method {
LZMA2 = 0x21,
LZMA = 0x030101,
}
export interface SevenZipEntry {
name: string;
isDir: boolean;
// -1 for entries without data (directories, empty files)
folder: number;
}
export class SevenZipArchive {
entries: SevenZipEntry[] = [];
private streams: SevenZipStreamsInfo = {
packPos: 0,
packSizes: [],
folders: [],
};
private packOffsets: number[] = [];
private lzma?: typeof lzma;
private lzma2?: typeof lzma2;
private crc32?: typeof crc32;
private constructor(private source: HTTPMultiRangeReader) {}
static async open(source: HTTPMultiRangeReader) {
const archive = new SevenZipArchive(source);
await archive.init();
return archive;
}
async read(entry: SevenZipEntry) {
if (entry.folder === -1) return new Uint8Array(0);
return this.decodeFolder(this.streams, this.packOffsets, entry.folder);
}
private async init() {
const napiLzma = await import("@napi-rs/lzma");
const zlib = await import("node:zlib");
this.lzma = napiLzma.lzma;
this.lzma2 = napiLzma.lzma2;
this.crc32 = zlib.crc32;
const signature = await this.source.read(
0,
SEVEN_ZIP_SIGNATURE_HEADER_SIZE,
);
const { startHeaderCrc, nextHeaderOffset, nextHeaderSize, nextHeaderCrc } =
new SevenZipReadStream(signature.buffer).signatureHeader();
if (this.crc32!(signature.subarray(12)) !== startHeaderCrc) {
throw new Error("7z: bad start header CRC");
}
let header = await this.source.read(
SEVEN_ZIP_SIGNATURE_HEADER_SIZE + nextHeaderOffset,
nextHeaderSize,
);
if (this.crc32!(header) !== nextHeaderCrc) {
throw new Error("7z: bad header CRC");
}
while (true) {
const parsed = new SevenZipReadStream(header.buffer).header();
if (!parsed.encoded) {
this.streams = parsed.streams;
this.packOffsets = this.computePackOffsets(parsed.streams);
this.indexEntries(parsed.files);
return;
}
header = await this.decodeFolder(
parsed.streams,
this.computePackOffsets(parsed.streams),
0,
);
}
}
// files with data fill each folder's unpack streams in order
private indexEntries(files: SevenZipFileInfo[]) {
const folders = this.streams.folders;
let folderIndex = 0;
let streamIndex = 0;
for (const file of files) {
if (!file.hasStream) {
this.entries.push({ name: file.name, isDir: file.isDir, folder: -1 });
continue;
}
while (
folderIndex < folders.length &&
streamIndex >= folders[folderIndex].numUnpackStreams
) {
folderIndex++;
streamIndex = 0;
}
if (folderIndex === folders.length) {
throw new Error("7z: more files than streams");
}
this.entries.push({ name: file.name, isDir: false, folder: folderIndex });
streamIndex++;
}
}
private computePackOffsets(streams: SevenZipStreamsInfo) {
const offsets = [SEVEN_ZIP_SIGNATURE_HEADER_SIZE + streams.packPos];
for (const size of streams.packSizes) {
offsets.push(offsets[offsets.length - 1] + size);
}
return offsets;
}
private async decodeFolder(
streams: SevenZipStreamsInfo,
packOffsets: number[],
index: number,
) {
const folder = streams.folders[index];
if (folder.numUnpackStreams !== 1) {
throw new Error("7z: solid folders are not supported");
}
// filter chains like bcj only wrap the exes and dlls, which are never read
if (folder.coders.length !== 1) {
throw new Error(
`7z: coder chain ${folder.coders.map((coder) =>
coder.method.toString(16),
)} is not supported`,
);
}
const start = packOffsets[folder.firstPackStream];
const packed = await this.source.read(
start,
packOffsets[folder.firstPackStream + 1] - start,
);
const data = await this.runCoder(
folder.coders[0],
packed,
folder.unpackSize,
);
if (folder.crc !== undefined && this.crc32!(data) !== folder.crc) {
throw new Error(`7z: CRC mismatch for folder ${index}`);
}
return data;
}
private async runCoder(
coder: SevenZipCoder,
input: Uint8Array<ArrayBuffer>,
size: number,
) {
let data: Uint8Array<ArrayBuffer>;
switch (coder.method) {
case Method.LZMA2:
data = await this.decodeLZMA2(input, coder.props);
break;
case Method.LZMA:
data = this.decodeLZMA(input, coder.props, size);
break;
default:
throw new Error(`7z: unsupported method ${coder.method.toString(16)}`);
}
if (data.length !== size) throw new Error("7z: unpacked size mismatch");
return data;
}
// 7z stores lzma props apart from the stream, so rebuild the .lzma header around it
private decodeLZMA(
input: Uint8Array<ArrayBuffer>,
props: Uint8Array<ArrayBuffer>,
size: number,
) {
const stream = new Uint8Array(13 + input.length);
const view = new DataView(stream.buffer);
stream.set(props.subarray(0, 5));
view.setBigUint64(5, BigInt(size), true);
stream.set(input, 13);
return new Uint8Array(this.lzma!.decompressSync(stream));
}
// raw lzma2 carries no dictionary size, so it comes from the coder's prop byte
private async decodeLZMA2(
input: Uint8Array<ArrayBuffer>,
props: Uint8Array<ArrayBuffer>,
) {
const bits = props[0];
const dictSize =
bits === 40 ? 0xffffffff : (2 | (bits & 1)) * 2 ** ((bits >>> 1) + 11);
const output = this.lzma2!.decompressStream(new Blob([input]).stream(), {
dictSize,
});
return new Uint8Array(await new Response(output).arrayBuffer());
}
}
@@ -1,80 +0,0 @@
import { AbstractVFS } from "../abstract";
import { SevenZipArchive, type SevenZipEntry } from "./archive";
import { HTTPMultiRangeReader } from "./rangeReader";
/**
* Reads a 7z archive straight from the CDN with HTTP range requests.
* Split volumes (.001, .002, ...) are raw byte slices of one archive, so they
* are stitched into a single virtual address space.
*
* Only non-solid archives (one block per file) are supported, so reading a file
* costs exactly one range request of its packed size.
*/
export class SevenZipVFS extends AbstractVFS {
entries = new Map<string, SevenZipEntry>();
private archive!: SevenZipArchive;
constructor(private source: string) {
super();
}
async _init() {
const urls: string[] = [];
// split volumes are suffixed .001, .002, ... until the cdn 404s
for (let index = 1; ; index++) {
const url = `${this.source}.${index.toString().padStart(3, "0")}`;
const response = await fetch(url, { method: "HEAD" });
if (response.status === 404) break;
if (!response.ok) {
throw new Error(`Wargaming response error status: ${response.status}`);
}
urls.push(url);
}
if (urls.length === 0) throw new Error(`No volumes at ${this.source}`);
const reader = await new HTTPMultiRangeReader(urls).init();
this.archive = await SevenZipArchive.open(reader);
for (const entry of this.archive.entries) {
if (entry.isDir) continue;
this.entries.set(this.normalizePath!(entry.name), entry);
}
return this;
}
async has(path: string) {
return this.entries.has(path);
}
async raw(path: string) {
console.log(path);
const entry = this.entries.get(path);
if (!entry) throw new Error(`File not found in 7z: ${path}`);
return this.archive.read(entry);
}
async _dir(path: string) {
const parentSegments = path.split("/").length;
const children = new Set<string>();
for (const child of this.entries.keys()) {
if (!child.startsWith(path) || child === path) continue;
const childSegments = child.split("/");
const nextSegment = childSegments[parentSegments];
children.add(nextSegment);
}
return Array.from(children);
}
dispose() {}
}
@@ -1,104 +0,0 @@
interface Volume {
url: string;
start: number;
size: number;
}
// Treats several URLs as one contiguous file
export class HTTPMultiRangeReader {
size = 0;
private volumes: Volume[] = [];
constructor(private urls: string[]) {}
async init() {
const sizes = await Promise.all(
this.urls.map(async (url) => {
const response = await fetch(url, { method: "HEAD" });
if (!response.ok) {
throw new Error(`HEAD ${url} failed: ${response.status}`);
}
const size = Number(response.headers.get("content-length"));
if (!Number.isFinite(size)) {
throw new Error(`No content-length for ${url}`);
}
return size;
}),
);
let start = 0;
this.volumes = this.urls.map((url, i) => {
const volume = { url, start, size: sizes[i] };
start += sizes[i];
return volume;
});
this.size = start;
return this;
}
async read(offset: number, length: number) {
const end = offset + length;
if (offset < 0 || end > this.size) {
throw new Error(`Read out of bounds: ${offset}+${length}`);
}
if (length === 0) return new Uint8Array(0);
const parts: Promise<Uint8Array<ArrayBuffer>>[] = [];
for (const volume of this.volumes) {
const start = Math.max(offset, volume.start);
const stop = Math.min(end, volume.start + volume.size);
if (start >= stop) continue;
parts.push(
this.fetch(volume.url, start - volume.start, stop - volume.start),
);
}
const chunks = await Promise.all(parts);
if (chunks.length === 1) return chunks[0];
const result = new Uint8Array(length);
let cursor = 0;
for (const chunk of chunks) {
result.set(chunk, cursor);
cursor += chunk.length;
}
return result;
}
private async fetch(url: string, start: number, stop: number) {
const response = await fetch(url, {
headers: { Range: `bytes=${start}-${stop - 1}` },
});
if (response.status !== 206) {
throw new Error(
`Expected 206 for ${url} [${start}, ${stop}), got ${response.status}`,
);
}
const data = new Uint8Array(await response.arrayBuffer());
if (data.length !== stop - start) {
throw new Error(
`Short read from ${url}: ${data.length} of ${stop - start} bytes`,
);
}
return data;
}
}
-115
View File
@@ -1,115 +0,0 @@
import type SteamUser from "steam-user";
import { AbstractVFS } from "./abstract";
interface SteamManifestFile {
chunks: {
sha: string;
crc: number;
offset: string;
cb_original: number;
cb_compressed: number;
}[];
filename: string;
size: string;
flags: number;
sha_filename: string;
sha_content: string;
linktarget: unknown;
}
interface SteamManifest {
files: SteamManifestFile[];
depot_id: number;
gid_manifest: string;
creation_time: number;
filenames_encrypted: boolean;
cb_disk_original: string;
cb_disk_compressed: string;
unique_chunks: number;
crc_encrypted: number;
crc_clear: number;
}
export class SteamVFS extends AbstractVFS {
private steam?: SteamUser;
private manifest: Map<string, SteamManifestFile> = new Map();
constructor(
private username: string,
private password: string,
private app: number,
private depot: number,
) {
super();
}
async _init() {
const steamUser = await import("steam-user");
this.steam = new steamUser.default({
protocol: steamUser.EConnectionProtocol.TCP,
});
this.steam.logOn({
accountName: this.username,
password: this.password,
});
await new Promise((resolve) => this.steam!.once("loggedOn", resolve));
const productInfo = await this.steam.getProductInfo([this.app], []);
const manifest: SteamManifest = await new Promise((resolve) => {
// @ts-expect-error
this.steam.getManifest(
this.app,
this.depot,
productInfo.apps[this.app].appinfo.depots[this.depot].manifests.public
.gid,
"public",
// @ts-expect-error
(_, response) => {
resolve(response);
},
);
});
for (const file of manifest.files) {
const path = file.filename.replaceAll("\\", "/");
this.manifest.set(path, file);
}
return this;
}
async has(path: string) {
return this.manifest.has(path);
}
async raw(path: string) {
const fileManifest = this.manifest.get(path)!;
const downloaded: { type: "complete"; file: Buffer } =
// @ts-expect-error
await this.steam.downloadFile(this.app, this.depot, fileManifest);
return new Uint8Array(downloaded.file);
}
async _dir(path: string) {
const parentSegments = path.split("/").length;
const children = new Set<string>();
for (const child of this.manifest.keys()) {
if (!child.startsWith(path) || child === path) continue;
const childSegments = child.split("/");
const nextSegment = childSegments[parentSegments];
children.add(nextSegment);
}
return Array.from(children);
}
dispose() {
this.steam!.logOff();
}
}
-54
View File
@@ -1,54 +0,0 @@
import { HTTPRangeReader, unzip, ZipEntry } from "unzipit";
import { AbstractVFS } from "./abstract";
export class ZipVFS extends AbstractVFS {
entries = new Map<string, ZipEntry>();
constructor(
private url: string,
private root = "app/",
) {
super();
}
async _init() {
const reader = new HTTPRangeReader(this.url);
const { entries } = await unzip(reader);
for (const entry of Object.values(entries)) {
const normalized = this.normalizePath!(
entry.name.slice(this.root.length),
);
this.entries.set(normalized, entry);
}
return this;
}
async has(path: string) {
return this.entries.has(path);
}
async raw(path: string) {
const arrayBuffer = await this.entries.get(path)!.arrayBuffer();
return new Uint8Array(arrayBuffer);
}
async _dir(path: string) {
const parentSegments = path.split("/").length;
const children = new Set<string>();
for (const child of this.entries.keys()) {
if (!child.startsWith(path) || child === path) continue;
const childSegments = child.split("/");
const nextSegment = childSegments[parentSegments];
children.add(nextSegment);
}
return Array.from(children);
}
dispose() {}
}
-1
View File
@@ -2,4 +2,3 @@ export * from "./gunTypeOrder";
export * from "./skills";
export * from "./tankClassOrder";
export * from "./treeTypeOrder";
export * from "./wgcClient";
-4
View File
@@ -1,4 +0,0 @@
export const WGC_CLIENT_GUID = "WOTB.WW.PRODUCTION";
export const WGC_CLIENT_URL = "https://wgus-eu.wargaming.net";
export const WGC_METADATA_PROTOCOL_VERSION = "7.10";
export const WGC_PATCHES_CHAIN_PROTOCOL_VERSION = "1.11";
-1
View File
@@ -6,5 +6,4 @@ export * from "./rts";
export * from "./sc2";
export * from "./scg";
export * from "./scpg";
export * from "./sevenZip";
export * from "./windows";
-411
View File
@@ -1,411 +0,0 @@
import { ReadStream } from "./buffer";
export const SEVEN_ZIP_SIGNATURE_HEADER_SIZE = 32;
const SIGNATURE = [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c];
const enum Id {
End = 0x00,
Header = 0x01,
ArchiveProperties = 0x02,
AdditionalStreamsInfo = 0x03,
MainStreamsInfo = 0x04,
FilesInfo = 0x05,
PackInfo = 0x06,
UnpackInfo = 0x07,
SubStreamsInfo = 0x08,
Size = 0x09,
CRC = 0x0a,
Folder = 0x0b,
CodersUnpackSize = 0x0c,
NumUnpackStream = 0x0d,
EmptyStream = 0x0e,
EmptyFile = 0x0f,
Name = 0x11,
EncodedHeader = 0x17,
}
export interface SevenZipCoder {
method: number;
numIn: number;
numOut: number;
props: Uint8Array<ArrayBuffer>;
}
// a folder is one compressed block; only single coder, single file folders are ever decoded
export interface SevenZipFolder {
coders: SevenZipCoder[];
packedCount: number;
firstPackStream: number;
unpackSize: number;
numUnpackStreams: number;
crc?: number;
}
export interface SevenZipStreamsInfo {
packPos: number;
packSizes: number[];
folders: SevenZipFolder[];
}
export interface SevenZipFileInfo {
name: string;
hasStream: boolean;
isDir: boolean;
}
export class SevenZipReadStream extends ReadStream {
signatureHeader() {
const signature = this.consumeUint8Array(SIGNATURE.length);
if (!SIGNATURE.every((byte, i) => signature[i] === byte)) {
throw new Error("Not a 7z archive");
}
// format version
this.seek(2);
return {
startHeaderCrc: this.uint32(),
nextHeaderOffset: Number(this.uint64()),
nextHeaderSize: Number(this.uint64()),
nextHeaderCrc: this.uint32(),
};
}
header() {
const id = this.number();
switch (id) {
case Id.Header:
return { encoded: false, ...this.mainHeader() } as const;
// the real header is itself compressed and stored as a packed stream
case Id.EncodedHeader:
return { encoded: true, streams: this.streamsInfo() } as const;
default:
throw new Error(`7z: unexpected header id ${id}`);
}
}
private mainHeader() {
let streams: SevenZipStreamsInfo = {
packPos: 0,
packSizes: [],
folders: [],
};
let files: SevenZipFileInfo[] = [];
for (let id = this.number(); id !== Id.End; id = this.number()) {
switch (id) {
case Id.ArchiveProperties:
while (this.number() !== Id.End) this.seek(this.number());
break;
case Id.AdditionalStreamsInfo:
throw new Error("7z: additional streams are not supported");
case Id.MainStreamsInfo:
streams = this.streamsInfo();
break;
case Id.FilesInfo:
files = this.filesInfo();
break;
default:
throw new Error(`7z: unexpected header id ${id}`);
}
}
return { streams, files };
}
private streamsInfo() {
const info: SevenZipStreamsInfo = {
packPos: 0,
packSizes: [],
folders: [],
};
for (let id = this.number(); id !== Id.End; id = this.number()) {
switch (id) {
case Id.PackInfo:
this.packInfo(info);
break;
case Id.UnpackInfo:
info.folders = this.unpackInfo();
break;
case Id.SubStreamsInfo:
this.subStreamsInfo(info.folders);
break;
default:
throw new Error(`7z: unexpected StreamsInfo id ${id}`);
}
}
let packIndex = 0;
for (const folder of info.folders) {
folder.firstPackStream = packIndex;
packIndex += folder.packedCount;
}
return info;
}
private packInfo(info: SevenZipStreamsInfo) {
info.packPos = this.number();
const count = this.number();
for (let id = this.number(); id !== Id.End; id = this.number()) {
switch (id) {
case Id.Size:
for (let i = 0; i < count; i++) info.packSizes.push(this.number());
break;
case Id.CRC:
this.digests(count);
break;
default:
throw new Error(`7z: unexpected PackInfo id ${id}`);
}
}
}
private unpackInfo() {
if (this.number() !== Id.Folder) throw new Error("7z: expected Folder");
const count = this.number();
if (this.uint8() !== 0) {
throw new Error("7z: external folders are not supported");
}
const folders: SevenZipFolder[] = [];
for (let i = 0; i < count; i++) folders.push(this.folder());
if (this.number() !== Id.CodersUnpackSize) {
throw new Error("7z: expected CodersUnpackSize");
}
// every coder output has a size, but single coder folders only have the one
for (const folder of folders) {
const outputs = folder.coders.reduce(
(sum, coder) => sum + coder.numOut,
0,
);
folder.unpackSize = this.number();
for (let i = 1; i < outputs; i++) this.number();
}
for (let id = this.number(); id !== Id.End; id = this.number()) {
switch (id) {
case Id.CRC:
this.digests(count).forEach((crc, i) => (folders[i].crc = crc));
break;
default:
throw new Error(`7z: unexpected UnpackInfo id ${id}`);
}
}
return folders;
}
private folder() {
const coderCount = this.number();
const coders: SevenZipCoder[] = [];
let totalIn = 0;
let totalOut = 0;
for (let i = 0; i < coderCount; i++) {
const flags = this.uint8();
if (flags & 0x80) {
throw new Error("7z: alternative coder methods are not supported");
}
// method ids are big endian
const method = this.consumeUint8Array(flags & 0x0f).reduce(
(value, byte) => value * 0x100 + byte,
0,
);
let numIn = 1;
let numOut = 1;
if (flags & 0x10) {
numIn = this.number();
numOut = this.number();
}
const props =
flags & 0x20
? this.consumeUint8Array(this.number())
: new Uint8Array(0);
coders.push({ method, numIn, numOut, props });
totalIn += numIn;
totalOut += numOut;
}
// bind pairs and packed stream indices only matter for coder chains, so they're skipped
const bindPairCount = totalOut - 1;
const packedCount = totalIn - bindPairCount;
for (let i = 0; i < bindPairCount * 2; i++) this.number();
if (packedCount > 1) for (let i = 0; i < packedCount; i++) this.number();
return {
coders,
packedCount,
firstPackStream: 0,
unpackSize: 0,
numUnpackStreams: 1,
} satisfies SevenZipFolder;
}
private subStreamsInfo(folders: SevenZipFolder[]) {
for (let id = this.number(); id !== Id.End; id = this.number()) {
switch (id) {
case Id.NumUnpackStream:
for (const folder of folders) folder.numUnpackStreams = this.number();
break;
// per file sizes only exist for solid folders, which are never read
case Id.Size:
for (const folder of folders) {
for (let i = 1; i < folder.numUnpackStreams; i++) this.number();
}
break;
// folders holding one file with a known crc have no digest here
case Id.CRC: {
const undigested = folders.filter(
(folder) =>
!(folder.numUnpackStreams === 1 && folder.crc !== undefined),
);
const total = undigested.reduce(
(sum, folder) => sum + folder.numUnpackStreams,
0,
);
const digests = this.digests(total);
let index = 0;
for (const folder of undigested) {
if (folder.numUnpackStreams === 1) folder.crc = digests[index];
index += folder.numUnpackStreams;
}
break;
}
default:
throw new Error(`7z: unexpected SubStreamsInfo id ${id}`);
}
}
}
private filesInfo() {
const count = this.number();
const files: SevenZipFileInfo[] = Array.from({ length: count }, () => ({
name: "",
hasStream: true,
isDir: false,
}));
let emptyStream: boolean[] | undefined;
let emptyFile: boolean[] | undefined;
for (let type = this.number(); type !== Id.End; type = this.number()) {
const data = new SevenZipReadStream(this.consume(this.number()));
switch (type) {
case Id.EmptyStream:
emptyStream = data.bits(count);
break;
case Id.EmptyFile:
emptyFile = data.bits(emptyStream?.filter(Boolean).length ?? 0);
break;
// names are consecutive null terminated utf-16 strings
case Id.Name: {
if (data.uint8() !== 0) {
throw new Error("7z: external names are not supported");
}
const names = new TextDecoder("utf-16le")
.decode(data.consumeRemaining())
.split("\0");
files.forEach((file, i) => (file.name = names[i]));
break;
}
// times, attributes, padding etc. are not needed
}
}
let emptyIndex = 0;
files.forEach((file, i) => {
if (!emptyStream?.[i]) return;
file.hasStream = false;
file.isDir = !emptyFile?.[emptyIndex];
emptyIndex++;
});
return files;
}
// 7z variable-length number: leading 1-bits in the first byte count extra bytes
private number() {
const first = this.uint8();
let mask = 0x80;
let value = 0;
for (let i = 0; i < 8; i++) {
if ((first & mask) === 0) {
return value + (first & (mask - 1)) * 2 ** (8 * i);
}
value += this.uint8() * 2 ** (8 * i);
mask >>>= 1;
}
return value;
}
private bits(count: number) {
const result: boolean[] = [];
let current = 0;
let mask = 0;
for (let i = 0; i < count; i++) {
if (mask === 0) {
current = this.uint8();
mask = 0x80;
}
result.push((current & mask) !== 0);
mask >>>= 1;
}
return result;
}
private digests(count: number) {
const defined =
this.uint8() !== 0
? new Array<boolean>(count).fill(true)
: this.bits(count);
return defined.map((isDefined) => (isDefined ? this.uint32() : undefined));
}
}
-1
View File
@@ -32,4 +32,3 @@ export * from "./vehicleDefinitionArmor";
export * from "./vehicleDefinitionList";
export * from "./vehicleDefinitions";
export * from "./vehicleFilter";
export * from "./wgcClient";
-87
View File
@@ -1,87 +0,0 @@
export interface WGCClientMetadata {
protocol: {
version: number;
predefined_section: PredefinedSection;
generated_section: GeneratedSection;
};
}
interface GeneratedSection {
launch_forbidden: string;
stop_supporting: string;
}
interface PredefinedSection {
app_id: string;
chain_id: string;
supported_languages: string;
default_language: string;
name: string;
fs_name: string;
shortcut_name: string;
executables: { executable: string };
keep_patches_interval: number;
client_types: { client_type: ClientType };
login_enabled: boolean;
realms_settings: RealmsSettings;
localization: Localization;
}
interface ClientType {
initial_app_type: string;
final_app_type: string;
min_supported_os: string;
client_parts: { client_part: string };
}
interface Localization {
item: { text: string[] };
}
interface RealmsSettings {
instances: { instance: Instance[] };
}
interface Instance {
game_id: string;
title_id: string;
platform_realm_id: string;
options: { option: string };
content_service_url: string;
}
export interface WGCPatchesChain {
protocol: {
parts_info: { part: Part };
patches_chain: { patch: Patch };
delay_preload: string;
web_seeds: { url: string };
meta_need_update: string;
version_name: string;
};
}
interface Part {
name: string;
version: number;
status: string;
}
interface Patch {
files: { file: File[] };
torrent: Torrent;
part: string;
version_from: number;
version_to: string;
}
interface File {
name: string;
size: number;
unpacked_size: number;
}
interface Torrent {
hash: string;
urls: { url: string };
}