const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
function isPlainObject(value) {
    const proto = Object.getPrototypeOf(value);
    return proto === Object.prototype || proto === null;
}
export function sanitizeJsonString(value) {
    return value.replace(LONE_SURROGATE_RE, "");
}
export function sanitizeJsonValue(value) {
    if (typeof value === "string") {
        return sanitizeJsonString(value);
    }
    if (Array.isArray(value)) {
        return value.map((item) => sanitizeJsonValue(item));
    }
    if (typeof value === "object" && value !== null) {
        if (!isPlainObject(value))
            return value;
        const sanitized = {};
        for (const [key, child] of Object.entries(value)) {
            sanitized[key] = sanitizeJsonValue(child);
        }
        return sanitized;
    }
    return value;
}
export function sanitizeJsonValueInPlace(value) {
    if (Array.isArray(value)) {
        let changed = false;
        for (let i = 0; i < value.length; i += 1) {
            const child = value[i];
            if (typeof child === "string") {
                const sanitized = sanitizeJsonString(child);
                if (sanitized !== child) {
                    value[i] = sanitized;
                    changed = true;
                }
            }
            else if (sanitizeJsonValueInPlace(child)) {
                changed = true;
            }
        }
        return changed;
    }
    if (typeof value === "object" && value !== null) {
        if (!isPlainObject(value))
            return false;
        let changed = false;
        for (const [key, child] of Object.entries(value)) {
            if (typeof child === "string") {
                const sanitized = sanitizeJsonString(child);
                if (sanitized !== child) {
                    value[key] = sanitized;
                    changed = true;
                }
            }
            else if (sanitizeJsonValueInPlace(child)) {
                changed = true;
            }
        }
        return changed;
    }
    return false;
}
//# sourceMappingURL=json-sanitize.js.map