@ai-devkit/channel-connector 0.10.0 โ 0.12.0
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/dist/__tests__/adapters/TelegramAdapter.test.js +204 -1
- package/dist/__tests__/adapters/TelegramAdapter.test.js.map +1 -1
- package/dist/adapters/TelegramAdapter.d.ts +21 -4
- package/dist/adapters/TelegramAdapter.d.ts.map +1 -1
- package/dist/adapters/TelegramAdapter.js +300 -8
- package/dist/adapters/TelegramAdapter.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +27 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
|
@@ -12,6 +12,8 @@ vi.mock('telegraf', ()=>{
|
|
|
12
12
|
}),
|
|
13
13
|
telegram: {
|
|
14
14
|
sendMessage: vi.fn().mockResolvedValue(undefined),
|
|
15
|
+
editMessageReplyMarkup: vi.fn().mockResolvedValue(undefined),
|
|
16
|
+
answerCbQuery: vi.fn().mockResolvedValue(undefined),
|
|
15
17
|
getMe: vi.fn().mockResolvedValue({
|
|
16
18
|
username: 'test_bot'
|
|
17
19
|
})
|
|
@@ -35,6 +37,28 @@ vi.mock('telegraf', ()=>{
|
|
|
35
37
|
await handlers['text'](ctx);
|
|
36
38
|
}
|
|
37
39
|
return ctx;
|
|
40
|
+
},
|
|
41
|
+
_triggerCallback: async (chatId, userId, data, messageId = 555)=>{
|
|
42
|
+
const ctx = {
|
|
43
|
+
callbackQuery: {
|
|
44
|
+
id: 'cbq-test',
|
|
45
|
+
data,
|
|
46
|
+
message: {
|
|
47
|
+
message_id: messageId,
|
|
48
|
+
chat: {
|
|
49
|
+
id: chatId
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
from: {
|
|
53
|
+
id: userId
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
answerCbQuery: vi.fn().mockResolvedValue(undefined)
|
|
57
|
+
};
|
|
58
|
+
if (handlers['callback_query']) {
|
|
59
|
+
await handlers['callback_query'](ctx);
|
|
60
|
+
}
|
|
61
|
+
return ctx;
|
|
38
62
|
}
|
|
39
63
|
};
|
|
40
64
|
return {
|
|
@@ -47,6 +71,12 @@ vi.mock('telegraf', ()=>{
|
|
|
47
71
|
function getMockBot() {
|
|
48
72
|
return telegrafModule.__mockBot;
|
|
49
73
|
}
|
|
74
|
+
function expectHtmlChunkWithinLimit(chunk) {
|
|
75
|
+
expect(chunk.length).toBeLessThanOrEqual(4096);
|
|
76
|
+
expect(chunk).not.toMatch(/&(?:l|lt|g|gt|a|am|amp|q|qu|quo|quot)$/);
|
|
77
|
+
expect((chunk.match(/<pre>/g) ?? []).length).toBe((chunk.match(/<\/pre>/g) ?? []).length);
|
|
78
|
+
expect((chunk.match(/<code(?: class="language-[^"]+")?>/g) ?? []).length).toBe((chunk.match(/<\/code>/g) ?? []).length);
|
|
79
|
+
}
|
|
50
80
|
describe('TelegramAdapter', ()=>{
|
|
51
81
|
let adapter;
|
|
52
82
|
beforeEach(()=>{
|
|
@@ -148,6 +178,72 @@ describe('TelegramAdapter', ()=>{
|
|
|
148
178
|
});
|
|
149
179
|
}
|
|
150
180
|
});
|
|
181
|
+
it('should split long fenced code into independently valid HTML code blocks', async ()=>{
|
|
182
|
+
const bot = getMockBot();
|
|
183
|
+
const codeLine = 'const sample = "<code>tag</code>" && value < limit;\n';
|
|
184
|
+
const longMessage = `Before\n\n\`\`\`ts\n${codeLine.repeat(100)}\`\`\`\n\nAfter`;
|
|
185
|
+
await adapter.sendMessage('12345', longMessage);
|
|
186
|
+
expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);
|
|
187
|
+
for (const call of bot.telegram.sendMessage.mock.calls){
|
|
188
|
+
const chunk = call[1];
|
|
189
|
+
expect(call[2]).toEqual({
|
|
190
|
+
parse_mode: 'HTML'
|
|
191
|
+
});
|
|
192
|
+
expectHtmlChunkWithinLimit(chunk);
|
|
193
|
+
if (chunk.includes('<pre>')) {
|
|
194
|
+
expect(chunk).toContain('<code class="language-ts">');
|
|
195
|
+
expect(chunk).toContain('<code>tag</code>');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
it('should split nested list fenced code without sending partial HTML tags', async ()=>{
|
|
200
|
+
const bot = getMockBot();
|
|
201
|
+
const codeLine = ' return "<code>tag</code>" && input < output;\n';
|
|
202
|
+
const longMessage = [
|
|
203
|
+
'- parent item',
|
|
204
|
+
' - child item with code',
|
|
205
|
+
' ```js',
|
|
206
|
+
codeLine.repeat(100).trimEnd(),
|
|
207
|
+
' ```',
|
|
208
|
+
'- final item'
|
|
209
|
+
].join('\n');
|
|
210
|
+
await adapter.sendMessage('12345', longMessage);
|
|
211
|
+
expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);
|
|
212
|
+
for (const call of bot.telegram.sendMessage.mock.calls){
|
|
213
|
+
const chunk = call[1];
|
|
214
|
+
expect(call[2]).toEqual({
|
|
215
|
+
parse_mode: 'HTML'
|
|
216
|
+
});
|
|
217
|
+
expectHtmlChunkWithinLimit(chunk);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
it('should split long paragraphs at readable markdown boundaries', async ()=>{
|
|
221
|
+
const bot = getMockBot();
|
|
222
|
+
const sentence = 'This is a long sentence with enough words to make chunking choose sentence boundaries. ';
|
|
223
|
+
const longMessage = sentence.repeat(80);
|
|
224
|
+
await adapter.sendMessage('12345', longMessage);
|
|
225
|
+
expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);
|
|
226
|
+
for (const call of bot.telegram.sendMessage.mock.calls){
|
|
227
|
+
const chunk = call[1];
|
|
228
|
+
expect(call[2]).toEqual({
|
|
229
|
+
parse_mode: 'HTML'
|
|
230
|
+
});
|
|
231
|
+
expectHtmlChunkWithinLimit(chunk);
|
|
232
|
+
expect(chunk.endsWith('.') || chunk.endsWith('.\n\n') || chunk.endsWith(' ')).toBe(true);
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
it('should keep emoji chunks within the configured JavaScript string length limit', async ()=>{
|
|
236
|
+
const bot = getMockBot();
|
|
237
|
+
const longMessage = `Status ${'๐งช'.repeat(2500)}`;
|
|
238
|
+
await adapter.sendMessage('12345', longMessage);
|
|
239
|
+
expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);
|
|
240
|
+
for (const call of bot.telegram.sendMessage.mock.calls){
|
|
241
|
+
expect(call[1].length).toBeLessThanOrEqual(4096);
|
|
242
|
+
expect(call[2]).toEqual({
|
|
243
|
+
parse_mode: 'HTML'
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
});
|
|
151
247
|
it('should hard split at 4096 when no newlines available', async ()=>{
|
|
152
248
|
const bot = getMockBot();
|
|
153
249
|
const longMessage = 'A'.repeat(5000);
|
|
@@ -164,7 +260,7 @@ describe('TelegramAdapter', ()=>{
|
|
|
164
260
|
await adapter.sendMessage('12345', message);
|
|
165
261
|
// First chunk should end at a \n\n boundary, not mid-paragraph
|
|
166
262
|
const firstChunk = bot.telegram.sendMessage.mock.calls[0][1];
|
|
167
|
-
expect(firstChunk.
|
|
263
|
+
expect(firstChunk).toBe(`${paragraph}\n\n${paragraph}`);
|
|
168
264
|
});
|
|
169
265
|
it('should send short messages in a single call', async ()=>{
|
|
170
266
|
const bot = getMockBot();
|
|
@@ -240,6 +336,113 @@ describe('TelegramAdapter', ()=>{
|
|
|
240
336
|
expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);
|
|
241
337
|
});
|
|
242
338
|
});
|
|
339
|
+
describe('sendInlineKeyboard', ()=>{
|
|
340
|
+
it('sends with parse_mode HTML and inline_keyboard payload, returns message_id', async ()=>{
|
|
341
|
+
const bot = getMockBot();
|
|
342
|
+
bot.telegram.sendMessage.mockResolvedValueOnce({
|
|
343
|
+
message_id: 42
|
|
344
|
+
});
|
|
345
|
+
const id = await adapter.sendInlineKeyboard('12345', '<b>hi</b>', [
|
|
346
|
+
[
|
|
347
|
+
{
|
|
348
|
+
text: 'A',
|
|
349
|
+
callbackData: 'q:1:o:0'
|
|
350
|
+
}
|
|
351
|
+
],
|
|
352
|
+
[
|
|
353
|
+
{
|
|
354
|
+
text: 'B',
|
|
355
|
+
callbackData: 'q:1:o:1'
|
|
356
|
+
}
|
|
357
|
+
]
|
|
358
|
+
]);
|
|
359
|
+
expect(id).toBe(42);
|
|
360
|
+
expect(bot.telegram.sendMessage).toHaveBeenCalledWith('12345', '<b>hi</b>', {
|
|
361
|
+
parse_mode: 'HTML',
|
|
362
|
+
reply_markup: {
|
|
363
|
+
inline_keyboard: [
|
|
364
|
+
[
|
|
365
|
+
{
|
|
366
|
+
text: 'A',
|
|
367
|
+
callback_data: 'q:1:o:0'
|
|
368
|
+
}
|
|
369
|
+
],
|
|
370
|
+
[
|
|
371
|
+
{
|
|
372
|
+
text: 'B',
|
|
373
|
+
callback_data: 'q:1:o:1'
|
|
374
|
+
}
|
|
375
|
+
]
|
|
376
|
+
]
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
});
|
|
381
|
+
describe('editInlineKeyboard', ()=>{
|
|
382
|
+
it('replaces the keyboard on an existing message', async ()=>{
|
|
383
|
+
const bot = getMockBot();
|
|
384
|
+
await adapter.editInlineKeyboard('12345', 99, [
|
|
385
|
+
[
|
|
386
|
+
{
|
|
387
|
+
text: 'โ A',
|
|
388
|
+
callbackData: 'q:1:o:0'
|
|
389
|
+
}
|
|
390
|
+
]
|
|
391
|
+
]);
|
|
392
|
+
expect(bot.telegram.editMessageReplyMarkup).toHaveBeenCalledWith('12345', 99, undefined, {
|
|
393
|
+
inline_keyboard: [
|
|
394
|
+
[
|
|
395
|
+
{
|
|
396
|
+
text: 'โ A',
|
|
397
|
+
callback_data: 'q:1:o:0'
|
|
398
|
+
}
|
|
399
|
+
]
|
|
400
|
+
]
|
|
401
|
+
});
|
|
402
|
+
});
|
|
403
|
+
it('passes undefined reply_markup to remove the keyboard', async ()=>{
|
|
404
|
+
const bot = getMockBot();
|
|
405
|
+
await adapter.editInlineKeyboard('12345', 99, null);
|
|
406
|
+
expect(bot.telegram.editMessageReplyMarkup).toHaveBeenCalledWith('12345', 99, undefined, undefined);
|
|
407
|
+
});
|
|
408
|
+
});
|
|
409
|
+
describe('answerCallback', ()=>{
|
|
410
|
+
it('forwards id and optional text to telegraf', async ()=>{
|
|
411
|
+
const bot = getMockBot();
|
|
412
|
+
await adapter.answerCallback('cbq-1', 'thanks');
|
|
413
|
+
expect(bot.telegram.answerCbQuery).toHaveBeenCalledWith('cbq-1', 'thanks');
|
|
414
|
+
});
|
|
415
|
+
});
|
|
416
|
+
describe('onCallback', ()=>{
|
|
417
|
+
it('invokes the registered handler with a normalized IncomingCallback', async ()=>{
|
|
418
|
+
const handler = vi.fn().mockResolvedValue(undefined);
|
|
419
|
+
adapter.onCallback(handler);
|
|
420
|
+
await adapter.start();
|
|
421
|
+
const bot = getMockBot();
|
|
422
|
+
await bot._triggerCallback(12345, 67890, 'q:abc:o:1', 777);
|
|
423
|
+
expect(handler).toHaveBeenCalledOnce();
|
|
424
|
+
const cb = handler.mock.calls[0][0];
|
|
425
|
+
expect(cb.channelType).toBe('telegram');
|
|
426
|
+
expect(cb.chatId).toBe('12345');
|
|
427
|
+
expect(cb.userId).toBe('67890');
|
|
428
|
+
expect(cb.messageId).toBe(777);
|
|
429
|
+
expect(cb.callbackData).toBe('q:abc:o:1');
|
|
430
|
+
expect(cb.callbackQueryId).toBe('cbq-test');
|
|
431
|
+
});
|
|
432
|
+
it('answers callbacks when no handler is registered', async ()=>{
|
|
433
|
+
await adapter.start();
|
|
434
|
+
const bot = getMockBot();
|
|
435
|
+
const ctx = await bot._triggerCallback(12345, 67890, 'q:x:o:0');
|
|
436
|
+
expect(ctx.answerCbQuery).toHaveBeenCalled();
|
|
437
|
+
});
|
|
438
|
+
it('answers with error when handler rejects', async ()=>{
|
|
439
|
+
adapter.onCallback(vi.fn().mockRejectedValue(new Error('boom')));
|
|
440
|
+
await adapter.start();
|
|
441
|
+
const bot = getMockBot();
|
|
442
|
+
const ctx = await bot._triggerCallback(12345, 67890, 'q:x:o:0');
|
|
443
|
+
expect(ctx.answerCbQuery).toHaveBeenCalledWith('Error');
|
|
444
|
+
});
|
|
445
|
+
});
|
|
243
446
|
describe('isHealthy', ()=>{
|
|
244
447
|
it('should return true after start', async ()=>{
|
|
245
448
|
await adapter.start();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/__tests__/adapters/TelegramAdapter.test.ts"],"sourcesContent":["import * as telegrafModule from 'telegraf';\nimport * as telegramHtml from '../../utils/telegramHtml.js';\nimport { TelegramAdapter } from '../../adapters/TelegramAdapter.js';\nimport type { IncomingMessage } from '../../types.js';\n\n// Mock telegraf\nvi.mock('telegraf', () => {\n const handlers: Record<string, (...args: any[]) => any> = {};\n const mockBot = {\n launch: vi.fn().mockResolvedValue(undefined),\n stop: vi.fn().mockResolvedValue(undefined),\n on: vi.fn((event: string, handler: (...args: any[]) => any) => {\n handlers[event] = handler;\n }),\n telegram: {\n sendMessage: vi.fn().mockResolvedValue(undefined),\n getMe: vi.fn().mockResolvedValue({ username: 'test_bot' }),\n },\n _handlers: handlers,\n _triggerText: async (chatId: number, userId: number, text: string) => {\n const ctx = {\n message: {\n chat: { id: chatId },\n from: { id: userId },\n text,\n date: Math.floor(Date.now() / 1000),\n },\n reply: vi.fn().mockResolvedValue(undefined),\n };\n if (handlers['text']) {\n await handlers['text'](ctx);\n }\n return ctx;\n },\n };\n return {\n Telegraf: vi.fn(function () { return mockBot; }),\n __mockBot: mockBot,\n };\n});\n\nfunction getMockBot() {\n return (telegrafModule as unknown as { __mockBot: ReturnType<typeof vi.fn>['mock'] & Record<string, unknown> }).__mockBot;\n}\n\ndescribe('TelegramAdapter', () => {\n let adapter: TelegramAdapter;\n\n beforeEach(() => {\n vi.clearAllMocks();\n adapter = new TelegramAdapter({ botToken: 'test-token-123' });\n });\n\n describe('type', () => {\n it('should return \"telegram\"', () => {\n expect(adapter.type).toBe('telegram');\n });\n });\n\n describe('start', () => {\n it('should launch the telegraf bot', async () => {\n const bot = getMockBot();\n await adapter.start();\n expect(bot.launch).toHaveBeenCalled();\n });\n });\n\n describe('stop', () => {\n it('should stop the telegraf bot', async () => {\n const bot = getMockBot();\n await adapter.start();\n await adapter.stop();\n expect(bot.stop).toHaveBeenCalled();\n });\n });\n\n describe('onMessage', () => {\n it('should silently ignore messages when no handler is registered', async () => {\n // Don't register a handler\n await adapter.start();\n\n const bot = getMockBot();\n const ctx = await bot._triggerText(12345, 67890, 'hello');\n\n // Should not throw or reply\n expect(ctx.reply).not.toHaveBeenCalled();\n });\n\n it('should handle non-Error thrown by handler', async () => {\n const handler = vi.fn().mockRejectedValue('string error');\n adapter.onMessage(handler);\n await adapter.start();\n\n const bot = getMockBot();\n const ctx = await bot._triggerText(12345, 67890, 'hello');\n\n expect(ctx.reply).toHaveBeenCalledWith(\n 'Error processing message: Unknown error'\n );\n });\n\n it('should call handler with IncomingMessage on incoming text', async () => {\n const handler = vi.fn().mockResolvedValue(undefined);\n adapter.onMessage(handler);\n await adapter.start();\n\n const bot = getMockBot();\n await bot._triggerText(12345, 67890, 'hello agent');\n\n expect(handler).toHaveBeenCalledTimes(1);\n const msg: IncomingMessage = handler.mock.calls[0][0];\n expect(msg.channelType).toBe('telegram');\n expect(msg.chatId).toBe('12345');\n expect(msg.userId).toBe('67890');\n expect(msg.text).toBe('hello agent');\n expect(msg.timestamp).toBeInstanceOf(Date);\n });\n\n it('should handle handler errors gracefully', async () => {\n const handler = vi.fn().mockRejectedValue(new Error('handler failed'));\n adapter.onMessage(handler);\n await adapter.start();\n\n const bot = getMockBot();\n const ctx = await bot._triggerText(12345, 67890, 'hello');\n\n // Should not throw, and should reply with error\n expect(ctx.reply).toHaveBeenCalledWith(\n expect.stringContaining('Error processing message')\n );\n });\n });\n\n describe('sendMessage', () => {\n it('should send plain text with parse_mode HTML', async () => {\n const bot = getMockBot();\n await adapter.sendMessage('12345', 'hello from bot');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledWith(\n '12345',\n 'hello from bot',\n { parse_mode: 'HTML' }\n );\n });\n\n it('should render markdown as Telegram HTML', async () => {\n const bot = getMockBot();\n await adapter.sendMessage('12345', '**bold** and *italic* and `code`');\n\n const sent = bot.telegram.sendMessage.mock.calls[0][1];\n expect(sent).toContain('<b>bold</b>');\n expect(sent).toContain('<i>italic</i>');\n expect(sent).toContain('<code>code</code>');\n expect(bot.telegram.sendMessage.mock.calls[0][2]).toEqual({\n parse_mode: 'HTML',\n });\n });\n\n it('should chunk messages exceeding 4096 chars', async () => {\n const bot = getMockBot();\n const line = 'A'.repeat(100) + '\\n';\n const longMessage = line.repeat(50); // 5050 chars\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);\n for (const call of bot.telegram.sendMessage.mock.calls) {\n expect(call[1].length).toBeLessThanOrEqual(4096);\n expect(call[2]).toEqual({ parse_mode: 'HTML' });\n }\n });\n\n it('should hard split at 4096 when no newlines available', async () => {\n const bot = getMockBot();\n const longMessage = 'A'.repeat(5000);\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBe(2);\n expect(bot.telegram.sendMessage.mock.calls[0][1].length).toBe(4096);\n expect(bot.telegram.sendMessage.mock.calls[1][1].length).toBe(904);\n });\n\n it('should prefer paragraph (\\\\n\\\\n) over single \\\\n when chunking', async () => {\n const bot = getMockBot();\n // 4 paragraphs of ~1500 chars each, total > 4096\n const paragraph = 'A'.repeat(1500);\n const message = `${paragraph}\\n\\n${paragraph}\\n\\n${paragraph}\\n\\n${paragraph}`;\n\n await adapter.sendMessage('12345', message);\n\n // First chunk should end at a \\n\\n boundary, not mid-paragraph\n const firstChunk = bot.telegram.sendMessage.mock.calls[0][1];\n expect(firstChunk.endsWith('\\n\\n')).toBe(true);\n });\n\n it('should send short messages in a single call', async () => {\n const bot = getMockBot();\n await adapter.sendMessage('12345', 'short message');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n });\n\n it('should retry as plain text when Telegram rejects HTML with parse-entities error', async () => {\n const bot = getMockBot();\n const parseError = Object.assign(new Error('400: Bad Request'), {\n description: \"Bad Request: can't parse entities: Unsupported start tag \\\"foo\\\"\",\n });\n bot.telegram.sendMessage\n .mockRejectedValueOnce(parseError)\n .mockResolvedValueOnce(undefined);\n\n await adapter.sendMessage('12345', '**hello**');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(2);\n\n // First call: rendered HTML with parse_mode\n const [, htmlChunk, htmlOpts] = bot.telegram.sendMessage.mock.calls[0];\n expect(htmlChunk).toContain('<b>hello</b>');\n expect(htmlOpts).toEqual({ parse_mode: 'HTML' });\n\n // Second call: same content, plain text (tags stripped, no parse_mode)\n const [, plainChunk, plainOpts] = bot.telegram.sendMessage.mock.calls[1];\n expect(plainChunk).toBe('hello');\n expect(plainOpts).toBeUndefined();\n });\n\n it('should detect parse-entities error from \"message\" field too', async () => {\n const bot = getMockBot();\n // Some error shapes carry the marker on `message` rather than `description`\n const parseError = new Error(\"can't parse entities\");\n bot.telegram.sendMessage\n .mockRejectedValueOnce(parseError)\n .mockResolvedValueOnce(undefined);\n\n await adapter.sendMessage('12345', '**hi**');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(2);\n });\n\n it('should decode HTML entities when falling back to plain text', async () => {\n const bot = getMockBot();\n const parseError = Object.assign(new Error('400'), {\n description: \"Bad Request: can't parse entities\",\n });\n bot.telegram.sendMessage\n .mockRejectedValueOnce(parseError)\n .mockResolvedValueOnce(undefined);\n\n // Source has chars that escapeHtml encodes; fallback should decode them\n await adapter.sendMessage('12345', 'a < b && c > d');\n\n const [, plainChunk] = bot.telegram.sendMessage.mock.calls[1];\n expect(plainChunk).toContain('a < b && c > d');\n expect(plainChunk).not.toContain('<');\n expect(plainChunk).not.toContain('&');\n });\n\n it('should deliver nested lists without throwing', async () => {\n const bot = getMockBot();\n\n await adapter.sendMessage('12345', '- agent\\n - Status');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n expect(bot.telegram.sendMessage.mock.calls[0][1]).toContain('Status');\n });\n\n it('should send plain text when markdown formatting throws', async () => {\n const bot = getMockBot();\n const formatter = vi.spyOn(telegramHtml, 'markdownToTelegramHtml')\n .mockImplementationOnce(() => {\n throw new Error('formatter failed');\n });\n\n await adapter.sendMessage('12345', '- agent\\n - Status');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n expect(bot.telegram.sendMessage.mock.calls[0][0]).toBe('12345');\n expect(bot.telegram.sendMessage.mock.calls[0][1]).toBe('- agent\\n - Status');\n expect(bot.telegram.sendMessage.mock.calls[0][2]).toBeUndefined();\n\n formatter.mockRestore();\n });\n\n it('should propagate non-parse-entities errors without falling back', async () => {\n const bot = getMockBot();\n const otherError = Object.assign(new Error('403'), {\n description: 'Forbidden: bot was blocked by the user',\n });\n bot.telegram.sendMessage.mockRejectedValueOnce(otherError);\n\n await expect(adapter.sendMessage('12345', 'hi')).rejects.toBe(otherError);\n\n // Only the HTML attempt should have happened โ no fallback retry\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n });\n });\n\n describe('isHealthy', () => {\n it('should return true after start', async () => {\n await adapter.start();\n expect(await adapter.isHealthy()).toBe(true);\n });\n\n it('should return false before start', async () => {\n expect(await adapter.isHealthy()).toBe(false);\n });\n\n it('should return false after stop', async () => {\n await adapter.start();\n await adapter.stop();\n expect(await adapter.isHealthy()).toBe(false);\n });\n });\n});\n"],"names":["telegrafModule","telegramHtml","TelegramAdapter","vi","mock","handlers","mockBot","launch","fn","mockResolvedValue","undefined","stop","on","event","handler","telegram","sendMessage","getMe","username","_handlers","_triggerText","chatId","userId","text","ctx","message","chat","id","from","date","Math","floor","Date","now","reply","Telegraf","__mockBot","getMockBot","describe","adapter","beforeEach","clearAllMocks","botToken","it","expect","type","toBe","bot","start","toHaveBeenCalled","not","mockRejectedValue","onMessage","toHaveBeenCalledWith","toHaveBeenCalledTimes","msg","calls","channelType","timestamp","toBeInstanceOf","Error","stringContaining","parse_mode","sent","toContain","toEqual","line","repeat","longMessage","length","toBeGreaterThan","call","toBeLessThanOrEqual","paragraph","firstChunk","endsWith","parseError","Object","assign","description","mockRejectedValueOnce","mockResolvedValueOnce","htmlChunk","htmlOpts","plainChunk","plainOpts","toBeUndefined","formatter","spyOn","mockImplementationOnce","mockRestore","otherError","rejects","isHealthy"],"mappings":"AAAA,YAAYA,oBAAoB,WAAW;AAC3C,YAAYC,kBAAkB,8BAA8B;AAC5D,SAASC,eAAe,QAAQ,oCAAoC;AAGpE,gBAAgB;AAChBC,GAAGC,IAAI,CAAC,YAAY;IAChB,MAAMC,WAAoD,CAAC;IAC3D,MAAMC,UAAU;QACZC,QAAQJ,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;QAClCC,MAAMR,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;QAChCE,IAAIT,GAAGK,EAAE,CAAC,CAACK,OAAeC;YACtBT,QAAQ,CAACQ,MAAM,GAAGC;QACtB;QACAC,UAAU;YACNC,aAAab,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;YACvCO,OAAOd,GAAGK,EAAE,GAAGC,iBAAiB,CAAC;gBAAES,UAAU;YAAW;QAC5D;QACAC,WAAWd;QACXe,cAAc,OAAOC,QAAgBC,QAAgBC;YACjD,MAAMC,MAAM;gBACRC,SAAS;oBACLC,MAAM;wBAAEC,IAAIN;oBAAO;oBACnBO,MAAM;wBAAED,IAAIL;oBAAO;oBACnBC;oBACAM,MAAMC,KAAKC,KAAK,CAACC,KAAKC,GAAG,KAAK;gBAClC;gBACAC,OAAO/B,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;YACrC;YACA,IAAIL,QAAQ,CAAC,OAAO,EAAE;gBA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ACnCC,OAAO,MAAML,QAAQsD,SAAS,IAAI/C,IAAI,CAAC;QAC3C;QAEAH,GAAG,kCAAkC;YACjC,MAAMJ,QAAQS,KAAK;YACnB,MAAMT,QAAQ5B,IAAI;YAClBiC,OAAO,MAAML,QAAQsD,SAAS,IAAI/C,IAAI,CAAC;QAC3C;IACJ;AACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../src/__tests__/adapters/TelegramAdapter.test.ts"],"sourcesContent":["import * as telegrafModule from 'telegraf';\nimport * as telegramHtml from '../../utils/telegramHtml.js';\nimport { TelegramAdapter } from '../../adapters/TelegramAdapter.js';\nimport type { IncomingMessage } from '../../types.js';\n\n// Mock telegraf\nvi.mock('telegraf', () => {\n const handlers: Record<string, (...args: any[]) => any> = {};\n const mockBot = {\n launch: vi.fn().mockResolvedValue(undefined),\n stop: vi.fn().mockResolvedValue(undefined),\n on: vi.fn((event: string, handler: (...args: any[]) => any) => {\n handlers[event] = handler;\n }),\n telegram: {\n sendMessage: vi.fn().mockResolvedValue(undefined),\n editMessageReplyMarkup: vi.fn().mockResolvedValue(undefined),\n answerCbQuery: vi.fn().mockResolvedValue(undefined),\n getMe: vi.fn().mockResolvedValue({ username: 'test_bot' }),\n },\n _handlers: handlers,\n _triggerText: async (chatId: number, userId: number, text: string) => {\n const ctx = {\n message: {\n chat: { id: chatId },\n from: { id: userId },\n text,\n date: Math.floor(Date.now() / 1000),\n },\n reply: vi.fn().mockResolvedValue(undefined),\n };\n if (handlers['text']) {\n await handlers['text'](ctx);\n }\n return ctx;\n },\n _triggerCallback: async (chatId: number, userId: number, data: string, messageId = 555) => {\n const ctx = {\n callbackQuery: {\n id: 'cbq-test',\n data,\n message: { message_id: messageId, chat: { id: chatId } },\n from: { id: userId },\n },\n answerCbQuery: vi.fn().mockResolvedValue(undefined),\n };\n if (handlers['callback_query']) {\n await handlers['callback_query'](ctx);\n }\n return ctx;\n },\n };\n return {\n Telegraf: vi.fn(function () { return mockBot; }),\n __mockBot: mockBot,\n };\n});\n\nfunction getMockBot() {\n return (telegrafModule as unknown as { __mockBot: ReturnType<typeof vi.fn>['mock'] & Record<string, unknown> }).__mockBot;\n}\n\nfunction expectHtmlChunkWithinLimit(chunk: string): void {\n expect(chunk.length).toBeLessThanOrEqual(4096);\n expect(chunk).not.toMatch(/&(?:l|lt|g|gt|a|am|amp|q|qu|quo|quot)$/);\n expect((chunk.match(/<pre>/g) ?? []).length).toBe((chunk.match(/<\\/pre>/g) ?? []).length);\n expect((chunk.match(/<code(?: class=\"language-[^\"]+\")?>/g) ?? []).length).toBe((chunk.match(/<\\/code>/g) ?? []).length);\n}\n\ndescribe('TelegramAdapter', () => {\n let adapter: TelegramAdapter;\n\n beforeEach(() => {\n vi.clearAllMocks();\n adapter = new TelegramAdapter({ botToken: 'test-token-123' });\n });\n\n describe('type', () => {\n it('should return \"telegram\"', () => {\n expect(adapter.type).toBe('telegram');\n });\n });\n\n describe('start', () => {\n it('should launch the telegraf bot', async () => {\n const bot = getMockBot();\n await adapter.start();\n expect(bot.launch).toHaveBeenCalled();\n });\n });\n\n describe('stop', () => {\n it('should stop the telegraf bot', async () => {\n const bot = getMockBot();\n await adapter.start();\n await adapter.stop();\n expect(bot.stop).toHaveBeenCalled();\n });\n });\n\n describe('onMessage', () => {\n it('should silently ignore messages when no handler is registered', async () => {\n // Don't register a handler\n await adapter.start();\n\n const bot = getMockBot();\n const ctx = await bot._triggerText(12345, 67890, 'hello');\n\n // Should not throw or reply\n expect(ctx.reply).not.toHaveBeenCalled();\n });\n\n it('should handle non-Error thrown by handler', async () => {\n const handler = vi.fn().mockRejectedValue('string error');\n adapter.onMessage(handler);\n await adapter.start();\n\n const bot = getMockBot();\n const ctx = await bot._triggerText(12345, 67890, 'hello');\n\n expect(ctx.reply).toHaveBeenCalledWith(\n 'Error processing message: Unknown error'\n );\n });\n\n it('should call handler with IncomingMessage on incoming text', async () => {\n const handler = vi.fn().mockResolvedValue(undefined);\n adapter.onMessage(handler);\n await adapter.start();\n\n const bot = getMockBot();\n await bot._triggerText(12345, 67890, 'hello agent');\n\n expect(handler).toHaveBeenCalledTimes(1);\n const msg: IncomingMessage = handler.mock.calls[0][0];\n expect(msg.channelType).toBe('telegram');\n expect(msg.chatId).toBe('12345');\n expect(msg.userId).toBe('67890');\n expect(msg.text).toBe('hello agent');\n expect(msg.timestamp).toBeInstanceOf(Date);\n });\n\n it('should handle handler errors gracefully', async () => {\n const handler = vi.fn().mockRejectedValue(new Error('handler failed'));\n adapter.onMessage(handler);\n await adapter.start();\n\n const bot = getMockBot();\n const ctx = await bot._triggerText(12345, 67890, 'hello');\n\n // Should not throw, and should reply with error\n expect(ctx.reply).toHaveBeenCalledWith(\n expect.stringContaining('Error processing message')\n );\n });\n });\n\n describe('sendMessage', () => {\n it('should send plain text with parse_mode HTML', async () => {\n const bot = getMockBot();\n await adapter.sendMessage('12345', 'hello from bot');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledWith(\n '12345',\n 'hello from bot',\n { parse_mode: 'HTML' }\n );\n });\n\n it('should render markdown as Telegram HTML', async () => {\n const bot = getMockBot();\n await adapter.sendMessage('12345', '**bold** and *italic* and `code`');\n\n const sent = bot.telegram.sendMessage.mock.calls[0][1];\n expect(sent).toContain('<b>bold</b>');\n expect(sent).toContain('<i>italic</i>');\n expect(sent).toContain('<code>code</code>');\n expect(bot.telegram.sendMessage.mock.calls[0][2]).toEqual({\n parse_mode: 'HTML',\n });\n });\n\n it('should chunk messages exceeding 4096 chars', async () => {\n const bot = getMockBot();\n const line = 'A'.repeat(100) + '\\n';\n const longMessage = line.repeat(50); // 5050 chars\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);\n for (const call of bot.telegram.sendMessage.mock.calls) {\n expect(call[1].length).toBeLessThanOrEqual(4096);\n expect(call[2]).toEqual({ parse_mode: 'HTML' });\n }\n });\n\n it('should split long fenced code into independently valid HTML code blocks', async () => {\n const bot = getMockBot();\n const codeLine = 'const sample = \"<code>tag</code>\" && value < limit;\\n';\n const longMessage = `Before\\n\\n\\`\\`\\`ts\\n${codeLine.repeat(100)}\\`\\`\\`\\n\\nAfter`;\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);\n for (const call of bot.telegram.sendMessage.mock.calls) {\n const chunk = call[1];\n expect(call[2]).toEqual({ parse_mode: 'HTML' });\n expectHtmlChunkWithinLimit(chunk);\n if (chunk.includes('<pre>')) {\n expect(chunk).toContain('<code class=\"language-ts\">');\n expect(chunk).toContain('<code>tag</code>');\n }\n }\n });\n\n it('should split nested list fenced code without sending partial HTML tags', async () => {\n const bot = getMockBot();\n const codeLine = ' return \"<code>tag</code>\" && input < output;\\n';\n const longMessage = [\n '- parent item',\n ' - child item with code',\n ' ```js',\n codeLine.repeat(100).trimEnd(),\n ' ```',\n '- final item',\n ].join('\\n');\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);\n for (const call of bot.telegram.sendMessage.mock.calls) {\n const chunk = call[1];\n expect(call[2]).toEqual({ parse_mode: 'HTML' });\n expectHtmlChunkWithinLimit(chunk);\n }\n });\n\n it('should split long paragraphs at readable markdown boundaries', async () => {\n const bot = getMockBot();\n const sentence = 'This is a long sentence with enough words to make chunking choose sentence boundaries. ';\n const longMessage = sentence.repeat(80);\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);\n for (const call of bot.telegram.sendMessage.mock.calls) {\n const chunk = call[1];\n expect(call[2]).toEqual({ parse_mode: 'HTML' });\n expectHtmlChunkWithinLimit(chunk);\n expect(chunk.endsWith('.') || chunk.endsWith('.\\n\\n') || chunk.endsWith(' ')).toBe(true);\n }\n });\n\n it('should keep emoji chunks within the configured JavaScript string length limit', async () => {\n const bot = getMockBot();\n const longMessage = `Status ${'๐งช'.repeat(2500)}`;\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBeGreaterThan(1);\n for (const call of bot.telegram.sendMessage.mock.calls) {\n expect(call[1].length).toBeLessThanOrEqual(4096);\n expect(call[2]).toEqual({ parse_mode: 'HTML' });\n }\n });\n\n it('should hard split at 4096 when no newlines available', async () => {\n const bot = getMockBot();\n const longMessage = 'A'.repeat(5000);\n\n await adapter.sendMessage('12345', longMessage);\n\n expect(bot.telegram.sendMessage.mock.calls.length).toBe(2);\n expect(bot.telegram.sendMessage.mock.calls[0][1].length).toBe(4096);\n expect(bot.telegram.sendMessage.mock.calls[1][1].length).toBe(904);\n });\n\n it('should prefer paragraph (\\\\n\\\\n) over single \\\\n when chunking', async () => {\n const bot = getMockBot();\n // 4 paragraphs of ~1500 chars each, total > 4096\n const paragraph = 'A'.repeat(1500);\n const message = `${paragraph}\\n\\n${paragraph}\\n\\n${paragraph}\\n\\n${paragraph}`;\n\n await adapter.sendMessage('12345', message);\n\n // First chunk should end at a \\n\\n boundary, not mid-paragraph\n const firstChunk = bot.telegram.sendMessage.mock.calls[0][1];\n expect(firstChunk).toBe(`${paragraph}\\n\\n${paragraph}`);\n });\n\n it('should send short messages in a single call', async () => {\n const bot = getMockBot();\n await adapter.sendMessage('12345', 'short message');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n });\n\n it('should retry as plain text when Telegram rejects HTML with parse-entities error', async () => {\n const bot = getMockBot();\n const parseError = Object.assign(new Error('400: Bad Request'), {\n description: \"Bad Request: can't parse entities: Unsupported start tag \\\"foo\\\"\",\n });\n bot.telegram.sendMessage\n .mockRejectedValueOnce(parseError)\n .mockResolvedValueOnce(undefined);\n\n await adapter.sendMessage('12345', '**hello**');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(2);\n\n // First call: rendered HTML with parse_mode\n const [, htmlChunk, htmlOpts] = bot.telegram.sendMessage.mock.calls[0];\n expect(htmlChunk).toContain('<b>hello</b>');\n expect(htmlOpts).toEqual({ parse_mode: 'HTML' });\n\n // Second call: same content, plain text (tags stripped, no parse_mode)\n const [, plainChunk, plainOpts] = bot.telegram.sendMessage.mock.calls[1];\n expect(plainChunk).toBe('hello');\n expect(plainOpts).toBeUndefined();\n });\n\n it('should detect parse-entities error from \"message\" field too', async () => {\n const bot = getMockBot();\n // Some error shapes carry the marker on `message` rather than `description`\n const parseError = new Error(\"can't parse entities\");\n bot.telegram.sendMessage\n .mockRejectedValueOnce(parseError)\n .mockResolvedValueOnce(undefined);\n\n await adapter.sendMessage('12345', '**hi**');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(2);\n });\n\n it('should decode HTML entities when falling back to plain text', async () => {\n const bot = getMockBot();\n const parseError = Object.assign(new Error('400'), {\n description: \"Bad Request: can't parse entities\",\n });\n bot.telegram.sendMessage\n .mockRejectedValueOnce(parseError)\n .mockResolvedValueOnce(undefined);\n\n // Source has chars that escapeHtml encodes; fallback should decode them\n await adapter.sendMessage('12345', 'a < b && c > d');\n\n const [, plainChunk] = bot.telegram.sendMessage.mock.calls[1];\n expect(plainChunk).toContain('a < b && c > d');\n expect(plainChunk).not.toContain('<');\n expect(plainChunk).not.toContain('&');\n });\n\n it('should deliver nested lists without throwing', async () => {\n const bot = getMockBot();\n\n await adapter.sendMessage('12345', '- agent\\n - Status');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n expect(bot.telegram.sendMessage.mock.calls[0][1]).toContain('Status');\n });\n\n it('should send plain text when markdown formatting throws', async () => {\n const bot = getMockBot();\n const formatter = vi.spyOn(telegramHtml, 'markdownToTelegramHtml')\n .mockImplementationOnce(() => {\n throw new Error('formatter failed');\n });\n\n await adapter.sendMessage('12345', '- agent\\n - Status');\n\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n expect(bot.telegram.sendMessage.mock.calls[0][0]).toBe('12345');\n expect(bot.telegram.sendMessage.mock.calls[0][1]).toBe('- agent\\n - Status');\n expect(bot.telegram.sendMessage.mock.calls[0][2]).toBeUndefined();\n\n formatter.mockRestore();\n });\n\n it('should propagate non-parse-entities errors without falling back', async () => {\n const bot = getMockBot();\n const otherError = Object.assign(new Error('403'), {\n description: 'Forbidden: bot was blocked by the user',\n });\n bot.telegram.sendMessage.mockRejectedValueOnce(otherError);\n\n await expect(adapter.sendMessage('12345', 'hi')).rejects.toBe(otherError);\n\n // Only the HTML attempt should have happened โ no fallback retry\n expect(bot.telegram.sendMessage).toHaveBeenCalledTimes(1);\n });\n });\n\n describe('sendInlineKeyboard', () => {\n it('sends with parse_mode HTML and inline_keyboard payload, returns message_id', async () => {\n const bot = getMockBot();\n (bot.telegram.sendMessage as any).mockResolvedValueOnce({ message_id: 42 });\n\n const id = await adapter.sendInlineKeyboard('12345', '<b>hi</b>', [\n [{ text: 'A', callbackData: 'q:1:o:0' }],\n [{ text: 'B', callbackData: 'q:1:o:1' }],\n ]);\n\n expect(id).toBe(42);\n expect(bot.telegram.sendMessage).toHaveBeenCalledWith('12345', '<b>hi</b>', {\n parse_mode: 'HTML',\n reply_markup: {\n inline_keyboard: [\n [{ text: 'A', callback_data: 'q:1:o:0' }],\n [{ text: 'B', callback_data: 'q:1:o:1' }],\n ],\n },\n });\n });\n });\n\n describe('editInlineKeyboard', () => {\n it('replaces the keyboard on an existing message', async () => {\n const bot = getMockBot();\n await adapter.editInlineKeyboard('12345', 99, [[{ text: 'โ A', callbackData: 'q:1:o:0' }]]);\n expect(bot.telegram.editMessageReplyMarkup).toHaveBeenCalledWith('12345', 99, undefined, {\n inline_keyboard: [[{ text: 'โ A', callback_data: 'q:1:o:0' }]],\n });\n });\n\n it('passes undefined reply_markup to remove the keyboard', async () => {\n const bot = getMockBot();\n await adapter.editInlineKeyboard('12345', 99, null);\n expect(bot.telegram.editMessageReplyMarkup).toHaveBeenCalledWith('12345', 99, undefined, undefined);\n });\n });\n\n describe('answerCallback', () => {\n it('forwards id and optional text to telegraf', async () => {\n const bot = getMockBot();\n await adapter.answerCallback('cbq-1', 'thanks');\n expect(bot.telegram.answerCbQuery).toHaveBeenCalledWith('cbq-1', 'thanks');\n });\n });\n\n describe('onCallback', () => {\n it('invokes the registered handler with a normalized IncomingCallback', async () => {\n const handler = vi.fn().mockResolvedValue(undefined);\n adapter.onCallback(handler);\n await adapter.start();\n\n const bot = getMockBot();\n await (bot as any)._triggerCallback(12345, 67890, 'q:abc:o:1', 777);\n\n expect(handler).toHaveBeenCalledOnce();\n const cb = handler.mock.calls[0][0];\n expect(cb.channelType).toBe('telegram');\n expect(cb.chatId).toBe('12345');\n expect(cb.userId).toBe('67890');\n expect(cb.messageId).toBe(777);\n expect(cb.callbackData).toBe('q:abc:o:1');\n expect(cb.callbackQueryId).toBe('cbq-test');\n });\n\n it('answers callbacks when no handler is registered', async () => {\n await adapter.start();\n const bot = getMockBot();\n const ctx = await (bot as any)._triggerCallback(12345, 67890, 'q:x:o:0');\n expect(ctx.answerCbQuery).toHaveBeenCalled();\n });\n\n it('answers with error when handler rejects', async () => {\n adapter.onCallback(vi.fn().mockRejectedValue(new Error('boom')));\n await adapter.start();\n const bot = getMockBot();\n const ctx = await (bot as any)._triggerCallback(12345, 67890, 'q:x:o:0');\n expect(ctx.answerCbQuery).toHaveBeenCalledWith('Error');\n });\n });\n\n describe('isHealthy', () => {\n it('should return true after start', async () => {\n await adapter.start();\n expect(await adapter.isHealthy()).toBe(true);\n });\n\n it('should return false before start', async () => {\n expect(await adapter.isHealthy()).toBe(false);\n });\n\n it('should return false after stop', async () => {\n await adapter.start();\n await adapter.stop();\n expect(await adapter.isHealthy()).toBe(false);\n });\n });\n});\n"],"names":["telegrafModule","telegramHtml","TelegramAdapter","vi","mock","handlers","mockBot","launch","fn","mockResolvedValue","undefined","stop","on","event","handler","telegram","sendMessage","editMessageReplyMarkup","answerCbQuery","getMe","username","_handlers","_triggerText","chatId","userId","text","ctx","message","chat","id","from","date","Math","floor","Date","now","reply","_triggerCallback","data","messageId","callbackQuery","message_id","Telegraf","__mockBot","getMockBot","expectHtmlChunkWithinLimit","chunk","expect","length","toBeLessThanOrEqual","not","toMatch","match","toBe","describe","adapter","beforeEach","clearAllMocks","botToken","it","type","bot","start","toHaveBeenCalled","mockRejectedValue","onMessage","toHaveBeenCalledWith","toHaveBeenCalledTimes","msg","calls","channelType","timestamp","toBeInstanceOf","Error","stringContaining","parse_mode","sent","toContain","toEqual","line","repeat","longMessage","toBeGreaterThan","call","codeLine","includes","trimEnd","join","sentence","endsWith","paragraph","firstChunk","parseError","Object","assign","description","mockRejectedValueOnce","mockResolvedValueOnce","htmlChunk","htmlOpts","plainChunk","plainOpts","toBeUndefined","formatter","spyOn","mockImplementationOnce","mockRestore","otherError","rejects","sendInlineKeyboard","callbackData","reply_markup","inline_keyboard","callback_data","editInlineKeyboard","answerCallback","onCallback","toHaveBeenCalledOnce","cb","callbackQueryId","isHealthy"],"mappings":"AAAA,YAAYA,oBAAoB,WAAW;AAC3C,YAAYC,kBAAkB,8BAA8B;AAC5D,SAASC,eAAe,QAAQ,oCAAoC;AAGpE,gBAAgB;AAChBC,GAAGC,IAAI,CAAC,YAAY;IAChB,MAAMC,WAAoD,CAAC;IAC3D,MAAMC,UAAU;QACZC,QAAQJ,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;QAClCC,MAAMR,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;QAChCE,IAAIT,GAAGK,EAAE,CAAC,CAACK,OAAeC;YACtBT,QAAQ,CAACQ,MAAM,GAAGC;QACtB;QACAC,UAAU;YACNC,aAAab,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;YACvCO,wBAAwBd,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;YAClDQ,eAAef,GAAGK,EAAE,GAAGC,iBAAiB,CAACC;YACzCS,OAAOhB,GAAGK,EAAE,GAAGC,iBAAiB,CAAC;gBAAEW,UAAU;YAAW;QAC5D;QACAC,WAAWhB;QACXiB,cAAc,OAAOC,QAAgBC,QAAgBC;YACjD,MAAMC,MAAM;gBACRC,SAAS;oBACLC,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,QAAQiE,SAAS,IAAInE,IAAI,CAAC;QAC3C;IACJ;AACJ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChannelAdapter } from './ChannelAdapter.js';
|
|
2
|
-
import type { IncomingMessage } from '../types.js';
|
|
2
|
+
import type { IncomingMessage, InlineKeyboard, CallbackHandler } from '../types.js';
|
|
3
3
|
export declare const TELEGRAM_CHANNEL_TYPE = "telegram";
|
|
4
4
|
export declare const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;
|
|
5
5
|
export interface TelegramAdapterOptions {
|
|
@@ -12,18 +12,35 @@ export declare class TelegramAdapter implements ChannelAdapter {
|
|
|
12
12
|
readonly type = "telegram";
|
|
13
13
|
private bot;
|
|
14
14
|
private messageHandler;
|
|
15
|
+
private callbackHandler;
|
|
15
16
|
private running;
|
|
16
17
|
constructor(options: TelegramAdapterOptions);
|
|
17
18
|
start(): Promise<void>;
|
|
18
19
|
stop(): Promise<void>;
|
|
19
20
|
/**
|
|
20
21
|
* Input is treated as markdown and rendered as Telegram-compatible HTML.
|
|
21
|
-
* Long messages are chunked
|
|
22
|
-
*
|
|
23
|
-
* mid-tag and produce a partial render in the second chunk.
|
|
22
|
+
* Long messages are chunked as markdown source before rendering so each
|
|
23
|
+
* Telegram HTML payload is independently valid.
|
|
24
24
|
*/
|
|
25
25
|
sendMessage(chatId: string, text: string): Promise<void>;
|
|
26
26
|
onMessage(handler: (msg: IncomingMessage) => Promise<void>): void;
|
|
27
|
+
onCallback(handler: CallbackHandler): void;
|
|
28
|
+
/**
|
|
29
|
+
* Send a message with an inline keyboard. `html` is sent verbatim with
|
|
30
|
+
* parse_mode=HTML โ callers must pre-escape any user-controlled fields.
|
|
31
|
+
* Returns the Telegram message_id of the sent message.
|
|
32
|
+
*/
|
|
33
|
+
sendInlineKeyboard(chatId: string, html: string, keyboard: InlineKeyboard): Promise<number>;
|
|
34
|
+
/**
|
|
35
|
+
* Replace the inline keyboard on an existing message. Pass `null` to remove
|
|
36
|
+
* the keyboard entirely.
|
|
37
|
+
*/
|
|
38
|
+
editInlineKeyboard(chatId: string, messageId: number, keyboard: InlineKeyboard | null): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Acknowledge a callback_query. Without this Telegram leaves a spinner on
|
|
41
|
+
* the tapped button. Pass `text` to show a transient toast.
|
|
42
|
+
*/
|
|
43
|
+
answerCallback(callbackQueryId: string, text?: string): Promise<void>;
|
|
27
44
|
isHealthy(): Promise<boolean>;
|
|
28
45
|
}
|
|
29
46
|
//# sourceMappingURL=TelegramAdapter.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TelegramAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/TelegramAdapter.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"TelegramAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/TelegramAdapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAoB,eAAe,EAAE,MAAM,aAAa,CAAC;AAEtG,eAAO,MAAM,qBAAqB,aAAa,CAAC;AAChD,eAAO,MAAM,2BAA2B,OAAO,CAAC;AAShD,MAAM,WAAW,sBAAsB;IACnC,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,qBAAa,eAAgB,YAAW,cAAc;IAClD,QAAQ,CAAC,IAAI,cAAyB;IAEtC,OAAO,CAAC,GAAG,CAAW;IACtB,OAAO,CAAC,cAAc,CAA0D;IAChF,OAAO,CAAC,eAAe,CAAgC;IACvD,OAAO,CAAC,OAAO,CAAS;gBAEZ,OAAO,EAAE,sBAAsB;IAIrC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA4DtB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAK3B;;;;OAIG;IACG,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA4B9D,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;IAIjE,UAAU,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;IAI1C;;;;OAIG;IACG,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAQjG;;;OAGG;IACG,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAM3G;;;OAGG;IACG,cAAc,CAAC,eAAe,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrE,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC;CAGtC"}
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { Telegraf } from 'telegraf';
|
|
2
|
+
import { Marked } from 'marked';
|
|
2
3
|
import { markdownToTelegramHtml } from '../utils/telegramHtml.js';
|
|
3
4
|
export const TELEGRAM_CHANNEL_TYPE = 'telegram';
|
|
4
5
|
export const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;
|
|
5
6
|
const TELEGRAM_PARSE_MODE = 'HTML';
|
|
7
|
+
const markdownLexer = new Marked();
|
|
6
8
|
/**
|
|
7
9
|
* Telegram Bot API adapter using telegraf with long polling.
|
|
8
10
|
*/ export class TelegramAdapter {
|
|
9
11
|
type = TELEGRAM_CHANNEL_TYPE;
|
|
10
12
|
bot;
|
|
11
13
|
messageHandler = null;
|
|
14
|
+
callbackHandler = null;
|
|
12
15
|
running = false;
|
|
13
16
|
constructor(options){
|
|
14
17
|
this.bot = new Telegraf(options.botToken);
|
|
@@ -30,6 +33,38 @@ const TELEGRAM_PARSE_MODE = 'HTML';
|
|
|
30
33
|
await ctx.reply(`Error processing message: ${errorMessage}`);
|
|
31
34
|
}
|
|
32
35
|
});
|
|
36
|
+
this.bot.on('callback_query', async (ctx)=>{
|
|
37
|
+
if (!this.callbackHandler) {
|
|
38
|
+
try {
|
|
39
|
+
await ctx.answerCbQuery();
|
|
40
|
+
} catch {}
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const query = ctx.callbackQuery;
|
|
44
|
+
const data = typeof query.data === 'string' ? query.data : '';
|
|
45
|
+
if (!query.message) {
|
|
46
|
+
try {
|
|
47
|
+
await ctx.answerCbQuery();
|
|
48
|
+
} catch {}
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const cb = {
|
|
52
|
+
channelType: TELEGRAM_CHANNEL_TYPE,
|
|
53
|
+
chatId: String(query.message.chat.id),
|
|
54
|
+
userId: String(query.from.id),
|
|
55
|
+
messageId: query.message.message_id,
|
|
56
|
+
callbackData: data,
|
|
57
|
+
callbackQueryId: query.id,
|
|
58
|
+
timestamp: new Date()
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
await this.callbackHandler(cb);
|
|
62
|
+
} catch {
|
|
63
|
+
try {
|
|
64
|
+
await ctx.answerCbQuery('Error');
|
|
65
|
+
} catch {}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
33
68
|
await this.bot.launch();
|
|
34
69
|
this.running = true;
|
|
35
70
|
}
|
|
@@ -39,39 +74,78 @@ const TELEGRAM_PARSE_MODE = 'HTML';
|
|
|
39
74
|
}
|
|
40
75
|
/**
|
|
41
76
|
* Input is treated as markdown and rendered as Telegram-compatible HTML.
|
|
42
|
-
* Long messages are chunked
|
|
43
|
-
*
|
|
44
|
-
* mid-tag and produce a partial render in the second chunk.
|
|
77
|
+
* Long messages are chunked as markdown source before rendering so each
|
|
78
|
+
* Telegram HTML payload is independently valid.
|
|
45
79
|
*/ async sendMessage(chatId, text) {
|
|
46
|
-
let
|
|
80
|
+
let chunks;
|
|
47
81
|
try {
|
|
48
|
-
|
|
82
|
+
chunks = chunkMarkdownForTelegram(text, TELEGRAM_MAX_MESSAGE_LENGTH);
|
|
49
83
|
} catch {
|
|
50
84
|
for (const chunk of chunkMessage(text, TELEGRAM_MAX_MESSAGE_LENGTH)){
|
|
51
85
|
await this.bot.telegram.sendMessage(chatId, chunk);
|
|
52
86
|
}
|
|
53
87
|
return;
|
|
54
88
|
}
|
|
55
|
-
for (const chunk of
|
|
89
|
+
for (const chunk of chunks){
|
|
90
|
+
if (!chunk.html) {
|
|
91
|
+
await this.bot.telegram.sendMessage(chatId, chunk.text);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
56
94
|
try {
|
|
57
|
-
await this.bot.telegram.sendMessage(chatId, chunk, {
|
|
95
|
+
await this.bot.telegram.sendMessage(chatId, chunk.text, {
|
|
58
96
|
parse_mode: TELEGRAM_PARSE_MODE
|
|
59
97
|
});
|
|
60
98
|
} catch (error) {
|
|
61
99
|
if (!isParseEntitiesError(error)) throw error;
|
|
62
100
|
// Telegram rejected the rendered HTML โ fall back to plain text
|
|
63
101
|
// so the user still gets the content (just unformatted).
|
|
64
|
-
await this.bot.telegram.sendMessage(chatId, htmlToPlainText(chunk));
|
|
102
|
+
await this.bot.telegram.sendMessage(chatId, htmlToPlainText(chunk.text));
|
|
65
103
|
}
|
|
66
104
|
}
|
|
67
105
|
}
|
|
68
106
|
onMessage(handler) {
|
|
69
107
|
this.messageHandler = handler;
|
|
70
108
|
}
|
|
109
|
+
onCallback(handler) {
|
|
110
|
+
this.callbackHandler = handler;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Send a message with an inline keyboard. `html` is sent verbatim with
|
|
114
|
+
* parse_mode=HTML โ callers must pre-escape any user-controlled fields.
|
|
115
|
+
* Returns the Telegram message_id of the sent message.
|
|
116
|
+
*/ async sendInlineKeyboard(chatId, html, keyboard) {
|
|
117
|
+
const result = await this.bot.telegram.sendMessage(chatId, html, {
|
|
118
|
+
parse_mode: TELEGRAM_PARSE_MODE,
|
|
119
|
+
reply_markup: {
|
|
120
|
+
inline_keyboard: toTelegrafKeyboard(keyboard)
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
return result.message_id;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Replace the inline keyboard on an existing message. Pass `null` to remove
|
|
127
|
+
* the keyboard entirely.
|
|
128
|
+
*/ async editInlineKeyboard(chatId, messageId, keyboard) {
|
|
129
|
+
await this.bot.telegram.editMessageReplyMarkup(chatId, messageId, undefined, keyboard ? {
|
|
130
|
+
inline_keyboard: toTelegrafKeyboard(keyboard)
|
|
131
|
+
} : undefined);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Acknowledge a callback_query. Without this Telegram leaves a spinner on
|
|
135
|
+
* the tapped button. Pass `text` to show a transient toast.
|
|
136
|
+
*/ async answerCallback(callbackQueryId, text) {
|
|
137
|
+
await this.bot.telegram.answerCbQuery(callbackQueryId, text);
|
|
138
|
+
}
|
|
71
139
|
async isHealthy() {
|
|
72
140
|
return this.running;
|
|
73
141
|
}
|
|
74
142
|
}
|
|
143
|
+
function toTelegrafKeyboard(keyboard) {
|
|
144
|
+
return keyboard.map((row)=>row.map((btn)=>({
|
|
145
|
+
text: btn.text,
|
|
146
|
+
callback_data: btn.callbackData
|
|
147
|
+
})));
|
|
148
|
+
}
|
|
75
149
|
function isParseEntitiesError(error) {
|
|
76
150
|
if (!error || typeof error !== 'object') return false;
|
|
77
151
|
const description = error.description;
|
|
@@ -81,6 +155,224 @@ function isParseEntitiesError(error) {
|
|
|
81
155
|
function htmlToPlainText(html) {
|
|
82
156
|
return html.replace(/<[^>]+>/g, '').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
|
|
83
157
|
}
|
|
158
|
+
function chunkMarkdownForTelegram(markdown, maxLen) {
|
|
159
|
+
const markdownChunks = splitMarkdownSource(markdown, maxLen);
|
|
160
|
+
const chunks = [];
|
|
161
|
+
for (const markdownChunk of markdownChunks){
|
|
162
|
+
const html = markdownToTelegramHtml(markdownChunk);
|
|
163
|
+
if (html.length <= maxLen) {
|
|
164
|
+
if (html.length > 0) chunks.push({
|
|
165
|
+
text: html,
|
|
166
|
+
html: true
|
|
167
|
+
});
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
for (const plainChunk of chunkMessage(markdownChunk, maxLen)){
|
|
171
|
+
if (plainChunk.length > 0) chunks.push({
|
|
172
|
+
text: plainChunk,
|
|
173
|
+
html: false
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return chunks;
|
|
178
|
+
}
|
|
179
|
+
function splitMarkdownSource(markdown, maxLen, depth = 0) {
|
|
180
|
+
if (markdown.length === 0) return [];
|
|
181
|
+
if (renderedLengthFits(markdown, maxLen)) return [
|
|
182
|
+
markdown
|
|
183
|
+
];
|
|
184
|
+
if (depth > 6) return splitPlainMarkdownText(markdown, maxLen);
|
|
185
|
+
const chunks = [];
|
|
186
|
+
let current = '';
|
|
187
|
+
const tokens = markdownLexer.lexer(markdown);
|
|
188
|
+
for (const token of tokens){
|
|
189
|
+
const raw = token.raw ?? '';
|
|
190
|
+
if (raw.length === 0) continue;
|
|
191
|
+
const candidate = current + raw;
|
|
192
|
+
if (candidate.length > 0 && renderedLengthFits(candidate, maxLen)) {
|
|
193
|
+
current = candidate;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (current.length > 0) {
|
|
197
|
+
chunks.push(current);
|
|
198
|
+
current = '';
|
|
199
|
+
}
|
|
200
|
+
if (renderedLengthFits(raw, maxLen)) {
|
|
201
|
+
current = raw;
|
|
202
|
+
} else {
|
|
203
|
+
chunks.push(...splitOversizedToken(token, maxLen, depth + 1));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (current.length > 0) chunks.push(current);
|
|
207
|
+
return chunks.flatMap((chunk)=>renderedLengthFits(chunk, maxLen) ? [
|
|
208
|
+
chunk
|
|
209
|
+
] : splitPlainMarkdownText(chunk, maxLen));
|
|
210
|
+
}
|
|
211
|
+
function splitOversizedToken(token, maxLen, depth) {
|
|
212
|
+
switch(token.type){
|
|
213
|
+
case 'code':
|
|
214
|
+
return splitCodeToken(token, maxLen);
|
|
215
|
+
case 'list':
|
|
216
|
+
return splitListToken(token, maxLen, depth);
|
|
217
|
+
case 'paragraph':
|
|
218
|
+
case 'text':
|
|
219
|
+
return splitPlainMarkdownText(token.raw, maxLen);
|
|
220
|
+
default:
|
|
221
|
+
if ('tokens' in token && Array.isArray(token.tokens) && token.raw !== undefined) {
|
|
222
|
+
return splitMarkdownSource(token.raw, maxLen, depth);
|
|
223
|
+
}
|
|
224
|
+
return splitPlainMarkdownText(token.raw ?? '', maxLen);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function splitListToken(token, maxLen, depth) {
|
|
228
|
+
const chunks = [];
|
|
229
|
+
let current = '';
|
|
230
|
+
for (const item of token.items){
|
|
231
|
+
const raw = item.raw;
|
|
232
|
+
const candidate = current + raw;
|
|
233
|
+
if (candidate.length > 0 && renderedLengthFits(candidate, maxLen)) {
|
|
234
|
+
current = candidate;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (current.length > 0) {
|
|
238
|
+
chunks.push(current);
|
|
239
|
+
current = '';
|
|
240
|
+
}
|
|
241
|
+
if (renderedLengthFits(raw, maxLen)) {
|
|
242
|
+
current = raw;
|
|
243
|
+
} else {
|
|
244
|
+
chunks.push(...splitMarkdownSource(raw, maxLen, depth + 1));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (current.length > 0) chunks.push(current);
|
|
248
|
+
return chunks;
|
|
249
|
+
}
|
|
250
|
+
function splitCodeToken(token, maxLen) {
|
|
251
|
+
const fence = token.raw.startsWith('~~~') ? '~~~' : '```';
|
|
252
|
+
const lang = token.lang ? token.lang.split(/\s/)[0] : '';
|
|
253
|
+
const lines = token.text.split('\n');
|
|
254
|
+
const chunks = [];
|
|
255
|
+
let currentLines = [];
|
|
256
|
+
const renderFence = (codeLines)=>`${fence}${lang}\n${codeLines.join('\n')}\n${fence}\n\n`;
|
|
257
|
+
for (const line of lines){
|
|
258
|
+
const candidateLines = [
|
|
259
|
+
...currentLines,
|
|
260
|
+
line
|
|
261
|
+
];
|
|
262
|
+
if (renderedLengthFits(renderFence(candidateLines), maxLen)) {
|
|
263
|
+
currentLines = candidateLines;
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (currentLines.length > 0) {
|
|
267
|
+
chunks.push(renderFence(currentLines));
|
|
268
|
+
currentLines = [];
|
|
269
|
+
}
|
|
270
|
+
if (renderedLengthFits(renderFence([
|
|
271
|
+
line
|
|
272
|
+
]), maxLen)) {
|
|
273
|
+
currentLines = [
|
|
274
|
+
line
|
|
275
|
+
];
|
|
276
|
+
} else {
|
|
277
|
+
for (const segment of splitCodeLine(line, fence, lang, maxLen)){
|
|
278
|
+
chunks.push(renderFence([
|
|
279
|
+
segment
|
|
280
|
+
]));
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (currentLines.length > 0) chunks.push(renderFence(currentLines));
|
|
285
|
+
return chunks;
|
|
286
|
+
}
|
|
287
|
+
function splitCodeLine(line, fence, lang, maxLen) {
|
|
288
|
+
const segments = [];
|
|
289
|
+
let current = '';
|
|
290
|
+
const renderFence = (value)=>`${fence}${lang}\n${value}\n${fence}\n\n`;
|
|
291
|
+
for (const char of Array.from(line)){
|
|
292
|
+
const candidate = current + char;
|
|
293
|
+
if (renderedLengthFits(renderFence(candidate), maxLen)) {
|
|
294
|
+
current = candidate;
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (current.length > 0) {
|
|
298
|
+
segments.push(current);
|
|
299
|
+
current = '';
|
|
300
|
+
}
|
|
301
|
+
if (renderedLengthFits(renderFence(char), maxLen)) {
|
|
302
|
+
current = char;
|
|
303
|
+
} else {
|
|
304
|
+
segments.push(char);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (current.length > 0) segments.push(current);
|
|
308
|
+
return segments;
|
|
309
|
+
}
|
|
310
|
+
function splitPlainMarkdownText(markdown, maxLen) {
|
|
311
|
+
if (markdown.length === 0) return [];
|
|
312
|
+
if (renderedLengthFits(markdown, maxLen)) return [
|
|
313
|
+
markdown
|
|
314
|
+
];
|
|
315
|
+
const newlineUnits = markdown.split(/(?<=\n)/u);
|
|
316
|
+
if (newlineUnits.length > 1) {
|
|
317
|
+
return packMarkdownUnits(newlineUnits, maxLen, splitPlainMarkdownText);
|
|
318
|
+
}
|
|
319
|
+
const sentenceUnits = markdown.match(/[^.!?]+[.!?]+(?:\s+|$)|[^.!?]+$/gu);
|
|
320
|
+
if (sentenceUnits && sentenceUnits.length > 1) {
|
|
321
|
+
return packMarkdownUnits(sentenceUnits, maxLen, splitPlainMarkdownText);
|
|
322
|
+
}
|
|
323
|
+
const wordUnits = markdown.match(/\S+\s*/gu);
|
|
324
|
+
if (wordUnits && wordUnits.length > 1) {
|
|
325
|
+
return packMarkdownUnits(wordUnits, maxLen, splitPlainMarkdownText);
|
|
326
|
+
}
|
|
327
|
+
return splitByCodePoint(markdown, maxLen);
|
|
328
|
+
}
|
|
329
|
+
function packMarkdownUnits(units, maxLen, splitOversized) {
|
|
330
|
+
const chunks = [];
|
|
331
|
+
let current = '';
|
|
332
|
+
for (const unit of units){
|
|
333
|
+
const candidate = current + unit;
|
|
334
|
+
if (renderedLengthFits(candidate, maxLen)) {
|
|
335
|
+
current = candidate;
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
if (current.length > 0) {
|
|
339
|
+
chunks.push(current);
|
|
340
|
+
current = '';
|
|
341
|
+
}
|
|
342
|
+
if (renderedLengthFits(unit, maxLen)) {
|
|
343
|
+
current = unit;
|
|
344
|
+
} else {
|
|
345
|
+
chunks.push(...splitOversized(unit, maxLen));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (current.length > 0) chunks.push(current);
|
|
349
|
+
return chunks;
|
|
350
|
+
}
|
|
351
|
+
function splitByCodePoint(text, maxLen) {
|
|
352
|
+
const chunks = [];
|
|
353
|
+
let current = '';
|
|
354
|
+
for (const char of Array.from(text)){
|
|
355
|
+
const candidate = current + char;
|
|
356
|
+
if (renderedLengthFits(candidate, maxLen)) {
|
|
357
|
+
current = candidate;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (current.length > 0) {
|
|
361
|
+
chunks.push(current);
|
|
362
|
+
current = '';
|
|
363
|
+
}
|
|
364
|
+
if (renderedLengthFits(char, maxLen)) {
|
|
365
|
+
current = char;
|
|
366
|
+
} else {
|
|
367
|
+
chunks.push(char);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (current.length > 0) chunks.push(current);
|
|
371
|
+
return chunks;
|
|
372
|
+
}
|
|
373
|
+
function renderedLengthFits(markdown, maxLen) {
|
|
374
|
+
return markdownToTelegramHtml(markdown).length <= maxLen;
|
|
375
|
+
}
|
|
84
376
|
/**
|
|
85
377
|
* Split text into chunks of maxLen or fewer characters. Prefers paragraph
|
|
86
378
|
* boundaries (\n\n), then single newlines (\n), then hard-splits at maxLen.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/TelegramAdapter.ts"],"sourcesContent":["import { Telegraf } from 'telegraf';\nimport type { ChannelAdapter } from './ChannelAdapter.js';\nimport { markdownToTelegramHtml } from '../utils/telegramHtml.js';\nimport type { IncomingMessage } from '../types.js';\n\nexport const TELEGRAM_CHANNEL_TYPE = 'telegram';\nexport const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;\nconst TELEGRAM_PARSE_MODE = 'HTML' as const;\n\nexport interface TelegramAdapterOptions {\n botToken: string;\n}\n\n/**\n * Telegram Bot API adapter using telegraf with long polling.\n */\nexport class TelegramAdapter implements ChannelAdapter {\n readonly type = TELEGRAM_CHANNEL_TYPE;\n\n private bot: Telegraf;\n private messageHandler: ((msg: IncomingMessage) => Promise<void>) | null = null;\n private running = false;\n\n constructor(options: TelegramAdapterOptions) {\n this.bot = new Telegraf(options.botToken);\n }\n\n async start(): Promise<void> {\n this.bot.on('text', async (ctx) => {\n if (!this.messageHandler) return;\n\n const msg: IncomingMessage = {\n channelType: TELEGRAM_CHANNEL_TYPE,\n chatId: String(ctx.message.chat.id),\n userId: String(ctx.message.from.id),\n text: ctx.message.text,\n timestamp: new Date(ctx.message.date * 1000),\n };\n\n try {\n await this.messageHandler(msg);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n await ctx.reply(`Error processing message: ${errorMessage}`);\n }\n });\n\n await this.bot.launch();\n this.running = true;\n }\n\n async stop(): Promise<void> {\n this.running = false;\n await this.bot.stop();\n }\n\n /**\n * Input is treated as markdown and rendered as Telegram-compatible HTML.\n * Long messages are chunked at paragraph boundaries when possible; very\n * long single blocks (e.g. a `<pre>` over 4096 chars) may still split\n * mid-tag and produce a partial render in the second chunk.\n */\n async sendMessage(chatId: string, text: string): Promise<void> {\n let html: string;\n try {\n html = markdownToTelegramHtml(text);\n } catch {\n for (const chunk of chunkMessage(text, TELEGRAM_MAX_MESSAGE_LENGTH)) {\n await this.bot.telegram.sendMessage(chatId, chunk);\n }\n return;\n }\n\n for (const chunk of chunkMessage(html, TELEGRAM_MAX_MESSAGE_LENGTH)) {\n try {\n await this.bot.telegram.sendMessage(chatId, chunk, { parse_mode: TELEGRAM_PARSE_MODE });\n } catch (error) {\n if (!isParseEntitiesError(error)) throw error;\n // Telegram rejected the rendered HTML โ fall back to plain text\n // so the user still gets the content (just unformatted).\n await this.bot.telegram.sendMessage(chatId, htmlToPlainText(chunk));\n }\n }\n }\n\n onMessage(handler: (msg: IncomingMessage) => Promise<void>): void {\n this.messageHandler = handler;\n }\n\n async isHealthy(): Promise<boolean> {\n return this.running;\n }\n}\n\nfunction isParseEntitiesError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n const description = (error as { description?: string }).description;\n const message = (error as { message?: string }).message;\n return ((description ?? '') + (message ?? '')).includes(\"can't parse entities\");\n}\n\nfunction htmlToPlainText(html: string): string {\n return html\n .replace(/<[^>]+>/g, '')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/&/g, '&');\n}\n\n/**\n * Split text into chunks of maxLen or fewer characters. Prefers paragraph\n * boundaries (\\n\\n), then single newlines (\\n), then hard-splits at maxLen.\n */\nfunction chunkMessage(text: string, maxLen: number): string[] {\n const chunks: string[] = [];\n let remaining = text;\n\n while (remaining.length > 0) {\n if (remaining.length <= maxLen) {\n chunks.push(remaining);\n break;\n }\n\n const lastParagraph = remaining.lastIndexOf('\\n\\n', maxLen - 2);\n const lastNewline = remaining.lastIndexOf('\\n', maxLen - 1);\n\n let splitAt: number;\n if (lastParagraph > 0) {\n splitAt = lastParagraph + 2;\n } else if (lastNewline > 0) {\n splitAt = lastNewline + 1;\n } else {\n splitAt = maxLen;\n }\n\n chunks.push(remaining.slice(0, splitAt));\n remaining = remaining.slice(splitAt);\n }\n\n return chunks;\n}\n"],"names":["Telegraf","markdownToTelegramHtml","TELEGRAM_CHANNEL_TYPE","TELEGRAM_MAX_MESSAGE_LENGTH","TELEGRAM_PARSE_MODE","TelegramAdapter","type","bot","messageHandler","running","options","botToken","start","on","ctx","msg","channelType","chatId","String","message","chat","id","userId","from","text","timestamp","Date","date","error","errorMessage","Error","reply","launch","stop","sendMessage","html","chunk","chunkMessage","telegram","parse_mode","isParseEntitiesError","htmlToPlainText","onMessage","handler","isHealthy","description","includes","replace","maxLen","chunks","remaining","length","push","lastParagraph","lastIndexOf","lastNewline","splitAt","slice"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,WAAW;AAEpC,SAASC,sBAAsB,QAAQ,2BAA2B;AAGlE,OAAO,MAAMC,wBAAwB,WAAW;AAChD,OAAO,MAAMC,8BAA8B,KAAK;AAChD,MAAMC,sBAAsB;AAM5B;;CAEC,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AAC,QAAQN,SAAS;QAC7D,MAAMO,cAAcL,UAAUI,WAAW,CAAC,MAAMN,SAAS;QAEzD,IAAIQ;QACJ,IAAIH,gBAAgB,GAAG;YACnBG,UAAUH,gBAAgB;QAC9B,OAAO,IAAIE,cAAc,GAAG;YACxBC,UAAUD,cAAc;QAC5B,OAAO;YACHC,UAAUR;QACd;QAEAC,OAAOG,IAAI,CAACF,UAAUO,KAAK,CAAC,GAAGD;QAC/BN,YAAYA,UAAUO,KAAK,CAACD;IAChC;IAEA,OAAOP;AACX"}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/TelegramAdapter.ts"],"sourcesContent":["import { Telegraf } from 'telegraf';\nimport { Marked, type Token, type Tokens } from 'marked';\nimport type { ChannelAdapter } from './ChannelAdapter.js';\nimport { markdownToTelegramHtml } from '../utils/telegramHtml.js';\nimport type { IncomingMessage, InlineKeyboard, IncomingCallback, CallbackHandler } from '../types.js';\n\nexport const TELEGRAM_CHANNEL_TYPE = 'telegram';\nexport const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;\nconst TELEGRAM_PARSE_MODE = 'HTML' as const;\nconst markdownLexer = new Marked();\n\ntype TelegramMessageChunk = {\n text: string;\n html: boolean;\n};\n\nexport interface TelegramAdapterOptions {\n botToken: string;\n}\n\n/**\n * Telegram Bot API adapter using telegraf with long polling.\n */\nexport class TelegramAdapter implements ChannelAdapter {\n readonly type = TELEGRAM_CHANNEL_TYPE;\n\n private bot: Telegraf;\n private messageHandler: ((msg: IncomingMessage) => Promise<void>) | null = null;\n private callbackHandler: CallbackHandler | null = null;\n private running = false;\n\n constructor(options: TelegramAdapterOptions) {\n this.bot = new Telegraf(options.botToken);\n }\n\n async start(): Promise<void> {\n this.bot.on('text', async (ctx) => {\n if (!this.messageHandler) return;\n\n const msg: IncomingMessage = {\n channelType: TELEGRAM_CHANNEL_TYPE,\n chatId: String(ctx.message.chat.id),\n userId: String(ctx.message.from.id),\n text: ctx.message.text,\n timestamp: new Date(ctx.message.date * 1000),\n };\n\n try {\n await this.messageHandler(msg);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n await ctx.reply(`Error processing message: ${errorMessage}`);\n }\n });\n\n this.bot.on('callback_query', async (ctx) => {\n if (!this.callbackHandler) {\n try { await ctx.answerCbQuery(); } catch { /* ignore */ }\n return;\n }\n\n const query = ctx.callbackQuery as {\n id: string;\n data?: string;\n message?: { message_id: number; chat: { id: number | string } };\n from: { id: number | string };\n };\n\n const data = typeof query.data === 'string' ? query.data : '';\n if (!query.message) {\n try { await ctx.answerCbQuery(); } catch { /* ignore */ }\n return;\n }\n\n const cb: IncomingCallback = {\n channelType: TELEGRAM_CHANNEL_TYPE,\n chatId: String(query.message.chat.id),\n userId: String(query.from.id),\n messageId: query.message.message_id,\n callbackData: data,\n callbackQueryId: query.id,\n timestamp: new Date(),\n };\n\n try {\n await this.callbackHandler(cb);\n } catch {\n try { await ctx.answerCbQuery('Error'); } catch { /* ignore */ }\n }\n });\n\n await this.bot.launch();\n this.running = true;\n }\n\n async stop(): Promise<void> {\n this.running = false;\n await this.bot.stop();\n }\n\n /**\n * Input is treated as markdown and rendered as Telegram-compatible HTML.\n * Long messages are chunked as markdown source before rendering so each\n * Telegram HTML payload is independently valid.\n */\n async sendMessage(chatId: string, text: string): Promise<void> {\n let chunks: TelegramMessageChunk[];\n try {\n chunks = chunkMarkdownForTelegram(text, TELEGRAM_MAX_MESSAGE_LENGTH);\n } catch {\n for (const chunk of chunkMessage(text, TELEGRAM_MAX_MESSAGE_LENGTH)) {\n await this.bot.telegram.sendMessage(chatId, chunk);\n }\n return;\n }\n\n for (const chunk of chunks) {\n if (!chunk.html) {\n await this.bot.telegram.sendMessage(chatId, chunk.text);\n continue;\n }\n\n try {\n await this.bot.telegram.sendMessage(chatId, chunk.text, { parse_mode: TELEGRAM_PARSE_MODE });\n } catch (error) {\n if (!isParseEntitiesError(error)) throw error;\n // Telegram rejected the rendered HTML โ fall back to plain text\n // so the user still gets the content (just unformatted).\n await this.bot.telegram.sendMessage(chatId, htmlToPlainText(chunk.text));\n }\n }\n }\n\n onMessage(handler: (msg: IncomingMessage) => Promise<void>): void {\n this.messageHandler = handler;\n }\n\n onCallback(handler: CallbackHandler): void {\n this.callbackHandler = handler;\n }\n\n /**\n * Send a message with an inline keyboard. `html` is sent verbatim with\n * parse_mode=HTML โ callers must pre-escape any user-controlled fields.\n * Returns the Telegram message_id of the sent message.\n */\n async sendInlineKeyboard(chatId: string, html: string, keyboard: InlineKeyboard): Promise<number> {\n const result = await this.bot.telegram.sendMessage(chatId, html, {\n parse_mode: TELEGRAM_PARSE_MODE,\n reply_markup: { inline_keyboard: toTelegrafKeyboard(keyboard) },\n }) as { message_id: number };\n return result.message_id;\n }\n\n /**\n * Replace the inline keyboard on an existing message. Pass `null` to remove\n * the keyboard entirely.\n */\n async editInlineKeyboard(chatId: string, messageId: number, keyboard: InlineKeyboard | null): Promise<void> {\n await this.bot.telegram.editMessageReplyMarkup(chatId, messageId, undefined, keyboard\n ? { inline_keyboard: toTelegrafKeyboard(keyboard) }\n : undefined);\n }\n\n /**\n * Acknowledge a callback_query. Without this Telegram leaves a spinner on\n * the tapped button. Pass `text` to show a transient toast.\n */\n async answerCallback(callbackQueryId: string, text?: string): Promise<void> {\n await this.bot.telegram.answerCbQuery(callbackQueryId, text);\n }\n\n async isHealthy(): Promise<boolean> {\n return this.running;\n }\n}\n\nfunction toTelegrafKeyboard(keyboard: InlineKeyboard): { text: string; callback_data: string }[][] {\n return keyboard.map((row) => row.map((btn) => ({ text: btn.text, callback_data: btn.callbackData })));\n}\n\nfunction isParseEntitiesError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n const description = (error as { description?: string }).description;\n const message = (error as { message?: string }).message;\n return ((description ?? '') + (message ?? '')).includes(\"can't parse entities\");\n}\n\nfunction htmlToPlainText(html: string): string {\n return html\n .replace(/<[^>]+>/g, '')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/&/g, '&');\n}\n\nfunction chunkMarkdownForTelegram(markdown: string, maxLen: number): TelegramMessageChunk[] {\n const markdownChunks = splitMarkdownSource(markdown, maxLen);\n const chunks: TelegramMessageChunk[] = [];\n\n for (const markdownChunk of markdownChunks) {\n const html = markdownToTelegramHtml(markdownChunk);\n if (html.length <= maxLen) {\n if (html.length > 0) chunks.push({ text: html, html: true });\n continue;\n }\n\n for (const plainChunk of chunkMessage(markdownChunk, maxLen)) {\n if (plainChunk.length > 0) chunks.push({ text: plainChunk, html: false });\n }\n }\n\n return chunks;\n}\n\nfunction splitMarkdownSource(markdown: string, maxLen: number, depth = 0): string[] {\n if (markdown.length === 0) return [];\n if (renderedLengthFits(markdown, maxLen)) return [markdown];\n if (depth > 6) return splitPlainMarkdownText(markdown, maxLen);\n\n const chunks: string[] = [];\n let current = '';\n const tokens = markdownLexer.lexer(markdown);\n\n for (const token of tokens) {\n const raw = token.raw ?? '';\n if (raw.length === 0) continue;\n\n const candidate = current + raw;\n if (candidate.length > 0 && renderedLengthFits(candidate, maxLen)) {\n current = candidate;\n continue;\n }\n\n if (current.length > 0) {\n chunks.push(current);\n current = '';\n }\n\n if (renderedLengthFits(raw, maxLen)) {\n current = raw;\n } else {\n chunks.push(...splitOversizedToken(token, maxLen, depth + 1));\n }\n }\n\n if (current.length > 0) chunks.push(current);\n return chunks.flatMap((chunk) => renderedLengthFits(chunk, maxLen) ? [chunk] : splitPlainMarkdownText(chunk, maxLen));\n}\n\nfunction splitOversizedToken(token: Token, maxLen: number, depth: number): string[] {\n switch (token.type) {\n case 'code':\n return splitCodeToken(token as Tokens.Code, maxLen);\n case 'list':\n return splitListToken(token as Tokens.List, maxLen, depth);\n case 'paragraph':\n case 'text':\n return splitPlainMarkdownText(token.raw, maxLen);\n default:\n if ('tokens' in token && Array.isArray(token.tokens) && token.raw !== undefined) {\n return splitMarkdownSource(token.raw, maxLen, depth);\n }\n return splitPlainMarkdownText(token.raw ?? '', maxLen);\n }\n}\n\nfunction splitListToken(token: Tokens.List, maxLen: number, depth: number): string[] {\n const chunks: string[] = [];\n let current = '';\n\n for (const item of token.items) {\n const raw = item.raw;\n const candidate = current + raw;\n if (candidate.length > 0 && renderedLengthFits(candidate, maxLen)) {\n current = candidate;\n continue;\n }\n\n if (current.length > 0) {\n chunks.push(current);\n current = '';\n }\n\n if (renderedLengthFits(raw, maxLen)) {\n current = raw;\n } else {\n chunks.push(...splitMarkdownSource(raw, maxLen, depth + 1));\n }\n }\n\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction splitCodeToken(token: Tokens.Code, maxLen: number): string[] {\n const fence = token.raw.startsWith('~~~') ? '~~~' : '```';\n const lang = token.lang ? token.lang.split(/\\s/)[0] : '';\n const lines = token.text.split('\\n');\n const chunks: string[] = [];\n let currentLines: string[] = [];\n\n const renderFence = (codeLines: string[]): string =>\n `${fence}${lang}\\n${codeLines.join('\\n')}\\n${fence}\\n\\n`;\n\n for (const line of lines) {\n const candidateLines = [...currentLines, line];\n if (renderedLengthFits(renderFence(candidateLines), maxLen)) {\n currentLines = candidateLines;\n continue;\n }\n\n if (currentLines.length > 0) {\n chunks.push(renderFence(currentLines));\n currentLines = [];\n }\n\n if (renderedLengthFits(renderFence([line]), maxLen)) {\n currentLines = [line];\n } else {\n for (const segment of splitCodeLine(line, fence, lang, maxLen)) {\n chunks.push(renderFence([segment]));\n }\n }\n }\n\n if (currentLines.length > 0) chunks.push(renderFence(currentLines));\n return chunks;\n}\n\nfunction splitCodeLine(line: string, fence: string, lang: string, maxLen: number): string[] {\n const segments: string[] = [];\n let current = '';\n const renderFence = (value: string): string => `${fence}${lang}\\n${value}\\n${fence}\\n\\n`;\n\n for (const char of Array.from(line)) {\n const candidate = current + char;\n if (renderedLengthFits(renderFence(candidate), maxLen)) {\n current = candidate;\n continue;\n }\n\n if (current.length > 0) {\n segments.push(current);\n current = '';\n }\n\n if (renderedLengthFits(renderFence(char), maxLen)) {\n current = char;\n } else {\n segments.push(char);\n }\n }\n\n if (current.length > 0) segments.push(current);\n return segments;\n}\n\nfunction splitPlainMarkdownText(markdown: string, maxLen: number): string[] {\n if (markdown.length === 0) return [];\n if (renderedLengthFits(markdown, maxLen)) return [markdown];\n\n const newlineUnits = markdown.split(/(?<=\\n)/u);\n if (newlineUnits.length > 1) {\n return packMarkdownUnits(newlineUnits, maxLen, splitPlainMarkdownText);\n }\n\n const sentenceUnits = markdown.match(/[^.!?]+[.!?]+(?:\\s+|$)|[^.!?]+$/gu);\n if (sentenceUnits && sentenceUnits.length > 1) {\n return packMarkdownUnits(sentenceUnits, maxLen, splitPlainMarkdownText);\n }\n\n const wordUnits = markdown.match(/\\S+\\s*/gu);\n if (wordUnits && wordUnits.length > 1) {\n return packMarkdownUnits(wordUnits, maxLen, splitPlainMarkdownText);\n }\n\n return splitByCodePoint(markdown, maxLen);\n}\n\nfunction packMarkdownUnits(\n units: string[],\n maxLen: number,\n splitOversized: (unit: string, maxLen: number) => string[],\n): string[] {\n const chunks: string[] = [];\n let current = '';\n\n for (const unit of units) {\n const candidate = current + unit;\n if (renderedLengthFits(candidate, maxLen)) {\n current = candidate;\n continue;\n }\n\n if (current.length > 0) {\n chunks.push(current);\n current = '';\n }\n\n if (renderedLengthFits(unit, maxLen)) {\n current = unit;\n } else {\n chunks.push(...splitOversized(unit, maxLen));\n }\n }\n\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction splitByCodePoint(text: string, maxLen: number): string[] {\n const chunks: string[] = [];\n let current = '';\n\n for (const char of Array.from(text)) {\n const candidate = current + char;\n if (renderedLengthFits(candidate, maxLen)) {\n current = candidate;\n continue;\n }\n\n if (current.length > 0) {\n chunks.push(current);\n current = '';\n }\n\n if (renderedLengthFits(char, maxLen)) {\n current = char;\n } else {\n chunks.push(char);\n }\n }\n\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction renderedLengthFits(markdown: string, maxLen: number): boolean {\n return markdownToTelegramHtml(markdown).length <= maxLen;\n}\n\n/**\n * Split text into chunks of maxLen or fewer characters. Prefers paragraph\n * boundaries (\\n\\n), then single newlines (\\n), then hard-splits at maxLen.\n */\nfunction chunkMessage(text: string, maxLen: number): string[] {\n const chunks: string[] = [];\n let remaining = text;\n\n while (remaining.length > 0) {\n if (remaining.length <= maxLen) {\n chunks.push(remaining);\n break;\n }\n\n const lastParagraph = remaining.lastIndexOf('\\n\\n', maxLen - 2);\n const lastNewline = remaining.lastIndexOf('\\n', maxLen - 1);\n\n let splitAt: number;\n if (lastParagraph > 0) {\n splitAt = lastParagraph + 2;\n } else if (lastNewline > 0) {\n splitAt = lastNewline + 1;\n } else {\n splitAt = maxLen;\n }\n\n chunks.push(remaining.slice(0, splitAt));\n remaining = remaining.slice(splitAt);\n }\n\n return chunks;\n}\n"],"names":["Telegraf","Marked","markdownToTelegramHtml","TELEGRAM_CHANNEL_TYPE","TELEGRAM_MAX_MESSAGE_LENGTH","TELEGRAM_PARSE_MODE","markdownLexer","TelegramAdapter","type","bot","messageHandler","callbackHandler","running","options","botToken","start","on","ctx","msg","channelType","chatId","String","message","chat","id","userId","from","text","timestamp","Date","date","error","errorMessage","Error","reply","answerCbQuery","query","callbackQuery","data","cb","messageId","message_id","callbackData","callbackQueryId","launch","stop","sendMessage","chunks","chunkMarkdownForTelegram","chunk","chunkMessage","telegram","html","parse_mode","isParseEntitiesError","htmlToPlainText","onMessage","handler","onCallback","sendInlineKeyboard","keyboard","result","reply_markup","inline_keyboard","toTelegrafKeyboard","editInlineKeyboard","editMessageReplyMarkup","undefined","answerCallback","isHealthy","map","row","btn","callback_data","description","includes","replace","markdown","maxLen","markdownChunks","splitMarkdownSource","markdownChunk","length","push","plainChunk","depth","renderedLengthFits","splitPlainMarkdownText","current","tokens","lexer","token","raw","candidate","splitOversizedToken","flatMap","splitCodeToken","splitListToken","Array","isArray","item","items","fence","startsWith","lang","split","lines","currentLines","renderFence","codeLines","join","line","candidateLines","segment","splitCodeLine","segments","value","char","newlineUnits","packMarkdownUnits","sentenceUnits","match","wordUnits","splitByCodePoint","units","splitOversized","unit","remaining","lastParagraph","lastIndexOf","lastNewline","splitAt","slice"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,WAAW;AACpC,SAASC,MAAM,QAAiC,SAAS;AAEzD,SAASC,sBAAsB,QAAQ,2BAA2B;AAGlE,OAAO,MAAMC,wBAAwB,WAAW;AAChD,OAAO,MAAMC,8BAA8B,KAAK;AAChD,MAAMC,sBAAsB;AAC5B,MAAMC,gBAAgB,IAAIL;AAW1B;;CAEC,GACD,OAAO,MAAMM;IACAC,OAAOL,sBAAsB;IAE9BM,IAAc;IACdC,iBAAmE,KAAK;IACxEC,kBAA0C,KAAK;IAC/CC,UAAU,MAAM;IAExB,YAAYC,OAA+B,CAAE;QACzC,IAAI,CAACJ,GAAG,GAAG,IAAIT,SAASa,QAAQC,QAAQ;IAC5C;IAEA,MAAMC,QAAuB;QACzB,IAAI,CAACN,GAAG,CAACO,EAAE,CAAC,QAAQ,OAAOC;YACvB,IAAI,CAAC,IAAI,CAACP,cAAc,EAAE;YAE1B,MAAMQ,MAAuB;gBACzBC,aAAahB;gBACbiB,QAAQC,OAAOJ,IAAIK,OAAO,CAACC,IAAI,CAACC,EAAE;gBAClCC,QAAQJ,OAAOJ,IAAIK,OAAO,CAACI,IAAI,CAACF,EAAE;gBAClCG,MAAMV,IAAIK,OAAO,CAACK,IAAI;gBACtBC,WAAW,IAAIC,KAAKZ,IAAIK,OAAO,CAACQ,IAAI,GAAG;YAC3C;YAEA,IAAI;gBACA,MAAM,IAAI,CAACpB,cAAc,CAACQ;YAC9B,EAAE,OAAOa,OAAO;gBACZ,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMT,OAAO,GAAG;gBAC9D,MAAML,IAAIiB,KAAK,CAAC,CAAC,0BAA0B,EAAEF,cAAc;YAC/D;QACJ;QAEA,IAAI,CAACvB,GAAG,CAACO,EAAE,CAAC,kBAAkB,OAAOC;YACjC,IAAI,CAAC,IAAI,CAACN,eAAe,EAAE;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js';
|
|
|
3
3
|
export { TelegramAdapter, TELEGRAM_CHANNEL_TYPE, TELEGRAM_MAX_MESSAGE_LENGTH } from './adapters/TelegramAdapter.js';
|
|
4
4
|
export type { TelegramAdapterOptions } from './adapters/TelegramAdapter.js';
|
|
5
5
|
export type { ChannelAdapter } from './adapters/ChannelAdapter.js';
|
|
6
|
-
export type { IncomingMessage, MessageHandler, ChannelConfig, ChannelEntry, ChannelType, TelegramConfig, } from './types.js';
|
|
6
|
+
export type { IncomingMessage, MessageHandler, ChannelConfig, ChannelEntry, ChannelType, TelegramConfig, InlineKeyboardButton, InlineKeyboard, IncomingCallback, CallbackHandler, } from './types.js';
|
|
7
7
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AACpH,YAAY,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAE5E,YAAY,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,YAAY,EACR,eAAe,EACf,cAAc,EACd,aAAa,EACb,YAAY,EACZ,WAAW,EACX,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AACpH,YAAY,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAE5E,YAAY,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,YAAY,EACR,eAAe,EACf,cAAc,EACd,aAAa,EACb,YAAY,EACZ,WAAW,EACX,cAAc,EACd,oBAAoB,EACpB,cAAc,EACd,gBAAgB,EAChB,eAAe,GAClB,MAAM,YAAY,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { ChannelManager } from './ChannelManager.js';\nexport { ConfigStore } from './ConfigStore.js';\nexport { TelegramAdapter, TELEGRAM_CHANNEL_TYPE, TELEGRAM_MAX_MESSAGE_LENGTH } from './adapters/TelegramAdapter.js';\nexport type { TelegramAdapterOptions } from './adapters/TelegramAdapter.js';\n\nexport type { ChannelAdapter } from './adapters/ChannelAdapter.js';\n\nexport type {\n IncomingMessage,\n MessageHandler,\n ChannelConfig,\n ChannelEntry,\n ChannelType,\n TelegramConfig,\n} from './types.js';\n"],"names":["ChannelManager","ConfigStore","TelegramAdapter","TELEGRAM_CHANNEL_TYPE","TELEGRAM_MAX_MESSAGE_LENGTH"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAsB;AACrD,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,eAAe,EAAEC,qBAAqB,EAAEC,2BAA2B,QAAQ,gCAAgC"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { ChannelManager } from './ChannelManager.js';\nexport { ConfigStore } from './ConfigStore.js';\nexport { TelegramAdapter, TELEGRAM_CHANNEL_TYPE, TELEGRAM_MAX_MESSAGE_LENGTH } from './adapters/TelegramAdapter.js';\nexport type { TelegramAdapterOptions } from './adapters/TelegramAdapter.js';\n\nexport type { ChannelAdapter } from './adapters/ChannelAdapter.js';\n\nexport type {\n IncomingMessage,\n MessageHandler,\n ChannelConfig,\n ChannelEntry,\n ChannelType,\n TelegramConfig,\n InlineKeyboardButton,\n InlineKeyboard,\n IncomingCallback,\n CallbackHandler,\n} from './types.js';\n"],"names":["ChannelManager","ConfigStore","TelegramAdapter","TELEGRAM_CHANNEL_TYPE","TELEGRAM_MAX_MESSAGE_LENGTH"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAsB;AACrD,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,eAAe,EAAEC,qBAAqB,EAAEC,2BAA2B,QAAQ,gCAAgC"}
|
package/dist/types.d.ts
CHANGED
|
@@ -42,4 +42,31 @@ export interface TelegramConfig {
|
|
|
42
42
|
botUsername: string;
|
|
43
43
|
authorizedChatId?: number;
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* A single button in a Telegram-style inline keyboard.
|
|
47
|
+
*/
|
|
48
|
+
export interface InlineKeyboardButton {
|
|
49
|
+
text: string;
|
|
50
|
+
callbackData: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* An inline keyboard layout: rows of buttons.
|
|
54
|
+
*/
|
|
55
|
+
export type InlineKeyboard = InlineKeyboardButton[][];
|
|
56
|
+
/**
|
|
57
|
+
* An inline-keyboard tap delivered as a callback_query.
|
|
58
|
+
*/
|
|
59
|
+
export interface IncomingCallback {
|
|
60
|
+
channelType: string;
|
|
61
|
+
chatId: string;
|
|
62
|
+
userId: string;
|
|
63
|
+
messageId: number;
|
|
64
|
+
callbackData: string;
|
|
65
|
+
callbackQueryId: string;
|
|
66
|
+
timestamp: Date;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Handler for inline-keyboard taps.
|
|
70
|
+
*/
|
|
71
|
+
export type CallbackHandler = (callback: IncomingCallback) => Promise<void>;
|
|
45
72
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC5B,WAA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C,CAAC;AAEzE;;GAEG;AACH,MAAM,WAAW,aAAa;IAC1B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CAC1C;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IACzB,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,cAAc,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,cAAc;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,oBAAoB,EAAE,EAAE,CAAC;AAEtD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,IAAI,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,QAAQ,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC"}
|
package/dist/types.js
CHANGED
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * An incoming message from a messaging platform.\n * Generic โ no agent-specific concepts.\n */\nexport interface IncomingMessage {\n channelType: string;\n chatId: string;\n userId: string;\n text: string;\n timestamp: Date;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Handler function provided by the consumer (e.g., CLI).\n * Fire-and-forget โ returns void. Responses are sent separately via sendMessage().\n */\nexport type MessageHandler = (message: IncomingMessage) => Promise<void>;\n\n/**\n * Root configuration for all channels.\n */\nexport interface ChannelConfig {\n channels: Record<string, ChannelEntry>;\n}\n\n/**\n * Configuration entry for a single channel.\n */\nexport interface ChannelEntry {\n type: ChannelType;\n enabled: boolean;\n createdAt: string;\n config: TelegramConfig;\n}\n\n/**\n * Supported channel types.\n */\nexport type ChannelType = 'telegram' | 'slack' | 'whatsapp';\n\n/**\n * Telegram-specific configuration.\n */\nexport interface TelegramConfig {\n botToken: string;\n botUsername: string;\n authorizedChatId?: number;\n}\n"],"names":[],"mappings":"AAAA;;;CAGC,
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * An incoming message from a messaging platform.\n * Generic โ no agent-specific concepts.\n */\nexport interface IncomingMessage {\n channelType: string;\n chatId: string;\n userId: string;\n text: string;\n timestamp: Date;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Handler function provided by the consumer (e.g., CLI).\n * Fire-and-forget โ returns void. Responses are sent separately via sendMessage().\n */\nexport type MessageHandler = (message: IncomingMessage) => Promise<void>;\n\n/**\n * Root configuration for all channels.\n */\nexport interface ChannelConfig {\n channels: Record<string, ChannelEntry>;\n}\n\n/**\n * Configuration entry for a single channel.\n */\nexport interface ChannelEntry {\n type: ChannelType;\n enabled: boolean;\n createdAt: string;\n config: TelegramConfig;\n}\n\n/**\n * Supported channel types.\n */\nexport type ChannelType = 'telegram' | 'slack' | 'whatsapp';\n\n/**\n * Telegram-specific configuration.\n */\nexport interface TelegramConfig {\n botToken: string;\n botUsername: string;\n authorizedChatId?: number;\n}\n\n/**\n * A single button in a Telegram-style inline keyboard.\n */\nexport interface InlineKeyboardButton {\n text: string;\n callbackData: string;\n}\n\n/**\n * An inline keyboard layout: rows of buttons.\n */\nexport type InlineKeyboard = InlineKeyboardButton[][];\n\n/**\n * An inline-keyboard tap delivered as a callback_query.\n */\nexport interface IncomingCallback {\n channelType: string;\n chatId: string;\n userId: string;\n messageId: number;\n callbackData: string;\n callbackQueryId: string;\n timestamp: Date;\n}\n\n/**\n * Handler for inline-keyboard taps.\n */\nexport type CallbackHandler = (callback: IncomingCallback) => Promise<void>;\n"],"names":[],"mappings":"AAAA;;;CAGC,GAyED;;CAEC,GACD,WAA4E"}
|