39 lines
1.4 KiB
TypeScript
39 lines
1.4 KiB
TypeScript
import { ServerContentBase } from "../ContentBase.ts";
|
|
import type Command from "./command.ts";
|
|
|
|
export class CommandsBase extends ServerContentBase {
|
|
|
|
#cmds: Set<Command> = new Set();
|
|
|
|
addRootCommand(cmd: Command) {
|
|
this.#cmds.add(cmd);
|
|
}
|
|
|
|
removeRootCommandByKey(key: string) {
|
|
for (const cmd of this.#cmds) if (cmd.getKey().includes(key))
|
|
this.#cmds.delete(cmd);
|
|
}
|
|
|
|
removeRootCommand(cmd: Command) {
|
|
this.#cmds.delete(cmd);
|
|
}
|
|
|
|
async dispatch(...args: string[]): Promise<unknown> {
|
|
const root = args[0];
|
|
if (typeof root !== 'string') return new Error("Root command must be of primitive type 'string'");
|
|
else {
|
|
const cmd = this.#cmds.values().toArray().find(cmd => cmd.getKey().includes(root));
|
|
if (cmd) {
|
|
const val = await cmd.dispatch(...args.slice(1));
|
|
if (val == null) return "null";
|
|
else if (typeof val == 'string') return `"${val}"`;
|
|
else if (typeof val == 'undefined') return "undefined";
|
|
else if (val instanceof Error) return val;
|
|
else if (typeof val == 'object') return JSON.stringify(val);
|
|
else return String(val);
|
|
}
|
|
else return new Error(`'${root.trim()}': Command not found (args: "${args.join(' ')}")`);
|
|
}
|
|
}
|
|
|
|
} |