@abextm/cache2
Version:
Utilities for reading OSRS "caches"
92 lines (91 loc) • 3.17 kB
JavaScript
import { Reader } from "./Reader.js";
export class Loadable {
static load(reader, ...args) {
if (reader instanceof ArrayBuffer || ArrayBuffer.isView(reader)) {
reader = new Reader(reader);
}
if (reader instanceof Reader) {
return this.decode(reader, ...args);
}
else {
return (async () => {
let data = await this.loadData(await reader, ...args);
if (data) {
return this.decode(data, ...args);
}
})();
}
}
}
export class PerArchiveLoadable extends Loadable {
static async loadData(cache, id) {
let archive = await cache.getArchive(this.index, id);
let version = await cache.getVersion(this.index);
let data = archive?.getFile(0)?.data;
return data ? new Reader(data, version) : undefined;
}
static async all(cache0) {
let cache = await cache0;
let ids = await cache.getArchives(this.index);
if (!ids) {
return [];
}
let archives = await Promise.all(ids.map(id => cache.getArchive(this.index, id)));
let version = await cache.getVersion(this.index);
return archives
.filter(v => v)
.map(v => {
try {
return this.decode(new Reader(v.getFile(0).data, version), v.archive);
}
catch (e) {
if (typeof e === "object" && e && "message" in e) {
let ea = e;
ea.message = v.archive + ": " + ea.message;
}
throw e;
}
});
}
}
export class NamedPerArchiveLoadable extends PerArchiveLoadable {
static async loadByName(cache0, name) {
let cache = await cache0;
let ar = await cache.getArchiveByName(this.index, name);
let version = await cache.getVersion(this.index);
let data = ar?.getFile(0)?.data;
if (data) {
return this.decode(new Reader(data, version), ar.archive);
}
}
}
export class PerFileLoadable extends Loadable {
static async loadData(cache, id) {
let archive = await cache.getArchive(this.index, this.archive);
let version = await cache.getVersion(this.index);
let data = archive?.getFile(id)?.data;
return data ? new Reader(data, version) : undefined;
}
static async all(cache0) {
let cache = await cache0;
let ad = await cache.getArchive(this.index, this.archive);
if (!ad) {
return [];
}
let version = await cache.getVersion(this.index);
return [...ad.getFiles().values()]
.filter(v => v.data.length > 1 && v.data[0] != 0)
.map(v => {
try {
return this.decode(new Reader(v.data, version), v.id);
}
catch (e) {
if (typeof e === "object" && e && "message" in e) {
let ea = e;
ea.message = v.id + ": " + ea.message;
}
throw e;
}
});
}
}