import { jsonrepair } from "jsonrepair";
function extractJSONFromCodeBlock(response) {
    try {
        const jsonMatch = response.match(/^\s*(\{[\s\S]*\})\s*$/);
        if (jsonMatch) return jsonMatch[1];
        const codeBlockMatch = response.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
        if (codeBlockMatch) return codeBlockMatch[1];
        const jsonLikeMatch = response.match(/\{[\s\S]*\}/);
        if (jsonLikeMatch) return jsonLikeMatch[0];
    } catch  {}
    return response;
}
function normalizeJsonObject(obj, context = {}) {
    if (null == obj) return obj;
    if (Array.isArray(obj)) return obj.map((item)=>normalizeJsonObject(item, context));
    if ('object' == typeof obj) {
        const normalized = {};
        for (const [key, value] of Object.entries(obj)){
            const trimmedKey = key.trim();
            const preserveStringValue = context.preserveStringValueKeys?.includes(trimmedKey) ?? false;
            const normalizedValue = 'string' == typeof value ? preserveStringValue ? value : value.trim() : normalizeJsonObject(value, context);
            normalized[trimmedKey] = normalizedValue;
        }
        return normalized;
    }
    if ('string' == typeof obj) return obj.trim();
    return obj;
}
const parseNormalJson = (input, rawResponse, context)=>{
    if (input?.match(/\((\d+),(\d+)\)/)) return input.match(/\((\d+),(\d+)\)/)?.slice(1).map(Number);
    let parsed;
    let lastError;
    try {
        parsed = JSON.parse(input);
        return normalizeJsonObject(parsed, context);
    } catch (error) {
        lastError = error;
    }
    try {
        parsed = JSON.parse(jsonrepair(input));
        return normalizeJsonObject(parsed, context);
    } catch (error) {
        lastError = error;
    }
    return {
        parsed: void 0,
        lastError,
        rawResponse
    };
};
function safeParseJson(raw, context) {
    const cleanJsonString = extractJSONFromCodeBlock(raw);
    const result = parseNormalJson(cleanJsonString, raw, context);
    if (result && 'object' == typeof result && 'parsed' in result && void 0 === result.parsed) throw Error(`failed to parse LLM response into JSON. Error - ${String(result.lastError ?? 'unknown error')}. Response - \n ${raw}`);
    return result;
}
const normalJsonParser = safeParseJson;
export { extractJSONFromCodeBlock, normalJsonParser, safeParseJson };

//# sourceMappingURL=json.mjs.map