// Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument: // to-adf stdin is markdown, stdout is the ADF document as JSON // to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order // Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}, // with "index", the refused document's place in the array, beside "error" in to-markdown. // Exit 1: the shim could not run, and stderr says why. import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec' const REFUSED = 2 async function readStdin() { const chunks = [] for await (const chunk of process.stdin) chunks.push(chunk) return Buffer.concat(chunks).toString('utf8') } function refuse(refusal) { process.stdout.write(JSON.stringify(refusal)) return REFUSED } function toAdf(markdown) { const result = portableMarkdownToAdf(markdown) if (!result.ok) return refuse({ error: result.error }) process.stdout.write(JSON.stringify(result.value)) return 0 } function toMarkdown(documents) { const texts = [] for (const [index, document] of documents.entries()) { const result = adfToPortableMarkdown(document) if (!result.ok) return refuse({ index, error: result.error }) texts.push(result.value) } process.stdout.write(JSON.stringify(texts)) return 0 } async function main(mode) { const input = await readStdin() if (mode === 'to-adf') return toAdf(input) if (mode === 'to-markdown') return toMarkdown(JSON.parse(input)) throw new Error(`mode must be to-adf or to-markdown, not ${mode}`) } main(process.argv[2]).then( (code) => { process.exitCode = code }, (failure) => { process.stderr.write(`${failure instanceof Error ? failure.message : failure}\n`) process.exitCode = 1 }, )