html.ts 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Minimal, dependency-free HTML→markdown-ish text conversion for `web_fetch`
  3. * presentation. This is intentionally NOT a full HTML parser: it strips
  4. * script/style/noscript, drops tags, decodes the common named/numeric entities,
  5. * and collapses whitespace into a readable plain-text approximation with a few
  6. * markdown affordances (headings, list bullets, links). A heavier converter can
  7. * replace this without touching the seam or the tool schema.
  8. *
  9. * @module @deepseek-ai/dsh-tool-web/html
  10. */
  11. /** Decode the handful of HTML entities common in textual content. */
  12. function decodeEntities(text: string): string {
  13. return text
  14. .replace(/&(#[xX][0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, entity: string) => {
  15. if (entity.startsWith('#x') || entity.startsWith('#X')) {
  16. const code = Number.parseInt(entity.slice(2), 16)
  17. return safeFromCodePoint(code, match)
  18. }
  19. if (entity.startsWith('#')) {
  20. const code = Number.parseInt(entity.slice(1), 10)
  21. return safeFromCodePoint(code, match)
  22. }
  23. return NAMED_ENTITIES[entity] ?? match
  24. })
  25. }
  26. const NAMED_ENTITIES: Record<string, string> = {
  27. amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
  28. copy: '©', reg: '®', trade: '™', hellip: '…', mdash: '—', ndash: '–',
  29. }
  30. function safeFromCodePoint(code: number, fallback: string): string {
  31. try {
  32. return String.fromCodePoint(code)
  33. } catch {
  34. // An out-of-range code point (RangeError) is the only failure here; keep the
  35. // original entity text rather than throwing out of pure presentation.
  36. return fallback
  37. }
  38. }
  39. /**
  40. * Convert an HTML document to a readable markdown-ish text approximation.
  41. * Best-effort and lossy by design — fidelity is the job of a future heavier
  42. * converter, not this fallback.
  43. */
  44. export function htmlToMarkdown(html: string): string {
  45. let text = html
  46. // Drop non-content elements entirely (including their contents).
  47. .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
  48. .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
  49. .replace(/<noscript\b[^>]*>[\s\S]*?<\/noscript>/gi, '')
  50. .replace(/<!--[\s\S]*?-->/g, '')
  51. // Convert links to markdown before stripping tags.
  52. text = text.replace(/<a\b[^>]*\bhref\s*=\s*["']([^"']*)["'][^>]*>([\s\S]*?)<\/a>/gi, (_match, href: string, label: string) => {
  53. const cleanLabel = label.replace(/<[^>]+>/g, '').trim()
  54. return cleanLabel.length > 0 ? `[${cleanLabel}](${href})` : href
  55. })
  56. // Headings → markdown hashes.
  57. text = text.replace(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi, (_match, level: string, body: string) => {
  58. const hashes = '#'.repeat(Number(level))
  59. return `\n\n${hashes} ${body.replace(/<[^>]+>/g, '').trim()}\n\n`
  60. })
  61. // List items → bullets.
  62. text = text.replace(/<li\b[^>]*>([\s\S]*?)<\/li>/gi, (_match, body: string) => `\n- ${body.replace(/<[^>]+>/g, '').trim()}`)
  63. // Block-level breaks become paragraph breaks.
  64. text = text
  65. .replace(/<\/(p|div|section|article|header|footer|tr|table|ul|ol|blockquote)>/gi, '\n\n')
  66. .replace(/<br\s*\/?>/gi, '\n')
  67. // Drop all remaining tags, decode entities, collapse whitespace.
  68. text = text.replace(/<[^>]+>/g, '')
  69. text = decodeEntities(text)
  70. text = text
  71. .replace(/[ \t\f\v]+/g, ' ')
  72. .replace(/ *\n */g, '\n')
  73. .replace(/\n{3,}/g, '\n\n')
  74. .trim()
  75. return text
  76. }