@devgrid/netron
Version:
Event bus, streams and remote object invocation.
86 lines • 2.95 kB
JavaScript
import { pathToFileURL } from 'url';
import { readdir } from 'fs/promises';
export class TaskManager {
constructor({ timeout = 5000, overwriteStrategy = 'replace', } = {}) {
this.tasks = new Map();
this.timeout = timeout;
this.overwriteStrategy = overwriteStrategy;
}
addTask(fn) {
if (typeof fn !== 'function') {
throw new Error('Task must be a function');
}
if (!fn.name) {
throw new Error('Task function must have a name');
}
const existingTask = this.tasks.get(fn.name);
if (existingTask) {
switch (this.overwriteStrategy) {
case 'replace':
this.tasks.set(fn.name, fn);
break;
case 'skip':
return;
case 'throw':
throw new Error(`Task already exists: ${fn.name}`);
default:
throw new Error(`Unknown overwrite strategy: ${this.overwriteStrategy}`);
}
}
else {
this.tasks.set(fn.name, fn);
}
}
async loadTasksFromDir(directory) {
try {
const files = (await readdir(directory)).filter((f) => f.endsWith('.js'));
for (const file of files) {
let fileUrl = `${directory}/${file}`;
if (typeof require !== 'function') {
fileUrl = pathToFileURL(`${directory}/${file}`).href;
}
const module = await import(fileUrl);
this._registerModule(module);
}
}
catch (error) {
throw new Error(`Failed to load tasks from directory (${directory}): ${error.message || error}`);
}
}
async runTask(name, ...args) {
const task = this.tasks.get(name);
if (!task) {
throw new Error(`Task not found: ${name}`);
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Task timed out: ${name} (${this.timeout}ms)`));
}, this.timeout);
try {
const result = task(...args);
if (result instanceof Promise) {
result
.then(resolve)
.catch(reject)
.finally(() => clearTimeout(timer));
}
else {
clearTimeout(timer);
resolve(result);
}
}
catch (error) {
clearTimeout(timer);
reject(error);
}
});
}
_registerModule(module) {
for (const [name, fn] of Object.entries(module)) {
if (typeof fn === 'function') {
this.addTask(fn);
}
}
}
}
//# sourceMappingURL=task-manager.js.map