import { ZenithClient } from '../Client'; import { Logger } from '../Helpers'; import { Collection, Util } from '../Util'; import * as fs from 'fs-nextra'; import { relative, sep, join, extname } from 'path'; export class HandlerModule extends Collection { public client: ZenithClient; public name: string; public coreDirs: any; public userDirs: any; public Directories: any; private Log: Logger; constructor(client, name) { super(); this.Log = new Logger('Handler'); this.client = client; this.name = name; this.coreDirs = new Set(); this.userDirs = new Set(); this.Directories = new Set(); } static get [Symbol.species]() { return Collection; } async registeruserDirs(dir) { this.userDirs.add(dir + this.name); return this; } async registercoreDirs(dir) { this.coreDirs.add(dir + this.name); return this; } async init() { await this.map(module => module.enabled ? module.init() : module.unload()); } async loadAll() { this.clear(); for (const dir of this.coreDirs) await this.loadAllHelper(this, dir); for (const userDir of this.userDirs) await this.loadAllHelper(this, userDir); } async loadAllHelper(handler, dir = `${__dirname}../../../${this.name}`) { // @ts-ignore const files = await fs.scan(dir, { filter: (stats, path) => extname(path) === '.js' }) .catch(err => this.Log.error(err)); if (!files) return true; return await Promise.all([...files.keys()] .map(file => handler.load(dir, relative(dir, file).split(sep)))); } async load(dir, file) { const location = join(dir, ...file); let module = null; try { const Module = (request => request.default || request)(require(location)); if (!Util.isClass) throw new TypeError('Exported Module is not a class.'); module = new Module(this.client, this, file, dir); await this.setup(module); } catch (err) { this.Log.error(`Failed to load file ${location}. Error:\n${err.stack || err}`); } delete require.cache[location]; return module; } setup(module) { const existing = this.get(module.name); if (existing) this.delete(existing); super.set(module.name, module); if (this.name === 'events') this.client.on(module.name, module.run.bind(this)); return module; } }