/**
 * 性能指标单位常量
 */ "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 PERFORMANCE_METRIC_UNITS () {
        return PERFORMANCE_METRIC_UNITS;
    },
    get PERFORMANCE_METRIC_UNIT_MAP () {
        return PERFORMANCE_METRIC_UNIT_MAP;
    },
    get PerformanceMonitor () {
        return PerformanceMonitor;
    },
    get convertMetricsToWithUnits () {
        return convertMetricsToWithUnits;
    }
});
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;
}
const PERFORMANCE_METRIC_UNITS = {
    /**
   * 毫秒单位
   */ ms: 'ms',
    /**
   * 无单位（分数）
   */ none: ''
};
let PerformanceMonitor = class PerformanceMonitor {
    /**
   * 初始化 Web Vitals 收集
   */ initWebVitals() {
        // 采样检查移到每次上报时进行，而不是初始化时
        // 这样可以确保监控功能始终初始化，只是选择性上报
        // 首次内容绘制 (FCP)
        this.observePaint('first-contentful-paint', (entry)=>{
            if (Math.random() <= this.config.sampleRate) {
                this.metrics.fcp = Math.round(entry.startTime);
                this.reportInternal();
            }
        });
        // 最大内容绘制 (LCP)
        this.observeLCP();
        // 首次输入延迟 (FID)
        this.observeFID();
        // 累积布局偏移 (CLS)
        this.observeCLS();
        // 可交互时间 (TTI) - 需要计算（延迟到页面加载完成后）
        if (typeof window !== 'undefined' && document.readyState === 'complete') {
            this.calculateTTI();
        } else if (typeof window !== 'undefined') {
            window.addEventListener('load', ()=>{
                // 使用 requestIdleCallback 在空闲时计算
                if (typeof requestIdleCallback !== 'undefined') {
                    requestIdleCallback(()=>{
                        this.calculateTTI();
                    }, {
                        timeout: 2000
                    });
                } else {
                    setTimeout(()=>{
                        this.calculateTTI();
                    }, 1000);
                }
            });
        }
    }
    /**
   * 观察 Paint 指标
   */ observePaint(name, callback) {
        if (typeof PerformanceObserver === 'undefined') {
            return;
        }
        try {
            const observer = new PerformanceObserver((list)=>{
                for (const entry of list.getEntries()){
                    if (entry.name === name) {
                        callback(entry);
                        observer.disconnect();
                    }
                }
            });
            observer.observe({
                entryTypes: [
                    'paint'
                ]
            });
            this.observers.push(observer);
        } catch (e) {
        // PerformanceObserver 不支持或已断开
        }
    }
    /**
   * 观察 LCP
   */ observeLCP() {
        if (typeof PerformanceObserver === 'undefined') {
            return;
        }
        try {
            const observer = new PerformanceObserver((list)=>{
                const entries = list.getEntries();
                const lastEntry = entries[entries.length - 1];
                const lcpValue = Math.round(lastEntry.renderTime || lastEntry.loadTime || lastEntry.startTime);
                // 采样检查和异常值检查
                if (Math.random() <= this.config.sampleRate && lcpValue > 0 && lcpValue < 60000) {
                    this.metrics.lcp = lcpValue;
                    this.reportInternal();
                }
            });
            observer.observe({
                entryTypes: [
                    'largest-contentful-paint'
                ]
            });
            this.observers.push(observer);
        } catch (e) {
        // PerformanceObserver 不支持
        }
    }
    /**
   * 观察 FID
   */ observeFID() {
        if (typeof PerformanceObserver === 'undefined') {
            return;
        }
        try {
            const observer = new PerformanceObserver((list)=>{
                for (const entry of list.getEntries()){
                    const fidEntry = entry;
                    const fidValue = Math.round(fidEntry.processingStart - fidEntry.startTime);
                    // 采样检查和异常值检查
                    if (Math.random() <= this.config.sampleRate && fidValue >= 0 && fidValue < 10000) {
                        this.metrics.fid = fidValue;
                        this.reportInternal();
                    }
                    observer.disconnect();
                }
            });
            observer.observe({
                entryTypes: [
                    'first-input'
                ]
            });
            this.observers.push(observer);
        } catch (e) {
        // PerformanceObserver 不支持
        }
    }
    /**
   * 观察 CLS
   */ observeCLS() {
        if (typeof PerformanceObserver === 'undefined') {
            return;
        }
        let clsValue = 0;
        let clsEntries = [];
        try {
            const observer = new PerformanceObserver((list)=>{
                for (const entry of list.getEntries()){
                    if (!entry.hadRecentInput) {
                        const firstSessionEntry = clsEntries[0];
                        const lastSessionEntry = clsEntries[clsEntries.length - 1];
                        if (!firstSessionEntry || entry.startTime - lastSessionEntry.startTime < 1000 || entry.startTime - firstSessionEntry.startTime > 5000) {
                            clsEntries = [
                                entry
                            ];
                            clsValue = entry.value;
                        } else {
                            clsEntries.push(entry);
                            clsValue += entry.value;
                        }
                        const roundedValue = Math.round(clsValue * 1000) / 1000;
                        // 采样检查和异常值检查
                        if (Math.random() <= this.config.sampleRate && roundedValue >= 0 && roundedValue < 1) {
                            this.metrics.cls = roundedValue;
                            this.reportInternal();
                        }
                    }
                }
            });
            observer.observe({
                entryTypes: [
                    'layout-shift'
                ]
            });
            this.observers.push(observer);
        } catch (e) {
        // PerformanceObserver 不支持
        }
    }
    /**
   * 计算 TTI
   */ calculateTTI() {
        if (typeof window === 'undefined' || !window.performance) {
            return;
        }
        try {
            const navigation = performance.getEntriesByType('navigation')[0];
            if (navigation) {
                const ttiValue = Math.round(navigation.domInteractive - navigation.fetchStart);
                // 采样检查和异常值检查
                if (Math.random() <= this.config.sampleRate && ttiValue > 0 && ttiValue < 60000) {
                    this.metrics.tti = ttiValue;
                    this.reportInternal();
                }
            }
        } catch (e) {
        // 忽略错误
        }
    }
    /**
   * 内部上报性能指标（自动上报当前指标）
   */ reportInternal() {
        if (this.config.onReport) {
            // 创建指标的副本，避免外部修改影响内部状态
            const metricsCopy = {};
            if (this.metrics.fcp !== undefined) metricsCopy.fcp = this.metrics.fcp;
            if (this.metrics.lcp !== undefined) metricsCopy.lcp = this.metrics.lcp;
            if (this.metrics.fid !== undefined) metricsCopy.fid = this.metrics.fid;
            if (this.metrics.cls !== undefined) metricsCopy.cls = this.metrics.cls;
            if (this.metrics.tti !== undefined) metricsCopy.tti = this.metrics.tti;
            if (this.metrics.tbt !== undefined) metricsCopy.tbt = this.metrics.tbt;
            if (this.metrics.si !== undefined) metricsCopy.si = this.metrics.si;
            this.config.onReport(metricsCopy);
        }
    }
    /**
   * 获取当前性能指标
   */ getMetrics() {
        return {
            ...this.metrics
        };
    }
    /**
   * 手动记录自定义指标
   */ recordMetric(name, value) {
        this.metrics[name] = value;
        this.reportInternal();
    }
    /**
   * 清理观察者
   */ disconnect() {
        this.observers.forEach((observer)=>observer.disconnect());
        this.observers = [];
        // 停止聚合定时器
        if (this.aggregationTimer) {
            clearInterval(this.aggregationTimer);
            this.aggregationTimer = undefined;
        }
        // 停止自动上报定时器
        if (this.autoReportTimer) {
            clearInterval(this.autoReportTimer);
            this.autoReportTimer = undefined;
        }
    }
    /**
   * 启动性能指标聚合
   */ startAggregation() {
        this.aggregationTimer = setInterval(()=>{
            this.aggregateMetrics();
        }, this.config.aggregationWindow);
    }
    /**
   * 聚合性能指标
   */ aggregateMetrics() {
        // 计算平均值、最大值、最小值等统计信息
        // 这里简化实现，实际可以根据需要扩展
        this.aggregatedMetrics = {
            ...this.metrics
        };
    }
    /**
   * 获取聚合后的性能指标
   */ getAggregatedMetrics() {
        return {
            ...this.aggregatedMetrics
        };
    }
    /**
   * 启动自动上报
   */ startAutoReport() {
        this.autoReportTimer = setInterval(()=>{
            const metrics = this.config.enableAggregation ? this.getAggregatedMetrics() : this.getMetrics();
            this.config.onReport(metrics);
        }, this.config.autoReportInterval);
    }
    /**
   * 手动上报性能指标
   */ report(metrics) {
        const metricsToReport = metrics || this.getMetrics();
        this.config.onReport(metricsToReport);
    }
    constructor(config = {}){
        _define_property(this, "config", void 0);
        _define_property(this, "metrics", {});
        _define_property(this, "observers", []);
        _define_property(this, "aggregatedMetrics", {});
        _define_property(this, "aggregationTimer", void 0);
        _define_property(this, "autoReportTimer", void 0);
        this.config = {
            collectWebVitals: config.collectWebVitals ?? true,
            onReport: config.onReport ?? (()=>{}),
            sampleRate: config.sampleRate ?? 1.0,
            enableAggregation: config.enableAggregation ?? false,
            aggregationWindow: config.aggregationWindow ?? 60000,
            autoReport: config.autoReport ?? false,
            autoReportInterval: config.autoReportInterval ?? 300000
        };
        if (this.config.collectWebVitals && typeof window !== 'undefined') {
            this.initWebVitals();
        }
        // 启动性能指标聚合
        if (this.config.enableAggregation) {
            this.startAggregation();
        }
        // 启动自动上报
        if (this.config.autoReport) {
            this.startAutoReport();
        }
    }
};
const PERFORMANCE_METRIC_UNIT_MAP = {
    // Web Vitals 指标
    fcp: PERFORMANCE_METRIC_UNITS.ms,
    lcp: PERFORMANCE_METRIC_UNITS.ms,
    fid: PERFORMANCE_METRIC_UNITS.ms,
    cls: PERFORMANCE_METRIC_UNITS.none,
    tti: PERFORMANCE_METRIC_UNITS.ms,
    tbt: PERFORMANCE_METRIC_UNITS.ms,
    si: PERFORMANCE_METRIC_UNITS.ms,
    // 启动性能指标
    serviceInitDuration: PERFORMANCE_METRIC_UNITS.ms,
    initializationDuration: PERFORMANCE_METRIC_UNITS.ms,
    firstRenderDuration: PERFORMANCE_METRIC_UNITS.ms,
    totalStartupDuration: PERFORMANCE_METRIC_UNITS.ms
};
function convertMetricsToWithUnits(metrics) {
    const result = {};
    for (const [key, value] of Object.entries(metrics)){
        if (value !== undefined && value !== null && typeof value === 'number') {
            // 从映射中获取单位，如果没有映射则默认为毫秒
            const unit = PERFORMANCE_METRIC_UNIT_MAP[key] || PERFORMANCE_METRIC_UNITS.ms;
            result[key] = {
                value,
                unit
            };
        }
    }
    return result;
}

//# sourceMappingURL=performance.js.map