UNPKG

2.57 kBJavaScriptView Raw
1/**
2 * The resource manager. Design to be able to use in both nodejs and browser environment.
3 * @template T The type of the resource content. If you use this in node, it's probably `Buffer`. If you are in browser, it might be `string`. Just align this with your `ResourceSource`
4 */
5export class ResourceManager {
6 constructor(list = []) {
7 this.list = list;
8 this.cache = {};
9 }
10 get allResourcePacks() { return this.list.map((l) => l.info); }
11 /**
12 * Add a new resource source to the end of the resource list.
13 */
14 async addResourcePack(resourcePack) {
15 let info;
16 try {
17 info = await resourcePack.info();
18 }
19 catch (_a) {
20 info = { pack_format: -1, description: "" };
21 }
22 const domains = await resourcePack.domains();
23 const wrapper = { info, source: resourcePack, domains };
24 this.list.push(wrapper);
25 }
26 /**
27 * Clear all cache
28 */
29 clearCache() { this.cache = {}; }
30 /**
31 * Clear all resource source and cache
32 */
33 clearAll() {
34 this.cache = {};
35 this.list.splice(0, this.list.length);
36 }
37 /**
38 * Swap the resource source priority.
39 */
40 swap(first, second) {
41 if (first >= this.list.length || first < 0 || second >= this.list.length || second < 0) {
42 throw new Error("Illegal index");
43 }
44 const fir = this.list[first];
45 this.list[first] = this.list[second];
46 this.list[second] = fir;
47 this.clearCache();
48 }
49 /**
50 * Invalidate the resource cache
51 */
52 invalidate(location) {
53 delete this.cache[`${location.domain}:${location.path}`];
54 }
55 /**
56 * Load the resource in that location. This will walk through current resource source list to load the resource.
57 * @param location The resource location
58 * @param urlOnly If true, it will force return uri, else it will return the normal resource content
59 */
60 async load(location, urlOnly = false) {
61 const cached = this.cache[`${location.domain}:${location.path}`];
62 if (cached) {
63 return cached;
64 }
65 for (const src of this.list) {
66 const loaded = await src.source.load(location, urlOnly);
67 if (!loaded) {
68 continue;
69 }
70 this.putCache(loaded);
71 return loaded;
72 }
73 return undefined;
74 }
75 putCache(res) {
76 this.cache[`${res.location.domain}:${res.location.path}`] = res;
77 }
78}
79export * from "./model-loader";