@theokit/gateway-telegram 0.4.0 → 0.6.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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { BasePlatformAdapter, GatewayConfigurationError } from '@theokit/gateway';
2
- import { Bot, GrammyError, HttpError } from 'grammy';
2
+ import { Bot, GrammyError, HttpError, InputFile } from 'grammy';
3
3
 
4
4
  // src/adapter.ts
5
5
 
@@ -82,6 +82,101 @@ function parseInbound(payload) {
82
82
  );
83
83
  }
84
84
 
85
+ // src/read-voice.ts
86
+ var MAX_VOICE_BYTES = 20 * 1024 * 1024;
87
+ var READ_TIMEOUT_MS = 3e4;
88
+ var DEFAULT_MEDIA_TYPE = "audio/ogg";
89
+ async function readVoice(ctx, token, fetchImpl = fetch) {
90
+ const voice = ctx.message?.voice ?? {};
91
+ if (typeof voice.file_id !== "string") return { reason: "no_file_id" };
92
+ if (typeof voice.file_size === "number" && voice.file_size > MAX_VOICE_BYTES) {
93
+ return { reason: "too_large" };
94
+ }
95
+ const controller = new AbortController();
96
+ const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);
97
+ try {
98
+ const path = await filePath(ctx, controller.signal);
99
+ if (typeof path !== "string") return path;
100
+ const url = `https://api.telegram.org/file/bot${token}/${path}`;
101
+ const bytes = await download(url, fetchImpl, controller.signal);
102
+ if (!(bytes instanceof Uint8Array)) return bytes;
103
+ return { audio: { data: bytes, ...voiceDetails(voice) } };
104
+ } finally {
105
+ clearTimeout(timer);
106
+ }
107
+ }
108
+ function voiceDetails(voice) {
109
+ const duration = voice.duration;
110
+ return {
111
+ mediaType: typeof voice.mime_type === "string" ? voice.mime_type : DEFAULT_MEDIA_TYPE,
112
+ durationSeconds: typeof duration === "number" && Number.isFinite(duration) ? duration : 0
113
+ };
114
+ }
115
+ async function filePath(ctx, signal) {
116
+ let file;
117
+ try {
118
+ file = await ctx.getFile(signal);
119
+ } catch {
120
+ return { reason: signal.aborted ? "timeout" : "get_file_failed" };
121
+ }
122
+ return file.file_path ?? { reason: "no_file_path" };
123
+ }
124
+ async function download(url, fetchImpl, signal) {
125
+ try {
126
+ const response = await fetchImpl(url, { signal });
127
+ if (!response.ok) return { reason: `download_status_${response.status}` };
128
+ if (response.body === null) return { reason: "download_failed" };
129
+ return await readBounded(response.body, signal);
130
+ } catch {
131
+ return { reason: signal.aborted ? "timeout" : "download_failed" };
132
+ }
133
+ }
134
+ async function readBounded(body, signal) {
135
+ const reader = body.getReader();
136
+ const cancel = () => void reader.cancel().catch(() => void 0);
137
+ signal.addEventListener("abort", cancel, { once: true });
138
+ try {
139
+ const chunks = await readChunks(reader);
140
+ if (signal.aborted) return { reason: "timeout" };
141
+ return chunks ?? { reason: "too_large" };
142
+ } finally {
143
+ signal.removeEventListener("abort", cancel);
144
+ }
145
+ }
146
+ async function readChunks(reader) {
147
+ const chunks = [];
148
+ let total = 0;
149
+ for (; ; ) {
150
+ const { done, value } = await reader.read();
151
+ if (done) break;
152
+ total += value.length;
153
+ if (total > MAX_VOICE_BYTES) {
154
+ await reader.cancel();
155
+ return void 0;
156
+ }
157
+ chunks.push(value);
158
+ }
159
+ const bytes = new Uint8Array(total);
160
+ let offset = 0;
161
+ for (const chunk of chunks) {
162
+ bytes.set(chunk, offset);
163
+ offset += chunk.length;
164
+ }
165
+ return bytes;
166
+ }
167
+
168
+ // src/refuse-attachments.ts
169
+ function refuseAttachments(out) {
170
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
171
+ return {
172
+ ok: false,
173
+ error: {
174
+ code: "attachments_unsupported",
175
+ message: "telegram adapter cannot attach to an edit"
176
+ }
177
+ };
178
+ }
179
+
85
180
  // src/split.ts
86
181
  var TELEGRAM_MAX_MESSAGE = 4096;
87
182
  var SAFE_CHUNK = 4e3;
@@ -94,40 +189,261 @@ function splitForTelegram(text) {
94
189
  parts.push(remaining);
95
190
  break;
96
191
  }
97
- let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
98
- if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
99
- if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;
192
+ let boundary = findBoundary(remaining);
193
+ const afterRow = takeRowSafe(parts, remaining, boundary);
194
+ if (afterRow !== void 0) {
195
+ remaining = afterRow;
196
+ continue;
197
+ }
100
198
  const rawChunk = remaining.slice(0, boundary);
101
199
  const balanced = balanceMarkdownPairs(rawChunk);
102
200
  const chunk = balanced.length > 0 ? balanced : rawChunk;
103
201
  boundary = chunk.length;
104
- parts.push(chunk);
105
- remaining = remaining.slice(boundary).replace(/^\n+/, "");
202
+ const [piece, reopen] = closeFence(chunk);
203
+ parts.push(piece);
204
+ remaining = reopen + remaining.slice(boundary).replace(/^\n+/, "");
106
205
  }
107
206
  return parts;
108
207
  }
208
+ function findBoundary(remaining) {
209
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
210
+ if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
211
+ return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;
212
+ }
213
+ function takeRowSafe(parts, remaining, boundary) {
214
+ const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);
215
+ if (moved === void 0) return void 0;
216
+ const [piece, reopen] = closeFence(remaining.slice(0, moved.end));
217
+ parts.push(piece);
218
+ return reopen + remaining.slice(moved.start);
219
+ }
220
+ var isLineEnd = (ch) => ch === "\n" || ch === "\r";
221
+ function rowSafeCut(text, cut, window) {
222
+ const start = tableRowStart(text, cut);
223
+ if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
224
+ let end = start;
225
+ while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
226
+ return end > 0 ? { end, start } : void 0;
227
+ }
228
+ function tableRowStart(text, cut) {
229
+ if (cut >= text.length || isLineEnd(text[cut])) return void 0;
230
+ let start = cut;
231
+ while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
232
+ return start > 0 && /^[^\S\r\n]*\|/.test(text.slice(start, cut + 1)) ? start : void 0;
233
+ }
234
+ function rowLength(text, start, cut, window) {
235
+ let rowEnd = cut;
236
+ while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
237
+ return rowEnd - start;
238
+ }
239
+ var FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
240
+ var MAX_INFO = 40;
241
+ function fencedRanges(text) {
242
+ const ranges = [];
243
+ let open;
244
+ let pos = 0;
245
+ for (const line of text.split("\n")) {
246
+ open = stepFence(open, line, pos, ranges);
247
+ pos += line.length + 1;
248
+ }
249
+ if (open !== void 0) ranges.push([open.start, text.length]);
250
+ return ranges;
251
+ }
252
+ function stepFence(open, line, pos, ranges) {
253
+ const m = FENCE_LINE.exec(line.replace(/\r$/, ""));
254
+ const marker = m?.[1];
255
+ if (marker === void 0) return open;
256
+ if (open === void 0) return { fence: { marker, info: (m?.[2] ?? "").trim() }, start: pos };
257
+ if (!closesFence(open.fence, marker, m?.[2] ?? "")) return open;
258
+ ranges.push([open.start, pos + line.length]);
259
+ return void 0;
260
+ }
261
+ function closesFence(fence, marker, rest) {
262
+ return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === "";
263
+ }
264
+ function openFenceAt(text) {
265
+ const last = fencedRanges(text).at(-1);
266
+ if (last === void 0 || last[1] !== text.length) return void 0;
267
+ const lines = text.slice(last[0]).split("\n");
268
+ const opener = FENCE_LINE.exec(lines[0] ?? "");
269
+ const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? "").replace(/\r$/, "")) : null;
270
+ if (opener?.[1] === void 0) return void 0;
271
+ const fence = { marker: opener[1], info: (opener[2] ?? "").trim().slice(0, MAX_INFO) };
272
+ if (closer?.[1] !== void 0 && closesFence(fence, closer[1], closer[2] ?? "")) return void 0;
273
+ return fence;
274
+ }
275
+ function closeFence(chunk) {
276
+ const open = openFenceAt(chunk);
277
+ if (open === void 0) return [chunk, ""];
278
+ return [`${chunk}
279
+ ${open.marker}`, `${open.marker}${open.info}
280
+ `];
281
+ }
109
282
  function balanceMarkdownPairs(chunk) {
110
283
  const markers = ["**", "__", "~~", "`"];
111
284
  let out = chunk;
112
285
  for (const m of markers) {
113
- const count = countOccurrences(out, m);
114
- if (count % 2 === 1) {
115
- const lastIdx = out.lastIndexOf(m);
116
- out = out.slice(0, lastIdx).trimEnd();
286
+ const outside = markerIndexes(out, m);
287
+ if (outside.length % 2 === 1) {
288
+ out = out.slice(0, outside[outside.length - 1]).trimEnd();
117
289
  }
118
290
  }
119
291
  return out;
120
292
  }
121
- function countOccurrences(haystack, needle) {
122
- let count = 0;
293
+ function markerIndexes(text, needle) {
294
+ const ranges = fencedRanges(text);
295
+ const found = [];
123
296
  let pos = 0;
124
297
  while (true) {
125
- const found = haystack.indexOf(needle, pos);
126
- if (found === -1) break;
127
- count += 1;
128
- pos = found + needle.length;
298
+ const at = text.indexOf(needle, pos);
299
+ if (at === -1) break;
300
+ pos = at + needle.length;
301
+ if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);
129
302
  }
130
- return count;
303
+ return found;
304
+ }
305
+
306
+ // src/send-photos.ts
307
+ var CAPTION_LIMIT = 1024;
308
+ var MAX_PHOTO_BYTES = 10 * 1024 * 1024;
309
+ var MAX_AUDIO_BYTES = 50 * 1024 * 1024;
310
+ var KIND_LIMITS = {
311
+ image: { maxBytes: MAX_PHOTO_BYTES, label: "an image", bound: "10 MiB" },
312
+ audio: { maxBytes: MAX_AUDIO_BYTES, label: "an audio", bound: "50 MiB" }
313
+ };
314
+ var MAX_PHOTOS_PER_SEND = 10;
315
+ function hasAttachments(out) {
316
+ return out.attachments != null && out.attachments.length !== 0;
317
+ }
318
+ async function sendPhotos(api, out) {
319
+ const chatId = Number(out.channel.id);
320
+ if (Number.isNaN(chatId)) {
321
+ return {
322
+ ok: false,
323
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
324
+ };
325
+ }
326
+ const refusal = validateAttachments(out.attachments);
327
+ if (refusal !== void 0) return refusal;
328
+ const shared = sharedOptions(out);
329
+ try {
330
+ let lastId = await sendEachAttachment(api, chatId, out, shared);
331
+ if (out.text.length > CAPTION_LIMIT) {
332
+ for (const chunk of splitForTelegram(out.text)) {
333
+ lastId = (await api.sendMessage(chatId, chunk, shared)).message_id;
334
+ }
335
+ }
336
+ return { ok: true, messageId: String(lastId) };
337
+ } catch (err) {
338
+ return mapSendError(err);
339
+ }
340
+ }
341
+ async function sendEachAttachment(api, chatId, out, shared) {
342
+ const attachments = out.attachments;
343
+ const caption = captionOf(out.text);
344
+ let lastId = 0;
345
+ for (const [index, attachment] of attachments.entries()) {
346
+ const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
347
+ const file = new InputFile(attachment.data, attachment.filename);
348
+ const msg = attachment.kind === "audio" ? await api.sendVoice(chatId, file, options) : await api.sendPhoto(chatId, file, options);
349
+ lastId = msg.message_id;
350
+ }
351
+ return lastId;
352
+ }
353
+ function captionOf(text) {
354
+ return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : void 0;
355
+ }
356
+ function firstPhotoOptions(out, caption) {
357
+ return {
358
+ ...caption !== void 0 ? { caption } : {},
359
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
360
+ };
361
+ }
362
+ function sharedOptions(out) {
363
+ const parseMode = mapFormat(out.format);
364
+ const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
365
+ return {
366
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
367
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {}
368
+ };
369
+ }
370
+ function validateAttachments(attachments) {
371
+ if (!Array.isArray(attachments)) {
372
+ return refuse("invalid_attachment", "attachments is not a list");
373
+ }
374
+ if (attachments.length > MAX_PHOTOS_PER_SEND) {
375
+ return refuse(
376
+ "invalid_attachment",
377
+ `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`
378
+ );
379
+ }
380
+ for (const attachment of attachments) {
381
+ const refusal = validateAttachment(attachment);
382
+ if (refusal !== void 0) return refusal;
383
+ }
384
+ return void 0;
385
+ }
386
+ function validateAttachment(attachment) {
387
+ if (typeof attachment !== "object" || attachment === null) {
388
+ return refuse("invalid_attachment", "an attachment is not an object");
389
+ }
390
+ if (attachment.kind !== "image" && attachment.kind !== "audio") {
391
+ return refuse(
392
+ "attachments_unsupported",
393
+ "telegram adapter sends only image and audio attachments"
394
+ );
395
+ }
396
+ const limit = KIND_LIMITS[attachment.kind];
397
+ if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {
398
+ return refuse("invalid_attachment", `${limit.label} attachment has no bytes`);
399
+ }
400
+ if (attachment.data.length > limit.maxBytes) {
401
+ return refuse(
402
+ "invalid_attachment",
403
+ `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`
404
+ );
405
+ }
406
+ return mediaTypeRefusal(attachment);
407
+ }
408
+ function mediaTypeRefusal(attachment) {
409
+ if (attachment.kind !== "audio") return void 0;
410
+ const mediaType = typeof attachment.mediaType === "string" ? attachment.mediaType : "";
411
+ if (mediaType.toLowerCase().startsWith("audio/")) return void 0;
412
+ return refuse("invalid_attachment", `an audio attachment has media type "${mediaType}"`);
413
+ }
414
+ function refuse(code, message) {
415
+ return { ok: false, error: { code, message } };
416
+ }
417
+ function mapFormat(format) {
418
+ if (format === "markdown") return "Markdown";
419
+ if (format === "html") return "HTML";
420
+ return void 0;
421
+ }
422
+ function parseModeOptions(format) {
423
+ const parseMode = mapFormat(format);
424
+ return parseMode !== void 0 ? { parse_mode: parseMode } : {};
425
+ }
426
+ function mapSendError(err) {
427
+ if (err instanceof GrammyError) {
428
+ const description = err.description.toLowerCase();
429
+ if (description.includes("rate limit") || err.error_code === 429) {
430
+ return { ok: false, error: { code: "rate_limited", message: err.description } };
431
+ }
432
+ if (description.includes("forbidden") || err.error_code === 403) {
433
+ return { ok: false, error: { code: "no_permission", message: err.description } };
434
+ }
435
+ if (description.includes("parse")) {
436
+ return { ok: false, error: { code: "markdown_error", message: err.description } };
437
+ }
438
+ return {
439
+ ok: false,
440
+ error: { code: `telegram_${err.error_code}`, message: err.description }
441
+ };
442
+ }
443
+ if (err instanceof HttpError) {
444
+ return { ok: false, error: { code: "network_error", message: err.message } };
445
+ }
446
+ return { ok: false, error: { code: "unknown", message: err.message } };
131
447
  }
132
448
 
133
449
  // src/adapter.ts
@@ -192,8 +508,9 @@ var TelegramAdapter = class extends BasePlatformAdapter {
192
508
  this.startPromise = void 0;
193
509
  }
194
510
  }
195
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.
511
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: photo dispatch (send-photos.ts) + validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.
196
512
  async sendMessage(out) {
513
+ if (hasAttachments(out)) return sendPhotos(this.bot.api, out);
197
514
  if (out.text.length === 0) {
198
515
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
199
516
  }
@@ -222,6 +539,59 @@ var TelegramAdapter = class extends BasePlatformAdapter {
222
539
  }
223
540
  return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
224
541
  }
542
+ /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
543
+ supportsAttachments = true;
544
+ /** Telegram edits a sent message's text through `editMessageText`. */
545
+ supportsEdit = true;
546
+ /**
547
+ * Replace the text of a message this bot sent, through `editMessageText`.
548
+ *
549
+ * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no
550
+ * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,
551
+ * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own
552
+ * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit
553
+ * replaces one message. Telegram's "message is not modified" refusal is answered as a success,
554
+ * because the message already shows the text; a caller that treated it as a failure would send
555
+ * the same text again as a second message.
556
+ */
557
+ async editMessage(messageId, out) {
558
+ return refuseAttachments(out) ?? this.editText(messageId, out);
559
+ }
560
+ async editText(messageId, out) {
561
+ if (out.text.length === 0) {
562
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
563
+ }
564
+ const id = parseMessageId(messageId);
565
+ if (id === void 0) {
566
+ return {
567
+ ok: false,
568
+ error: {
569
+ code: "invalid_message_id",
570
+ message: `message id "${messageId}" is not a positive integer`
571
+ }
572
+ };
573
+ }
574
+ const chatIdNum = Number(out.channel.id);
575
+ if (Number.isNaN(chatIdNum)) {
576
+ return {
577
+ ok: false,
578
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
579
+ };
580
+ }
581
+ const parts = splitForTelegram(out.text);
582
+ if (parts.length !== 1) return editPartsRefusal(parts.length);
583
+ try {
584
+ await this.bot.api.editMessageText(
585
+ chatIdNum,
586
+ id,
587
+ parts[0],
588
+ parseModeOptions(out.format)
589
+ );
590
+ } catch (err) {
591
+ if (!isNotModified(err)) return mapSendError(err);
592
+ }
593
+ return { ok: true, messageId };
594
+ }
225
595
  onInbound(handler) {
226
596
  this.handler = handler;
227
597
  return () => {
@@ -245,7 +615,21 @@ var TelegramAdapter = class extends BasePlatformAdapter {
245
615
  }
246
616
  const event = normalizeEvent(ctx);
247
617
  if (event === void 0) return;
248
- await this.dispatchEvent(event);
618
+ await this.dispatchEvent(await this.withVoice(ctx, event));
619
+ }
620
+ /**
621
+ * The event with the voice note's audio when the message has one (B-715, ADR D1).
622
+ *
623
+ * An unreadable voice leaves the event as it was and writes the reason to stderr: the message is
624
+ * delivered either way, as it was before voice notes were read.
625
+ */
626
+ async withVoice(ctx, event) {
627
+ if (ctx.message?.voice === void 0) return event;
628
+ const read = await readVoice(ctx, this.bot.token);
629
+ if ("audio" in read) return { ...event, audio: read.audio };
630
+ process.stderr.write(`[telegram] voice not read: ${read.reason}
631
+ `);
632
+ return event;
249
633
  }
250
634
  /**
251
635
  * Dispatch a pre-built event to the current handler, honouring EC-H replace
@@ -287,32 +671,25 @@ function normalizeEvent(ctx) {
287
671
  if (chat === void 0 || msg === void 0) return void 0;
288
672
  return buildEvent(chat, msg, ctx.from, ctx);
289
673
  }
290
- function mapFormat(format) {
291
- if (format === "markdown") return "Markdown";
292
- if (format === "html") return "HTML";
293
- return void 0;
674
+ function parseMessageId(messageId) {
675
+ if (!/^\d+$/.test(messageId)) return void 0;
676
+ const id = Number(messageId);
677
+ return Number.isSafeInteger(id) && id > 0 ? id : void 0;
294
678
  }
295
- function mapSendError(err) {
296
- if (err instanceof GrammyError) {
297
- const description = err.description.toLowerCase();
298
- if (description.includes("rate limit") || err.error_code === 429) {
299
- return { ok: false, error: { code: "rate_limited", message: err.description } };
300
- }
301
- if (description.includes("forbidden") || err.error_code === 403) {
302
- return { ok: false, error: { code: "no_permission", message: err.description } };
303
- }
304
- if (description.includes("parse")) {
305
- return { ok: false, error: { code: "markdown_error", message: err.description } };
306
- }
679
+ function isNotModified(err) {
680
+ return err instanceof GrammyError && err.description.toLowerCase().includes("message is not modified");
681
+ }
682
+ function editPartsRefusal(partCount) {
683
+ if (partCount > 1) {
307
684
  return {
308
685
  ok: false,
309
- error: { code: `telegram_${err.error_code}`, message: err.description }
686
+ error: {
687
+ code: "edit_too_long",
688
+ message: `text needs ${partCount} Telegram messages; an edit replaces one`
689
+ }
310
690
  };
311
691
  }
312
- if (err instanceof HttpError) {
313
- return { ok: false, error: { code: "network_error", message: err.message } };
314
- }
315
- return { ok: false, error: { code: "unknown", message: err.message } };
692
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
316
693
  }
317
694
  var ConfigurationError = class extends GatewayConfigurationError {
318
695
  name = "ConfigurationError";