/**
 * 服务初始化模块
 * 负责初始化框架所需的各种服务
 */ "use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "initializeServices", {
    enumerable: true,
    get: function() {
        return initializeServices;
    }
});
const _utils = require("../../utils");
const _monitoring = require("../../utils/monitoring");
const _performance = require("../../utils/performance");
const _library = require("../../library");
const _state = require("../../state");
const _AppEventBus = require("../event/AppEventBus");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
/**
 * 带重试的异步函数执行器
 */ async function withRetry(fn, config = {}, serviceName) {
    const maxRetries = config.maxRetries ?? 3;
    const retryDelay = config.retryDelay ?? 1000;
    const exponentialBackoff = config.exponentialBackoff ?? true;
    let lastError;
    for(let attempt = 0; attempt <= maxRetries; attempt++){
        try {
            return await fn();
        } catch (error) {
            lastError = error;
            if (attempt < maxRetries) {
                const delay = exponentialBackoff ? retryDelay * Math.pow(2, attempt) : retryDelay;
                _utils.logger.warn(`${serviceName} 初始化失败（尝试 ${attempt + 1}/${maxRetries + 1}），${delay}ms 后重试...`, error);
                await new Promise((resolve)=>setTimeout(resolve, delay));
            }
        }
    }
    _utils.logger.error(`${serviceName} 初始化失败，已重试 ${maxRetries} 次`);
    throw lastError;
}
async function initializeServices(options = {}) {
    const startTime = performance.now();
    // 重试配置
    const retryConfig = {
        maxRetries: options.serviceRetry?.maxRetries ?? 3,
        retryDelay: options.serviceRetry?.retryDelay ?? 1000,
        exponentialBackoff: options.serviceRetry?.exponentialBackoff ?? true
    };
    // ========== 关键服务：必须在应用渲染前初始化 ==========
    // 这些服务是应用运行的基础，必须并行初始化完成
    // 1. 监控服务（必须最先初始化，因为其他服务可能依赖它）
    const monitoringPromise = withRetry(()=>Promise.resolve((0, _monitoring.initMonitoring)({
            ...options.errorMonitor,
            onError: (error)=>{
                _utils.logger.error('监控服务捕获到错误:', error);
                options.errorMonitor?.onError?.(error);
            }
        })), retryConfig, '监控服务');
    // 2. 存储服务（关键服务，应用可能需要立即使用存储）
    const storagePromise = withRetry(()=>Promise.resolve().then(()=>{
            _library.storage.initialize(options.storageOptions);
            return _library.storage;
        }), retryConfig, '存储服务');
    // 3. 状态管理器（关键服务，应用状态管理的基础）
    const stateManagerPromise = withRetry(()=>Promise.resolve().then(()=>{
            if (options.stateManager !== undefined) {
                return new _state.StateManager(options.stateManager);
            } else {
                // 默认初始化状态管理器
                return new _state.StateManager({
                    enableRegistry: true,
                    defaultScope: 'app'
                });
            }
        }), retryConfig, '状态管理器');
    // 4. 事件总线（关键服务，用于应用内部通信）
    const eventBusPromise = withRetry(()=>Promise.resolve().then(()=>{
            const eventBusConfig = {
                enableTracking: options.eventBus?.enableTracking ?? process.env.NODE_ENV === 'development',
                maxHistorySize: options.eventBus?.maxHistorySize ?? 100,
                enableValidation: options.eventBus?.enableValidation ?? false,
                enablePerformanceMonitoring: options.eventBus?.enablePerformanceMonitoring ?? process.env.NODE_ENV === 'development',
                namespacePrefix: options.eventBus?.namespacePrefix,
                instanceId: options.eventBus?.instanceId,
                enableSecurityMode: options.eventBus?.enableSecurityMode ?? false,
                allowedSources: options.eventBus?.allowedSources
            };
            return new _AppEventBus.AppEventBus(eventBusConfig);
        }), retryConfig, '事件总线');
    // 并行执行关键服务初始化
    const [monitoring, , stateManager, eventBus] = await Promise.all([
        monitoringPromise,
        storagePromise,
        stateManagerPromise,
        eventBusPromise
    ]);
    _utils.logger.info('关键服务初始化完成');
    // 初始化性能监控（依赖监控服务，必须在监控服务初始化后）
    const performanceMonitor = new _performance.PerformanceMonitor({
        ...options.performanceMonitor,
        onReport: (metrics)=>{
            monitoring.reportPerformance(metrics);
            options.performanceMonitor?.onReport?.(metrics);
        }
    });
    // 在页面卸载时清理性能监控
    if (typeof window !== 'undefined') {
        const cleanupHandler = ()=>{
            performanceMonitor.disconnect();
            window.removeEventListener('beforeunload', cleanupHandler);
        };
        window.addEventListener('beforeunload', cleanupHandler);
    }
    const criticalServicesDuration = performance.now() - startTime;
    _utils.logger.debug(`关键服务初始化完成，耗时: ${criticalServicesDuration.toFixed(2)}ms`);
    // ========== 非关键服务：延迟到应用渲染后初始化 ==========
    // 这些服务不影响首屏渲染，可以在空闲时初始化
    /**
   * 延迟初始化非关键服务
   * 在应用渲染后调用，使用 requestIdleCallback 在空闲时初始化
   */ const initializeNonCriticalServices = async ()=>{
        const nonCriticalStartTime = performance.now();
        // 使用 requestIdleCallback 在浏览器空闲时初始化非关键服务
        // 如果不支持 requestIdleCallback，则使用 setTimeout 延迟执行
        const scheduleInit = (callback)=>{
            if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
                window.requestIdleCallback(callback, {
                    timeout: 5000
                });
            } else {
                setTimeout(callback, 100);
            }
        };
        return new Promise((resolve)=>{
            scheduleInit(async ()=>{
                try {
                    // 1. 分析服务（可选，非关键）
                    if (options.analytics) {
                        try {
                            await withRetry(()=>Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../../utils/analytics"))).then(({ initAnalytics })=>{
                                    initAnalytics(options.analytics);
                                    return true;
                                }), retryConfig, '分析服务');
                            _utils.logger.debug('分析服务初始化完成');
                        } catch (error) {
                            _utils.logger.warn('分析服务初始化失败（不影响应用运行）:', error);
                        }
                    }
                    // 2. 运行时安全服务（可选，非关键）
                    if (options.runtimeSecurity) {
                        try {
                            await withRetry(()=>Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../../utils/runtimeSecurity"))).then(({ RuntimeSecurity })=>{
                                    RuntimeSecurity.initialize(options.runtimeSecurity);
                                    return true;
                                }), retryConfig, '运行时安全服务');
                            _utils.logger.debug('运行时安全服务初始化完成');
                        } catch (error) {
                            _utils.logger.warn('运行时安全服务初始化失败（不影响应用运行）:', error);
                        }
                    }
                    const nonCriticalDuration = performance.now() - nonCriticalStartTime;
                    _utils.logger.debug(`非关键服务初始化完成，耗时: ${nonCriticalDuration.toFixed(2)}ms`);
                } catch (error) {
                    _utils.logger.warn('非关键服务初始化过程中出现错误:', error);
                } finally{
                    resolve();
                }
            });
        });
    };
    // 记录关键服务初始化性能指标
    if (monitoring.reportPerformance) {
        monitoring.reportPerformance({
            serviceInitDuration: criticalServicesDuration
        });
    }
    return {
        monitoring,
        performanceMonitor,
        stateManager,
        eventBus,
        initializeNonCriticalServices
    };
}

//# sourceMappingURL=initializeServices.js.map