/**
 * 请求插件系统
 * 
 * 插件系统提供生命周期钩子，允许扩展请求能力
 */ 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/logger";
/**
 * 插件生命周期阶段
 */ export var PluginLifecycleStage = /*#__PURE__*/ function(PluginLifecycleStage) {
    /**
   * 初始化阶段
   */ PluginLifecycleStage["INIT"] = "init";
    /**
   * 请求前阶段
   */ PluginLifecycleStage["BEFORE_REQUEST"] = "beforeRequest";
    /**
   * 请求后阶段（成功）
   */ PluginLifecycleStage["AFTER_REQUEST"] = "afterRequest";
    /**
   * 错误处理阶段
   */ PluginLifecycleStage["ON_ERROR"] = "onError";
    /**
   * 最终阶段（无论成功或失败）
   */ PluginLifecycleStage["FINALLY"] = "finally";
    return PluginLifecycleStage;
}({});
/**
 * 插件优先级
 */ export var PluginPriority = /*#__PURE__*/ function(PluginPriority) {
    /**
   * 最高优先级（如：认证、签名）
   */ PluginPriority[PluginPriority["HIGHEST"] = 0] = "HIGHEST";
    /**
   * 高优先级（如：请求转换、参数验证）
   */ PluginPriority[PluginPriority["HIGH"] = 25] = "HIGH";
    /**
   * 默认优先级
   */ PluginPriority[PluginPriority["NORMAL"] = 50] = "NORMAL";
    /**
   * 低优先级（如：日志、监控）
   */ PluginPriority[PluginPriority["LOW"] = 75] = "LOW";
    /**
   * 最低优先级（如：缓存、重试）
   */ PluginPriority[PluginPriority["LOWEST"] = 100] = "LOWEST";
    return PluginPriority;
}({});
/**
 * 插件管理器
 */ export class PluginManager {
    /**
   * 注册插件
   * 
   * @param plugin - 请求插件
   */ register(plugin) {
        if (this.plugins.has(plugin.name)) {
            logger.warn(`插件 ${plugin.name} 已存在，将被覆盖`);
        }
        this.plugins.set(plugin.name, plugin);
        this.updatePluginOrder();
    }
    /**
   * 注销插件
   * 
   * @param name - 插件名称
   */ unregister(name) {
        this.plugins.delete(name);
        this.updatePluginOrder();
    }
    /**
   * 获取插件
   * 
   * @param name - 插件名称
   * @returns 插件实例
   */ get(name) {
        return this.plugins.get(name);
    }
    /**
   * 获取所有插件
   * 
   * @returns 插件数组
   */ getAll() {
        return this.pluginOrder.map((name)=>this.plugins.get(name)).filter(Boolean);
    }
    /**
   * 更新插件执行顺序（考虑依赖和优先级）
   */ updatePluginOrder() {
        const plugins = Array.from(this.plugins.values());
        // 构建依赖图
        const dependencyGraph = new Map();
        const priorities = new Map();
        for (const plugin of plugins){
            dependencyGraph.set(plugin.name, plugin.dependencies || []);
            priorities.set(plugin.name, plugin.priority ?? 50);
        }
        // 拓扑排序
        const visited = new Set();
        const visiting = new Set();
        const result = [];
        const visit = (pluginName)=>{
            if (visiting.has(pluginName)) {
                logger.warn(`检测到循环依赖，涉及插件: ${pluginName}`);
                return;
            }
            if (visited.has(pluginName)) {
                return;
            }
            visiting.add(pluginName);
            const deps = dependencyGraph.get(pluginName) || [];
            for (const dep of deps){
                visit(dep);
            }
            visiting.delete(pluginName);
            visited.add(pluginName);
            result.push(pluginName);
        };
        // 按优先级排序后拓扑排序
        const sortedPlugins = plugins.sort((a, b)=>{
            const priorityA = priorities.get(a.name) ?? 50;
            const priorityB = priorities.get(b.name) ?? 50;
            return priorityA - priorityB;
        });
        for (const plugin of sortedPlugins){
            visit(plugin.name);
        }
        this.pluginOrder = result;
    }
    /**
   * 执行插件钩子
   * 
   * @param stage - 生命周期阶段
   * @param context - 请求上下文
   * @returns 处理结果
   */ async executeHook(stage, context) {
        const plugins = this.getAll();
        for (const plugin of plugins){
            // 检查是否跳过此插件
            if (context.request.skipPlugins?.includes(plugin.name)) {
                continue;
            }
            try {
                let result = undefined;
                switch(stage){
                    case "init":
                        result = await plugin.onInit?.(context);
                        break;
                    case "beforeRequest":
                        result = await plugin.onBeforeRequest?.(context);
                        if (result && typeof result === 'object' && 'url' in result) {
                            context.request = result;
                            // 如果返回了修改后的请求配置，立即返回
                            return result;
                        }
                        break;
                    case "afterRequest":
                        result = await plugin.onAfterRequest?.(context);
                        if (result && typeof result === 'object' && 'data' in result) {
                            context.response = result;
                            // 如果返回了修改后的响应，立即返回
                            return result;
                        }
                        break;
                    case "onError":
                        result = await plugin.onError?.(context);
                        if (result === true) {
                            return true; // 错误已处理，停止传播
                        }
                        break;
                    case "finally":
                        await plugin.onFinally?.(context);
                        break;
                }
            } catch (error) {
                logger.error(`插件 ${plugin.name} 的 ${stage} 钩子执行失败:`, error);
            // 继续执行其他插件
            }
        }
        return undefined;
    }
    /**
   * 清除所有插件
   */ clear() {
        this.plugins.clear();
        this.pluginOrder = [];
    }
    constructor(){
        _define_property(this, "plugins", new Map());
        _define_property(this, "pluginOrder", []);
    }
}

//# sourceMappingURL=RequestPlugin.js.map