telegram-md2html 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,306 +1,320 @@
1
- # Telegram Markdown to HTML Converter
2
-
3
- [![npm version](https://img.shields.io/npm/v/telegram-md2html.svg)](https://www.npmjs.com/package/telegram-md2html)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
- [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
6
-
7
- A smart, efficient, and reliable library for converting Telegram-style Markdown to Telegram-compatible HTML. Perfect for Telegram bots, messaging applications, and content processing pipelines.
8
-
9
- ## ✨ Features
10
-
11
- - ✅ **Complete Telegram Markdown Support** - All Telegram-specific formatting
12
- - ✅ **Smart Parsing** - Context-aware (ignores formatting inside code blocks)
13
- - **Nested Formatting** - Proper handling of nested styles
14
- - **HTML Safety** - Automatic escaping of HTML special characters
15
- - **Auto-recovery** - Automatically closes unclosed code blocks
16
- - **Dual Module Support** - Works with both CommonJS (`require`) and ES Modules (`import`)
17
- - **TypeScript Ready** - Full type definitions included
18
- - **Highly Customizable** - Extensible with custom processors
19
- - **Production Ready** - Minified builds, comprehensive tests
20
- - **Zero Dependencies** - Lightweight and fast
21
-
22
- ## 📦 Installation
23
-
24
- ```bash
25
- npm install telegram-md2html
26
- # or
27
- yarn add telegram-md2html
28
- # or
29
- pnpm add telegram-md2html
30
- ```
31
-
32
- ## 🚀 Quick Start
33
-
34
- ### Basic Usage
35
-
36
- ```javascript
37
- // CommonJS
38
- const { markdownToHtml } = require('telegram-md2html');
39
-
40
- // ES Modules
41
- import { markdownToHtml } from 'telegram-md2html';
42
-
43
- const markdown = '**Bold text** and *italic text* with a [link](https://example.com)';
44
- const html = markdownToHtml(markdown);
45
-
46
- console.log(html);
47
- // Output: <b>Bold text</b> and <i>italic text</i> with a <a href="https://example.com">link</a>
48
- ```
49
-
50
- ### Complex Example
51
-
52
- ```javascript
53
- import { markdownToHtml } from 'telegram-md2html';
54
-
55
- const markdown = `
56
- # Welcome to Telegram Bot!
57
-
58
- **Important Features:**
59
- *Italic* and __underline__ formatting
60
- • ~~Strikethrough~~ and ||spoiler|| text
61
- • \`Inline code\` and code blocks:
62
- \`\`\`javascript
63
- function greet() {
64
- console.log("Hello, Telegram!");
65
- }
66
- \`\`\`
67
-
68
- > This is a regular blockquote
69
- **> This is an expandable blockquote
70
-
71
- [Learn more](https://core.telegram.org/bots/api#html-style)
72
- `;
73
-
74
- const html = markdownToHtml(markdown);
75
- // Send to Telegram bot...
76
- ```
77
-
78
- ## 📚 Supported Syntax
79
-
80
- | Markdown Syntax | HTML Output | Description |
81
- |----------------|-------------|-------------|
82
- | `**bold**` | `<b>bold</b>` | Bold text |
83
- | `*italic*` | `<i>italic</i>` | Italic text (asterisk) |
84
- | `_italic_` | `<i>italic</i>` | Italic text (underscore) |
85
- | `__underline__` | `<u>underline</u>` | Underlined text |
86
- | `~~strikethrough~~` | `<s>strikethrough</s>` | Strikethrough text |
87
- | `\|\|spoiler\|\|` | `<span class="tg-spoiler">spoiler</span>` | Spoiler text |
88
- | `` `code` `` | `<code>code</code>` | Inline code |
89
- | ```` ```language\ncode\n``` ```` | `<pre><code class="language-xxx">code</code></pre>` | Code block with syntax highlighting |
90
- | `[text](url)` | `<a href="url">text</a>` | Hyperlink |
91
- | `> quote` | `<blockquote>quote</blockquote>` | Regular blockquote |
92
- | `**> quote` | `<blockquote expandable>quote</blockquote>` | Expandable blockquote |
93
-
94
- ## ⚙️ Advanced Usage
95
-
96
- ### Custom Converter with Options
97
-
98
- ```javascript
99
- import { createConverter } from 'telegram-md2html';
100
-
101
- // Create a custom converter with advanced options
102
- const converter = createConverter({
103
- escapeHtml: true, // Escape HTML special characters (default: true)
104
- autoCloseCodeBlocks: true, // Auto-close unclosed code blocks (default: true)
105
-
106
- // Custom link processor
107
- linkProcessor: (url, text) =>
108
- `<a href="${url}" target="_blank" rel="noopener noreferrer">🔗 ${text}</a>`,
109
-
110
- // Custom code block processor
111
- codeBlockProcessor: (code, language) =>
112
- `<div class="code-container">
113
- <div class="code-header">${language || 'code'}</div>
114
- <pre><code>${code}</code></pre>
115
- </div>`
116
- });
117
-
118
- const customHtml = converter.convert('Check [this](https://example.com) out!');
119
- ```
120
-
121
- ### Disable HTML Escaping (Use with Caution)
122
-
123
- ```javascript
124
- import { markdownToHtml } from 'telegram-md2html';
125
-
126
- // For trusted content where you want to preserve existing HTML
127
- const html = markdownToHtml('Mix <b>HTML</b> with **Markdown**', {
128
- escapeHtml: false
129
- });
130
- // Output: Mix <b>HTML</b> with <b>Markdown</b>
131
- ```
132
-
133
- ## 🔧 API Reference
134
-
135
- ### `markdownToHtml(text: string, options?: ConvertOptions): string`
136
-
137
- Main conversion function that converts Markdown to Telegram HTML.
138
-
139
- **Parameters:**
140
- - `text` - The Markdown text to convert
141
- - `options` - Optional conversion settings (see below)
142
-
143
- **Returns:** Telegram-compatible HTML string
144
-
145
- ### `createConverter(options?: ConvertOptions): MarkdownConverter`
146
-
147
- Creates a reusable converter instance with custom options.
148
-
149
- ### `ConvertOptions` Interface
150
-
151
- ```typescript
152
- interface ConvertOptions {
153
- /**
154
- * Whether to escape HTML special characters (&, <, >, ", ')
155
- * @default true
156
- */
157
- escapeHtml?: boolean;
158
-
159
- /**
160
- * Whether to automatically append missing ``` to close code blocks
161
- * @default true
162
- */
163
- autoCloseCodeBlocks?: boolean;
164
-
165
- /**
166
- * Custom processor for links
167
- * @param url - The URL
168
- * @param text - The link text
169
- * @returns HTML string for the link
170
- */
171
- linkProcessor?: (url: string, text: string) => string;
172
-
173
- /**
174
- * Custom processor for code blocks
175
- * @param code - The code content
176
- * @param language - Optional language specified after ```
177
- * @returns HTML string for the code block
178
- */
179
- codeBlockProcessor?: (code: string, language?: string) => string;
180
- }
181
- ```
182
-
183
- ## 💡 Real-World Examples
184
-
185
- ### Telegram Bot Integration
186
-
187
- ```javascript
188
- const { Telegraf } = require('telegraf');
189
- const { markdownToHtml } = require('telegram-md2html');
190
-
191
- const bot = new Telegraf(process.env.BOT_TOKEN);
192
-
193
- bot.command('format', (ctx) => {
194
- const markdown = `
195
- **Formatting Examples:**
196
-
197
- *Bold*: **bold text**
198
- *Italic*: *italic text* or _italic text_
199
- *Code*: \`inline code\`
200
- *Link*: [Telegram](https://telegram.org)
201
- *Quote*:
202
- > To be or not to be
203
- `;
204
-
205
- // Convert to Telegram HTML
206
- const html = markdownToHtml(markdown);
207
-
208
- // Send as HTML message
209
- ctx.replyWithHTML(html);
210
- });
211
-
212
- bot.launch();
213
- ```
214
-
215
- ### Content Processing Pipeline
216
-
217
- ```javascript
218
- import { createConverter } from 'telegram-md2html';
219
- import { readFileSync, writeFileSync } from 'fs';
220
-
221
- // Process multiple files
222
- const converter = createConverter({
223
- codeBlockProcessor: (code, language) => `
224
- <details>
225
- <summary>${language ? `📁 ${language.toUpperCase()}` : '📄 CODE'}</summary>
226
- <pre><code>${code}</code></pre>
227
- </details>
228
- `
229
- });
230
-
231
- const input = readFileSync('document.md', 'utf-8');
232
- const output = converter.convert(input);
233
- writeFileSync('document.html', output);
234
- ```
235
-
236
- ## 🧪 Testing
237
-
238
- ```bash
239
- # Run tests
240
- npm test
241
-
242
- # Run tests with coverage
243
- npm test -- --coverage
244
- ```
245
-
246
- ## 🔍 How It Works
247
-
248
- The library uses a sophisticated tokenizer that:
249
- 1. Scans the text for Markdown patterns
250
- 2. Intelligently ignores formatting inside code blocks and inline code
251
- 3. Processes nested formatting correctly
252
- 4. Applies custom processors if provided
253
- 5. Escapes HTML characters for security
254
- 6. Auto-closes unclosed code blocks
255
-
256
- ## 📖 Common Use Cases
257
-
258
- 1. **Telegram Bots** - Format bot responses with rich text
259
- 2. **Content Management Systems** - Convert user input to safe HTML
260
- 3. **Documentation Tools** - Generate Telegram-compatible documentation
261
- 4. **Chat Applications** - Format messages for display
262
- 5. **Export Tools** - Convert Markdown to Telegram HTML for export
263
-
264
- ### Development Setup
265
-
266
- ```bash
267
- # Clone the repository
268
- git clone https://github.com/soumyadeep765/telegram-md2html.git
269
- cd telegram-md2html
270
-
271
- # Install dependencies
272
- npm install
273
-
274
- # Build the library
275
- npm run build
276
-
277
- # Run tests
278
- npm test
279
-
280
- # Development mode (watch for changes)
281
- npm run dev
282
- ```
283
-
284
- ## License
285
-
286
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
287
-
288
- ## Issue Reporting
289
-
290
- Found a bug or have a feature request? Please open an issue on the [GitHub repository](https://github.com/soumyadeep765/telegram-md2html/issues).
291
-
292
- ## Acknowledgments
293
-
294
- - Telegram for their awesome Bot API and HTML formatting support
295
- - All contributors who help improve this library
296
-
297
- ## Support
298
-
299
- For support, questions, or discussions:
300
- - Open an issue on GitHub
301
- - Check the [examples](examples/) directory
302
- - Refer to the [Telegram Bot API documentation](https://core.telegram.org/bots/api#html-style)
303
-
304
- ---
305
-
306
- **Happy coding!** If you find this library useful, please consider giving it a ⭐ on GitHub!
1
+ # Telegram Markdown to HTML Converter
2
+
3
+ A smart and efficient TypeScript/JavaScript library for converting Telegram-style Markdown to Telegram-compatible HTML. Perfect for Telegram bots, chat applications, and content processing.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/telegram-md2html.svg)](https://www.npmjs.com/package/telegram-md2html)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
8
+ [![Node.js Version](https://img.shields.io/badge/node-%3E%3D14.0.0-brightgreen.svg)](https://nodejs.org/)
9
+ [![npm downloads](https://img.shields.io/npm/dm/telegram-md2html.svg)](https://www.npmjs.com/package/telegram-md2html)
10
+
11
+ ## Features
12
+
13
+ - **Complete Telegram Markdown Support**: All Telegram-specific formatting options
14
+ - **Smart Parsing**: Handles nested styles and complex formatting
15
+ - **HTML Safety**: Automatic escaping of HTML special characters
16
+ - **Code Block Support**: Inline code and multiline code blocks with language specification
17
+ - **Blockquote Support**: Regular and expandable blockquotes
18
+ - **Customizable**: Extensible with custom processors
19
+ - **TypeScript Ready**: Full TypeScript definitions included
20
+ - **Dual Module Support**: Works with both CommonJS and ES Modules
21
+ - **Browser Compatible**: Can be used in modern browsers
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install telegram-md2html
27
+ # or
28
+ yarn add telegram-md2html
29
+ # or
30
+ pnpm add telegram-md2html
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ```javascript
36
+ // CommonJS
37
+ const { markdownToHtml } = require('telegram-md2html');
38
+
39
+ // ES Modules
40
+ import { markdownToHtml } from 'telegram-md2html';
41
+
42
+ // Convert Telegram markdown to HTML
43
+ const html = markdownToHtml('**Hello** *World*!');
44
+ console.log(html);
45
+ // Output: <b>Hello</b> <i>World</i>!
46
+ ```
47
+
48
+ ## Usage Examples
49
+
50
+ ### Basic Conversion
51
+
52
+ ```javascript
53
+ import { markdownToHtml } from 'telegram-md2html';
54
+
55
+ const markdown = `
56
+ # Welcome to Telegram Bot
57
+
58
+ **Bold text** and *italic text*
59
+ __Underlined__ and ~~strikethrough~~
60
+ ||Spoiler text||
61
+
62
+ \`inline code\`
63
+
64
+ [Visit Google](https://google.com)
65
+
66
+ > This is a quote
67
+ **> Expandable quote
68
+
69
+ \`\`\`javascript
70
+ console.log("Hello World");
71
+ \`\`\`
72
+ `;
73
+
74
+ const html = markdownToHtml(markdown);
75
+ console.log(html);
76
+ ```
77
+
78
+ ### Advanced Usage with Options
79
+
80
+ ```javascript
81
+ import { createConverter } from 'telegram-md2html';
82
+
83
+ // Create a converter with custom options
84
+ const converter = createConverter({
85
+ escapeHtml: true,
86
+ autoCloseCodeBlocks: true,
87
+ linkProcessor: (url, text) =>
88
+ `<a href="${url}" target="_blank" rel="noopener">${text}</a>`,
89
+ codeBlockProcessor: (code, language) =>
90
+ `<pre><code class="language-${language || 'text'}">${code}</code></pre>`
91
+ });
92
+
93
+ const html = converter.convert('**[Important Link](https://example.com)**');
94
+ ```
95
+
96
+ ## Supported Markdown Syntax
97
+
98
+ | Markdown | HTML Output | Description |
99
+ |----------|-------------|-------------|
100
+ | `**text**` | `<b>text</b>` | Bold text |
101
+ | `*text*` or `_text_` | `<i>text</i>` | Italic text |
102
+ | `__text__` | `<u>text</u>` | Underlined text |
103
+ | `~~text~~` | `<s>text</s>` | Strikethrough text |
104
+ | `\|\|text\|\|` | `<span class="tg-spoiler">text</span>` | Spoiler text |
105
+ | `` `code` `` | `<code>code</code>` | Inline code |
106
+ | ```` ```language\ncode\n``` ```` | `<pre><code class="language-xxx">code</code></pre>` | Code block |
107
+ | `[text](url)` | `<a href="url">text</a>` | Link |
108
+ | `> text` | `<blockquote>text</blockquote>` | Blockquote |
109
+ | `**> text` | `<blockquote expandable>text</blockquote>` | Expandable blockquote |
110
+
111
+ ## API Reference
112
+
113
+ ### `markdownToHtml(text: string, options?: ConvertOptions): string`
114
+
115
+ Main conversion function that converts Telegram-style markdown to HTML.
116
+
117
+ **Parameters:**
118
+ - `text`: The markdown text to convert
119
+ - `options`: Optional conversion options
120
+
121
+ **Returns:** Telegram-compatible HTML string
122
+
123
+ ### `createConverter(options?: ConvertOptions): MarkdownConverter`
124
+
125
+ Creates a converter instance with custom options for reuse.
126
+
127
+ ### ConvertOptions Interface
128
+
129
+ ```typescript
130
+ interface ConvertOptions {
131
+ /** Whether to escape HTML special characters (default: true) */
132
+ escapeHtml?: boolean;
133
+
134
+ /** Whether to auto-close unclosed code blocks (default: true) */
135
+ autoCloseCodeBlocks?: boolean;
136
+
137
+ /** Custom link processor function */
138
+ linkProcessor?: (url: string, text: string) => string;
139
+
140
+ /** Custom code block processor function */
141
+ codeBlockProcessor?: (code: string, language?: string) => string;
142
+ }
143
+ ```
144
+
145
+ ## TypeScript Support
146
+
147
+ The library includes full TypeScript definitions. Just import and use:
148
+
149
+ ```typescript
150
+ import { markdownToHtml, ConvertOptions } from 'telegram-md2html';
151
+
152
+ const options: ConvertOptions = {
153
+ escapeHtml: false,
154
+ linkProcessor: (url: string, text: string): string => {
155
+ return `<a href="${url}" class="custom-link">${text}</a>`;
156
+ }
157
+ };
158
+
159
+ const html: string = markdownToHtml('**TypeScript** works!', options);
160
+ ```
161
+
162
+ ## Browser Usage
163
+
164
+ The library can be used in modern browsers:
165
+
166
+ ### Using ES Modules (Recommended)
167
+
168
+ ```html
169
+ <script type="module">
170
+ import { markdownToHtml } from 'https://cdn.jsdelivr.net/npm/telegram-md2html/dist/index.mjs';
171
+
172
+ const html = markdownToHtml('**Hello** from browser!');
173
+ document.getElementById('output').innerHTML = html;
174
+ </script>
175
+ ```
176
+
177
+ ### Using from GitHub
178
+
179
+ ```html
180
+ <script type="module">
181
+ import { markdownToHtml } from 'https://cdn.jsdelivr.net/gh/Soumyadeep765/telegram-md2html@main/dist/index.mjs';
182
+
183
+ const html = markdownToHtml('**Hello** World');
184
+ document.getElementById('output').innerHTML = html;
185
+ </script>
186
+ ```
187
+
188
+ ### Using a CDN
189
+
190
+ ```html
191
+ <script src="https://cdn.jsdelivr.net/npm/telegram-md2html/dist/index.js"></script>
192
+ <script>
193
+ // Available as window.telegramMd2Html
194
+ const html = telegramMd2Html.markdownToHtml('**CDN** Example');
195
+ document.getElementById('output').innerHTML = html;
196
+ </script>
197
+ ```
198
+
199
+ ### Complex Nested Example
200
+
201
+ ```javascript
202
+ const result = markdownToHtml(`
203
+ **Welcome to our bot!**
204
+
205
+ Features:
206
+ *Easy formatting*
207
+ • __Multiple styles__
208
+ ~~Clean output~~
209
+
210
+ \`\`\`python
211
+ def greet():
212
+ print("Hello from Python!")
213
+ \`\`\`
214
+
215
+ > Remember: **Formatting** makes messages _better_
216
+ **> Click to expand details
217
+ `);
218
+
219
+ console.log(result);
220
+ ```
221
+
222
+ ## Error Handling
223
+
224
+ The library handles edge cases gracefully:
225
+
226
+ - Unclosed code blocks are automatically closed
227
+ - HTML characters are properly escaped by default
228
+ - Invalid markdown is treated as plain text
229
+ - Nested styles are processed correctly
230
+
231
+ ## Performance
232
+
233
+ The library is optimized for performance:
234
+ - Efficient tokenization algorithm
235
+ - Minimal memory usage
236
+ - No external dependencies
237
+ - Fast parsing even for large documents
238
+
239
+ ## Contributing
240
+
241
+ Contributions are welcome! Here's how you can help:
242
+
243
+ 1. Fork the repository
244
+ 2. Create a feature branch: `git checkout -b feature-name`
245
+ 3. Make your changes
246
+ 4. Add tests for new functionality
247
+ 5. Run tests: `npm test`
248
+ 6. Commit your changes: `git commit -am 'Add feature'`
249
+ 7. Push to the branch: `git push origin feature-name`
250
+ 8. Submit a pull request
251
+
252
+ ### Development Setup
253
+
254
+ ```bash
255
+ # Clone the repository
256
+ git clone https://github.com/Soumyadeep765/telegram-md2html.git
257
+ cd telegram-md2html
258
+
259
+ # Install dependencies
260
+ npm install
261
+
262
+ # Build the library
263
+ npm run build
264
+
265
+ # Run tests
266
+ npm test
267
+
268
+ # Watch mode for development
269
+ npm run dev
270
+ ```
271
+
272
+ ## Testing
273
+
274
+ The library includes comprehensive tests:
275
+
276
+ ```bash
277
+ # Run all tests
278
+ npm test
279
+
280
+ # Run tests with coverage
281
+ npm test -- --coverage
282
+ ```
283
+
284
+ ## License
285
+
286
+ This project is licensed under the **MIT** License
287
+
288
+ ## Support
289
+
290
+ If you find this library useful, please consider:
291
+
292
+ - Starring the repository on GitHub
293
+ - Sharing it with others
294
+ - Reporting issues
295
+ - Suggesting new features
296
+
297
+ ## Changelog
298
+
299
+ ### v1.0.1
300
+ - Initial release
301
+ - Complete Telegram markdown support
302
+ - TypeScript definitions
303
+ - Browser compatibility
304
+ - Custom processor support
305
+
306
+ ## Author
307
+
308
+ **Soumyadeep Das**
309
+ - GitHub: [@Soumyadeep765](https://github.com/Soumyadeep765)
310
+ - Email: soumyadeepdas765@gmail.com
311
+
312
+ ## Acknowledgments
313
+
314
+ - Telegram for their excellent Bot API
315
+ - All contributors and users of this library
316
+ - The open source community for inspiration and support
317
+
318
+ ---
319
+
320
+ **Note**: This library is not affiliated with or endorsed by Telegram.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MarkdownConverter } from './converter.js';
2
- import { ConvertOptions } from './types.js';
2
+ import type { ConvertOptions } from './types.js';
3
3
  /**
4
4
  * Convert Telegram-style Markdown to HTML
5
5
  * @param text - Markdown text to convert
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MarkdownConverter } from './converter.js';
2
- import { ConvertOptions } from './types.js';
2
+ import type { ConvertOptions } from './types.js';
3
3
  /**
4
4
  * Convert Telegram-style Markdown to HTML
5
5
  * @param text - Markdown text to convert