loopzero-gateway-telegram 0.0.0-stage → 0.2.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.cjs ADDED
@@ -0,0 +1,1193 @@
1
+ 'use strict';
2
+
3
+ var grammy = require('grammy');
4
+ var loopzeroGateway = require('loopzero-gateway');
5
+
6
+ // src/adapter.ts
7
+
8
+ // src/group-policy.ts
9
+ function shouldRespond(input, policy) {
10
+ if (input.chatType === "private") return true;
11
+ if (input.text.startsWith("/")) return true;
12
+ if (input.replyToFromId !== void 0 && input.replyToFromId === policy.botId) return true;
13
+ return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);
14
+ }
15
+ function shouldRespondInChat(ctx, policy) {
16
+ const chat = ctx.chat;
17
+ if (chat === void 0) return false;
18
+ return shouldRespond(
19
+ {
20
+ chatType: chat.type,
21
+ text: ctx.message?.text ?? ctx.message?.caption ?? "",
22
+ replyToFromId: ctx.message?.reply_to_message?.from?.id
23
+ },
24
+ policy
25
+ );
26
+ }
27
+ function stripBotMention(text, botUsername) {
28
+ const regex = new RegExp(`@${botUsername}`, "gi");
29
+ return text.replace(regex, "").trim();
30
+ }
31
+
32
+ // src/inline-keyboard.ts
33
+ var TELEGRAM_BUTTONS = { actionKinds: ["url", "web_app"] };
34
+ function refusal(code, message) {
35
+ return { ok: false, error: { code, message } };
36
+ }
37
+ function absoluteUrl(value) {
38
+ if (typeof value !== "string") return void 0;
39
+ try {
40
+ return new URL(value);
41
+ } catch {
42
+ return void 0;
43
+ }
44
+ }
45
+ function urlButton(label, url, at) {
46
+ if (absoluteUrl(url) === void 0) {
47
+ return refusal("invalid_buttons", `the URL of ${at} is not an absolute URL`);
48
+ }
49
+ return { text: label, url };
50
+ }
51
+ function webAppButton(label, url, at, channelType) {
52
+ if (channelType !== "dm") {
53
+ return refusal(
54
+ "buttons_unsupported",
55
+ "telegram adapter sends a web_app button only in a private chat"
56
+ );
57
+ }
58
+ if (absoluteUrl(url)?.protocol !== "https:") {
59
+ return refusal("invalid_buttons", `the web_app URL of ${at} must be an absolute https: URL`);
60
+ }
61
+ return { text: label, web_app: { url } };
62
+ }
63
+ function toInlineButton(button, at, channelType) {
64
+ if (typeof button?.label !== "string" || button.label.trim() === "") {
65
+ return refusal("invalid_buttons", `${at} has no label`);
66
+ }
67
+ const action = button.action;
68
+ switch (action?.kind) {
69
+ case "url":
70
+ return urlButton(button.label, action.url, at);
71
+ case "web_app":
72
+ return webAppButton(button.label, action.url, at, channelType);
73
+ case "callback":
74
+ return refusal("buttons_unsupported", "telegram adapter cannot send a callback button");
75
+ default:
76
+ return refusal("invalid_buttons", `${at} has no known action kind`);
77
+ }
78
+ }
79
+ function keyboardRow(buttons, row, channelType) {
80
+ if (!Array.isArray(buttons) || buttons.length === 0) {
81
+ return refusal("invalid_buttons", `button row ${row + 1} is empty`);
82
+ }
83
+ const line = [];
84
+ for (const [column, button] of buttons.entries()) {
85
+ const mapped = toInlineButton(button, `button ${column + 1} of row ${row + 1}`, channelType);
86
+ if ("ok" in mapped) return mapped;
87
+ line.push(mapped);
88
+ }
89
+ return line;
90
+ }
91
+ function inlineKeyboardOf(out) {
92
+ const rows = out.buttons;
93
+ if (rows == null || rows.length === 0) return {};
94
+ if (out.attachments != null && out.attachments.length !== 0) {
95
+ return refusal("buttons_unsupported", "telegram adapter cannot send buttons with attachments");
96
+ }
97
+ if (!Array.isArray(rows)) return refusal("invalid_buttons", "buttons is not a list of rows");
98
+ const keyboard = [];
99
+ for (const [row, buttons] of rows.entries()) {
100
+ const line = keyboardRow(buttons, row, out.channel.type);
101
+ if (!Array.isArray(line)) return line;
102
+ keyboard.push(line);
103
+ }
104
+ return { reply_markup: { inline_keyboard: keyboard } };
105
+ }
106
+ function isRefusal(value) {
107
+ return "ok" in value;
108
+ }
109
+
110
+ // src/parse-inbound.ts
111
+ function buildEvent(chat, msg, from, raw) {
112
+ let channelType;
113
+ if (chat.type === "private") {
114
+ channelType = "dm";
115
+ } else if (msg.message_thread_id !== void 0) {
116
+ channelType = "thread";
117
+ } else {
118
+ channelType = "group";
119
+ }
120
+ return {
121
+ id: `tg-${chat.id}-${msg.message_id}`,
122
+ platform: "telegram",
123
+ sender: {
124
+ id: String(from?.id ?? "anonymous"),
125
+ ...from?.username !== void 0 ? { username: from.username } : {},
126
+ ...from?.first_name !== void 0 ? { displayName: from.first_name } : {}
127
+ },
128
+ channel: {
129
+ id: String(chat.id),
130
+ type: channelType,
131
+ ...msg.message_thread_id !== void 0 ? { topicId: String(msg.message_thread_id) } : {}
132
+ },
133
+ text: msg.text ?? msg.caption ?? "",
134
+ // Telegram sends seconds; the canonical event is milliseconds.
135
+ receivedAt: msg.date * 1e3,
136
+ ...msg.reply_to_message?.message_id !== void 0 ? { replyTo: String(msg.reply_to_message.message_id) } : {},
137
+ telegram: {
138
+ chatId: chat.id,
139
+ messageId: msg.message_id,
140
+ ...msg.message_thread_id !== void 0 ? { threadId: msg.message_thread_id } : {},
141
+ raw
142
+ }
143
+ };
144
+ }
145
+ function isRecord(value) {
146
+ return typeof value === "object" && value !== null && !Array.isArray(value);
147
+ }
148
+ function narrowMessage(msg, messageId, date) {
149
+ const threadId = msg.message_thread_id;
150
+ const replyTo = msg.reply_to_message;
151
+ return {
152
+ message_id: messageId,
153
+ date,
154
+ ...typeof msg.text === "string" ? { text: msg.text } : {},
155
+ ...typeof msg.caption === "string" ? { caption: msg.caption } : {},
156
+ ...typeof threadId === "number" && Number.isFinite(threadId) ? { message_thread_id: threadId } : {},
157
+ ...isRecord(replyTo) && typeof replyTo.message_id === "number" && Number.isFinite(replyTo.message_id) ? { reply_to_message: { message_id: replyTo.message_id } } : {}
158
+ };
159
+ }
160
+ function narrowSender(value) {
161
+ if (!isRecord(value)) return void 0;
162
+ if (typeof value.id !== "number" || !Number.isFinite(value.id)) return void 0;
163
+ return {
164
+ id: value.id,
165
+ ...typeof value.username === "string" ? { username: value.username } : {},
166
+ ...typeof value.first_name === "string" ? { first_name: value.first_name } : {}
167
+ };
168
+ }
169
+ function parseInbound(payload) {
170
+ if (!isRecord(payload)) return null;
171
+ const msg = payload.message;
172
+ if (!isRecord(msg)) return null;
173
+ const messageId = msg.message_id;
174
+ const date = msg.date;
175
+ if (typeof messageId !== "number" || !Number.isFinite(messageId)) return null;
176
+ if (typeof date !== "number" || !Number.isFinite(date * 1e3)) return null;
177
+ const chat = msg.chat;
178
+ if (!isRecord(chat)) return null;
179
+ if (typeof chat.id !== "number" || !Number.isFinite(chat.id)) return null;
180
+ if (typeof chat.type !== "string") return null;
181
+ return buildEvent(
182
+ { id: chat.id, type: chat.type },
183
+ narrowMessage(msg, messageId, date),
184
+ narrowSender(msg.from),
185
+ payload
186
+ );
187
+ }
188
+
189
+ // src/read-voice.ts
190
+ var MAX_VOICE_BYTES = 20 * 1024 * 1024;
191
+ var READ_TIMEOUT_MS = 3e4;
192
+ var DEFAULT_API_BASE = "https://api.telegram.org";
193
+ var DEFAULT_MEDIA_TYPE = "audio/ogg";
194
+ var DEFAULT_AUDIO_FILE_MEDIA_TYPE = "audio/mpeg";
195
+ var VoiceReadError = class extends Error {
196
+ constructor(reason) {
197
+ super(`voice not read: ${reason}`);
198
+ this.reason = reason;
199
+ }
200
+ reason;
201
+ name = "VoiceReadError";
202
+ };
203
+ var AudioReadError = class extends Error {
204
+ constructor(reason) {
205
+ super(`audio not read: ${reason}`);
206
+ this.reason = reason;
207
+ }
208
+ reason;
209
+ name = "AudioReadError";
210
+ };
211
+ function deferVoice(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
212
+ const voice = ctx.message?.voice ?? {};
213
+ return deferMessageAudio(ctx, voice, DEFAULT_MEDIA_TYPE, token, {
214
+ onFailure,
215
+ toError: (reason) => new VoiceReadError(reason),
216
+ fetchImpl,
217
+ apiBase
218
+ });
219
+ }
220
+ function deferAudioFile(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
221
+ const audio = ctx.message?.audio ?? {};
222
+ return deferMessageAudio(ctx, audio, DEFAULT_AUDIO_FILE_MEDIA_TYPE, token, {
223
+ onFailure,
224
+ toError: (reason) => new AudioReadError(reason),
225
+ fetchImpl,
226
+ apiBase
227
+ });
228
+ }
229
+ function deferMessageAudio(ctx, fields, defaultMediaType, token, settings) {
230
+ let pending;
231
+ const fetchBytes = async () => {
232
+ const result = await readMessageFile(ctx, fields, token, settings.fetchImpl, settings.apiBase);
233
+ if ("reason" in result) {
234
+ settings.onFailure(result.reason);
235
+ throw settings.toError(result.reason);
236
+ }
237
+ return result.data;
238
+ };
239
+ return {
240
+ read: () => pending ??= fetchBytes(),
241
+ ...typeof fields.file_size === "number" ? { size: fields.file_size } : {},
242
+ ...audioDetails(fields, defaultMediaType)
243
+ };
244
+ }
245
+ async function readMessageFile(ctx, fields, token, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
246
+ if (typeof fields.file_id !== "string") return { reason: "no_file_id" };
247
+ if (typeof fields.file_size === "number" && fields.file_size > MAX_VOICE_BYTES) {
248
+ return { reason: "too_large" };
249
+ }
250
+ const controller = new AbortController();
251
+ const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);
252
+ try {
253
+ const path = await filePath(ctx, controller.signal);
254
+ if (typeof path !== "string") return path;
255
+ const url = `${apiBase}/file/bot${token}/${path}`;
256
+ const bytes = await download(url, fetchImpl, controller.signal);
257
+ if (!(bytes instanceof Uint8Array)) return bytes;
258
+ return { data: bytes };
259
+ } finally {
260
+ clearTimeout(timer);
261
+ }
262
+ }
263
+ function audioDetails(voice, defaultMediaType) {
264
+ const duration = voice.duration;
265
+ return {
266
+ mediaType: typeof voice.mime_type === "string" ? voice.mime_type : defaultMediaType,
267
+ durationSeconds: typeof duration === "number" && Number.isFinite(duration) ? duration : 0
268
+ };
269
+ }
270
+ async function filePath(ctx, signal) {
271
+ let file;
272
+ try {
273
+ file = await ctx.getFile(signal);
274
+ } catch {
275
+ return { reason: signal.aborted ? "timeout" : "get_file_failed" };
276
+ }
277
+ return file.file_path ?? { reason: "no_file_path" };
278
+ }
279
+ async function download(url, fetchImpl, signal) {
280
+ try {
281
+ const response = await fetchImpl(url, { signal });
282
+ if (!response.ok) return { reason: `download_status_${response.status}` };
283
+ if (response.body === null) return { reason: "download_failed" };
284
+ return await readBounded(response.body, signal);
285
+ } catch {
286
+ return { reason: signal.aborted ? "timeout" : "download_failed" };
287
+ }
288
+ }
289
+ async function readBounded(body, signal) {
290
+ const reader = body.getReader();
291
+ const cancel = () => void reader.cancel().catch(() => void 0);
292
+ signal.addEventListener("abort", cancel, { once: true });
293
+ try {
294
+ const chunks = await readChunks(reader);
295
+ if (signal.aborted) return { reason: "timeout" };
296
+ return chunks ?? { reason: "too_large" };
297
+ } finally {
298
+ signal.removeEventListener("abort", cancel);
299
+ }
300
+ }
301
+ async function readChunks(reader) {
302
+ const chunks = [];
303
+ let total = 0;
304
+ for (; ; ) {
305
+ const { done, value } = await reader.read();
306
+ if (done) break;
307
+ total += value.length;
308
+ if (total > MAX_VOICE_BYTES) {
309
+ await reader.cancel();
310
+ return void 0;
311
+ }
312
+ chunks.push(value);
313
+ }
314
+ const bytes = new Uint8Array(total);
315
+ let offset = 0;
316
+ for (const chunk of chunks) {
317
+ bytes.set(chunk, offset);
318
+ offset += chunk.length;
319
+ }
320
+ return bytes;
321
+ }
322
+
323
+ // src/read-document.ts
324
+ var UNKNOWN_MEDIA_TYPE = "application/octet-stream";
325
+ var DocumentReadError = class extends Error {
326
+ constructor(reason) {
327
+ super(`document not read: ${reason}`);
328
+ this.reason = reason;
329
+ }
330
+ reason;
331
+ name = "DocumentReadError";
332
+ };
333
+ function deferDocument(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
334
+ const document = ctx.message?.document;
335
+ if (document === void 0 || document === null) return void 0;
336
+ let pending;
337
+ const fetchBytes = async () => {
338
+ const result = await readMessageFile(ctx, document, token, fetchImpl, apiBase);
339
+ if ("reason" in result) {
340
+ onFailure(result.reason);
341
+ throw new DocumentReadError(result.reason);
342
+ }
343
+ return result.data;
344
+ };
345
+ return {
346
+ read: () => {
347
+ pending ??= fetchBytes();
348
+ return pending;
349
+ },
350
+ mediaType: typeof document.mime_type === "string" ? document.mime_type : UNKNOWN_MEDIA_TYPE,
351
+ ...typeof document.file_size === "number" ? { size: document.file_size } : {},
352
+ ...typeof document.file_name === "string" ? { filename: document.file_name } : {}
353
+ };
354
+ }
355
+
356
+ // src/refuse-attachments.ts
357
+ function refuseAttachments(out) {
358
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
359
+ return {
360
+ ok: false,
361
+ error: {
362
+ code: "attachments_unsupported",
363
+ message: "telegram adapter cannot attach to an edit"
364
+ }
365
+ };
366
+ }
367
+
368
+ // src/split.ts
369
+ var TELEGRAM_MAX_MESSAGE = 4096;
370
+ var SAFE_CHUNK = 4e3;
371
+ function splitForTelegram(text) {
372
+ if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];
373
+ const parts = [];
374
+ let remaining = text;
375
+ while (remaining.length > 0) {
376
+ if (remaining.length <= SAFE_CHUNK) {
377
+ parts.push(remaining);
378
+ break;
379
+ }
380
+ let boundary = findBoundary(remaining);
381
+ const afterRow = takeRowSafe(parts, remaining, boundary);
382
+ if (afterRow !== void 0) {
383
+ remaining = afterRow;
384
+ continue;
385
+ }
386
+ const rawChunk = remaining.slice(0, boundary);
387
+ const balanced = balanceMarkdownPairs(rawChunk);
388
+ const chunk = balanced.length > 0 ? balanced : rawChunk;
389
+ boundary = chunk.length;
390
+ const [piece, reopen] = closeFence(chunk);
391
+ parts.push(piece);
392
+ remaining = reopen + remaining.slice(boundary).replace(/^\n+/, "");
393
+ }
394
+ return parts;
395
+ }
396
+ function findBoundary(remaining) {
397
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
398
+ if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
399
+ return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;
400
+ }
401
+ function takeRowSafe(parts, remaining, boundary) {
402
+ const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);
403
+ if (moved === void 0) return void 0;
404
+ const [piece, reopen] = closeFence(remaining.slice(0, moved.end));
405
+ parts.push(piece);
406
+ return reopen + remaining.slice(moved.start);
407
+ }
408
+ var isLineEnd = (ch) => ch === "\n" || ch === "\r";
409
+ function rowSafeCut(text, cut, window) {
410
+ const start = tableRowStart(text, cut);
411
+ if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
412
+ let end = start;
413
+ while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
414
+ return end > 0 ? { end, start } : void 0;
415
+ }
416
+ function tableRowStart(text, cut) {
417
+ if (cut >= text.length || isLineEnd(text[cut])) return void 0;
418
+ let start = cut;
419
+ while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
420
+ return start > 0 && /^[^\S\r\n]*\|/.test(text.slice(start, cut + 1)) ? start : void 0;
421
+ }
422
+ function rowLength(text, start, cut, window) {
423
+ let rowEnd = cut;
424
+ while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
425
+ return rowEnd - start;
426
+ }
427
+ var FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
428
+ var MAX_INFO = 40;
429
+ function fencedRanges(text) {
430
+ const ranges = [];
431
+ let open;
432
+ let pos = 0;
433
+ for (const line of text.split("\n")) {
434
+ open = stepFence(open, line, pos, ranges);
435
+ pos += line.length + 1;
436
+ }
437
+ if (open !== void 0) ranges.push([open.start, text.length]);
438
+ return ranges;
439
+ }
440
+ function stepFence(open, line, pos, ranges) {
441
+ const m = FENCE_LINE.exec(line.replace(/\r$/, ""));
442
+ const marker = m?.[1];
443
+ if (marker === void 0) return open;
444
+ if (open === void 0) return { fence: { marker, info: (m?.[2] ?? "").trim() }, start: pos };
445
+ if (!closesFence(open.fence, marker, m?.[2] ?? "")) return open;
446
+ ranges.push([open.start, pos + line.length]);
447
+ return void 0;
448
+ }
449
+ function closesFence(fence, marker, rest) {
450
+ return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === "";
451
+ }
452
+ function openFenceAt(text) {
453
+ const last = fencedRanges(text).at(-1);
454
+ if (last === void 0 || last[1] !== text.length) return void 0;
455
+ const lines = text.slice(last[0]).split("\n");
456
+ const opener = FENCE_LINE.exec(lines[0] ?? "");
457
+ const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? "").replace(/\r$/, "")) : null;
458
+ if (opener?.[1] === void 0) return void 0;
459
+ const fence = { marker: opener[1], info: (opener[2] ?? "").trim().slice(0, MAX_INFO) };
460
+ if (closer?.[1] !== void 0 && closesFence(fence, closer[1], closer[2] ?? "")) return void 0;
461
+ return fence;
462
+ }
463
+ function closeFence(chunk) {
464
+ const open = openFenceAt(chunk);
465
+ if (open === void 0) return [chunk, ""];
466
+ return [`${chunk}
467
+ ${open.marker}`, `${open.marker}${open.info}
468
+ `];
469
+ }
470
+ function balanceMarkdownPairs(chunk) {
471
+ const markers = ["**", "__", "~~", "`"];
472
+ let out = chunk;
473
+ for (const m of markers) {
474
+ const outside = markerIndexes(out, m);
475
+ if (outside.length % 2 === 1) {
476
+ out = out.slice(0, outside[outside.length - 1]).trimEnd();
477
+ }
478
+ }
479
+ return out;
480
+ }
481
+ function markerIndexes(text, needle) {
482
+ const ranges = fencedRanges(text);
483
+ const found = [];
484
+ let pos = 0;
485
+ while (true) {
486
+ const at = text.indexOf(needle, pos);
487
+ if (at === -1) break;
488
+ pos = at + needle.length;
489
+ if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);
490
+ }
491
+ return found;
492
+ }
493
+
494
+ // src/send-photos.ts
495
+ var CAPTION_LIMIT = 1024;
496
+ var MAX_PHOTO_BYTES = 10 * 1024 * 1024;
497
+ var MAX_AUDIO_BYTES = 50 * 1024 * 1024;
498
+ var TELEGRAM_FILE_UPLOAD = { maxBytes: MAX_AUDIO_BYTES };
499
+ var KIND_LIMITS = {
500
+ image: { maxBytes: MAX_PHOTO_BYTES, label: "an image", bound: "10 MiB" },
501
+ audio: { maxBytes: MAX_AUDIO_BYTES, label: "an audio", bound: "50 MiB" }
502
+ };
503
+ var MAX_PHOTOS_PER_SEND = 10;
504
+ function hasAttachments(out) {
505
+ return out.attachments != null && out.attachments.length !== 0;
506
+ }
507
+ async function sendPhotos(api, out) {
508
+ const chatId = Number(out.channel.id);
509
+ if (Number.isNaN(chatId)) {
510
+ return {
511
+ ok: false,
512
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
513
+ };
514
+ }
515
+ const refusal2 = validateAttachments(out.attachments);
516
+ if (refusal2 !== void 0) return refusal2;
517
+ const payloads = await payloadsOf(out.attachments);
518
+ if ("error" in payloads) return { ok: false, error: payloads.error };
519
+ const shared = sharedOptions(out);
520
+ try {
521
+ let lastId = await sendEachAttachment(api, chatId, out, payloads, shared);
522
+ if (out.text.length > CAPTION_LIMIT) {
523
+ for (const chunk of splitForTelegram(out.text)) {
524
+ lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts))).message_id;
525
+ }
526
+ }
527
+ return { ok: true, messageId: String(lastId) };
528
+ } catch (err) {
529
+ return mapSendError(err);
530
+ }
531
+ }
532
+ async function payloadsOf(attachments) {
533
+ const payloads = [];
534
+ for (const attachment of attachments) {
535
+ if (attachment.kind !== "file") {
536
+ payloads.push({
537
+ kind: attachment.kind,
538
+ bytes: attachment.data,
539
+ filename: attachment.filename
540
+ });
541
+ continue;
542
+ }
543
+ const read = await loopzeroGateway.readFileAttachment(attachment, TELEGRAM_FILE_UPLOAD.maxBytes);
544
+ if (!read.ok) return { error: read.error };
545
+ payloads.push({ kind: "file", bytes: read.bytes, filename: attachment.filename });
546
+ }
547
+ return payloads;
548
+ }
549
+ async function sendEachAttachment(api, chatId, out, payloads, shared) {
550
+ const caption = captionOf(out.text);
551
+ let lastId = 0;
552
+ for (const [index, payload] of payloads.entries()) {
553
+ const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
554
+ const msg = await withPlainFallback(options, (opts) => {
555
+ const file = new grammy.InputFile(payload.bytes, payload.filename);
556
+ if (payload.kind === "audio") return api.sendVoice(chatId, file, opts);
557
+ if (payload.kind === "file") return api.sendDocument(chatId, file, opts);
558
+ return api.sendPhoto(chatId, file, opts);
559
+ });
560
+ lastId = msg.message_id;
561
+ }
562
+ return lastId;
563
+ }
564
+ async function withPlainFallback(options, send) {
565
+ try {
566
+ return await send(options);
567
+ } catch (err) {
568
+ if (options.parse_mode === void 0) throw err;
569
+ const mapped = mapSendError(err);
570
+ if (mapped.ok || mapped.error?.code !== "markdown_error") throw err;
571
+ process.stderr.write(
572
+ `[loopzero-gateway-telegram] ${mapped.error.message}; resending as plain text
573
+ `
574
+ );
575
+ const { parse_mode: _dropped, ...plain } = options;
576
+ return send(plain);
577
+ }
578
+ }
579
+ function captionOf(text) {
580
+ return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : void 0;
581
+ }
582
+ function firstPhotoOptions(out, caption) {
583
+ return {
584
+ ...caption !== void 0 ? { caption } : {},
585
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
586
+ };
587
+ }
588
+ function sharedOptions(out) {
589
+ const parseMode = mapFormat(out.format);
590
+ const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
591
+ return {
592
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
593
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {}
594
+ };
595
+ }
596
+ function validateAttachments(attachments) {
597
+ if (!Array.isArray(attachments)) {
598
+ return refuse("invalid_attachment", "attachments is not a list");
599
+ }
600
+ if (attachments.length > MAX_PHOTOS_PER_SEND) {
601
+ return refuse(
602
+ "invalid_attachment",
603
+ `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`
604
+ );
605
+ }
606
+ for (const attachment of attachments) {
607
+ const refusal2 = validateAttachment(attachment);
608
+ if (refusal2 !== void 0) return refusal2;
609
+ }
610
+ return void 0;
611
+ }
612
+ function validateAttachment(attachment) {
613
+ if (typeof attachment !== "object" || attachment === null) {
614
+ return refuse("invalid_attachment", "an attachment is not an object");
615
+ }
616
+ if (attachment.kind === "file") {
617
+ return loopzeroGateway.refuseFileAttachment(attachment, TELEGRAM_FILE_UPLOAD, "telegram");
618
+ }
619
+ if (attachment.kind !== "image" && attachment.kind !== "audio") {
620
+ return refuse(
621
+ "attachments_unsupported",
622
+ "telegram adapter sends only image, audio and file attachments"
623
+ );
624
+ }
625
+ const limit = KIND_LIMITS[attachment.kind];
626
+ if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {
627
+ return refuse("invalid_attachment", `${limit.label} attachment has no bytes`);
628
+ }
629
+ if (attachment.data.length > limit.maxBytes) {
630
+ return refuse(
631
+ "invalid_attachment",
632
+ `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`
633
+ );
634
+ }
635
+ return mediaTypeRefusal(attachment);
636
+ }
637
+ function mediaTypeRefusal(attachment) {
638
+ if (attachment.kind !== "audio") return void 0;
639
+ const mediaType = typeof attachment.mediaType === "string" ? attachment.mediaType : "";
640
+ if (mediaType.toLowerCase().startsWith("audio/")) return void 0;
641
+ return refuse("invalid_attachment", `an audio attachment has media type "${mediaType}"`);
642
+ }
643
+ function refuse(code, message) {
644
+ return { ok: false, error: { code, message } };
645
+ }
646
+ function mapFormat(format) {
647
+ if (format === "markdown") return "Markdown";
648
+ if (format === "html") return "HTML";
649
+ return void 0;
650
+ }
651
+ function parseModeOptions(format) {
652
+ const parseMode = mapFormat(format);
653
+ return parseMode !== void 0 ? { parse_mode: parseMode } : {};
654
+ }
655
+ function mapGrammyError(err) {
656
+ const message = err.description ?? err.message;
657
+ const description = message.toLowerCase();
658
+ if (description.includes("rate limit") || err.error_code === 429) {
659
+ const retryAfter = err.parameters?.retry_after;
660
+ return {
661
+ ok: false,
662
+ error: {
663
+ code: "rate_limit",
664
+ message,
665
+ ...typeof retryAfter === "number" ? { retryAfterMs: retryAfter * 1e3 } : {}
666
+ }
667
+ };
668
+ }
669
+ if (description.includes("forbidden") || err.error_code === 403) {
670
+ return {
671
+ ok: false,
672
+ error: { code: "permission_denied", message, platformCode: String(err.error_code) }
673
+ };
674
+ }
675
+ if (description.includes("parse")) {
676
+ return { ok: false, error: { code: "markdown_error", message } };
677
+ }
678
+ return { ok: false, error: { code: `telegram_${err.error_code ?? "unknown"}`, message } };
679
+ }
680
+ function mapSendError(err) {
681
+ if (err instanceof grammy.GrammyError) return mapGrammyError(err);
682
+ if (err instanceof grammy.HttpError) {
683
+ return { ok: false, error: { code: "network_error", message: err.message } };
684
+ }
685
+ return { ok: false, error: { code: "unknown", message: err.message } };
686
+ }
687
+
688
+ // src/adapter.ts
689
+ function isObj(v) {
690
+ return typeof v === "object" && v !== null;
691
+ }
692
+ function policyInput(event) {
693
+ const raw = event.telegram?.raw;
694
+ const msg = isObj(raw) && isObj(raw.message) ? raw.message : void 0;
695
+ const replyTo = msg !== void 0 && isObj(msg.reply_to_message) ? msg.reply_to_message : void 0;
696
+ const from = replyTo !== void 0 && isObj(replyTo.from) ? replyTo.from : void 0;
697
+ return {
698
+ chatType: event.channel.type === "dm" ? "private" : "group",
699
+ text: event.text,
700
+ replyToFromId: typeof from?.id === "number" ? from.id : void 0
701
+ };
702
+ }
703
+ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
704
+ get capabilities() {
705
+ return { ...super.capabilities, maxMessageChars: TELEGRAM_MAX_MESSAGE, threads: true };
706
+ }
707
+ platform = "telegram";
708
+ bot;
709
+ allowedUsers;
710
+ handler;
711
+ inbound;
712
+ requireMention;
713
+ apiBase;
714
+ warnedNoIdentity = false;
715
+ connected = false;
716
+ startPromise;
717
+ constructor(opts) {
718
+ super();
719
+ this.apiBase = opts.apiBase === void 0 ? void 0 : opts.apiBase.replace(/\/+$/, "");
720
+ this.bot = new grammy.Bot(
721
+ opts.token,
722
+ this.apiBase === void 0 ? void 0 : { client: { apiRoot: this.apiBase } }
723
+ );
724
+ this.allowedUsers = new Set(opts.allowedUsers ?? []);
725
+ this.inbound = opts.inbound ?? "polling";
726
+ this.requireMention = opts.requireMention === true;
727
+ this.bot.on("message", async (ctx) => this.handleInbound(ctx));
728
+ this.bot.catch((err) => {
729
+ process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
730
+ `);
731
+ });
732
+ }
733
+ /**
734
+ * Expose the underlying grammy `Bot` so consumers can register
735
+ * grammy-specific event handlers that don't fit the portable
736
+ * contract — `callbackQuery`, `bot.on(":voice")`, `bot.command(...)`,
737
+ * etc. Register BEFORE calling `runner.start()`.
738
+ *
739
+ * @public
740
+ */
741
+ getBot() {
742
+ return this.bot;
743
+ }
744
+ async connect() {
745
+ if (this.connected) return true;
746
+ try {
747
+ await this.bot.init();
748
+ } catch (err) {
749
+ process.stderr.write(`[telegram] connect failed: ${err.message}
750
+ `);
751
+ return false;
752
+ }
753
+ if (this.inbound === "polling")
754
+ this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {
755
+ process.stderr.write(`[telegram] polling stopped: ${err.message}
756
+ `);
757
+ });
758
+ this.connected = true;
759
+ return true;
760
+ }
761
+ async disconnect() {
762
+ if (!this.connected) return;
763
+ this.connected = false;
764
+ if (this.inbound === "webhook") return;
765
+ try {
766
+ await this.bot.stop();
767
+ } catch (cause) {
768
+ const message = cause instanceof Error ? cause.message : String(cause);
769
+ process.stderr.write(
770
+ `[loopzero-gateway-telegram] bot.stop() failed during disconnect: ${message}
771
+ `
772
+ );
773
+ }
774
+ if (this.startPromise !== void 0) {
775
+ await this.startPromise.catch(() => void 0);
776
+ this.startPromise = void 0;
777
+ }
778
+ }
779
+ // 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.
780
+ async sendMessage(out) {
781
+ const keyboard = inlineKeyboardOf(out);
782
+ if (isRefusal(keyboard)) return keyboard;
783
+ if (hasAttachments(out)) return sendPhotos(this.bot.api, out);
784
+ if (out.text.length === 0) {
785
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
786
+ }
787
+ const chatIdNum = Number(out.channel.id);
788
+ if (Number.isNaN(chatIdNum)) {
789
+ return {
790
+ ok: false,
791
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
792
+ };
793
+ }
794
+ const parseMode = mapFormat(out.format);
795
+ const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
796
+ const chunks = splitForTelegram(out.text);
797
+ let lastId;
798
+ for (const [index, chunk] of chunks.entries()) {
799
+ try {
800
+ const msg = await withPlainFallback(
801
+ {
802
+ // The keyboard belongs under the whole reply, so only the last part carries it.
803
+ ...index === chunks.length - 1 ? keyboard : {},
804
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
805
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {},
806
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
807
+ },
808
+ (opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts)
809
+ );
810
+ lastId = String(msg.message_id);
811
+ } catch (err) {
812
+ return mapSendError(err);
813
+ }
814
+ }
815
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
816
+ }
817
+ /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
818
+ supportsAttachments = true;
819
+ /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
820
+ attachmentKinds = ["image", "audio"];
821
+ /** Telegram sends a file through `sendDocument`: any media type, up to 50 MiB. */
822
+ fileUpload = TELEGRAM_FILE_UPLOAD;
823
+ /**
824
+ * Telegram shows rows of buttons under a message as an inline keyboard: URL buttons, and
825
+ * `web_app` buttons that open a Mini App in a private chat. A `callback` button is refused until
826
+ * the adapter receives `callback_query` updates.
827
+ */
828
+ buttonSupport = TELEGRAM_BUTTONS;
829
+ /** Telegram edits a sent message's text through `editMessageText`. */
830
+ supportsEdit = true;
831
+ /**
832
+ * A streamed reply is previewed by editing one message. Telegram allows about one message per
833
+ * second in a chat, and an edit of up to 4096 characters is one `editMessageText`.
834
+ */
835
+ streamingPreview = {
836
+ minUpdateIntervalMs: 1e3,
837
+ maxCharsPerMessage: () => TELEGRAM_MAX_MESSAGE
838
+ };
839
+ /**
840
+ * Replace the text of a message this bot sent, through `editMessageText`.
841
+ *
842
+ * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no
843
+ * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,
844
+ * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own
845
+ * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit
846
+ * replaces one message. Telegram's "message is not modified" refusal is answered as a success,
847
+ * because the message already shows the text; a caller that treated it as a failure would send
848
+ * the same text again as a second message.
849
+ */
850
+ async editMessage(messageId, out) {
851
+ return refuseAttachments(out) ?? this.editText(messageId, out);
852
+ }
853
+ async editText(messageId, out) {
854
+ const keyboard = inlineKeyboardOf(out);
855
+ if (isRefusal(keyboard)) return keyboard;
856
+ if (out.text.length === 0) {
857
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
858
+ }
859
+ const id = parseMessageId(messageId);
860
+ if (id === void 0) {
861
+ return {
862
+ ok: false,
863
+ error: {
864
+ code: "invalid_message_id",
865
+ message: `message id "${messageId}" is not a positive integer`
866
+ }
867
+ };
868
+ }
869
+ const chatIdNum = Number(out.channel.id);
870
+ if (Number.isNaN(chatIdNum)) {
871
+ return {
872
+ ok: false,
873
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
874
+ };
875
+ }
876
+ const parts = splitForTelegram(out.text);
877
+ if (parts.length !== 1) return editPartsRefusal(parts.length);
878
+ try {
879
+ await this.bot.api.editMessageText(chatIdNum, id, parts[0], {
880
+ ...parseModeOptions(out.format),
881
+ ...keyboard
882
+ });
883
+ } catch (err) {
884
+ if (!isNotModified(err)) return mapSendError(err);
885
+ }
886
+ return { ok: true, messageId };
887
+ }
888
+ async react(channelId, messageId, emoji) {
889
+ const chatId = Number(channelId);
890
+ const id = parseMessageId(messageId);
891
+ if (Number.isNaN(chatId) || id === void 0 || emoji.length === 0) {
892
+ return {
893
+ ok: false,
894
+ error: {
895
+ code: "invalid_reaction",
896
+ message: "numeric channel, message id and emoji needed"
897
+ }
898
+ };
899
+ }
900
+ try {
901
+ await this.bot.api.setMessageReaction(chatId, id, [
902
+ { type: "emoji", emoji }
903
+ ]);
904
+ } catch (err) {
905
+ return mapSendError(err);
906
+ }
907
+ return { ok: true, messageId };
908
+ }
909
+ onInbound(handler) {
910
+ this.handler = handler;
911
+ return () => {
912
+ if (this.handler === handler) this.handler = void 0;
913
+ };
914
+ }
915
+ async startTyping(channelId) {
916
+ const chatId = Number(channelId);
917
+ if (Number.isNaN(chatId)) return;
918
+ try {
919
+ await this.bot.api.sendChatAction(chatId, "typing");
920
+ } catch {
921
+ }
922
+ }
923
+ async handleInbound(ctx) {
924
+ if (this.handler === void 0) return;
925
+ if (ctx.from?.is_bot === true) return;
926
+ if (this.allowedUsers.size > 0) {
927
+ const senderId = String(ctx.from?.id ?? "");
928
+ if (!this.allowedUsers.has(senderId)) return;
929
+ }
930
+ const normalized = normalizeEvent(ctx);
931
+ if (normalized === void 0) return;
932
+ const event = this.gateMention(normalized);
933
+ if (event === void 0) return;
934
+ await this.dispatchEvent(
935
+ this.withDocument(ctx, this.withVoice(ctx, event))
936
+ );
937
+ }
938
+ /**
939
+ * Marks whether the bot was addressed and applies the `requireMention` gate, shared by the
940
+ * polled and webhook paths. Returns `undefined` when the gate drops the event. A direct message
941
+ * is left unmarked; `addressed` stays unset while the bot's identity is not known.
942
+ */
943
+ gateMention(event) {
944
+ if (event.channel.type === "dm") return event;
945
+ let me;
946
+ try {
947
+ me = this.bot.botInfo;
948
+ } catch {
949
+ me = void 0;
950
+ }
951
+ if (me?.username === void 0) {
952
+ if (!this.requireMention) return event;
953
+ if (!this.warnedNoIdentity) {
954
+ this.warnedNoIdentity = true;
955
+ process.stderr.write(
956
+ "[telegram] requireMention: bot identity not known yet; dropping group message\n"
957
+ );
958
+ }
959
+ return void 0;
960
+ }
961
+ const addressed = shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });
962
+ if (this.requireMention && !addressed) return void 0;
963
+ return { ...event, addressed };
964
+ }
965
+ /**
966
+ * The event with the voice note's audio when the message has one (B-715, ADR D1), or with the
967
+ * audio file's when it carries one instead (`message.audio`, OC-103). A message holds at most
968
+ * one of the two.
969
+ *
970
+ * The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event
971
+ * costs no download. An unreadable voice or audio file rejects `audio.read()` and writes the
972
+ * reason to stderr.
973
+ */
974
+ withVoice(ctx, event) {
975
+ const voice = ctx.message?.voice;
976
+ if (voice !== void 0) {
977
+ if (typeof voice.file_id !== "string") {
978
+ process.stderr.write("[telegram] voice not read: no_file_id\n");
979
+ return event;
980
+ }
981
+ const audio2 = deferVoice(
982
+ ctx,
983
+ this.bot.token,
984
+ (reason) => process.stderr.write(`[telegram] voice not read: ${reason}
985
+ `),
986
+ void 0,
987
+ this.apiBase
988
+ );
989
+ return { ...event, audio: audio2 };
990
+ }
991
+ const audioFile = ctx.message?.audio;
992
+ if (audioFile === void 0) return event;
993
+ if (typeof audioFile.file_id !== "string") {
994
+ process.stderr.write("[telegram] audio not read: no_file_id\n");
995
+ return event;
996
+ }
997
+ const audio = deferAudioFile(
998
+ ctx,
999
+ this.bot.token,
1000
+ (reason) => process.stderr.write(`[telegram] audio not read: ${reason}
1001
+ `),
1002
+ void 0,
1003
+ this.apiBase
1004
+ );
1005
+ return { ...event, audio };
1006
+ }
1007
+ /**
1008
+ * The event with the message's document as `files`, when it has one. Deferred like the voice
1009
+ * note: no request leaves here. An unreadable document rejects `read()` and writes the reason
1010
+ * to stderr.
1011
+ */
1012
+ withDocument(ctx, event) {
1013
+ const file = deferDocument(
1014
+ ctx,
1015
+ this.bot.token,
1016
+ (reason) => process.stderr.write(`[telegram] document not read: ${reason}
1017
+ `),
1018
+ void 0,
1019
+ this.apiBase
1020
+ );
1021
+ return file === void 0 ? event : { ...event, files: [file] };
1022
+ }
1023
+ /**
1024
+ * Dispatch a pre-built event to the current handler, honouring EC-H replace
1025
+ * semantics.
1026
+ *
1027
+ * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H
1028
+ * contract had no honest test without it: a grammy `Context` cannot be
1029
+ * synthesized here, `handler` is private, and the test that claimed to cover
1030
+ * replacement asserted an empty array — true whether onInbound replaces,
1031
+ * stacks, or discards.
1032
+ *
1033
+ * @internal
1034
+ */
1035
+ async dispatchEvent(event) {
1036
+ if (this.handler === void 0) return "no_handler";
1037
+ try {
1038
+ await this.handler(event);
1039
+ } catch (err) {
1040
+ const m = err instanceof Error ? err.message : String(err);
1041
+ process.stderr.write(`[telegram] handler threw: ${m}
1042
+ `);
1043
+ return "handler_threw";
1044
+ }
1045
+ return "ok";
1046
+ }
1047
+ /**
1048
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
1049
+ *
1050
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
1051
+ * named as the handler's failure rather than the platform's, and delivery continues.
1052
+ */
1053
+ async deliver(event) {
1054
+ const gated = this.gateMention(event);
1055
+ if (gated === void 0) return "ok";
1056
+ return this.runHandler(this.handler, gated);
1057
+ }
1058
+ };
1059
+ function normalizeEvent(ctx) {
1060
+ const chat = ctx.chat;
1061
+ const msg = ctx.message;
1062
+ if (chat === void 0 || msg === void 0) return void 0;
1063
+ return buildEvent(chat, msg, ctx.from, ctx);
1064
+ }
1065
+ function parseMessageId(messageId) {
1066
+ if (!/^\d+$/.test(messageId)) return void 0;
1067
+ const id = Number(messageId);
1068
+ return Number.isSafeInteger(id) && id > 0 ? id : void 0;
1069
+ }
1070
+ function isNotModified(err) {
1071
+ return err instanceof grammy.GrammyError && (err.description ?? "").toLowerCase().includes("message is not modified");
1072
+ }
1073
+ function editPartsRefusal(partCount) {
1074
+ if (partCount > 1) {
1075
+ return {
1076
+ ok: false,
1077
+ error: {
1078
+ code: "edit_too_long",
1079
+ message: `text needs ${partCount} Telegram messages; an edit replaces one`
1080
+ }
1081
+ };
1082
+ }
1083
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
1084
+ }
1085
+ var ConfigurationError = class extends loopzeroGateway.GatewayConfigurationError {
1086
+ name = "ConfigurationError";
1087
+ constructor(opts) {
1088
+ super("gateway-telegram", opts);
1089
+ }
1090
+ };
1091
+
1092
+ // src/channel.ts
1093
+ function invalid(key, expected) {
1094
+ return new ConfigurationError({
1095
+ code: "invalid_config",
1096
+ message: `gateway-telegram: config.${key} must be ${expected}`,
1097
+ detail: key
1098
+ });
1099
+ }
1100
+ function readToken(config) {
1101
+ const token = config.token;
1102
+ if (typeof token !== "string") throw invalid("token", "a string");
1103
+ if (token.length === 0) {
1104
+ throw new ConfigurationError({
1105
+ code: "token_required",
1106
+ message: "gateway-telegram: config.token is empty",
1107
+ detail: "token"
1108
+ });
1109
+ }
1110
+ return token;
1111
+ }
1112
+ function readAllowedUsers(config) {
1113
+ const value = config.allowedUsers;
1114
+ if (value === void 0 || value === null) return void 0;
1115
+ const expected = "an array of user id strings or a comma-separated string of user ids";
1116
+ const ids = typeof value === "string" ? value.split(",").map((id) => id.trim()) : value;
1117
+ if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) {
1118
+ throw invalid("allowedUsers", expected);
1119
+ }
1120
+ return ids;
1121
+ }
1122
+ function readRequireMention(config) {
1123
+ const value = config.requireMention;
1124
+ if (value === void 0) return void 0;
1125
+ if (value === "true") return true;
1126
+ if (value === "false") return false;
1127
+ if (typeof value !== "boolean") throw invalid("requireMention", "a boolean");
1128
+ return value;
1129
+ }
1130
+ function readApiBase(config) {
1131
+ const value = config.apiBase;
1132
+ if (value === void 0 || value === null) return void 0;
1133
+ if (typeof value !== "string" || value.length === 0)
1134
+ throw invalid("apiBase", "a non-empty URL string");
1135
+ return value;
1136
+ }
1137
+ var CONFIG = [
1138
+ {
1139
+ key: "token",
1140
+ env: "TELEGRAM_TOKEN",
1141
+ required: true,
1142
+ secret: true,
1143
+ description: "The bot token BotFather issued for this bot."
1144
+ },
1145
+ {
1146
+ key: "allowedUsers",
1147
+ env: "TELEGRAM_ALLOWED_USERS",
1148
+ required: false,
1149
+ secret: false,
1150
+ description: "Telegram user ids allowed to reach the handler; absent or empty allows everyone."
1151
+ },
1152
+ {
1153
+ key: "apiBase",
1154
+ env: "TELEGRAM_API_BASE",
1155
+ required: false,
1156
+ secret: false,
1157
+ description: "Bot API root, for a self-hosted Bot API server; default https://api.telegram.org."
1158
+ },
1159
+ {
1160
+ key: "requireMention",
1161
+ required: false,
1162
+ secret: false,
1163
+ description: "When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false."
1164
+ }
1165
+ ];
1166
+ var telegramChannel = {
1167
+ platform: "telegram",
1168
+ transport: "socket",
1169
+ senderIdentity: "authenticated",
1170
+ config: CONFIG,
1171
+ create(config) {
1172
+ const token = readToken(config);
1173
+ const allowedUsers = readAllowedUsers(config);
1174
+ const requireMention = readRequireMention(config);
1175
+ const apiBase = readApiBase(config);
1176
+ return new TelegramAdapter({
1177
+ token,
1178
+ ...apiBase === void 0 ? {} : { apiBase },
1179
+ ...allowedUsers === void 0 ? {} : { allowedUsers },
1180
+ ...requireMention === void 0 ? {} : { requireMention }
1181
+ });
1182
+ }
1183
+ };
1184
+
1185
+ exports.ConfigurationError = ConfigurationError;
1186
+ exports.TelegramAdapter = TelegramAdapter;
1187
+ exports.parseInbound = parseInbound;
1188
+ exports.shouldRespondInChat = shouldRespondInChat;
1189
+ exports.splitForTelegram = splitForTelegram;
1190
+ exports.stripBotMention = stripBotMention;
1191
+ exports.telegramChannel = telegramChannel;
1192
+ //# sourceMappingURL=index.cjs.map
1193
+ //# sourceMappingURL=index.cjs.map