peppa/packages/testkit/src/mock-telegram.ts
Асель fec0a698e7 PEP-143: feedback table, core, feedback agent tick, bot mode and buttons
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 11:23:09 +05:00

327 lines
16 KiB
TypeScript

// Mock Telegram Bot API server for bot tests: the methods Peppa's bot uses, long-polling
// getUpdates, injectable user actions, and failure injection (429 / 5xx).
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
export interface MockTgMessage {
message_id: number;
chat_id: number;
text: string;
reply_markup?: { inline_keyboard: Array<Array<{ text: string; callback_data?: string }>> };
edits: number;
reply_to?: number;
}
export interface MockTgUser {
id: number;
chatId: number;
username?: string;
}
/** Fields of a multipart/form-data body: text fields as strings, files as {filename, mime, data}. */
function parseMultipart(body: Buffer, boundary: string): Record<string, unknown> {
const out: Record<string, unknown> = {};
const delim = Buffer.from(`--${boundary}`);
let at = body.indexOf(delim);
while (at >= 0) {
const next = body.indexOf(delim, at + delim.length);
if (next < 0) break;
const part = body.subarray(at + delim.length + 2, next - 2);
const split = part.indexOf("\r\n\r\n");
if (split >= 0) {
const head = part.subarray(0, split).toString("utf8");
const data = part.subarray(split + 4);
const name = /name="([^"]*)"/.exec(head)?.[1];
const filename = /filename="([^"]*)"/.exec(head)?.[1];
if (name) out[name] = filename !== undefined ? { filename, mime: /content-type:\s*(\S+)/i.exec(head)?.[1] ?? "application/octet-stream", data: Buffer.from(data) } : parseField(data.toString("utf8"));
}
at = next;
}
return out;
}
/** JSON-serialized fields (reply_markup) come back as objects, like a JSON body would carry them. */
function parseField(v: string): unknown {
if (!/^[[{]/.test(v)) return v;
try {
return JSON.parse(v);
} catch {
return v;
}
}
/** Groups have negative ids in Telegram. */
const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
export class MockTelegram {
/** Bot token: methods accept any, files (/file/bot<token>/…) only this one — like Telegram. */
readonly token: string;
/** PEP-85: a second instance stands in for a user's own bot — give it its own identity (and token, PEP-108). */
constructor(bot: { id?: number; username?: string; token?: string } = {}) {
this.token = bot.token ?? "mock-123:TOKEN";
this.bot = { id: bot.id ?? 999, username: bot.username ?? "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
}
readonly bot: { id: number; username: string; is_bot: boolean; first_name: string };
readonly messages = new Map<number, MockTgMessage>();
/** PEP-143: photos the bot uploaded with sendPhoto. */
readonly photos: Array<{ message_id: number; chat_id: number; caption: string; filename: string; mime: string; data: Buffer }> = [];
readonly callbackAnswers: Array<{ id: string; text?: string }> = [];
readonly calls: Array<{ method: string; params: Record<string, unknown> }> = [];
private updates: Array<Record<string, unknown> & { update_id: number }> = [];
private nextUpdateId = 1;
private nextMessageId = 100;
private waiters: Array<() => void> = [];
private failures: Array<{ method: string; code: number; retryAfter?: number }> = [];
private server: Server | null = null;
/** PEP-45: uploaded voice files by file_id (served at /file/bot<token>/<file_path>). */
private files = new Map<string, { path: string; data: Buffer }>();
/** PEP-60: channels by chat id; the bot's membership decides what getChat/sendMessage do. */
readonly channels = new Map<number, { title: string; bot: "administrator" | "member" | "left"; canPost: boolean }>();
url = "";
/** A channel; by default the bot is its admin with the right to post. */
addChannel(chatId: number, title: string, o: { bot?: "administrator" | "member" | "left"; canPost?: boolean } = {}) {
this.channels.set(chatId, { title, bot: o.bot ?? "administrator", canPost: o.canPost ?? true });
}
async start(port = 0): Promise<this> {
this.server = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", async () => {
const raw = Buffer.concat(chunks);
// PEP-143: sendPhoto uploads the file as multipart/form-data.
const boundary = /multipart\/form-data;\s*boundary=(.+)$/i.exec(req.headers["content-type"] ?? "")?.[1];
if (boundary) {
const params = parseMultipart(raw, boundary.replace(/^"|"$/g, ""));
const result = await this.handle(req.url!.split("/").pop()!, params);
res.writeHead(result.ok ? 200 : (result.error_code as number), { "Content-Type": "application/json" });
return res.end(JSON.stringify(result));
}
const body = raw.toString("utf8");
if (req.method === "GET" && req.url!.startsWith(`/file/bot${this.token}/`)) {
const path = decodeURIComponent(req.url!.slice(`/file/bot${this.token}/`.length));
const f = [...this.files.values()].find((x) => x.path === path);
res.writeHead(f ? 200 : 404, { "Content-Type": "application/octet-stream" });
return res.end(f?.data ?? "");
}
if (req.url!.startsWith("/_mock/")) {
const r = this.inspect(req.method!, req.url!, body ? JSON.parse(body) : {});
res.writeHead(r.status, { "Content-Type": "application/json" });
return res.end(JSON.stringify(r.body));
}
const method = req.url!.split("/").pop()!;
const params = body ? (JSON.parse(body) as Record<string, unknown>) : {};
const result = await this.handle(method, params);
res.writeHead(result.ok ? 200 : (result.error_code as number), { "Content-Type": "application/json" });
res.end(JSON.stringify(result));
});
});
await new Promise<void>((r) => this.server!.listen(port, "127.0.0.1", r));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
return this;
}
async stop() {
this.waiters.forEach((w) => w());
await new Promise<void>((r) => this.server?.close(() => r()) ?? r());
}
/** The next call to `method` fails with this code (429 carries retry_after). */
failNext(method: string, code: number, retryAfter?: number) {
this.failures.push({ method, code, retryAfter });
}
private async handle(method: string, p: Record<string, unknown>): Promise<Record<string, unknown>> {
if (method !== "getUpdates") this.calls.push({ method, params: p });
const f = this.failures.findIndex((x) => x.method === method);
if (f >= 0) {
const { code, retryAfter } = this.failures.splice(f, 1)[0]!;
return { ok: false, error_code: code, description: code === 429 ? "Too Many Requests" : "Internal Server Error", ...(retryAfter != null ? { parameters: { retry_after: retryAfter } } : {}) };
}
switch (method) {
case "getMe":
return { ok: true, result: this.bot };
case "getUpdates": {
const offset = Number(p.offset ?? 0);
const timeout = Math.min(Number(p.timeout ?? 0), 1);
const pending = () => this.updates.filter((u) => u.update_id >= offset);
if (!pending().length && timeout > 0) {
await new Promise<void>((r) => {
const t = setTimeout(r, timeout * 1000);
this.waiters.push(() => (clearTimeout(t), r()));
});
}
return { ok: true, result: pending() };
}
case "getChat": {
const c = this.channels.get(Number(p.chat_id));
if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
return { ok: true, result: { id: Number(p.chat_id), type: "channel", title: c.title } };
}
case "getChatMember": {
const c = this.channels.get(Number(p.chat_id));
if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
if (Number(p.user_id) !== this.bot.id) return { ok: false, error_code: 400, description: "Bad Request: user not found" };
return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } };
}
case "sendMessage": {
// Channels added with addChannel: the bot must be an admin that may post. Other «-100…»
// ids are supergroups (PEP-62) and accept messages as before.
const ch = this.channels.get(Number(p.chat_id));
if (ch && ch.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" };
if (ch && (ch.bot !== "administrator" || !ch.canPost)) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" };
const m: MockTgMessage = {
message_id: this.nextMessageId++,
chat_id: Number(p.chat_id),
text: String(p.text),
reply_markup: p.reply_markup as MockTgMessage["reply_markup"],
edits: 0,
reply_to: (p.reply_parameters as { message_id?: number } | undefined)?.message_id,
};
this.messages.set(m.message_id, m);
return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: chatType(m.chat_id) }, text: m.text } };
}
case "sendPhoto": {
const file = p.photo as { filename: string; mime: string; data: Buffer } | undefined;
if (!file || !Buffer.isBuffer(file.data) || !file.data.length) return { ok: false, error_code: 400, description: "Bad Request: there is no photo in the request" };
const m: MockTgMessage = { message_id: this.nextMessageId++, chat_id: Number(p.chat_id), text: String(p.caption ?? ""), edits: 0 };
this.messages.set(m.message_id, m);
this.photos.push({ message_id: m.message_id, chat_id: m.chat_id, caption: m.text, filename: file.filename, mime: file.mime, data: file.data });
return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: chatType(m.chat_id) }, caption: m.text, photo: [{ file_id: `mock-sent-${m.message_id}` }] } };
}
case "editMessageReplyMarkup": {
const m = this.messages.get(Number(p.message_id));
if (!m) return { ok: false, error_code: 400, description: "Bad Request: message to edit not found" };
m.reply_markup = p.reply_markup as MockTgMessage["reply_markup"];
m.edits++;
return { ok: true, result: { message_id: m.message_id } };
}
case "editMessageText": {
const m = this.messages.get(Number(p.message_id));
if (!m) return { ok: false, error_code: 400, description: "Bad Request: message to edit not found" };
if (m.text === p.text) return { ok: false, error_code: 400, description: "Bad Request: message is not modified" };
m.text = String(p.text);
m.reply_markup = p.reply_markup as MockTgMessage["reply_markup"];
m.edits++;
return { ok: true, result: { message_id: m.message_id } };
}
case "getFile": {
const f = this.files.get(String(p.file_id));
if (!f) return { ok: false, error_code: 400, description: "Bad Request: invalid file_id" };
return { ok: true, result: { file_id: p.file_id, file_unique_id: `u-${p.file_id}`, file_size: f.data.length, file_path: f.path } };
}
case "answerCallbackQuery":
this.callbackAnswers.push({ id: String(p.callback_query_id), text: p.text as string | undefined });
return { ok: true, result: true };
default:
return { ok: false, error_code: 404, description: `mock: unknown method ${method}` };
}
}
private push(update: Record<string, unknown>) {
const u = { update_id: this.nextUpdateId++, ...update };
this.updates.push(u);
this.waiters.splice(0).forEach((w) => w());
return u.update_id;
}
/** User sends a text message (optionally as a reply). */
userSends(user: MockTgUser, text: string, replyTo?: number) {
return this.push({
message: {
message_id: this.nextMessageId++,
chat: { id: user.chatId, type: "private" },
from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
text,
...(replyTo ? { reply_to_message: { message_id: replyTo, chat: { id: user.chatId, type: "private" } } } : {}),
},
});
}
/** PEP-62: a user writes in a group (negative chat id, as in Telegram), optionally as a reply. */
userSendsInGroup(user: MockTgUser, group: { id: number; title: string }, text: string, replyTo?: number) {
const chat = { id: group.id, type: "group", title: group.title };
return this.push({
message: {
message_id: this.nextMessageId++,
chat,
from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
text,
...(replyTo ? { reply_to_message: { message_id: replyTo, chat } } : {}),
},
});
}
/** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */
userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) {
const fileId = `mock-voice-${this.nextMessageId}`;
this.files.set(fileId, { path: `voice/file_${this.nextMessageId}.oga`, data: audio });
return this.push({
message: {
message_id: this.nextMessageId++,
chat: { id: user.chatId, type: "private" },
from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
voice: { file_id: fileId, file_unique_id: `u-${fileId}`, duration, mime_type: "audio/ogg", file_size: audio.length },
},
});
}
/** PEP-143: user sends a photo (optionally with a caption, as part of an album, or «as a file»). */
userSendsPhoto(user: MockTgUser, image: Buffer, caption?: string, o: { mediaGroupId?: string; asDocument?: boolean } = {}) {
const fileId = `mock-photo-${this.nextMessageId}`;
this.files.set(fileId, { path: `photos/file_${this.nextMessageId}.jpg`, data: image });
const small = `${fileId}-s`;
this.files.set(small, { path: `photos/file_${this.nextMessageId}_s.jpg`, data: image.subarray(0, 16) });
return this.push({
message: {
message_id: this.nextMessageId++,
chat: { id: user.chatId, type: "private" },
from: { id: user.id, username: user.username, first_name: user.username ?? "user" },
...(o.asDocument
? { document: { file_id: fileId, file_unique_id: `u-${fileId}`, file_name: "screen.png", mime_type: "image/png", file_size: image.length } }
: { photo: [{ file_id: small, file_unique_id: `u-${small}`, width: 90, height: 60, file_size: 16 }, { file_id: fileId, file_unique_id: `u-${fileId}`, width: 1280, height: 800, file_size: image.length }] }),
...(caption ? { caption } : {}),
...(o.mediaGroupId ? { media_group_id: o.mediaGroupId } : {}),
},
});
}
/** User presses an inline button on a bot message. */
userClicks(user: MockTgUser, messageId: number, data: string) {
const id = `cb-${this.nextUpdateId}`;
const m = this.messages.get(messageId);
this.push({
callback_query: {
id,
from: { id: user.id, username: user.username },
message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: chatType(m?.chat_id ?? user.chatId) }, text: m?.text },
data,
},
});
return id;
}
/** The user that /_mock/send and /_mock/click act as (the dev stand's PM). */
pmUser: MockTgUser = { id: 4242, chatId: 4242, username: "mock-pm" };
/** Inspection/actions for the dev stand (peppa-dev tg). */
private inspect(method: string, url: string, body: Record<string, unknown>): { status: number; body: unknown } {
const path = url.split("?")[0];
if (method === "GET" && path === "/_mock/messages") {
return { status: 200, body: this.botMessages(this.pmUser.chatId) };
}
if (method === "GET" && path === "/_mock/callbacks") return { status: 200, body: this.callbackAnswers };
if (method === "POST" && path === "/_mock/send") {
return { status: 200, body: { update_id: this.userSends(this.pmUser, String(body.text), body.replyTo ? Number(body.replyTo) : undefined) } };
}
if (method === "POST" && path === "/_mock/click") {
return { status: 200, body: { callback_id: this.userClicks(this.pmUser, Number(body.messageId), String(body.data)) } };
}
return { status: 404, body: { error: `mock-telegram: ${method} ${path}` } };
}
botMessages(chatId: number) {
return [...this.messages.values()].filter((m) => m.chat_id === chatId);
}
}