UNPKG

@krauters/debuggable

Version:

A TypeScript utility that automatically adds detailed debug logs before and after method calls in classes, simplifying the tracking of execution flow and troubleshooting.

42 lines 1.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.debuggable = debuggable; const duration_tracker_1 = require("./duration-tracker"); const utils_1 = require("./utils"); function debuggable(log) { const tracker = new duration_tracker_1.DurationTracker(log); log ??= console; return function (target, context) { const className = String(context?.name ?? target.name); logMethods(log, className, tracker)(target); logMethods(log, className, tracker)(target.prototype); }; } function logMethods(log, className, tracker) { return function (target) { if (typeof target !== 'object' && typeof target !== 'function') { log.debug(`Target [${target}] is not an object or function, skipping decoration`); return; } const keys = Reflect.ownKeys(target); log.debug(`Decorating the following [${className}] methods with debuggable: [${keys.join(', ')}]`); keys.forEach((key) => { const method = String(key); const descriptor = Object.getOwnPropertyDescriptor(target, key); if (descriptor && typeof descriptor.value === 'function') { const originalMethod = descriptor.value; descriptor.value = function (...args) { log.debug((0, utils_1.getPreRunLog)({ args, className, method })); const trackerKey = tracker.start(method); const result = originalMethod.apply(this, args); const duration = tracker.end(String(trackerKey)); const suffix = duration !== undefined ? ` and took [${duration}] ms` : ``; log.debug((0, utils_1.getPostRunLog)({ className, method, result, suffix })); return result; }; Object.defineProperty(target, key, descriptor); } }); }; } //# sourceMappingURL=decorators.js.map