UNPKG

traceperf

Version:

High-performance function execution tracking and monitoring for Node.js

116 lines 2.92 kB
"use strict"; /** * Utilities for managing call stacks and function tracking */ Object.defineProperty(exports, "__esModule", { value: true }); exports.CallStackManager = void 0; exports.getFunctionName = getFunctionName; exports.getCallStack = getCallStack; /** * Extract the name of a function * * @param fn - The function to extract the name from * @returns The function name or a placeholder if not available */ function getFunctionName(fn) { if (fn.name) { return fn.name; } // Try to extract name from function toString() const fnStr = fn.toString(); const nameMatch = fnStr.match(/function\s+([^(]+)/); if (nameMatch) { return nameMatch[1].trim(); } // For arrow functions or anonymous functions const arrowMatch = fnStr.match(/^\s*(?:async\s+)?(?:\([^)]*\)|\w+)\s*=>/); if (arrowMatch) { return '<arrow function>'; } return '<anonymous>'; } /** * Get the current call stack * * @returns An array of function names in the call stack */ function getCallStack() { const stack = new Error().stack; if (!stack) { return []; } // Parse the stack trace return stack .split('\n') .slice(2) // Skip the Error and this function .map(line => { const match = line.match(/at\s+([^\s]+)/); return match ? match[1] : line.trim(); }); } /** * CallStackManager - Manages a call stack for execution tracking */ class CallStackManager { constructor() { this._stack = []; } /** * Push a function name onto the call stack * * @param name - The function name * @returns The current stack depth */ push(name) { this._stack.push(name); return this._stack.length; } /** * Pop a function name from the call stack * * @returns The popped function name or undefined if the stack is empty */ pop() { return this._stack.pop(); } /** * Get the current call stack * * @returns A copy of the current call stack */ getStack() { return [...this._stack]; } /** * Get the current stack depth * * @returns The current stack depth */ getDepth() { return this._stack.length; } /** * Clear the call stack */ clear() { this._stack = []; } /** * Get the current function name (top of the stack) * * @returns The current function name or undefined if the stack is empty */ getCurrentFunction() { return this._stack[this._stack.length - 1]; } /** * Get the parent function name * * @returns The parent function name or undefined if there is no parent */ getParentFunction() { return this._stack[this._stack.length - 2]; } } exports.CallStackManager = CallStackManager; //# sourceMappingURL=stack.js.map