parea-ai
Version:
Client SDK library to connect to Parea AI.
79 lines (78 loc) • 3.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = trace;
exports.traceInsert = traceInsert;
exports.getCurrentTraceId = getCurrentTraceId;
const TraceManager_1 = require("./core/TraceManager");
const helpers_1 = require("./helpers");
/**
* Wraps a function with tracing functionality.
* @param name The name of the trace.
* @param fn The function to wrap.
* @param options Additional options for the trace.
* @returns The wrapped function.
*/
function trace(name, fn, options) {
return function (...args) {
const traceDisabled = process.env.PAREA_TRACE_ENABLED === 'false';
if (traceDisabled) {
return fn.apply(this, args);
}
const traceManager = TraceManager_1.TraceManager.getInstance();
return traceManager.runInContext(() => {
let target;
const opts = options || {};
const numParams = (0, helpers_1.extractFunctionParamNames)(fn)?.length || 0;
if (args?.length > numParams && typeof args[args.length - 1] === 'string') {
target = args.pop();
opts.target = target;
}
const trace = traceManager.createTrace(name, opts);
const inputs = (0, helpers_1.extractFunctionParams)(fn, args);
trace.updateLog({ inputs });
try {
const result = fn.apply(this, args);
if (result instanceof Promise) {
return result.then((value) => {
traceManager.setTraceOutput(trace, value, options?.accessOutputOfFunc);
traceManager.finalizeTrace(trace);
return value;
}, (error) => {
trace.updateLog({ error: error.toString(), status: 'error' });
traceManager.finalizeTrace(trace);
throw error;
});
}
else {
traceManager.setTraceOutput(trace, result, options?.accessOutputOfFunc);
traceManager.finalizeTrace(trace);
return result;
}
}
catch (error) {
const msg = `Error occurred in traced function '${name}: trace_id: ${trace.id}', ${error.toString()}`;
console.error(msg, error);
trace.updateLog({ error: msg, status: 'error' });
traceManager.finalizeTrace(trace);
throw error;
}
});
};
}
/**
* Inserts data into the current trace log or a specified trace log.
* @param data The data to insert into the trace log.
* @param traceId Optional trace ID to insert data into. If not provided, uses the current trace.
*/
function traceInsert(data, traceId) {
const traceManager = TraceManager_1.TraceManager.getInstance();
traceManager.insertTraceData(data, traceId);
}
/**
* Retrieves the ID of the current trace.
* @returns The current trace ID or undefined if no trace is active.
*/
function getCurrentTraceId() {
const traceManager = TraceManager_1.TraceManager.getInstance();
return traceManager.getCurrentTraceId();
}