@gramio/autoload
Version:
Autoload commands plugin for GramIO
51 lines (46 loc) • 2.01 kB
JavaScript
;
var path = require('node:path');
var url = require('node:url');
var fdir = require('fdir');
var gramio = require('gramio');
var process = require('node:process');
function getPath(dir) {
if (path.isAbsolute(dir)) return dir;
if (path.isAbsolute(process.argv[1]))
return path.join(process.argv[1], "..", dir);
return path.join(process.cwd(), process.argv[1], "..", dir);
}
async function autoload(options) {
const failGlob = options?.failGlob ?? true;
const patterns = typeof options?.patterns === "string" ? [options?.patterns] : options?.patterns ?? ["**/*.{ts,js,cjs,mjs}"];
const pathToAutoload = options?.path ?? "./commands";
const directoryPath = getPath(pathToAutoload);
const getImportName = options?.import ?? "default";
const plugin = new gramio.Plugin("@gramio/autoload");
const paths = await new fdir.fdir(options?.fdir || {}).withRelativePaths().globWithOptions(patterns, options?.picomatch || {}).crawl(directoryPath).withPromise();
if (failGlob && paths.length === 0)
throw new Error(
`No matches found in ${directoryPath}. You can disable this error by setting the failGlob parameter to false in the options of autoload plugin`
);
for await (const filePath of paths) {
const absolute = String(
url.pathToFileURL(path.join(directoryPath, filePath))
);
if (options?.onLoad) options.onLoad({ absolute, relative: filePath });
const file = await import(absolute);
const importName = typeof getImportName === "string" ? getImportName : getImportName(file);
if (!file[importName] && options?.skipImportErrors) continue;
if (!file[importName])
throw new Error(`${filePath} don't provide export ${importName}`);
plugin.group(file[importName]);
}
if (options?.onFinish)
options.onFinish(
paths.map((filePath) => ({
absolute: String(url.pathToFileURL(path.join(directoryPath, filePath))),
relative: filePath
}))
);
return plugin;
}
exports.autoload = autoload;