57 lines
2.2 KiB
JavaScript
57 lines
2.2 KiB
JavaScript
// Converts between markdown and ADF with @larvit/adf-codec. 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
|
|
// to-adf-lossless, to-markdown-lossless the same, through adf-codec's lossless pair in place of its portable pair
|
|
// 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 { adfToLosslessMarkdown, adfToPortableMarkdown, losslessMarkdownToAdf, 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(convert, markdown) {
|
|
const result = convert(markdown)
|
|
if (!result.ok) return refuse({ error: result.error })
|
|
process.stdout.write(JSON.stringify(result.value))
|
|
return 0
|
|
}
|
|
|
|
function toMarkdown(convert, documents) {
|
|
const texts = []
|
|
for (const [index, document] of documents.entries()) {
|
|
const result = convert(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(portableMarkdownToAdf, input)
|
|
if (mode === 'to-adf-lossless') return toAdf(losslessMarkdownToAdf, input)
|
|
if (mode === 'to-markdown') return toMarkdown(adfToPortableMarkdown, JSON.parse(input))
|
|
if (mode === 'to-markdown-lossless') return toMarkdown(adfToLosslessMarkdown, JSON.parse(input))
|
|
throw new Error(`mode must be to-adf, to-adf-lossless, to-markdown or to-markdown-lossless, 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
|
|
},
|
|
)
|