export class JsonCleaner {
    static cleanupJson(json) {
        // Handle dangling commas
        json = json.replace(/,}/g, "}");
        json = json.replace(/,]/g, "]");
        const stringResult = this.correctUnendedStrings(json);
        json = stringResult.correctedJson;
        let isComplete = stringResult.isComplete;
        // Process the JSON string character by character
        let isInString = false;
        let isEscape = false;
        const openStack = [];
        for (let i = 0; i < json.length; i++) {
            const c = json[i];
            if (c === '"' && !isEscape) {
                isInString = !isInString;
            }
            if (!isInString) {
                switch (c) {
                    case "{":
                        openStack.push(c);
                        break;
                    case "}":
                        if (openStack.length > 0) {
                            openStack.pop();
                        }
                        break;
                    case "[":
                        openStack.push(c);
                        break;
                    case "]":
                        if (openStack.length > 0) {
                            openStack.pop();
                        }
                        break;
                }
            }
            isEscape = isInString && c === "\\" && !isEscape;
        }
        // Append missing closing brackets
        while (openStack.length > 0) {
            const open = openStack.pop();
            if (open === "{") {
                json += "}";
            }
            else if (open === "[") {
                json += "]";
            }
            isComplete = false;
        }
        return {
            cleanedJson: json,
            isComplete: isComplete,
        };
    }
    static correctUnendedStrings(json) {
        let isComplete = true;
        let isInString = false;
        let isEscape = false;
        for (let i = 0; i < json.length; i++) {
            if (json[i] === '"' && !isEscape) {
                isInString = !isInString;
            }
            isEscape = isInString && json[i] === "\\" && !isEscape;
        }
        if (isInString) {
            json += '[...]"';
            isComplete = false;
        }
        return {
            correctedJson: json,
            isComplete: isComplete,
        };
    }
}
//# sourceMappingURL=jsonCleaner.js.map