|
| 1 | +import { escape } from 'html-escaper'; |
| 2 | +import { bold, underline } from 'kleur/colors'; |
| 3 | +import { AstroErrorData, type ErrorWithMetadata } from '../index.js'; |
| 4 | + |
| 5 | +/** |
| 6 | + * The docs has kebab-case urls for errors, so we need to convert the error name |
| 7 | + * @param errorName |
| 8 | + */ |
| 9 | +function getKebabErrorName(errorName: string): string { |
| 10 | + return errorName.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); |
| 11 | +} |
| 12 | +export function getDocsForError(err: ErrorWithMetadata): string | undefined { |
| 13 | + if (err.name !== 'UnknownError' && err.name in AstroErrorData) { |
| 14 | + return `https://docs.astro.build/en/reference/errors/${getKebabErrorName(err.name)}/`; |
| 15 | + } |
| 16 | + return undefined; |
| 17 | +} |
| 18 | + |
| 19 | +const linkRegex = /\[([^[]+)\]\((.*)\)/g; |
| 20 | +const boldRegex = /\*\*(.+)\*\*/g; |
| 21 | +const urlRegex = / ((?:https?|ftp):\/\/[-\w+&@#\\/%?=~|!:,.;]*[-\w+&@#\\/%=~|])/gi; |
| 22 | +const codeRegex = /`([^`]+)`/g; |
| 23 | + |
| 24 | +/** |
| 25 | + * Render a subset of Markdown to HTML or a CLI output |
| 26 | + */ |
| 27 | +export function renderErrorMarkdown(markdown: string, target: 'html' | 'cli') { |
| 28 | + if (target === 'html') { |
| 29 | + return escape(markdown) |
| 30 | + .replace(linkRegex, `<a href="$2" target="_blank">$1</a>`) |
| 31 | + .replace(boldRegex, '<b>$1</b>') |
| 32 | + .replace(urlRegex, ' <a href="$1" target="_blank">$1</a>') |
| 33 | + .replace(codeRegex, '<code>$1</code>'); |
| 34 | + } else { |
| 35 | + return markdown |
| 36 | + .replace(linkRegex, (_, m1, m2) => `${bold(m1)} ${underline(m2)}`) |
| 37 | + .replace(urlRegex, (fullMatch) => ` ${underline(fullMatch.trim())}`) |
| 38 | + .replace(boldRegex, (_, m1) => `${bold(m1)}`); |
| 39 | + } |
| 40 | +} |
0 commit comments