#!/bin/sh set -eu src=${1:?source markdown} template=${2:?html template} out=${3:?output html} tmp="${out}.body" if command -v cmark >/dev/null 2>&1; then cmark --unsafe "$src" > "$tmp" else awk ' function esc(s) { gsub(/&/, "\\&", s) gsub(//, "\\>", s) return s } function inline_code(s, out, pre, code, post) { out = "" while(match(s, /`[^`]+`/)) { pre = substr(s, 1, RSTART - 1) code = substr(s, RSTART + 1, RLENGTH - 2) post = substr(s, RSTART + RLENGTH) out = out esc(pre) "" esc(code) "" s = post } return out esc(s) } function close_list() { if(in_list) { print "" in_list = 0 } } function close_para() { if(in_para) { print "

" in_para = 0 } } function slug(s) { gsub(/`/, "", s) gsub(/[^A-Za-z0-9]+/, "-", s) gsub(/^-+|-+$/, "", s) return tolower(s) } BEGIN { in_code = 0 in_list = 0 in_para = 0 } /^```/ { close_para() close_list() if(in_code) { print "" in_code = 0 } else { lang = substr($0, 4) printf "
"
        in_code = 1
    }
    next
}
in_code {
    print esc($0)
    next
}
/^# / {
    close_para()
    close_list()
    text = substr($0, 3)
    printf "

%s

\n", slug(text), inline_code(text) next } /^## / { close_para() close_list() text = substr($0, 4) printf "

%s

\n", slug(text), inline_code(text) next } /^### / { close_para() close_list() text = substr($0, 5) printf "

%s

\n", slug(text), inline_code(text) next } /^#### / { close_para() close_list() text = substr($0, 6) printf "

%s

\n", slug(text), inline_code(text) next } /^- / { close_para() if(!in_list) { print "
" } ' "$src" > "$tmp" fi # cmark does not add heading IDs. Use the same slugs as the fallback renderer # so published API links work regardless of the installed Markdown renderer. python3 - "$tmp" <<'PY' import html import posixpath import re import sys from pathlib import Path path = Path(sys.argv[1]) used = set() def anchor(match): level, attributes, label = match.groups() existing = re.search(r'\bid="([^"]+)"', attributes) plain = html.unescape(re.sub(r'<[^>]+>', '', label)) slug = existing[1] if existing else re.sub(r'[^A-Za-z0-9]+', '-', plain).strip('-').lower() candidate = slug suffix = 1 while candidate in used: candidate = f'{slug}-{suffix}' suffix += 1 used.add(candidate) attributes = re.sub(r'\s+id="[^"]+"', '', attributes) return f'{label}' body = re.sub(r']*)>(.*?)', anchor, path.read_text(), flags=re.S) def markdown_link(match): destination = posixpath.normpath('docs/' + match[1]) return 'href="https://github.com/kryonlabs/kryon/blob/master/' + destination + '"' body = re.sub(r'href="([^":]+\.md(?:#[^"]*)?)"', markdown_link, body) # Preserve the older contents link to the KSS documentation section. if 'id="style-sheets"' not in body: body = body.replace('

', '

') path.write_text(body) PY awk ' FNR == NR { body = body $0 "\n" next } { p = index($0, "{{ API_BODY }}") if(p) { print substr($0, 1, p - 1) body substr($0, p + 14) } else { print } } ' "$tmp" "$template" > "$out" rm "$tmp"