rashi-discord-bot-lib
Version:
🚀 Powerful Discord bot framework with built-in database, event handling, and utilities
201 lines • 6.8 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileLoader = void 0;
// src/utils/FileLoader.ts
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class FileLoader {
defaultOptions = {
extensions: ['.js', '.ts'],
recursive: true,
blacklist: [],
requireDefault: true,
};
constructor() { }
/**
* Load all files from directory with given options
*/
async loadFiles(dirPath, options = {}) {
const opts = { ...this.defaultOptions, ...options };
const result = {
files: [],
count: 0,
errors: [],
};
try {
if (!fs.existsSync(dirPath)) {
// brak katalogu -> po prostu zwróć pusty wynik
return result;
}
const filePaths = this.getFilePaths(dirPath, opts);
for (const filePath of filePaths) {
const fileName = this.getFileNameFromPath(filePath);
if (opts.blacklist?.includes(fileName)) {
// pomiń z blacklisty
continue;
}
try {
const loadedFile = await this.loadFile(filePath, opts);
if (loadedFile) {
result.files.push(loadedFile);
result.count++;
}
}
catch (error) {
result.errors.push(`Failed to load file ${filePath}: ${error}`);
}
}
return result;
}
catch (error) {
result.errors.push(`Failed to load files from ${dirPath}: ${error}`);
return result;
}
}
/**
* Load single file
*/
async loadFile(filePath, options = {}) {
const opts = { ...this.defaultOptions, ...options };
try {
// wyczyść cache require dla hot-reloadu
const resolvedPath = require.resolve(path.resolve(filePath));
delete require.cache[resolvedPath];
const moduleExport = require(resolvedPath);
// wspieraj default export i commonjs
let loadedModule;
if (opts.requireDefault && moduleExport?.default) {
loadedModule = moduleExport.default;
}
else if (opts.requireDefault && !moduleExport.default && typeof moduleExport === 'object') {
loadedModule = moduleExport;
}
else {
loadedModule = moduleExport;
}
if (!this.validateLoadedModule(loadedModule)) {
return null;
}
return loadedModule;
}
catch (error) {
// fallback dla .ts: dynamic import
if (filePath.endsWith('.ts')) {
return await this.loadTypeScriptFile(filePath, opts);
}
throw error;
}
}
/**
* Alternative TypeScript file loading
*/
async loadTypeScriptFile(filePath, options) {
try {
const moduleUrl = path.resolve(filePath);
const moduleExport = await Promise.resolve(`${moduleUrl}`).then(s => __importStar(require(s)));
let loadedModule;
if (options.requireDefault && moduleExport?.default) {
loadedModule = moduleExport.default;
}
else {
loadedModule = moduleExport;
}
if (!this.validateLoadedModule(loadedModule)) {
return null;
}
return loadedModule;
}
catch {
return null;
}
}
/**
* Get all file paths from directory
*/
getFilePaths(dirPath, options) {
const files = [];
const scanDirectory = (currentDir) => {
const items = fs.readdirSync(currentDir);
for (const item of items) {
const fullPath = path.join(currentDir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory() && options.recursive) {
scanDirectory(fullPath);
}
else if (stat.isFile() && this.isValidFile(item, options.extensions)) {
files.push(fullPath);
}
}
};
scanDirectory(dirPath);
return files;
}
/**
* Check if file has valid extension
*/
isValidFile(filename, extensions) {
if (filename.endsWith('.d.ts'))
return false;
return extensions.some((ext) => filename.endsWith(ext));
}
/**
* Get file name without extension from path
*/
getFileNameFromPath(filePath) {
const filename = path.basename(filePath);
return filename.replace(/\.(js|ts)$/, '');
}
/**
* Validate loaded module (override in subclasses)
*/
validateLoadedModule(mod) {
return !!mod && typeof mod === 'object';
}
/**
* Helpers
*/
static getFileExtension(filename) {
return path.extname(filename);
}
static pathExists(filePath) {
return fs.existsSync(filePath);
}
static getRelativePath(from, to) {
return path.relative(from, to);
}
}
exports.FileLoader = FileLoader;
//# sourceMappingURL=FileLoader.js.map