export const MAX_SQL_LENGTH = 10_000;
export const DORIS_API_PREFIX = '/gateway/cli-service/cli/doris';
export function validateSql(sql) {
    const trimmed = sql.trim();
    if (!trimmed)
        throw new Error('SQL is required');
    if (trimmed.length > MAX_SQL_LENGTH) {
        throw new Error(`SQL must be ${MAX_SQL_LENGTH} characters or fewer`);
    }
    return trimmed;
}
export async function readStdin(input = process.stdin) {
    const chunks = [];
    for await (const chunk of input) {
        chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
    }
    return Buffer.concat(chunks).toString('utf8');
}
export async function resolveSql(sqlFlag, input) {
    if (sqlFlag !== undefined)
        return validateSql(sqlFlag);
    if (input === undefined && process.stdin.isTTY)
        return validateSql('');
    return validateSql(await readStdin(input));
}
export async function writeNdjsonStream(stream, write = (chunk) => {
    process.stdout.write(chunk);
}) {
    let buffer = '';
    let hasError = false;
    const inspectLine = (line) => {
        const text = line.trim();
        if (!text)
            return;
        try {
            const parsed = JSON.parse(text);
            if (parsed.type === 'error')
                hasError = true;
        }
        catch {
            // Preserve malformed server lines for the caller; do not reinterpret the stream.
        }
    };
    for await (const chunk of stream) {
        const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
        write(text);
        buffer += text;
        const lines = buffer.split('\n');
        buffer = lines.pop() ?? '';
        for (const line of lines)
            inspectLine(line);
    }
    inspectLine(buffer);
    return { hasError };
}
//# sourceMappingURL=doris.js.map