Files
claude-config/bin/adf_codec/node_shim/shim.mjs
T
2026-11-14 16:27:40 +01:00

39 lines
1.4 KiB
JavaScript

// 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 an ADF document as JSON, stdout is markdown
// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}.
// 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 finish(result, render) {
if (result.ok) {
process.stdout.write(render(result.value))
return 0
}
process.stdout.write(JSON.stringify({ error: result.error }))
return REFUSED
}
async function main(mode) {
const input = await readStdin()
if (mode === 'to-adf') return finish(portableMarkdownToAdf(input), (doc) => JSON.stringify(doc))
if (mode === 'to-markdown') return finish(adfToPortableMarkdown(JSON.parse(input)), (markdown) => markdown)
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
},
)