/**
 * Ky 适配器
 * 
 * 基于 ky 库的适配器实现（浏览器环境）
 */ "use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "kyAdapter", {
    enumerable: true,
    get: function() {
        return kyAdapter;
    }
});
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 kyAdapter() {
    // 动态导入 ky（按需加载）
    // 使用多种方式尝试导入，以兼容不同的构建工具
    let ky;
    let importError = null;
    // 方法1：使用 Function 构造函数（避免构建时解析）
    try {
        // @ts-ignore - ky 是可选依赖
        ky = await new Function('return import("ky")')();
    } catch (error) {
        importError = error;
        // 方法2：直接使用动态导入（某些构建工具可能需要这种方式）
        try {
            // @ts-ignore - ky 是可选依赖
            ky = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("ky")));
        } catch (error2) {
            importError = error2;
        }
    }
    // 如果两种方法都失败，检查是否是模块未找到错误
    if (!ky || !ky.default) {
        if (importError instanceof Error) {
            const errorMessage = importError.message.toLowerCase();
            // 检查是否是模块未找到相关的错误
            const isModuleNotFound = errorMessage.includes('cannot find module') || errorMessage.includes('cannot resolve') || errorMessage.includes('module not found') || errorMessage.includes('failed to resolve') || errorMessage.includes('does not exist') || errorMessage.includes('failed to fetch dynamically imported module') || errorMessage.includes('loading chunk') || errorMessage.includes('networkerror') || errorMessage.includes('ky') && (errorMessage.includes('resolve') || errorMessage.includes('find') || errorMessage.includes('not found'));
            if (isModuleNotFound) {
                // 模块未找到，抛出友好的依赖缺失错误
                const { createDependencyError } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../utils/dependencyCheck")));
                const errorMessage = createDependencyError('ky', {
                    adapterName: 'ky',
                    environment: 'browser'
                });
                throw new Error(errorMessage);
            }
        }
        throw new Error('ky 库导入失败，请检查安装是否正确');
    }
    const kyInstance = ky.default;
    return {
        name: 'ky',
        capabilities: {
            supportsAbort: true,
            supportsTimeout: true,
            supportsProgress: false,
            supportsInterceptors: false
        },
        async request (options) {
            const { url, method = 'GET', headers = {}, query, body, timeout, signal, credentials } = options;
            // 构建 ky 选项
            const kyOptions = {
                method: method,
                headers: headers,
                searchParams: query,
                json: typeof body === 'object' && body !== null && !(body instanceof FormData) ? body : undefined,
                body: body instanceof FormData || body instanceof URLSearchParams || body instanceof Blob || body instanceof ArrayBuffer ? body : undefined,
                timeout: timeout,
                signal: signal,
                credentials: credentials,
                retry: 0
            };
            try {
                // 执行请求
                const kyResponse = await kyInstance(url, kyOptions);
                // 解析响应数据
                let data;
                const responseType = options.responseType || 'json';
                switch(responseType){
                    case 'text':
                        data = await kyResponse.text();
                        break;
                    case 'blob':
                        data = await kyResponse.blob();
                        break;
                    case 'arrayBuffer':
                        data = await kyResponse.arrayBuffer();
                        break;
                    case 'formData':
                        data = await kyResponse.formData();
                        break;
                    case 'json':
                    default:
                        // @ts-ignore - ky 类型定义
                        data = await kyResponse.json();
                        break;
                }
                // 构建响应头对象
                const responseHeaders = {};
                kyResponse.headers.forEach((value, key)=>{
                    responseHeaders[key] = value;
                });
                // 返回响应对象
                return {
                    data,
                    status: kyResponse.status,
                    statusText: kyResponse.statusText,
                    headers: responseHeaders,
                    raw: kyResponse
                };
            } catch (error) {
                // ky 的错误处理
                if (error.response) {
                    // HTTP 错误
                    const status = error.response.status;
                    const statusText = error.response.statusText || '';
                    // 尝试解析错误响应体
                    let errorData;
                    try {
                        errorData = await error.response.json();
                    } catch  {
                        try {
                            errorData = await error.response.text();
                        } catch  {
                            errorData = null;
                        }
                    }
                    throw {
                        message: `HTTP ${status} ${statusText}`,
                        status,
                        statusText,
                        response: {
                            data: errorData,
                            status,
                            statusText,
                            headers: {}
                        },
                        request: options
                    };
                }
                // 其他错误
                throw error;
            }
        }
    };
}

//# sourceMappingURL=kyAdapter.js.map