execution-engine
Version:
A TypeScript library for tracing and visualizing code execution workflows.
75 lines (74 loc) • 2.78 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.EngineTask = void 0;
exports.engine = engine;
exports.run = run;
/* eslint-disable @typescript-eslint/no-explicit-any */
const executionEngine_1 = require("./executionEngine");
/* eslint-disable @typescript-eslint/no-unsafe-function-type */
function isAsync(func) {
return func.constructor.name === 'AsyncFunction';
}
const executionEngines = {};
/**
* Represents an abstract EngineTask with a reference to the ExecutionEngine.
*
* @abstract
*/
class EngineTask {
}
exports.EngineTask = EngineTask;
/**
* A class decorator that enhances a class with execution engine capabilities.
* @param options - Configuration options for the execution engine.
*/
function engine(options) {
/**
* The actual decorator function.
* @param target - The target class.
*/
return (target) => {
const originalConstructor = target;
/**
* A new constructor function that incorporates the execution engine.
* @param args - Arguments passed to the constructor.
*/
const newConstructor = function (...args) {
const instance = new originalConstructor(...args);
let executionId = options?.id;
if (!executionId || !executionEngines[executionId]) {
const engineInstance = new executionEngine_1.ExecutionEngine({ executionId: options?.id });
executionId = engineInstance.getOptions().executionId;
executionEngines[executionId] = engineInstance;
}
instance.engine = executionEngines[executionId];
return instance;
};
// Optionally, you can copy prototype methods from the original constructor to the new one
Object.setPrototypeOf(newConstructor, originalConstructor.prototype);
// Return the new constructor
return newConstructor;
};
}
/**
* A method decorator that enables tracing for the decorated method.
*
* @param {TraceOptions<Array<any>, O> | TraceOptions<Array<any>, O>['trace']} [options] - Optional tracing options.
* @returns {Function} - A decorator function.
*/
function run(options) {
return function (target, propertyKey, descriptor) {
// Store the original method
const originalMethod = descriptor.value;
// Modify the descriptor's value property
descriptor.value = function (...args) {
if (isAsync(originalMethod)) {
return this.engine.run(originalMethod.bind(this), args, options)?.then((r) => r.outputs);
}
else {
return this.engine.run(originalMethod.bind(this), args, options)?.outputs;
}
};
return descriptor;
};
}
;