"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.YcmdClient = void 0;
exports.getFileTypes = getFileTypes;
const crypto = __importStar(require("crypto"));
class YcmdClient {
    serverInfo;
    baseUrl;
    constructor(serverInfo) {
        this.serverInfo = serverInfo;
        this.baseUrl = `http://${serverInfo.host}:${serverInfo.port}`;
    }
    async request(endpoint, data, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const method = options.method || (data ? "POST" : "GET");
        const timeout = options.timeout || 10000;
        const body = data ? JSON.stringify(data) : undefined;
        const hmac = this.generateHmac(method, endpoint, body || "");
        const headers = {
            "Content-Type": "application/json",
            "X-Ycm-Hmac": hmac,
            ...options.headers,
        };
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), timeout);
            const response = await fetch(url, {
                method,
                headers,
                body,
                signal: controller.signal,
            });
            clearTimeout(timeoutId);
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`ycmd server error (${response.status}): ${errorText}`);
            }
            const result = await response.json();
            return result;
        }
        catch (error) {
            if (error instanceof Error && error.name === "AbortError") {
                throw new Error(`Request to ycmd server timed out after ${timeout}ms`);
            }
            throw error;
        }
    }
    generateHmac(method, path, body) {
        const secret = Buffer.from(this.serverInfo.hmacSecret, "base64");
        const methodHmac = crypto
            .createHmac("sha256", secret)
            .update(method, "utf8")
            .digest();
        const pathHmac = crypto
            .createHmac("sha256", secret)
            .update(path, "utf8")
            .digest();
        const bodyHmac = crypto
            .createHmac("sha256", secret)
            .update(body, "utf8")
            .digest();
        const joinedHmacInput = Buffer.concat([methodHmac, pathHmac, bodyHmac]);
        const finalHmac = crypto
            .createHmac("sha256", secret)
            .update(joinedHmacInput)
            .digest();
        return Buffer.from(finalHmac).toString("base64");
    }
    generateSimpleHmac(method, path, body) {
        const hmac = crypto.createHmac("sha256", Buffer.from(this.serverInfo.hmacSecret, "base64"));
        const message = `${method}&${path}&${body}`;
        hmac.update(message);
        return Buffer.from(hmac.digest()).toString("base64");
    }
    async isReady() {
        try {
            await this.request("/ready");
            return true;
        }
        catch {
            return false;
        }
    }
    async isHealthy() {
        try {
            await this.request("/ready");
            return true;
        }
        catch {
            return false;
        }
    }
    async loadExtraConfFile(filepath) {
        try {
            const response = await this.request("/load_extra_conf_file", {
                filepath,
            });
            return response.found;
        }
        catch {
            return false;
        }
    }
    async getCompletions(request) {
        return this.request("/completions", request);
    }
    async getCompletionDetail(request) {
        return this.request("/detailed_diagnostic", request);
    }
    async getDiagnostics(filepath, contents, filetypes, line_num = 1, column_num = 1) {
        const response = await this.request("/event_notification", {
            event_name: "FileReadyToParse",
            filepath,
            line_num,
            column_num,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
        return response || [];
    }
    async goToDefinition(filepath, line, column, contents, filetypes) {
        return this.request("/run_completer_command", {
            command_arguments: ["GoTo"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async goToDeclaration(filepath, line, column, contents, filetypes) {
        return this.request("/run_completer_command", {
            command_arguments: ["GoToDeclaration"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async goToReferences(filepath, line, column, contents, filetypes) {
        return this.request("/run_completer_command", {
            command_arguments: ["GoToReferences"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async getSignatureHelp(filepath, line, column, contents, filetypes) {
        return this.request("/run_completer_command", {
            command_arguments: ["GetType"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async getRefactorCommands(filepath, line, column, contents, filetypes) {
        return this.request("/defined_subcommands", {
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async refactorRename(filepath, line, column, contents, filetypes, newName) {
        return this.request("/run_completer_command", {
            command_arguments: ["RefactorRename", newName],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async refactorExtractMethod(filepath, line, column, contents, filetypes) {
        return this.request("/run_completer_command", {
            command_arguments: ["RefactorExtractMethod"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async refactorOrganizeImports(filepath, line, column, contents, filetypes) {
        return this.request("/run_completer_command", {
            command_arguments: ["OrganizeImports"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async refactorFixIt(filepath, line, column, contents, filetypes, fixitIndex) {
        return this.request("/run_completer_command", {
            command_arguments: ["FixIt"],
            filepath,
            line_num: line,
            column_num: column,
            file_data: {
                [filepath]: {
                    contents,
                    filetypes,
                },
            },
        });
    }
    async executeRefactor(command, args) {
        return this.request(`/run_completer_command`, {
            command_arguments: [command, ...Object.values(args)],
            ...args,
        });
    }
    async notifyFileEvent(event, filepath, contents, filetypes, line_num = 1, column_num = 1) {
        const eventData = {
            event_name: event,
            filepath,
            line_num,
            column_num,
        };
        eventData.file_data = {
            [filepath]: {
                contents: contents || "",
                filetypes: filetypes || ["text"],
            },
        };
        await this.request("/event_notification", eventData);
    }
    async shutdown() {
        try {
            await this.request("/shutdown", {}, { method: "POST" });
        }
        catch {
        }
    }
}
exports.YcmdClient = YcmdClient;
function getFileTypes(filepath) {
    const ext = filepath.split(".").pop()?.toLowerCase();
    const typeMap = {
        py: ["python"],
        js: ["javascript"],
        ts: ["typescript"],
        jsx: ["javascript", "jsx"],
        tsx: ["typescript", "tsx"],
        cpp: ["cpp"],
        cc: ["cpp"],
        cxx: ["cpp"],
        c: ["c"],
        h: ["c"],
        hpp: ["cpp"],
        java: ["java"],
        cs: ["cs"],
        go: ["go"],
        rs: ["rust"],
        php: ["php"],
        rb: ["ruby"],
        swift: ["swift"],
        kt: ["kotlin"],
        scala: ["scala"],
        sh: ["sh"],
        bash: ["sh"],
        zsh: ["sh"],
        fish: ["sh"],
        vim: ["vim"],
        lua: ["lua"],
        r: ["r"],
        R: ["r"],
        sql: ["sql"],
        html: ["html"],
        xml: ["xml"],
        css: ["css"],
        scss: ["scss"],
        sass: ["sass"],
        less: ["less"],
        json: ["json"],
        yaml: ["yaml"],
        yml: ["yaml"],
        toml: ["toml"],
        ini: ["dosini"],
        cfg: ["dosini"],
        conf: ["conf"],
        md: ["markdown"],
        markdown: ["markdown"],
        tex: ["tex"],
        latex: ["tex"],
    };
    return typeMap[ext || ""] || ["text"];
}
//# sourceMappingURL=client.js.map