/**
* a2host - Lightweight Markdown Parser (ES Module)
* Renderizador de Markdown a HTML semántico y seguro, optimizado para especificaciones técnicas (IEEE, OpenAPI, Tablas).
*/
export function renderMarkdown(markdownText) {
if (!markdownText) return '';
// Escapar HTML no deseado primero
let text = markdownText
.replace(/&/g, '&')
.replace(//g, '>');
// Restaurar saltos de línea consistentes
text = text.replace(/\r\n/g, '\n');
// Procesar bloques de código con triple backtick ```lang ... ```
text = text.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g, (match, lang, code) => {
const language = lang || 'text';
const cleanCode = code.trim();
const encoded = encodeURIComponent(cleanCode);
return `
`;
});
// Procesar Tablas Markdown (| Col 1 | Col 2 | ...)
text = text.replace(/((?:^|\n)\|[^\n]+\|\n\|(?:\s*[:-]+[-| :]*\s*)\|\n(?:\|[^\n]+\|\n?)+)/g, (match) => {
const lines = match.trim().split('\n');
if (lines.length < 2) return match;
const parseRow = (line) => {
return line
.replace(/^\|/, '')
.replace(/\|$/, '')
.split('|')
.map(cell => cell.trim());
};
const headerCells = parseRow(lines[0]);
// líneas de delimitadores como |:---|:---:|---:|
const alignLine = parseRow(lines[1]);
const aligns = alignLine.map(a => {
const start = a.startsWith(':');
const end = a.endsWith(':');
if (start && end) return 'center';
if (end) return 'right';
return 'left';
});
const bodyLines = lines.slice(2);
let html = ``;
headerCells.forEach((th, idx) => {
const align = aligns[idx] || 'left';
html += `| ${formatInline(th)} | `;
});
html += `
`;
bodyLines.forEach(row => {
if (!row.trim()) return;
const cells = parseRow(row);
html += ``;
cells.forEach((td, idx) => {
const align = aligns[idx] || 'left';
html += `| ${formatInline(td)} | `;
});
html += `
`;
});
html += `
`;
return html;
});
// Procesar Encabezados (# H1 a ###### H6)
text = text.replace(/^(#{1,6})\s+(.+)$/gm, (match, hashes, content) => {
const level = hashes.length;
const cleanContent = formatInline(content.trim());
const id = content
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-');
return `${cleanContent}`;
});
// Blockquotes (> Cita)
text = text.replace(/^(?:>|>)\s*(.+)$/gm, (match, content) => {
return `${formatInline(content.trim())}
`;
});
// Reglas horizontales (--- o ***)
text = text.replace(/^(?:---|\*\*\*|___)\s*$/gm, '
');
// Listas ordenadas e inordenadas
// Convertir listas no ordenadas (- o *)
text = text.replace(/^(?:[-*+])\s+(.+)$/gm, '$1');
text = text.replace(/((?:.*<\/li>\s*)+)/g, '');
// Convertir listas ordenadas (1. 2. 3.)
text = text.replace(/^(\d+)\.\s+(.+)$/gm, '$2');
text = text.replace(/((?:.*<\/li>\s*)+)/g, '$1
');
// Párrafos regulares (líneas que no están ya envueltas en tags de bloque)
const paragraphs = text.split(/\n{2,}/);
text = paragraphs.map(p => {
p = p.trim();
if (!p) return '';
if (
p.startsWith('${formatInline(p)}`;
}).join('\n\n');
return text;
}
/**
* Formateo en línea (Inline formatting): negrita, cursiva, links, inline code, badges
*/
function formatInline(str) {
if (!str) return '';
return str
// Código en línea `code`
.replace(/`([^`]+)`/g, '$1')
// Negrita **text**
.replace(/\*\*([^*]+)\*\*/g, '$1')
// Cursiva *text*
.replace(/\*([^*]+)\*/g, '$1')
// Enlaces [label](url)
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1');
}
function escapeText(str) {
if (!str) return '';
return str.replace(/&/g, '&').replace(//g, '>');
}