GoonCord/src/lib/managers/plugins.ts

178 lines
5.6 KiB
TypeScript
Raw Normal View History

2024-05-23 20:27:16 +08:00
import { allSettled } from "@core/polyfills/allSettled";
import { createVdPluginObject } from "@core/polyfills/vendettaObject";
2024-03-06 01:57:59 +08:00
import { awaitSyncWrapper, createMMKVBackend, createStorage, purgeStorage, wrapSync } from "@lib/api/storage";
import { settings } from "@lib/settings";
2023-04-15 19:54:23 +01:00
import { safeFetch } from "@lib/utils";
import { BUNNY_PROXY_PREFIX, PROXY_PREFIX } from "@lib/utils/constants";
2024-05-23 20:27:16 +08:00
import { logger } from "@lib/utils/logger";
2024-03-06 01:57:59 +08:00
import { Author } from "@lib/utils/types";
2023-01-03 08:05:16 +00:00
type EvaledPlugin = {
onLoad?(): void;
onUnload(): void;
settings: () => JSX.Element;
2023-01-03 08:05:16 +00:00
};
2024-02-23 15:11:35 +08:00
// See https://github.com/vendetta-mod/polymanifest
export interface PluginManifest {
name: string;
description: string;
authors: Author[];
main: string;
hash: string;
// Vendor-specific field, contains our own data
vendetta?: {
icon?: string;
};
}
2024-02-23 19:30:23 +08:00
export interface BunnyPlugin {
2024-02-23 15:11:35 +08:00
id: string;
manifest: PluginManifest;
enabled: boolean;
update: boolean;
2024-05-23 21:35:53 +08:00
error?: string;
2024-02-23 15:11:35 +08:00
js: string;
}
2024-02-23 19:30:23 +08:00
export const plugins = wrapSync(createStorage<Record<string, BunnyPlugin>>(createMMKVBackend("VENDETTA_PLUGINS")));
const loadedPlugins: Record<string, EvaledPlugin> = {};
2023-01-07 23:05:14 +00:00
async function pluginFetch(url: string) {
if (url.startsWith(PROXY_PREFIX)) {
url = url.replace(PROXY_PREFIX, BUNNY_PROXY_PREFIX);
}
return await safeFetch(url, { cache: "no-store" });
}
export async function fetchPlugin(id: string) {
2023-01-07 23:05:14 +00:00
if (!id.endsWith("/")) id += "/";
const existingPlugin = plugins[id];
let pluginManifest: PluginManifest;
try {
pluginManifest = await (await pluginFetch(id + "manifest.json")).json();
} catch {
2023-01-07 23:05:14 +00:00
throw new Error(`Failed to fetch manifest for ${id}`);
}
let pluginJs: string | undefined;
2023-01-03 08:05:16 +00:00
if (existingPlugin?.manifest.hash !== pluginManifest.hash) {
try {
// by polymanifest spec, plugins should always specify their main file, but just in case
pluginJs = await (await pluginFetch(id + (pluginManifest.main || "index.js"))).text();
2024-03-06 01:57:59 +08:00
} catch { } // Empty catch, checked below
}
2023-01-04 08:01:56 +00:00
2023-02-19 22:35:53 +00:00
if (!pluginJs && !existingPlugin) throw new Error(`Failed to fetch JS for ${id}`);
2023-01-03 08:05:16 +00:00
plugins[id] = {
id: id,
manifest: pluginManifest,
enabled: existingPlugin?.enabled ?? false,
update: existingPlugin?.update ?? true,
js: pluginJs ?? existingPlugin.js,
2024-05-23 21:35:53 +08:00
error: existingPlugin?.error
};
}
2023-01-30 00:40:56 +00:00
export async function installPlugin(id: string, enabled = true) {
if (!id.endsWith("/")) id += "/";
if (typeof id !== "string" || id in plugins) throw new Error("Plugin already installed");
await fetchPlugin(id);
2023-01-30 00:40:56 +00:00
if (enabled) await startPlugin(id);
2023-01-03 08:05:16 +00:00
}
2024-03-11 15:04:11 +08:00
/**
* @internal
*/
export async function evalPlugin(plugin: BunnyPlugin) {
2024-05-23 20:27:16 +08:00
const vdObject = await createVdPluginObject(plugin);
const pluginString = `vendetta=>{return ${plugin.js}}\n//# sourceURL=${plugin.id}?hash=${plugin.manifest.hash}`;
2023-01-03 08:05:16 +00:00
2024-05-23 20:27:16 +08:00
const raw = (0, eval)(pluginString)(vdObject);
2024-03-06 01:57:59 +08:00
const ret = typeof raw === "function" ? raw() : raw;
2023-04-16 14:02:22 +01:00
return ret?.default ?? ret ?? {};
2023-01-03 08:05:16 +00:00
}
export async function startPlugin(id: string) {
if (!id.endsWith("/")) id += "/";
2023-01-03 08:05:16 +00:00
const plugin = plugins[id];
if (!plugin) throw new Error("Attempted to start non-existent plugin");
try {
if (!settings.safeMode?.enabled) {
2024-03-11 15:04:11 +08:00
const pluginRet: EvaledPlugin = await evalPlugin(plugin);
loadedPlugins[id] = pluginRet;
pluginRet.onLoad?.();
}
2024-05-23 21:35:53 +08:00
delete plugin.error;
2023-01-03 08:05:16 +00:00
plugin.enabled = true;
} catch (e) {
2023-01-03 08:05:16 +00:00
logger.error(`Plugin ${plugin.id} errored whilst loading, and will be unloaded`, e);
2024-05-23 21:35:53 +08:00
plugin.error = e instanceof Error ? e.stack : String(e);
2023-01-03 08:05:16 +00:00
try {
loadedPlugins[plugin.id]?.onUnload?.();
} catch (e2) {
2023-01-03 08:05:16 +00:00
logger.error(`Plugin ${plugin.id} errored whilst unloading`, e2);
}
delete loadedPlugins[id];
plugin.enabled = false;
}
}
export function stopPlugin(id: string, disable = true) {
if (!id.endsWith("/")) id += "/";
2023-01-03 08:05:16 +00:00
const plugin = plugins[id];
const pluginRet = loadedPlugins[id];
if (!plugin) throw new Error("Attempted to stop non-existent plugin");
if (!settings.safeMode?.enabled) {
try {
pluginRet?.onUnload?.();
} catch (e) {
logger.error(`Plugin ${plugin.id} errored whilst unloading`, e);
}
delete loadedPlugins[id];
2023-01-03 08:05:16 +00:00
}
disable && (plugin.enabled = false);
2023-01-03 08:05:16 +00:00
}
export async function removePlugin(id: string) {
if (!id.endsWith("/")) id += "/";
const plugin = plugins[id];
if (plugin.enabled) stopPlugin(id);
2023-01-07 23:05:14 +00:00
delete plugins[id];
await purgeStorage(id);
2023-01-07 23:05:14 +00:00
}
2024-03-11 15:04:11 +08:00
/**
* @internal
*/
export async function initPlugins() {
await awaitSyncWrapper(settings);
2023-01-30 14:59:47 +01:00
await awaitSyncWrapper(plugins);
const allIds = Object.keys(plugins);
2023-02-20 18:58:07 +00:00
if (!settings.safeMode?.enabled) {
// Loop over any plugin that is enabled, update it if allowed, then start it.
2024-03-06 01:57:59 +08:00
await allSettled(allIds.filter(pl => plugins[pl].enabled).map(async pl => (plugins[pl].update && await fetchPlugin(pl).catch((e: Error) => logger.error(e.message)), await startPlugin(pl))));
// Wait for the above to finish, then update all disabled plugins that are allowed to.
allIds.filter(pl => !plugins[pl].enabled && plugins[pl].update).forEach(pl => fetchPlugin(pl));
2024-03-06 01:57:59 +08:00
}
return stopAllPlugins;
2023-01-30 14:59:47 +01:00
}
2023-02-05 00:10:34 +00:00
const stopAllPlugins = () => Object.keys(loadedPlugins).forEach(p => stopPlugin(p, false));
export const getSettings = (id: string) => loadedPlugins[id]?.settings;