"""Converts markdown to ADF (Atlassian Document Format, the rich text of Jira Cloud and Confluence) and back. It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means. """ import dataclasses import hashlib import json import pathlib import subprocess import typing from failure import Failure SHIM = pathlib.Path(__file__).resolve().parent / "node_shim" SHIM_FILES = ("Dockerfile", "package.json", "package-lock.json", "shim.mjs") # `--memory` and `--memory-swap` both take this, so the container can't swap: a document too big for it ends in a Failure. MEMORY = "256m" RUN_SECONDS = 60 BUILD_SECONDS = 300 REFUSED = 2 @dataclasses.dataclass(frozen=True) class Ran: status: int out: str err: str # Runs the shim in the given mode (`to-adf` or `to-markdown`) on a text, or fails to run it. Run = typing.Callable[[str, str], Ran | Failure] # Runs a docker command line on a text, in at most the given seconds, or fails to run it. Docker = typing.Callable[[list[str], str, int], Ran | Failure] def image_tag(shim: pathlib.Path) -> str: """A tag that changes with every file the image is built from, so an edited shim or a bumped adf-codec builds a new image.""" digest = hashlib.sha256() for name in SHIM_FILES: digest.update((shim / name).read_bytes()) return f"claude-config-adf-codec:{digest.hexdigest()[:12]}" def docker_args(image: str, mode: str) -> list[str]: return ["docker", "run", "--rm", "-i", "--memory", MEMORY, "--memory-swap", MEMORY, "--network", "none", "--read-only", image, mode] def docker(args: list[str], text: str, seconds: int, call: typing.Callable[..., typing.Any] = subprocess.run) -> Ran | Failure: try: done = call(args, input=text, capture_output=True, text=True, encoding="utf-8", timeout=seconds) except FileNotFoundError: return Failure("docker is not installed, and the adf-codec shim runs in a container") except subprocess.TimeoutExpired: return Failure(f"`{' '.join(args[:2])}` took more than {seconds} seconds") return Ran(done.returncode, done.stdout, done.stderr) def ensure_image(shim: pathlib.Path, run_docker: Docker = docker) -> str | Failure: """The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag.""" tag = image_tag(shim) found = run_docker(["docker", "image", "inspect", tag], "", RUN_SECONDS) if isinstance(found, Failure) or found.status == 0: return found if isinstance(found, Failure) else tag built = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS) if isinstance(built, Failure): return built if built.status != 0: return Failure(f"building the adf-codec shim's image failed with exit {built.status}: {built.err.strip()}") return tag def container_run(mode: str, text: str, run_docker: Docker = docker, shim: pathlib.Path = SHIM) -> Ran | Failure: image = ensure_image(shim, run_docker) if isinstance(image, Failure): return image return run_docker(docker_args(image, mode), text, RUN_SECONDS) def answer(mode: str, text: str, run: Run) -> str | Failure: """What the shim printed for text, or a Failure saying why it gave no answer.""" ran = run(mode, text) if isinstance(ran, Failure): return ran if ran.status == 0: return ran.out if ran.status == REFUSED: return refusal(ran.out) return Failure(f"the adf-codec shim failed with exit {ran.status}: {ran.err.strip()}") def refusal(out: str) -> Failure: try: error = json.loads(out)["error"] where = f"line {error['position']['line']}" if "position" in error else ".".join(str(step) for step in error["path"]) or "the document" return Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})") except (ValueError, KeyError, TypeError): return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}") def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure: """The ADF document for the markdown.""" out = answer("to-adf", markdown, run) if isinstance(out, Failure): return out try: document = json.loads(out) except ValueError: return Failure(f"the adf-codec shim printed output that is not JSON: {out.strip()}") return document def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure: """The markdown for the ADF document.""" return answer("to-markdown", json.dumps(document), run)