"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get MonitoringService () {
        return MonitoringService;
    },
    get getMonitoring () {
        return getMonitoring;
    },
    get initMonitoring () {
        return initMonitoring;
    }
});
const _logger = require("./logger");
const _errors = require("./errors");
const _performance = require("./performance");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
let MonitoringService = class MonitoringService {
    /**
   * 初始化错误捕获
   */ initErrorCapture() {
        // 捕获未处理的 Promise 错误
        this.unhandledRejectionHandler = (event)=>{
            const error = _errors.errorUtils.normalizeError(event.reason);
            this.captureError(error, {
                type: 'unhandledrejection',
                reason: event.reason
            });
        };
        window.addEventListener('unhandledrejection', this.unhandledRejectionHandler);
        // 捕获全局错误
        this.errorHandler = (event)=>{
            const error = _errors.errorUtils.normalizeError(event.error || new Error(event.message));
            this.captureError(error, {
                type: 'global',
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno
            });
        };
        window.addEventListener('error', this.errorHandler);
    }
    /**
   * 清理资源
   */ destroy() {
        // 移除事件监听器
        if (typeof window !== 'undefined') {
            if (this.unhandledRejectionHandler) {
                window.removeEventListener('unhandledrejection', this.unhandledRejectionHandler);
            }
            if (this.errorHandler) {
                window.removeEventListener('error', this.errorHandler);
            }
        }
        // 停止聚合定时器
        if (this.aggregationTimer) {
            clearInterval(this.aggregationTimer);
            this.aggregationTimer = undefined;
        }
        // 清空错误处理器
        this.errorHandlers = [];
        this.errorRecords = [];
        this.errorAggregations.clear();
    }
    /**
   * 启动错误聚合定时器
   */ startAggregationTimer() {
        this.aggregationTimer = setInterval(()=>{
            this.aggregateErrors();
        }, this.errorConfig.aggregationWindow);
    }
    /**
   * 聚合错误
   */ aggregateErrors() {
        const now = Date.now();
        const windowStart = now - this.errorConfig.aggregationWindow;
        // 过滤窗口内的错误
        const windowErrors = this.errorRecords.filter((record)=>record.timestamp >= windowStart);
        // 按错误代码聚合
        const aggregations = new Map();
        for (const record of windowErrors){
            const error = record.error;
            const key = `${error.code}_${error.type}`;
            if (!aggregations.has(key)) {
                aggregations.set(key, {
                    code: error.code,
                    message: error.message,
                    type: error.type,
                    count: 0,
                    firstOccurrence: record.timestamp,
                    lastOccurrence: record.timestamp,
                    stack: error.originalError?.stack,
                    context: error.context
                });
            }
            const agg = aggregations.get(key);
            agg.count++;
            agg.lastOccurrence = Math.max(agg.lastOccurrence, record.timestamp);
        }
        // 更新聚合结果
        this.errorAggregations = aggregations;
    }
    /**
   * 捕获错误
   */ captureError(error, context) {
        // 采样检查
        if (Math.random() > this.errorConfig.sampleRate) {
            return;
        }
        const normalizedError = _errors.errorUtils.normalizeError(error);
        // 创建带上下文的错误对象（使用 Object.assign 来更新只读属性）
        const errorWithContext = Object.assign(normalizedError, {
            context: {
                ...normalizedError.context,
                ...context,
                timestamp: new Date().toISOString(),
                userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,
                url: typeof window !== 'undefined' ? window.location.href : undefined
            }
        });
        // 记录错误
        const timestamp = Date.now();
        this.errorRecords.push({
            error: errorWithContext,
            timestamp
        });
        // 限制错误记录数量
        if (this.errorRecords.length > this.errorConfig.maxErrorRecords) {
            this.errorRecords.shift();
        }
        // 记录日志
        if (this.errorConfig.showInConsole) {
            _logger.logger.error('监控服务捕获到错误:', errorWithContext.toJSON());
        }
        // 调用错误回调
        this.errorConfig.onError(errorWithContext, context);
        // 调用注册的错误处理器
        this.errorHandlers.forEach((handler)=>{
            try {
                handler(errorWithContext);
            } catch (e) {
            // 忽略处理器错误
            }
        });
    }
    /**
   * 获取错误聚合信息
   * 
   * @param code - 错误代码（可选，如果提供则只返回该错误的聚合信息）
   * @returns 错误聚合信息
   */ getErrorAggregations(code) {
        if (code) {
            const aggregation = this.errorAggregations.get(code);
            return aggregation ? [
                aggregation
            ] : [];
        }
        return Array.from(this.errorAggregations.values());
    }
    /**
   * 获取错误记录
   * 
   * @param limit - 限制返回的记录数
   * @param since - 只返回此时间之后的错误
   * @returns 错误记录
   */ getErrorRecords(limit, since) {
        let records = this.errorRecords;
        if (since) {
            records = records.filter((record)=>record.timestamp >= since);
        }
        if (limit) {
            records = records.slice(-limit);
        }
        return [
            ...records
        ];
    }
    /**
   * 清空错误记录
   */ clearErrorRecords() {
        this.errorRecords = [];
        this.errorAggregations.clear();
    }
    /**
   * 注册错误处理器
   */ onError(handler) {
        this.errorHandlers.push(handler);
        return ()=>{
            const index = this.errorHandlers.indexOf(handler);
            if (index > -1) {
                this.errorHandlers.splice(index, 1);
            }
        };
    }
    /**
   * 上报性能指标
   */ reportPerformance(metrics, context) {
        // 将传入的指标转换为带单位的格式
        const metricsWithUnits = (0, _performance.convertMetricsToWithUnits)(metrics);
        // 合并到现有指标中
        this.performanceMetrics = {
            ...this.performanceMetrics,
            ...metricsWithUnits
        };
        // 记录性能指标（带上下文）
        if (context) {
            _logger.logger.debug('性能指标更新:', {
                metrics: metricsWithUnits,
                context
            });
        } else {
            _logger.logger.debug('性能指标更新:', metricsWithUnits);
        }
    }
    /**
   * 批量上报性能指标
   */ reportPerformanceBatch(metricsArray) {
        for (const { metrics, context } of metricsArray){
            this.reportPerformance(metrics, context);
        }
    }
    /**
   * 获取性能指标（带单位）
   */ getPerformanceMetrics() {
        return {
            ...this.performanceMetrics
        };
    }
    /**
   * 获取性能指标（原始数值格式，向后兼容）
   */ getPerformanceMetricsRaw() {
        const result = {};
        for (const [key, metricValue] of Object.entries(this.performanceMetrics)){
            if (metricValue && typeof metricValue === 'object' && 'value' in metricValue) {
                result[key] = metricValue.value;
            }
        }
        return result;
    }
    /**
   * 记录用户行为（匿名）
   */ trackEvent(eventName, properties) {
        _logger.logger.debug('用户事件:', {
            eventName,
            properties
        });
    }
    constructor(errorConfig = {}){
        _define_property(this, "errorConfig", void 0);
        _define_property(this, "errorHandlers", []);
        _define_property(this, "performanceMetrics", {});
        _define_property(this, "unhandledRejectionHandler", void 0);
        _define_property(this, "errorHandler", void 0);
        _define_property(this, "errorRecords", []);
        _define_property(this, "errorAggregations", new Map());
        _define_property(this, "aggregationTimer", void 0);
        this.errorConfig = {
            autoCapture: errorConfig.autoCapture ?? true,
            onError: errorConfig.onError ?? (()=>{}),
            sampleRate: errorConfig.sampleRate ?? 1.0,
            showInConsole: errorConfig.showInConsole ?? true,
            enableAggregation: errorConfig.enableAggregation ?? true,
            aggregationWindow: errorConfig.aggregationWindow ?? 60000,
            maxErrorRecords: errorConfig.maxErrorRecords ?? 1000
        };
        if (this.errorConfig.autoCapture && typeof window !== 'undefined') {
            this.initErrorCapture();
        }
        // 启动错误聚合定时器
        if (this.errorConfig.enableAggregation) {
            this.startAggregationTimer();
        }
    }
};
/**
 * 默认监控服务实例
 */ let defaultMonitoringService = null;
function initMonitoring(config) {
    if (!defaultMonitoringService) {
        defaultMonitoringService = new MonitoringService(config);
    }
    return defaultMonitoringService;
}
function getMonitoring() {
    if (!defaultMonitoringService) {
        return initMonitoring();
    }
    return defaultMonitoringService;
}

//# sourceMappingURL=monitoring.js.map