"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveOpenAIModelsUrl = exports.resolveOpenAIChatCompletionsUrl = void 0;
function normalizePathname(pathname) {
    const trimmed = pathname.replace(/\/+$/, '');
    return trimmed || '';
}
function ensureSupportedProtocol(parsed) {
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
        throw new Error(`Unsupported upstream protocol: ${parsed.protocol}`);
    }
}
function isOpenRouterHost(hostname) {
    const normalized = hostname.toLowerCase();
    return normalized === 'openrouter.ai' || normalized.endsWith('.openrouter.ai');
}
function buildResolvedUrl(baseUrl, suffix) {
    const parsed = new URL(baseUrl);
    ensureSupportedProtocol(parsed);
    const pathname = normalizePathname(parsed.pathname);
    if (pathname.endsWith(suffix)) {
        return parsed.toString();
    }
    if (isOpenRouterHost(parsed.hostname) && pathname.endsWith('/api')) {
        parsed.pathname = `${pathname}/v1${suffix}`;
        return parsed.toString();
    }
    if (pathname.endsWith('/v1') || pathname.endsWith('/api')) {
        parsed.pathname = `${pathname}${suffix.startsWith('/') ? suffix : `/${suffix}`}`;
        return parsed.toString();
    }
    parsed.pathname = pathname ? `${pathname}/v1${suffix}` : `/v1${suffix}`;
    return parsed.toString();
}
function resolveOpenAIChatCompletionsUrl(baseUrl) {
    return buildResolvedUrl(baseUrl, '/chat/completions');
}
exports.resolveOpenAIChatCompletionsUrl = resolveOpenAIChatCompletionsUrl;
function resolveOpenAIModelsUrl(baseUrl) {
    return buildResolvedUrl(baseUrl, '/models');
}
exports.resolveOpenAIModelsUrl = resolveOpenAIModelsUrl;
//# sourceMappingURL=upstream-url.js.map