export function writeOutput(data, args) {
    if (args.format === 'text') {
        process.stdout.write(renderText(data) + '\n');
        return;
    }
    const json = args.compact
        ? JSON.stringify(data, args.sortKeys ? sortReplacer() : undefined)
        : JSON.stringify(data, args.sortKeys ? sortReplacer() : undefined, 2);
    process.stdout.write(json + '\n');
}
export function writeError(err) {
    const payload = {
        error: {
            code: err.code,
            message: err.message,
            ...(err.hint ? { hint: err.hint } : {}),
        },
    };
    process.stderr.write(JSON.stringify(payload, null, 2) + '\n');
}
function sortReplacer() {
    return function (_key, value) {
        if (value && typeof value === 'object' && !Array.isArray(value)) {
            return Object.keys(value)
                .sort()
                .reduce((acc, k) => {
                acc[k] = value[k];
                return acc;
            }, {});
        }
        return value;
    };
}
function renderText(data, indent = 0) {
    if (data === null || data === undefined)
        return 'null';
    if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean')
        return String(data);
    if (Array.isArray(data)) {
        if (data.length === 0)
            return '(empty)';
        return data
            .map((item, i) => `${'  '.repeat(indent)}[${i}] ${renderText(item, indent + 1)}`)
            .join('\n');
    }
    if (typeof data === 'object') {
        const obj = data;
        const entries = Object.entries(obj);
        if (!entries.length)
            return '{}';
        return entries
            .map(([k, v]) => `${'  '.repeat(indent)}${k}: ${renderText(v, indent + 1)}`)
            .join('\n');
    }
    return String(data);
}
//# sourceMappingURL=output.js.map