GoonCord/src/lib/api/assets.ts

57 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-05-10 02:15:32 +08:00
// TODO: Rewrite the whole thing to fit new metro :3
import { after } from "@lib/api/patcher";
2024-05-20 15:36:33 +08:00
import { getMetroCache, registerAssetCacheId } from "@metro/caches";
import { getImportingModuleId, requireModule } from "@metro/modules";
2022-10-22 23:26:06 +01:00
export const all: Record<string, Asset> = {};
2022-10-22 23:26:06 +01:00
2024-02-23 15:11:35 +08:00
export interface Asset {
name: string;
id: number;
2024-05-10 02:15:32 +08:00
moduleId: number;
}
interface AssetModule {
registerAsset(assetDefinition: any): number;
getAssetByID(id: number): any;
2024-02-23 15:11:35 +08:00
}
2024-05-10 02:15:32 +08:00
let assetsModule: AssetModule;
2024-03-11 15:04:11 +08:00
/**
* @internal
*/
2024-05-10 02:15:32 +08:00
export function patchAssets(module: AssetModule) {
if (assetsModule) return;
assetsModule = module;
const unpatch = after("registerAsset", assetsModule, (args: Asset[], id: number) => {
const asset = args[0];
2024-05-10 02:15:32 +08:00
const moduleId = Number(getImportingModuleId());
registerAssetCacheId(asset.name, moduleId);
all[asset.name] = {
...asset,
id,
moduleId
};
});
2022-10-22 23:26:06 +01:00
for (let id = 1; ; id++) {
2024-05-10 02:15:32 +08:00
const asset = assetsModule.getAssetByID(id);
if (!asset) break;
if (all[asset.name]) continue;
all[asset.name] = { ...asset, id: id };
2024-03-06 01:57:59 +08:00
}
return unpatch;
2022-10-22 23:26:06 +01:00
}
export const find = (filter: (a: any) => void): Asset | null | undefined => Object.values(all).find(filter);
export const getAssetByName = (name: string): Asset => all[name];
2024-05-10 02:15:32 +08:00
export const getAssetByID = (id: number): Asset => assetsModule.getAssetByID(id);
2024-05-20 20:42:57 +08:00
export const getAssetIDByName = (name: string) => all[name]?.id ?? requireModule(getMetroCache().assetsIndex[name]);