diff options
Diffstat (limited to 'viewer/loader.ts')
-rw-r--r-- | viewer/loader.ts | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/viewer/loader.ts b/viewer/loader.ts new file mode 100644 index 0000000..487102f --- /dev/null +++ b/viewer/loader.ts @@ -0,0 +1,71 @@ +import { Resource, RespackEntry } from "./resources.ts"; + +export abstract class Loader { + num_loading: number = 0 + abstract download(res: Resource<undefined>): Promise<Uint8Array> + abstract get_entry(): Promise<Resource<RespackEntry>>; + abstract wait_ready(): Promise<void> +} + +export class HTTPLoader extends Loader { + constructor() { + super(); + } + // deno-lint-ignore require-await + async wait_ready(): Promise<void> { + return + } + async download<T>(res: Resource<T>): Promise<Uint8Array> { + this.num_loading += 1 + const resp = await fetch(`http://127.0.0.1:28556/${res.toString()}`) + if (!resp.ok) throw new Error("aaaa"); + const buf = await resp.bytes() + this.num_loading -= 1 + return buf + } + async get_entry(): Promise<Resource<RespackEntry>> { + const resp = await fetch("http://127.0.0.1:28556/entry") + if (!resp.ok) throw new Error("aaaa"); + return new Resource(await resp.bytes()) + } +} +export class WSLoader extends Loader { + ws: WebSocket + queue: ((r: Uint8Array) => void)[] = [] + constructor() { + super() + this.ws = new WebSocket(`http://127.0.0.1:28557/`) + this.ws.onopen = () => console.log("open"); + this.ws.onclose = () => console.log("close"); + this.ws.onmessage = m => { + if (typeof m.data == "string") throw new Error(m.data); + if (m.data instanceof Blob) { + const h = this.queue.shift()! + m.data.arrayBuffer() + .then(b => new Uint8Array(b)) + .then(h) + .then(() => this.num_loading -= 1) + } + } + } + wait_ready(): Promise<void> { + return new Promise(resolve => { + if (this.ws.readyState == this.ws.OPEN) return resolve() + else this.ws.addEventListener("open", () => resolve()) + }) + } + download<T>(res: Resource<T>): Promise<Uint8Array> { + return new Promise(resolve => { + this.num_loading += 1 + this.queue.push(resolve) + this.ws.send(res.hash) + }) + } + get_entry(): Promise<Resource<RespackEntry>> { + return new Promise(resolve => { + this.num_loading += 1 + this.queue.push(buf => resolve(new Resource(buf))) + this.ws.send("entry") + }) + } +} |