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;
}
/**
 * 路由插件管理器
 * 负责插件的注册、执行和生命周期管理
 */ import { logger } from "../../../utils";
import { PluginLifecycleStage } from "./types";
/**
 * 路由插件管理器
 */ export class RouterPluginManager {
    /**
   * 注册插件
   * 
   * @param plugin - 插件实例
   * @param options - 注册选项
   * @returns 取消注册函数
   */ register(plugin, options = {}) {
        // 验证插件
        if (!plugin.name) {
            throw new Error('插件必须提供名称');
        }
        // 检查是否已存在
        if (this.plugins.has(plugin.name) && !options.overwrite) {
            throw new Error(`插件 "${plugin.name}" 已存在`);
        }
        // 设置默认值
        const pluginWithDefaults = {
            priority: 100,
            enabled: true,
            ...plugin
        };
        // 检查依赖
        if (pluginWithDefaults.dependencies) {
            const missingDeps = pluginWithDefaults.dependencies.filter((dep)=>!this.plugins.has(dep));
            if (missingDeps.length > 0) {
                throw new Error(`插件 "${plugin.name}" 缺少依赖: ${missingDeps.join(', ')}`);
            }
        }
        // 注册插件
        this.plugins.set(plugin.name, {
            plugin: pluginWithDefaults,
            status: 'registered',
            registeredAt: Date.now()
        });
        logger.debug(`路由插件已注册: ${plugin.name}`);
        // 调用注册钩子
        if (pluginWithDefaults.hooks?.onRegister) {
            try {
                const context = {
                    config: {},
                    meta: {
                        stage: PluginLifecycleStage.REGISTER
                    }
                };
                pluginWithDefaults.hooks.onRegister(context);
            } catch (error) {
                logger.error(`插件注册钩子执行失败: ${plugin.name}`, error);
            }
        }
        // 返回取消注册函数
        return ()=>{
            this.unregister(plugin.name);
        };
    }
    /**
   * 批量注册插件
   * 
   * @param plugins - 插件数组
   * @param options - 注册选项
   */ registerBatch(plugins, options = {}) {
        // 按依赖关系排序
        const sortedPlugins = this.sortByDependencies(plugins);
        sortedPlugins.forEach((plugin)=>{
            this.register(plugin, options);
        });
    }
    /**
   * 按依赖关系排序插件（拓扑排序）
   */ sortByDependencies(plugins) {
        const sorted = [];
        const visited = new Set();
        const visiting = new Set();
        const visit = (plugin)=>{
            if (visiting.has(plugin.name || '')) {
                throw new Error(`检测到循环依赖: ${plugin.name}`);
            }
            if (visited.has(plugin.name || '')) {
                return;
            }
            visiting.add(plugin.name || '');
            // 先访问依赖
            if (plugin.dependencies) {
                plugin.dependencies.forEach((depName)=>{
                    const dep = plugins.find((p)=>p.name === depName);
                    if (dep) {
                        visit(dep);
                    }
                });
            }
            visiting.delete(plugin.name || '');
            visited.add(plugin.name || '');
            sorted.push(plugin);
        };
        plugins.forEach((plugin)=>{
            if (!visited.has(plugin.name || '')) {
                visit(plugin);
            }
        });
        return sorted;
    }
    /**
   * 取消注册插件
   * 
   * @param name - 插件名称
   */ unregister(name) {
        const registration = this.plugins.get(name);
        if (!registration) {
            return;
        }
        // 调用销毁钩子
        if (registration.plugin.hooks?.onDestroy) {
            try {
                const context = {
                    config: {},
                    meta: {
                        stage: PluginLifecycleStage.DESTROY
                    }
                };
                registration.plugin.hooks.onDestroy(context);
            } catch (error) {
                logger.error(`插件销毁钩子执行失败: ${name}`, error);
            }
        }
        this.plugins.delete(name);
        logger.debug(`路由插件已取消注册: ${name}`);
    }
    /**
   * 执行插件钩子
   * 
   * @param stage - 生命周期阶段
   * @param context - 插件上下文
   */ async executeHooks(stage, context) {
        // 获取启用的插件并按优先级排序
        const enabledPlugins = Array.from(this.plugins.values()).filter((reg)=>reg.plugin.enabled !== false).sort((a, b)=>(a.plugin.priority || 100) - (b.plugin.priority || 100));
        // 根据阶段选择钩子
        const hookMap = {
            [PluginLifecycleStage.REGISTER]: 'onRegister',
            [PluginLifecycleStage.BEFORE_INIT]: 'onBeforeInit',
            [PluginLifecycleStage.AFTER_INIT]: 'onAfterInit',
            [PluginLifecycleStage.BEFORE_TRANSFORM]: 'onBeforeTransform',
            [PluginLifecycleStage.AFTER_TRANSFORM]: 'onAfterTransform',
            [PluginLifecycleStage.BEFORE_MATCH]: 'onBeforeMatch',
            [PluginLifecycleStage.AFTER_MATCH]: 'onAfterMatch',
            [PluginLifecycleStage.DESTROY]: 'onDestroy'
        };
        const hookName = hookMap[stage];
        if (!hookName) {
            return;
        }
        // 执行钩子
        for (const registration of enabledPlugins){
            const hook = registration.plugin.hooks?.[hookName];
            if (hook) {
                try {
                    await hook(context);
                } catch (error) {
                    logger.error(`插件钩子执行失败: ${registration.plugin.name}.${hookName}`, error);
                }
            }
        }
    }
    /**
   * 获取插件
   * 
   * @param name - 插件名称
   * @returns 插件实例，如果不存在返回 undefined
   */ getPlugin(name) {
        return this.plugins.get(name)?.plugin;
    }
    /**
   * 获取所有插件
   * 
   * @returns 插件数组
   */ getAllPlugins() {
        return Array.from(this.plugins.values()).map((reg)=>reg.plugin);
    }
    /**
   * 获取启用的插件
   * 
   * @returns 启用的插件数组
   */ getEnabledPlugins() {
        return Array.from(this.plugins.values()).filter((reg)=>reg.plugin.enabled !== false).map((reg)=>reg.plugin);
    }
    /**
   * 清空所有插件
   */ clear() {
        // 调用所有插件的销毁钩子
        for (const [name, registration] of this.plugins.entries()){
            if (registration.plugin.hooks?.onDestroy) {
                try {
                    const context = {
                        config: {},
                        meta: {
                            stage: PluginLifecycleStage.DESTROY
                        }
                    };
                    registration.plugin.hooks.onDestroy(context);
                } catch (error) {
                    logger.error(`插件销毁钩子执行失败: ${name}`, error);
                }
            }
        }
        this.plugins.clear();
        logger.debug('所有路由插件已清空');
    }
    /**
   * 获取插件数量
   * 
   * @returns 插件数量
   */ getCount() {
        return this.plugins.size;
    }
    constructor(){
        _define_property(this, "plugins", new Map());
    }
}
/**
 * 获取路由插件管理器单例
 */ let pluginManagerInstance = null;
export function getRouterPluginManager() {
    if (!pluginManagerInstance) {
        pluginManagerInstance = new RouterPluginManager();
    }
    return pluginManagerInstance;
}

//# sourceMappingURL=RouterPluginManager.js.map