38 lines
1013 B
JavaScript
38 lines
1013 B
JavaScript
|
import Ecs from '@/ecs/ecs.js';
|
||
|
import Script from '@/util/script.js';
|
||
|
|
||
|
import {LRUCache} from 'lru-cache';
|
||
|
|
||
|
const cache = new LRUCache({
|
||
|
max: 128,
|
||
|
});
|
||
|
|
||
|
export default class ClientEcs extends Ecs {
|
||
|
async readAsset(uri) {
|
||
|
if (!cache.has(uri)) {
|
||
|
let promise, resolve, reject;
|
||
|
promise = new Promise((res, rej) => {
|
||
|
resolve = res;
|
||
|
reject = rej;
|
||
|
});
|
||
|
cache.set(uri, promise);
|
||
|
fetch(new URL(uri, window.location.origin))
|
||
|
.then(async (response) => {
|
||
|
resolve(response.ok ? response.arrayBuffer() : new ArrayBuffer(0));
|
||
|
})
|
||
|
.catch(reject);
|
||
|
}
|
||
|
return cache.get(uri);
|
||
|
}
|
||
|
async readJson(uri) {
|
||
|
const chars = await this.readAsset(uri);
|
||
|
return chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {};
|
||
|
}
|
||
|
async readScript(uri, context = {}) {
|
||
|
const code = await this.readAsset(uri);
|
||
|
if (code.byteLength > 0) {
|
||
|
return Script.fromCode((new TextDecoder()).decode(code), context);
|
||
|
}
|
||
|
}
|
||
|
}
|