import type { NeutralMessage } from "../../types"; import { repoUrlFromMessage, splitMessageTitle } from "../../formatters/helpers"; /** Telegram caps a single message at 4096 characters (HTML entities included). */ const MAX_TEXT = 4096; function esc(s: string): string { return s .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } function mdToHtml(s: string): string { let out = esc(s); out = out.replace( /\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `${label}`, ); out = out.replace(/\*\*([^*]+)\*\*/g, "$1"); out = out.replace(/`([^`]+)`/g, "$1"); out = out.replace(/(^|[^*])\*([^*]+)\*/g, "$1$2"); out = out.replace(/~~([^~]+)~~/g, "$1"); return out; } function formatTimestamp(ts?: string): string { if (!ts) return ""; const d = new Date(ts); if (Number.isNaN(d.getTime())) return ts; const pad = (n: number): string => String(n).padStart(2, "0"); return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`; } /** * Truncate Telegram HTML to `max` characters without breaking markup: drops * an incomplete trailing tag and closes every tag still open at the cut * point, so parse_mode HTML never rejects the message. */ function capHtml(text: string, max: number): string { if (text.length <= max) return text; let cut = text.slice(0, max).replace(/<[^>]*$/u, ""); const stack: string[] = []; const re = /<(\/?)([a-z]+)(?:\s[^>]*)?>/g; let m: RegExpExecArray | null; while ((m = re.exec(cut)) !== null) { const tag = m[2]!; if (m[1] === "/") { const open = stack.lastIndexOf(tag); if (open >= 0) stack.splice(open); } else { stack.push(tag); } } const closers = stack .reverse() .map((tag) => ``) .join(""); return `${cut}…${closers}`; } export function renderNeutralMessage(message: NeutralMessage): string { const parts: string[] = []; // HTML allows partial links, so keep the `{repo}{#number}: {subject}` line // intact with only the repo head linked (the subject stays plain text). const { head, subject } = splitMessageTitle(message.title); const repoUrl = repoUrlFromMessage(message.url); const title = subject ? `${repoUrl ? `${mdToHtml(head)}` : mdToHtml(head)}: ${mdToHtml(subject)}` : message.url ? `${mdToHtml(message.title)}` : `${mdToHtml(message.title)}`; parts.push(title); if (message.author) { const name = mdToHtml(message.author.name); const author = message.author.url ? `${name}` : name; parts.push(`👤 ${author}`); } if (message.description) { parts.push(mdToHtml(message.description)); } for (const field of message.fields ?? []) { parts.push(`${mdToHtml(field.name)}: ${mdToHtml(field.value)}`); } const meta: string[] = []; if (message.footer) meta.push(esc(message.footer)); const ts = formatTimestamp(message.timestamp); if (ts) meta.push(ts); if (meta.length > 0) { parts.push(`${meta.join(" · ")}`); } return capHtml(parts.join("\n"), MAX_TEXT); }