/*
 * @Author: Henry
 * @Date: 2026-04-09 16:12:52
 */
// packages/skill-shared/src/http.ts
import axios from "axios";
import { NotAuthenticatedError, PermissionError, MBSError } from "./errors.js";
/**
 * 错误码映射表。新增错误码在此追加一行即可。
 * key: 服务端 code 值
 * value: 工厂函数，返回对应的 Error 实例
 */
const API_CODE_HANDLERS = {
    601: () => new NotAuthenticatedError(),
    109: () => new PermissionError(),
    403: () => new NotAuthenticatedError(),
    401: () => new NotAuthenticatedError(),
    500: () => new NotAuthenticatedError(),
};
export class APIClient {
    instance;
    refreshAuth;
    constructor(baseURL, cookie, refreshAuth) {
        this.refreshAuth = refreshAuth;
        this.instance = axios.create({
            baseURL,
            headers: { Cookie: cookie, "client-type": "cli" },
        });
        this.instance.interceptors.response.use((response) => {
            const raw = response.data;
            if (typeof raw?.code !== "number")
                return response; // 非标准端点，直接放行
            if (raw.code === 0 || raw.code === 200)
                return response; // 成功，放行
            const handler = API_CODE_HANDLERS[raw.code];
            if (handler)
                throw handler();
            throw new MBSError(raw.msg ?? `API error (code: ${raw.code})`);
        });
    }
    updateCookie(cookie) {
        this.instance.defaults.headers["Cookie"] = cookie;
    }
    async withRetry(request) {
        try {
            return await request();
        }
        catch (err) {
            if (err instanceof NotAuthenticatedError) {
                const newCookie = await this.refreshAuth();
                this.updateCookie(newCookie);
                return await request();
            }
            throw err;
        }
    }
    async get(path, options) {
        const { pathPrefix, ...config } = options ?? {};
        const url = pathPrefix ? pathPrefix + path : path;
        return await this.withRetry(() => this.instance.get(url, config).then((r) => r.data));
    }
    async post(path, body, options) {
        const url = options?.pathPrefix ? options.pathPrefix + path : path;
        return await this.withRetry(() => this.instance.post(url, body).then((r) => r.data));
    }
    async postStream(path, body, options) {
        const url = options?.pathPrefix ? options.pathPrefix + path : path;
        return await this.withRetry(() => this.instance
            .post(url, body, {
            responseType: "stream",
            headers: { Accept: "application/x-ndjson" },
        })
            .then((r) => r.data));
    }
    async request(method, path, options) {
        return await this.withRetry(() => this.instance.request({ method, url: path, params: options?.params, data: options?.body }).then((r) => r.data));
    }
}
//# sourceMappingURL=http.js.map