Convert ADF to markdown and back through adf-codec's lossless pair
CI / tests (pull_request) Successful in 1m47s

This commit is contained in:
2026-11-16 13:07:30 +01:00
parent 7fc64d860a
commit 4985e6a2a9
5 changed files with 119 additions and 20 deletions
+13 -9
View File
@@ -1,10 +1,12 @@
// Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument:
// 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
// The portable calls behind those two drop each block's localId and empty paragraphs. The same two modes with the suffix
// -lossless, to-adf-lossless and to-markdown-lossless, call adf-codec's lossless pair, which keeps both.
// 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'
import { adfToLosslessMarkdown, adfToPortableMarkdown, losslessMarkdownToAdf, portableMarkdownToAdf } from '@larvit/adf-codec'
const REFUSED = 2
@@ -19,17 +21,17 @@ function refuse(refusal) {
return REFUSED
}
function toAdf(markdown) {
const result = portableMarkdownToAdf(markdown)
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(documents) {
function toMarkdown(convert, documents) {
const texts = []
for (const [index, document] of documents.entries()) {
const result = adfToPortableMarkdown(document)
const result = convert(document)
if (!result.ok) return refuse({ index, error: result.error })
texts.push(result.value)
}
@@ -39,9 +41,11 @@ function toMarkdown(documents) {
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}`)
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(