(input: string)
| 39 | } |
| 40 | |
| 41 | export function telegramHtml(input: string): string { |
| 42 | if (!input) return input; |
| 43 | |
| 44 | // ── 1. Pull code regions out so we don't touch them. ── |
| 45 | const codeRegions: string[] = []; |
| 46 | |
| 47 | // Fenced code blocks first (```…```) |
| 48 | let body = input.replace(/```([\s\S]*?)```/g, (_match, inner: string) => { |
| 49 | const escaped = escapeHtml(inner.replace(/^\n/, "").replace(/\n$/, "")); |
| 50 | codeRegions.push(`<pre>${escaped}</pre>`); |
| 51 | return codePlaceholder(codeRegions.length - 1); |
| 52 | }); |
| 53 | |
| 54 | // Inline code `…` |
| 55 | body = body.replace(/`([^`\n]*)`/g, (_match, inner: string) => { |
| 56 | const escaped = escapeHtml(inner); |
| 57 | codeRegions.push(`<code>${escaped}</code>`); |
| 58 | return codePlaceholder(codeRegions.length - 1); |
| 59 | }); |
| 60 | |
| 61 | // ── 1b. Pull markdown links out before bold/italic transforms mangle URLs. ── |
| 62 | // The link text and URL will be HTML-escaped in step 2 below via the |
| 63 | // global escapeHtml pass on the placeholder-free body; the final <a> tag |
| 64 | // is assembled after escaping so the URL keeps its escaped form (single-escape, |
| 65 | // consistent with the existing `&`-in-URL behaviour). |
| 66 | const linkRegions: Array<{ text: string; url: string }> = []; |
| 67 | |
| 68 | body = body.replace( |
| 69 | /\[([^\]\n]+)\]\(([^)\s]+)\)/g, |
| 70 | (_m, text: string, url: string) => { |
| 71 | linkRegions.push({ text, url }); |
| 72 | return linkPlaceholder(linkRegions.length - 1); |
| 73 | }, |
| 74 | ); |
| 75 | |
| 76 | // ── 2. Escape HTML-special chars in the remaining (non-code) text. ── |
| 77 | body = escapeHtml(body); |
| 78 | |
| 79 | // ── 3. Bold first, into a sentinel; then italic won't eat its output. ── |
| 80 | const BOLD_OPEN = "\x01B\x01"; |
| 81 | const BOLD_CLOSE = "\x02B\x02"; |
| 82 | |
| 83 | body = body.replace(/\*\*([^\n*]+?)\*\*/g, `${BOLD_OPEN}$1${BOLD_CLOSE}`); |
| 84 | body = body.replace(/__([^\n_]+?)__/g, `${BOLD_OPEN}$1${BOLD_CLOSE}`); |
| 85 | |
| 86 | // Headings (#…) → bold |
| 87 | body = body.replace( |
| 88 | /^\s{0,3}#{1,6}\s+(.*)$/gm, |
| 89 | (_m, text: string) => `${BOLD_OPEN}${text.trim()}${BOLD_CLOSE}`, |
| 90 | ); |
| 91 | |
| 92 | // Strikethrough ~~text~~ → <s>text</s> |
| 93 | body = body.replace(/~~([^\n~]+?)~~/g, "<s>$1</s>"); |
| 94 | |
| 95 | // Italic *text* or _text_ → <i>text</i> (skip bold sentinels) |
| 96 | body = body.replace(/(^|[^*\w])\*(\S(?:[^*\n]*\S)?)\*(?!\w)/g, "$1<i>$2</i>"); |
| 97 | body = body.replace(/(^|[^_\w])_(\S(?:[^_\n]*\S)?)_(?!\w)/g, "$1<i>$2</i>"); |
| 98 |
no test coverage detected
searching dependent graphs…