import fs from 'node:fs'; import { WaError } from './rpc.js'; import { format } from './format/index.js'; // Parses --params / --json: literal JSON, @file or - (stdin). export function parseJsonArg(value, flag) { if (value === undefined) return {}; let text = value; try { if (value === '-') text = fs.readFileSync(0, 'utf8'); else if (value.startsWith('@')) text = fs.readFileSync(value.slice(1), 'utf8'); } catch (e) { throw new WaError('EINVAL', `${flag}: ${e.message}`); } try { return JSON.parse(text); } catch (e) { throw new WaError('EINVAL', `${flag}: invalid JSON (${e.message})`); } } export function print(data, fmt = 'json', { columns, output } = {}) { let text; try { text = format(data, fmt, { columns }); } catch (e) { throw new WaError(e.code || 'EINVAL', e.message); } if (output) { fs.writeFileSync(output, text ? `${text}\n` : ''); } else if (text) { process.stdout.write(`${text}\n`); } } export function readStdin() { return fs.readFileSync(0, 'utf8').replace(/\n$/, ''); }