/**
 * 缓存插件
 * 
 * 提供请求缓存能力，支持内存、localStorage、sessionStorage 存储
 */ 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 { PluginPriority } from "./RequestPlugin";
import { logger } from "../../utils/logger";
/**
 * 内存缓存存储实现
 */ let MemoryCacheStorage = class MemoryCacheStorage {
    async get(key) {
        const item = this.cache.get(key);
        if (!item) {
            return null;
        }
        if (Date.now() > item.expires) {
            this.cache.delete(key);
            return null;
        }
        return item.value;
    }
    async set(key, value, ttl) {
        const expires = Date.now() + ttl;
        this.cache.set(key, {
            value,
            expires
        });
    }
    async delete(key) {
        this.cache.delete(key);
    }
    async clear() {
        this.cache.clear();
    }
    constructor(){
        _define_property(this, "cache", new Map());
    }
};
/**
 * LocalStorage 缓存存储实现
 */ let LocalStorageCacheStorage = class LocalStorageCacheStorage {
    async get(key) {
        if (typeof localStorage === 'undefined') {
            return null;
        }
        try {
            const item = localStorage.getItem(this.prefix + key);
            if (!item) {
                return null;
            }
            const { value, expires } = JSON.parse(item);
            if (Date.now() > expires) {
                localStorage.removeItem(this.prefix + key);
                return null;
            }
            return value;
        } catch  {
            return null;
        }
    }
    async set(key, value, ttl) {
        if (typeof localStorage === 'undefined') {
            return;
        }
        try {
            const expires = Date.now() + ttl;
            localStorage.setItem(this.prefix + key, JSON.stringify({
                value,
                expires
            }));
        } catch (error) {
            // 存储失败（可能是存储空间不足）
            logger.warn('缓存存储失败:', error);
        }
    }
    async delete(key) {
        if (typeof localStorage === 'undefined') {
            return;
        }
        localStorage.removeItem(this.prefix + key);
    }
    async clear() {
        if (typeof localStorage === 'undefined') {
            return;
        }
        const keys = Object.keys(localStorage);
        for (const key of keys){
            if (key.startsWith(this.prefix)) {
                localStorage.removeItem(key);
            }
        }
    }
    constructor(){
        _define_property(this, "prefix", 'request_cache_');
    }
};
/**
 * SessionStorage 缓存存储实现
 */ let SessionStorageCacheStorage = class SessionStorageCacheStorage {
    async get(key) {
        if (typeof sessionStorage === 'undefined') {
            return null;
        }
        try {
            const item = sessionStorage.getItem(this.prefix + key);
            if (!item) {
                return null;
            }
            const { value, expires } = JSON.parse(item);
            if (Date.now() > expires) {
                sessionStorage.removeItem(this.prefix + key);
                return null;
            }
            return value;
        } catch  {
            return null;
        }
    }
    async set(key, value, ttl) {
        if (typeof sessionStorage === 'undefined') {
            return;
        }
        try {
            const expires = Date.now() + ttl;
            sessionStorage.setItem(this.prefix + key, JSON.stringify({
                value,
                expires
            }));
        } catch (error) {
            logger.warn('缓存存储失败:', error);
        }
    }
    async delete(key) {
        if (typeof sessionStorage === 'undefined') {
            return;
        }
        sessionStorage.removeItem(this.prefix + key);
    }
    async clear() {
        if (typeof sessionStorage === 'undefined') {
            return;
        }
        const keys = Object.keys(sessionStorage);
        for (const key of keys){
            if (key.startsWith(this.prefix)) {
                sessionStorage.removeItem(key);
            }
        }
    }
    constructor(){
        _define_property(this, "prefix", 'request_cache_');
    }
};
/**
 * 获取缓存存储实例
 */ function getCacheStorage(storage = 'memory') {
    switch(storage){
        case 'localStorage':
            return new LocalStorageCacheStorage();
        case 'sessionStorage':
            return new SessionStorageCacheStorage();
        case 'memory':
        default:
            return new MemoryCacheStorage();
    }
}
/**
 * 生成缓存键
 */ function generateCacheKey(request) {
    const { url, method = 'GET', query, body } = request;
    const cacheKey = request.cache?.key || `${method}:${url}`;
    // 包含查询参数和请求体（如果存在）
    const keyParts = [
        cacheKey
    ];
    if (query) {
        keyParts.push(JSON.stringify(query));
    }
    if (body && typeof body === 'object') {
        keyParts.push(JSON.stringify(body));
    }
    return keyParts.join('|');
}
/**
 * 创建缓存插件
 * 
 * @param config - 缓存插件配置
 * @returns 缓存插件实例
 */ export function createCachePlugin(config = {}) {
    const { defaultTTL = 5 * 60 * 1000, defaultStorage = 'memory', enabled = true } = config;
    return {
        name: 'cache',
        priority: PluginPriority.LOWEST,
        async onBeforeRequest (context) {
            if (!enabled) {
                return;
            }
            const cacheConfig = context.request.cache;
            if (!cacheConfig) {
                // 如果没有配置缓存，跳过
                return;
            }
            // 如果强制刷新，跳过缓存
            if (cacheConfig.forceRefresh) {
                return;
            }
            // 只缓存 GET 请求
            if (context.request.method && context.request.method !== 'GET') {
                return;
            }
            const storage = getCacheStorage(cacheConfig.storage || defaultStorage);
            const cacheKey = generateCacheKey(context.request);
            // 尝试从缓存获取
            const cachedResponse = await storage.get(cacheKey);
            if (cachedResponse) {
                // 缓存命中，标记并设置缓存的响应
                context.meta.hit = true;
                context.response = cachedResponse;
                // 标记请求已取消，避免实际发送请求
                context.cancelled = true;
                return;
            }
            // 缓存未命中
            context.meta.hit = false;
        },
        async onAfterRequest (context) {
            if (!enabled || !context.response) {
                return;
            }
            const cacheConfig = context.request.cache;
            if (!cacheConfig) {
                return;
            }
            // 检查是否应该缓存
            const shouldCache = cacheConfig.shouldCache ? cacheConfig.shouldCache(context.response) : context.response.status >= 200 && context.response.status < 300;
            if (!shouldCache) {
                return;
            }
            // 只缓存 GET 请求
            if (context.request.method && context.request.method !== 'GET') {
                return;
            }
            const storage = getCacheStorage(cacheConfig.storage || defaultStorage);
            const cacheKey = generateCacheKey(context.request);
            const ttl = cacheConfig.ttl || defaultTTL;
            // 存储到缓存
            await storage.set(cacheKey, context.response, ttl);
        }
    };
}

//# sourceMappingURL=cache.js.map