Refactor of asset bundles

This commit is contained in:
Zef Hemel
2022-10-12 11:47:13 +02:00
parent 9dd94c5397
commit 4c19ab21f2
96 changed files with 6279 additions and 770 deletions
+69
View File
@@ -0,0 +1,69 @@
import { base64Decode, base64Encode } from "./base64.ts";
import { mime } from "../deps.ts";
export type AssetJson = Record<string, string>;
export class AssetBundle {
readonly bundle: AssetJson;
constructor(bundle: AssetJson = {}) {
this.bundle = bundle;
}
has(path: string): boolean {
return path in this.bundle;
}
listFiles(): string[] {
return Object.keys(this.bundle);
}
readFileSync(
path: string,
): Uint8Array {
const content = this.bundle[path];
if (!content) {
throw new Error(`No such file ${path}`);
}
const data = content.split(",", 2)[1];
return base64Decode(data);
}
readFileAsDataUrl(path: string): string {
const content = this.bundle[path];
if (!content) {
throw new Error(`No such file ${path}`);
}
return content;
}
readTextFileSync(
path: string,
): string {
return new TextDecoder().decode(this.readFileSync(path));
}
getMimeType(
path: string,
): string {
const content = this.bundle[path];
if (!content) {
throw new Error(`No such file ${path}`);
}
return content.split(";")[0].split(":")[1];
}
writeFileSync(path: string, data: Uint8Array) {
const encoded = base64Encode(data);
const mimeType = mime.getType(path);
this.bundle[path] = `data:${mimeType};base64,${encoded}`;
}
writeTextFileSync(path: string, s: string) {
this.writeFileSync(path, new TextEncoder().encode(s));
}
toJSON(): AssetJson {
return this.bundle;
}
}