// This file is auto-generated by @hey-api/openapi-ts
import { getAuthToken } from "../core/auth.gen.js";
import { jsonBodySerializer } from "../core/bodySerializer.gen.js";
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from "../core/pathSerializer.gen.js";
import { getUrl } from "../core/utils.gen.js";
export const createQuerySerializer = ({ allowReserved, array, object, } = {}) => {
    const querySerializer = (queryParams) => {
        const search = [];
        if (queryParams && typeof queryParams === "object") {
            for (const name in queryParams) {
                const value = queryParams[name];
                if (value === undefined || value === null) {
                    continue;
                }
                if (Array.isArray(value)) {
                    const serializedArray = serializeArrayParam({
                        allowReserved,
                        explode: true,
                        name,
                        style: "form",
                        value,
                        ...array,
                    });
                    if (serializedArray)
                        search.push(serializedArray);
                }
                else if (typeof value === "object") {
                    const serializedObject = serializeObjectParam({
                        allowReserved,
                        explode: true,
                        name,
                        style: "deepObject",
                        value: value,
                        ...object,
                    });
                    if (serializedObject)
                        search.push(serializedObject);
                }
                else {
                    const serializedPrimitive = serializePrimitiveParam({
                        allowReserved,
                        name,
                        value: value,
                    });
                    if (serializedPrimitive)
                        search.push(serializedPrimitive);
                }
            }
        }
        return search.join("&");
    };
    return querySerializer;
};
/**
 * Infers parseAs value from provided Content-Type header.
 */
export const getParseAs = (contentType) => {
    if (!contentType) {
        // If no Content-Type header is provided, the best we can do is return the raw response body,
        // which is effectively the same as the 'stream' option.
        return "stream";
    }
    const cleanContent = contentType.split(";")[0]?.trim();
    if (!cleanContent) {
        return;
    }
    if (cleanContent.startsWith("application/json") ||
        cleanContent.endsWith("+json")) {
        return "json";
    }
    if (cleanContent === "multipart/form-data") {
        return "formData";
    }
    if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
        return "blob";
    }
    if (cleanContent.startsWith("text/")) {
        return "text";
    }
    return;
};
const checkForExistence = (options, name) => {
    if (!name) {
        return false;
    }
    if (options.headers.has(name) ||
        options.query?.[name] ||
        options.headers.get("Cookie")?.includes(`${name}=`)) {
        return true;
    }
    return false;
};
export const setAuthParams = async ({ security, ...options }) => {
    for (const auth of security) {
        if (checkForExistence(options, auth.name)) {
            continue;
        }
        const token = await getAuthToken(auth, options.auth);
        if (!token) {
            continue;
        }
        const name = auth.name ?? "Authorization";
        switch (auth.in) {
            case "query":
                if (!options.query) {
                    options.query = {};
                }
                options.query[name] = token;
                break;
            case "cookie":
                options.headers.append("Cookie", `${name}=${token}`);
                break;
            case "header":
            default:
                options.headers.set(name, token);
                break;
        }
    }
};
export const buildUrl = (options) => getUrl({
    baseUrl: options.baseUrl,
    path: options.path,
    query: options.query,
    querySerializer: typeof options.querySerializer === "function"
        ? options.querySerializer
        : createQuerySerializer(options.querySerializer),
    url: options.url,
});
export const mergeConfigs = (a, b) => {
    const config = { ...a, ...b };
    if (config.baseUrl?.endsWith("/")) {
        config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
    }
    config.headers = mergeHeaders(a.headers, b.headers);
    return config;
};
const headersEntries = (headers) => {
    const entries = [];
    headers.forEach((value, key) => {
        entries.push([key, value]);
    });
    return entries;
};
export const mergeHeaders = (...headers) => {
    const mergedHeaders = new Headers();
    for (const header of headers) {
        if (!header) {
            continue;
        }
        const iterator = header instanceof Headers
            ? headersEntries(header)
            : Object.entries(header);
        for (const [key, value] of iterator) {
            if (value === null) {
                mergedHeaders.delete(key);
            }
            else if (Array.isArray(value)) {
                for (const v of value) {
                    mergedHeaders.append(key, v);
                }
            }
            else if (value !== undefined) {
                // assume object headers are meant to be JSON stringified, i.e. their
                // content value in OpenAPI specification is 'application/json'
                mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
            }
        }
    }
    return mergedHeaders;
};
class Interceptors {
    fns = [];
    clear() {
        this.fns = [];
    }
    eject(id) {
        const index = this.getInterceptorIndex(id);
        if (this.fns[index]) {
            this.fns[index] = null;
        }
    }
    exists(id) {
        const index = this.getInterceptorIndex(id);
        return Boolean(this.fns[index]);
    }
    getInterceptorIndex(id) {
        if (typeof id === "number") {
            return this.fns[id] ? id : -1;
        }
        return this.fns.indexOf(id);
    }
    update(id, fn) {
        const index = this.getInterceptorIndex(id);
        if (this.fns[index]) {
            this.fns[index] = fn;
            return id;
        }
        return false;
    }
    use(fn) {
        this.fns.push(fn);
        return this.fns.length - 1;
    }
}
export const createInterceptors = () => ({
    error: new Interceptors(),
    request: new Interceptors(),
    response: new Interceptors(),
});
const defaultQuerySerializer = createQuerySerializer({
    allowReserved: false,
    array: {
        explode: true,
        style: "form",
    },
    object: {
        explode: true,
        style: "deepObject",
    },
});
const defaultHeaders = {
    "Content-Type": "application/json",
};
export const createConfig = (override = {}) => ({
    ...jsonBodySerializer,
    headers: defaultHeaders,
    parseAs: "auto",
    querySerializer: defaultQuerySerializer,
    ...override,
});
//# sourceMappingURL=utils.gen.js.map