UNPKG

execution-engine

Version:

A TypeScript library for tracing and visualizing code execution workflows.

51 lines (50 loc) 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.trace = trace; const trace_1 = require("./trace"); const functionMetadata_1 = require("../common/utils/functionMetadata"); const isAsync_1 = require("../common/utils/isAsync"); /** * Method decorator to trace function execution, capturing metadata, inputs, outputs, and errors. * * @param onTraceEvent - handle function of the trace context. * @param additionalContext - Additional metadata to attach to the trace context. * @param options - Configuration options: * - `contextKey`: Key to store trace context on the instance. * - `errorStrategy`: Determines whether errors should be caught (`'catch'`) or thrown (`'throw'`). * * @returns A method decorator that wraps the original function with execution tracing. */ function trace(onTraceEvent, // eslint-disable-next-line @typescript-eslint/no-explicit-any additionalContext = {}, options = { contextKey: undefined, errorStrategy: 'throw' }) { return function (target, propertyKey, descriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args) { const thisTraceContext = { metadata: (0, functionMetadata_1.extractClassMethodMetadata)(target.constructor.name, propertyKey, originalMethod), ...additionalContext }; if (options.contextKey) { this[options.contextKey] = thisTraceContext; } if ((0, isAsync_1.isAsync)(originalMethod)) { return trace_1.executionTrace.bind(this)(originalMethod.bind(this), args, (traceContext) => { return onTraceEvent.bind(this)({ ...traceContext, ...thisTraceContext }); }, options)?.then((r) => (options?.errorStrategy === 'catch' ? r.errors : r.outputs)); } else { const result = trace_1.executionTrace.bind(this)(originalMethod.bind(this), args, (traceContext) => { return onTraceEvent.bind(this)({ ...traceContext, ...thisTraceContext }); }, options); if (result instanceof Promise) { return result.then((r) => (options?.errorStrategy === 'catch' ? r.errors : r.outputs)); } return result?.outputs; } }; }; }