"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runtimeTracer = exports.RuntimeTracer = void 0;
class RuntimeTracer {
    maxRecords;
    spans = [];
    events = [];
    constructor(maxRecords = 500) {
        this.maxRecords = maxRecords;
    }
    startSpan(name, attributes = {}) {
        const record = {
            id: createTraceId(),
            name,
            startedAt: new Date().toISOString(),
            attributes,
        };
        const started = Date.now();
        this.spans.push(record);
        this.trim();
        return {
            id: record.id,
            end: (status = 'ok', attributes = {}) => {
                if (record.endedAt)
                    return;
                record.endedAt = new Date().toISOString();
                record.durationMs = Date.now() - started;
                record.status = status;
                record.attributes = { ...record.attributes, ...attributes };
            },
            fail: (error, attributes = {}) => {
                if (record.endedAt)
                    return;
                record.endedAt = new Date().toISOString();
                record.durationMs = Date.now() - started;
                record.status = 'error';
                record.error = error instanceof Error ? error.message : String(error);
                record.attributes = { ...record.attributes, ...attributes };
            },
        };
    }
    recordEvent(name, attributes = {}) {
        this.events.push({ id: createTraceId(), name, timestamp: new Date().toISOString(), attributes });
        this.trim();
    }
    snapshot() {
        return {
            spans: this.spans.map((span) => ({ ...span, attributes: { ...span.attributes } })),
            events: this.events.map((event) => ({ ...event, attributes: { ...event.attributes } })),
        };
    }
    clear() {
        this.spans = [];
        this.events = [];
    }
    trim() {
        if (this.spans.length > this.maxRecords) {
            this.spans = this.spans.slice(-this.maxRecords);
        }
        if (this.events.length > this.maxRecords) {
            this.events = this.events.slice(-this.maxRecords);
        }
    }
}
exports.RuntimeTracer = RuntimeTracer;
exports.runtimeTracer = new RuntimeTracer();
function createTraceId() {
    return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
//# sourceMappingURL=tracing.js.map