HTML Formatting Engine
Relevant source files
The following files were used as context for generating this wiki page:
The HTML Formatting Engine transforms raw analysis data and statistics into user-friendly, HTML-formatted messages compatible with the Telegram Bot API. It ensures that complex data—such as criminal code violations, user activity summaries, and risk levels—is presented clearly using bolding, italics, emojis, and structured lists while maintaining strict security via HTML entity escaping.
The engine handles three primary responsibilities: low-level HTML tag construction, high-level message orchestration for specific features, and safety measures to prevent malformed tags from breaking the Telegram message delivery pipeline.
Sources: src/core/html-builder.ts:1-5, src/core/message-formatter.ts:1-7, tests/chunkText-entities.test.ts:1-15
Architecture and Core Components
The formatting system follows a layered architecture where utility functions provide basic building blocks, the HTMLBuilder class manages tag wrapping, and the MessageFormatter class assembles complex business logic into final strings.
The diagram shows the relationship between utility functions, the low-level builder, and the high-level formatter.
Sources: src/core/html-builder.ts:35-40, src/core/message-formatter.ts:55-60, src/core/html-utils.ts:1-5
HTML Utilities
The utility layer provides stateless functions for common formatting tasks. It defines the visual representation of severity levels using a standardized emoji set.
- Severity Mapping: Converts numeric severity (1-10) into color-coded circles: 🟢 (Low: 1-3), 🟡 (Medium: 4-6), and 🔴 (High: 7-10).
- HTML Escaping: Sanitizes strings by replacing characters like
<,>, and&with their corresponding HTML entities to prevent injection. - Article Normalization: Formats Russian Criminal Code (УК РФ) article strings to ensure a canonical display format (e.g., "Статья 282 УК РФ").
Sources: src/core/html-utils.ts:10-70, tests/html-utils.test.ts:10-40
HTML Builder
The HTMLBuilder class implements the IHTMLBuilder interface to provide a programmatic way to wrap text in Telegram-supported HTML tags.
| Method | Output Format | Purpose |
|---|---|---|
bold(text) | <b>text</b> | Emphasizes headers or labels |
italic(text) | <i>text</i> | Used for quotes or secondary warnings |
underline(text) | <u>text</u> | Text decoration |
code(text) | <code>text</code> | Inline monospaced text |
preformatted(text) | <pre>text</pre> | Block-level monospaced text |
Sources: src/core/html-builder.ts:50-95, tests/html-builder.test.ts:35-65
Message Formatting Logic
The MessageFormatter converts structured data models into multi-line strings. It orchestrates the layout for violation reports and statistics.
Violation Reports
When a violation is detected, the formatter builds a detailed report containing the article name, the specific quote from the text, the legal punishment, and a confidence warning if the AI's confidence score is below 0.7.
The flow shows how individual violation data is transformed into a formatted message block.
Sources: src/core/message-formatter.ts:85-115, src/core/html-builder.ts:110-130
Statistics Formatting
The engine supports three types of statistical summaries:
- User Stats: Displays total violations, average severity, risk level, and a breakdown of specific articles violated by a single user.
- Period Stats: Summarizes chat-wide activity over a specific date range, including trends (increases or decreases) in violation frequency.
- General Stats: Generates "Top 5" leaderboards for the most frequent violations and the most active violators in a chat.
Sources: src/core/message-formatter.ts:150-250, src/core/message-formatter.ts:285-350
Safety and Chunking
Telegram imposes a 4096-character limit per message. The formatting engine works with a delivery pipeline that performs "HTML-aware chunking." This process ensures that:
- An HTML tag pair (e.g.,
<b>...</b>) is never split across two different messages. - HTML entities (e.g.,
<) are not severed in the middle of the entity string. - Emoji surrogate pairs remain intact.
If the formatted string exceeds the limit, the system calculates a safe boundary, closes any open tags at the end of the first chunk, and re-opens them at the start of the next chunk to maintain valid HTML state.
Sources: tests/chunkText-entities.test.ts:15-60, tests/chunkText-entities.test.ts:110-140
Configuration and Data Structures
Violation Data Model
The formatter expects data conforming to the Violation or ViolationMessageData interfaces.
| Field | Type | Description |
|---|---|---|
article | string | The legal article number (e.g., "282") |
quote | string | The offending text snippet |
punishment | string | Legal consequence description |
severity | number | Numeric value from 1 to 10 |
confidence | number | AI confidence score from 0 to 1 |
Sources: src/core/message-formatter.ts:35-45, src/core/html-builder.ts:20-28
Summary
The HTML Formatting Engine provides a robust framework for generating secure, structured, and visually informative messages for Telegram. By abstracting tag construction into the HTMLBuilder and business logic into the MessageFormatter, the project maintains a clean separation of concerns while ensuring that all output is sanitized and compliant with Telegram's specific HTML parsing requirements.