"use strict";
/*
 * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonErr = jsonErr;
exports.json = json;
exports.jsonl = jsonl;
exports.jsonlErr = jsonlErr;
exports.textErr = textErr;
exports.text = text;
exports.bytesErr = bytesErr;
exports.bytes = bytes;
exports.streamErr = streamErr;
exports.stream = stream;
exports.sseErr = sseErr;
exports.sse = sse;
exports.nilErr = nilErr;
exports.nil = nil;
exports.fail = fail;
exports.match = match;
exports.unpackHeaders = unpackHeaders;
const apierror_js_1 = require("../models/errors/apierror.js");
const responsevalidationerror_js_1 = require("../models/errors/responsevalidationerror.js");
const fp_js_1 = require("../types/fp.js");
const http_js_1 = require("./http.js");
const is_plain_object_js_1 = require("./is-plain-object.js");
const DEFAULT_CONTENT_TYPES = {
    jsonl: "application/jsonl",
    json: "application/json",
    text: "text/plain",
    bytes: "application/octet-stream",
    stream: "application/octet-stream",
    sse: "text/event-stream",
    nil: "*",
    fail: "*",
};
function jsonErr(codes, schema, options) {
    return { ...options, err: true, enc: "json", codes, schema };
}
function json(codes, schema, options) {
    return { ...options, enc: "json", codes, schema };
}
function jsonl(codes, schema, options) {
    return { ...options, enc: "jsonl", codes, schema };
}
function jsonlErr(codes, schema, options) {
    return { ...options, err: true, enc: "jsonl", codes, schema };
}
function textErr(codes, schema, options) {
    return { ...options, err: true, enc: "text", codes, schema };
}
function text(codes, schema, options) {
    return { ...options, enc: "text", codes, schema };
}
function bytesErr(codes, schema, options) {
    return { ...options, err: true, enc: "bytes", codes, schema };
}
function bytes(codes, schema, options) {
    return { ...options, enc: "bytes", codes, schema };
}
function streamErr(codes, schema, options) {
    return { ...options, err: true, enc: "stream", codes, schema };
}
function stream(codes, schema, options) {
    return { ...options, enc: "stream", codes, schema };
}
function sseErr(codes, schema, options) {
    return { ...options, err: true, enc: "sse", codes, schema };
}
function sse(codes, schema, options) {
    return { ...options, enc: "sse", codes, schema };
}
function nilErr(codes, schema, options) {
    return { ...options, err: true, enc: "nil", codes, schema };
}
function nil(codes, schema, options) {
    return { ...options, enc: "nil", codes, schema };
}
function fail(codes) {
    return { enc: "fail", codes };
}
function match(...matchers) {
    return async function matchFunc(response, request, options) {
        let raw;
        let matcher;
        for (const match of matchers) {
            const { codes } = match;
            const ctpattern = "ctype" in match
                ? match.ctype
                : DEFAULT_CONTENT_TYPES[match.enc];
            if (ctpattern && (0, http_js_1.matchResponse)(response, codes, ctpattern)) {
                matcher = match;
                break;
            }
            else if (!ctpattern && (0, http_js_1.matchStatusCode)(response, codes)) {
                matcher = match;
                break;
            }
        }
        if (!matcher) {
            return [{
                    ok: false,
                    error: new apierror_js_1.APIError("Unexpected Status or Content-Type", {
                        response,
                        request,
                        body: await response.text().catch(() => ""),
                    }),
                }, raw];
        }
        const encoding = matcher.enc;
        let body = "";
        switch (encoding) {
            case "json":
                body = await response.text();
                raw = JSON.parse(body);
                break;
            case "jsonl":
                raw = response.body;
                break;
            case "bytes":
                raw = new Uint8Array(await response.arrayBuffer());
                break;
            case "stream":
                raw = response.body;
                break;
            case "text":
                body = await response.text();
                raw = body;
                break;
            case "sse":
                raw = response.body;
                break;
            case "nil":
                body = await response.text();
                raw = undefined;
                break;
            case "fail":
                body = await response.text();
                raw = undefined;
                break;
            default:
                throw new Error(`Unsupported response type: ${encoding}`);
        }
        if (matcher.enc === "fail") {
            return [{
                    ok: false,
                    error: new apierror_js_1.APIError("API error occurred", { request, response, body }),
                }, raw];
        }
        const resultKey = matcher.key || options?.resultKey;
        let data;
        if ("err" in matcher) {
            data = {
                ...options?.extraFields,
                ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null),
                ...((0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null),
                request$: request,
                response$: response,
                body$: body,
            };
        }
        else if (resultKey) {
            data = {
                ...options?.extraFields,
                ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null),
                [resultKey]: raw,
            };
        }
        else {
            data = {
                ...options?.extraFields,
                ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null),
            };
        }
        if ("err" in matcher) {
            const result = safeParseResponse(data, (v) => matcher.schema.parse(v), "Response validation failed", { request, response, body });
            return [result.ok ? { ok: false, error: result.value } : result, raw];
        }
        else {
            return [
                safeParseResponse(data, (v) => matcher.schema.parse(v), "Response validation failed", { request, response, body }),
                raw,
            ];
        }
    };
}
const headerValRE = /, */;
/**
 * Iterates over a Headers object and returns an object with all the header
 * entries. Values are represented as an array to account for repeated headers.
 */
function unpackHeaders(headers) {
    const out = {};
    for (const [k, v] of headers.entries()) {
        out[k] = v.split(headerValRE);
    }
    return out;
}
function safeParseResponse(rawValue, fn, errorMessage, httpMeta) {
    try {
        return (0, fp_js_1.OK)(fn(rawValue));
    }
    catch (err) {
        return (0, fp_js_1.ERR)(new responsevalidationerror_js_1.ResponseValidationError(errorMessage, {
            cause: err,
            rawValue,
            rawMessage: errorMessage,
            ...httpMeta,
        }));
    }
}
//# sourceMappingURL=matchers.js.map