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