@capybara-hq/testing 0.1.0-rc.2 → 0.1.0-rc.21
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/containers.d.ts +7 -2
- package/dist/containers.js +7 -3
- package/dist/dual-replica.d.ts +11 -2
- package/dist/dual-replica.js +48 -0
- package/dist/fake-channel.d.ts +31 -2
- package/dist/fake-channel.js +29 -2
- package/dist/fake-e2b.d.ts +34 -0
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.d.ts +32 -4
- package/dist/fake-git-server.js +87 -19
- package/dist/fake-oauth-server.d.ts +16 -2
- package/dist/fake-oauth-server.js +21 -1
- package/dist/fake-telegram.d.ts +165 -0
- package/dist/fake-telegram.js +569 -0
- package/dist/fixtures.d.ts +21 -4
- package/dist/fixtures.js +30 -4
- package/dist/index.d.ts +8 -5
- package/dist/index.js +6 -3
- package/dist/kernel-helpers.d.ts +48 -16
- package/dist/kernel-helpers.js +73 -13
- package/dist/model-conformance.d.ts +11 -10
- package/dist/model-conformance.js +38 -14
- package/dist/replica-runner.js +16 -8
- package/dist/sandbox-native-conformance.d.ts +31 -0
- package/dist/sandbox-native-conformance.js +153 -0
- package/dist/sandbox-permission-conformance.d.ts +60 -0
- package/dist/sandbox-permission-conformance.js +486 -0
- package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
- package/fixtures/extensions/fake-client/package.json +12 -0
- package/fixtures/extensions/fake-client/src/client.tsx +51 -0
- package/fixtures/extensions/fake-client/src/index.ts +43 -0
- package/fixtures/extensions/fake-client/themes/fake.json +11 -0
- package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-client-broken/package.json +12 -0
- package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
- package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
- package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-config-form/package.json +12 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
- package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-context/package.json +12 -0
- package/fixtures/extensions/fake-context/src/index.ts +81 -0
- package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
- package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
- package/fixtures/extensions/fake-embed/src/index.ts +26 -26
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
- package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
- package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
- package/fixtures/extensions/fake-im/src/channel.ts +3 -1
- package/fixtures/extensions/fake-im/src/checks.ts +94 -0
- package/fixtures/extensions/fake-im/src/index.ts +36 -1
- package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
- package/fixtures/extensions/fake-lifecycle/package.json +12 -0
- package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
- package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
- package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
- package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
- package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web/package.json +12 -0
- package/fixtures/extensions/fake-web/src/index.ts +22 -0
- package/fixtures/extensions/fake-web/src/web.ts +183 -0
- package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web-2/package.json +12 -0
- package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
- package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
- package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
- package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
- package/fixtures/plugins/fake-theme/logo.svg +1 -0
- package/fixtures/plugins/fake-theme/package.json +8 -0
- package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
- package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
- package/package.json +6 -5
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
const MAX_TEXT = 4096;
|
|
3
|
+
const ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"' };
|
|
4
|
+
/**
|
|
5
|
+
* The text length Telegram limits: UTF-16 code units after entity parsing. With `parse_mode`
|
|
6
|
+
* HTML, tags (including `<a href>`) are removed and character references decoded.
|
|
7
|
+
*/
|
|
8
|
+
function telegramTextLength(text, parseMode) {
|
|
9
|
+
if (parseMode?.toUpperCase() !== "HTML")
|
|
10
|
+
return text.length;
|
|
11
|
+
return text
|
|
12
|
+
.replace(/<[^>]*>/g, "")
|
|
13
|
+
.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|amp|quot);/g, (_, ref) => {
|
|
14
|
+
if (ref.startsWith("#x"))
|
|
15
|
+
return String.fromCodePoint(Number.parseInt(ref.slice(2), 16));
|
|
16
|
+
if (ref.startsWith("#"))
|
|
17
|
+
return String.fromCodePoint(Number.parseInt(ref.slice(1), 10));
|
|
18
|
+
return ENTITIES[ref] ?? "";
|
|
19
|
+
}).length;
|
|
20
|
+
}
|
|
21
|
+
const JSON_PARAMS = new Set(["reply_markup", "reply_parameters", "allowed_updates", "entities"]);
|
|
22
|
+
const DEFAULT_BOT = {
|
|
23
|
+
token: "123456:fake-telegram-token",
|
|
24
|
+
id: 123456,
|
|
25
|
+
username: "capybara_bot",
|
|
26
|
+
firstName: "Capybara",
|
|
27
|
+
};
|
|
28
|
+
class TelegramError extends Error {
|
|
29
|
+
code;
|
|
30
|
+
constructor(code, description) {
|
|
31
|
+
super(description);
|
|
32
|
+
this.code = code;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const readBody = (req) => new Promise((resolve, reject) => {
|
|
36
|
+
let body = "";
|
|
37
|
+
req.on("data", (c) => {
|
|
38
|
+
body += c.toString();
|
|
39
|
+
});
|
|
40
|
+
req.on("end", () => resolve(body));
|
|
41
|
+
req.on("error", reject);
|
|
42
|
+
});
|
|
43
|
+
function parseParams(url, raw, contentType) {
|
|
44
|
+
const out = {};
|
|
45
|
+
const fromForm = (form) => {
|
|
46
|
+
for (const [k, v] of form) {
|
|
47
|
+
if (JSON_PARAMS.has(k)) {
|
|
48
|
+
try {
|
|
49
|
+
out[k] = JSON.parse(v);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// keep the raw string
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
out[k] = v;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
fromForm(url.searchParams);
|
|
60
|
+
if (raw === "")
|
|
61
|
+
return out;
|
|
62
|
+
if (contentType?.includes("application/json")) {
|
|
63
|
+
let body;
|
|
64
|
+
try {
|
|
65
|
+
body = JSON.parse(raw);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
throw new TelegramError(400, "Bad Request: invalid JSON");
|
|
69
|
+
}
|
|
70
|
+
if (body !== null && typeof body === "object")
|
|
71
|
+
Object.assign(out, body);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
fromForm(new URLSearchParams(raw));
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
const num = (v) => {
|
|
79
|
+
if (typeof v === "number")
|
|
80
|
+
return v;
|
|
81
|
+
if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)))
|
|
82
|
+
return Number(v);
|
|
83
|
+
return undefined;
|
|
84
|
+
};
|
|
85
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
86
|
+
const nowSec = () => Math.floor(Date.now() / 1000);
|
|
87
|
+
/** The update's type: its one field besides `update_id`. */
|
|
88
|
+
const updateType = (u) => Object.keys(u).find((k) => k !== "update_id");
|
|
89
|
+
/** Starts the fake Telegram Bot API (listens on a random 127.0.0.1 port). */
|
|
90
|
+
export async function startFakeTelegram(opts = {}) {
|
|
91
|
+
const bots = opts.bots && opts.bots.length > 0 ? opts.bots : [DEFAULT_BOT];
|
|
92
|
+
const states = new Map();
|
|
93
|
+
for (const [i, bot] of bots.entries()) {
|
|
94
|
+
if (states.has(bot.token))
|
|
95
|
+
throw new Error(`fake telegram: duplicate bot token ${bot.token}`);
|
|
96
|
+
states.set(bot.token, {
|
|
97
|
+
bot,
|
|
98
|
+
queue: [],
|
|
99
|
+
nextUpdateId: 100_000_001 + i * 10_000_000,
|
|
100
|
+
confirmed: 0,
|
|
101
|
+
webhook: "",
|
|
102
|
+
allowed: undefined,
|
|
103
|
+
pollers: [],
|
|
104
|
+
peakPollers: 0,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const first = bots[0];
|
|
108
|
+
const messages = [];
|
|
109
|
+
const edits = [];
|
|
110
|
+
const calls = [];
|
|
111
|
+
const callbackAnswers = [];
|
|
112
|
+
const failures = [];
|
|
113
|
+
const delays = new Map();
|
|
114
|
+
/** Per bot and chat: the last message id sent. */
|
|
115
|
+
const lastMessageId = new Map();
|
|
116
|
+
/** Per bot, chat and message: the current text and markup (for "message is not modified"). */
|
|
117
|
+
const current = new Map();
|
|
118
|
+
/** Pending `delay` waits, cleared (and released) on close. */
|
|
119
|
+
const delayTimers = new Map();
|
|
120
|
+
let closed = false;
|
|
121
|
+
const stateOf = (token) => {
|
|
122
|
+
const s = states.get(token ?? first.token);
|
|
123
|
+
if (!s)
|
|
124
|
+
throw new Error(`fake telegram: unknown bot token ${token}`);
|
|
125
|
+
return s;
|
|
126
|
+
};
|
|
127
|
+
const reply = (res, status, body) => {
|
|
128
|
+
if (res.headersSent || res.destroyed)
|
|
129
|
+
return;
|
|
130
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
131
|
+
res.end(JSON.stringify(body));
|
|
132
|
+
};
|
|
133
|
+
const ok = (res, result) => reply(res, 200, { ok: true, result });
|
|
134
|
+
const fail = (res, code, description) => reply(res, code, { ok: false, error_code: code, description });
|
|
135
|
+
const botUser = (bot) => ({
|
|
136
|
+
id: bot.id,
|
|
137
|
+
is_bot: true,
|
|
138
|
+
first_name: bot.firstName ?? bot.username,
|
|
139
|
+
username: bot.username,
|
|
140
|
+
});
|
|
141
|
+
/** Drops updates of types not allowed, then returns up to `limit` of the queue. */
|
|
142
|
+
const collect = (s, limit) => {
|
|
143
|
+
if (s.allowed) {
|
|
144
|
+
const allowed = s.allowed;
|
|
145
|
+
s.queue = s.queue.filter((u) => allowed.has(updateType(u) ?? ""));
|
|
146
|
+
}
|
|
147
|
+
return s.queue.slice(0, limit);
|
|
148
|
+
};
|
|
149
|
+
const removePoller = (s, p) => {
|
|
150
|
+
clearTimeout(p.timer);
|
|
151
|
+
const i = s.pollers.indexOf(p);
|
|
152
|
+
if (i >= 0)
|
|
153
|
+
s.pollers.splice(i, 1);
|
|
154
|
+
};
|
|
155
|
+
const getUpdates = (s, params, req) => {
|
|
156
|
+
if (s.webhook !== "") {
|
|
157
|
+
throw new TelegramError(409, "Conflict: can't use getUpdates method while webhook is active; use deleteWebhook to delete the webhook first");
|
|
158
|
+
}
|
|
159
|
+
const offset = num(params.offset);
|
|
160
|
+
if (offset !== undefined && offset > 0) {
|
|
161
|
+
s.queue = s.queue.filter((u) => u.update_id >= offset);
|
|
162
|
+
s.confirmed = Math.max(s.confirmed, offset);
|
|
163
|
+
}
|
|
164
|
+
else if (offset !== undefined && offset < 0) {
|
|
165
|
+
s.queue = s.queue.slice(offset);
|
|
166
|
+
}
|
|
167
|
+
const allowed = params.allowed_updates;
|
|
168
|
+
if (Array.isArray(allowed)) {
|
|
169
|
+
s.allowed = allowed.length > 0 ? new Set(allowed.map(String)) : undefined;
|
|
170
|
+
}
|
|
171
|
+
// An overlapping request counts as concurrent even though Telegram ends the earlier one.
|
|
172
|
+
s.peakPollers = Math.max(s.peakPollers, s.pollers.length + 1);
|
|
173
|
+
for (const earlier of [...s.pollers]) {
|
|
174
|
+
removePoller(s, earlier);
|
|
175
|
+
fail(earlier.res, 409, "Conflict: terminated by other getUpdates request");
|
|
176
|
+
}
|
|
177
|
+
const limit = Math.min(Math.max(num(params.limit) ?? 100, 1), 100);
|
|
178
|
+
const timeout = Math.max(num(params.timeout) ?? 0, 0);
|
|
179
|
+
return { limit, timeout, ready: collect(s, limit), port: req.socket.remotePort };
|
|
180
|
+
};
|
|
181
|
+
const sendMessage = (s, params) => {
|
|
182
|
+
const chatId = num(params.chat_id);
|
|
183
|
+
if (chatId === undefined)
|
|
184
|
+
throw new TelegramError(400, "Bad Request: chat not found");
|
|
185
|
+
const text = str(params.text) ?? "";
|
|
186
|
+
if (text === "")
|
|
187
|
+
throw new TelegramError(400, "Bad Request: message text is empty");
|
|
188
|
+
if (telegramTextLength(text, str(params.parse_mode)) > MAX_TEXT) {
|
|
189
|
+
throw new TelegramError(400, "Bad Request: message is too long");
|
|
190
|
+
}
|
|
191
|
+
const chatKey = `${s.bot.token}|${chatId}`;
|
|
192
|
+
const messageId = (lastMessageId.get(chatKey) ?? 0) + 1;
|
|
193
|
+
lastMessageId.set(chatKey, messageId);
|
|
194
|
+
const threadId = num(params.message_thread_id);
|
|
195
|
+
const replyParams = params.reply_parameters;
|
|
196
|
+
const replyTo = num(replyParams?.message_id) ?? num(params.reply_to_message_id);
|
|
197
|
+
const parseMode = str(params.parse_mode);
|
|
198
|
+
const m = {
|
|
199
|
+
chatId,
|
|
200
|
+
messageId,
|
|
201
|
+
text,
|
|
202
|
+
...(parseMode !== undefined && { parseMode }),
|
|
203
|
+
...(params.reply_markup !== undefined && { replyMarkup: params.reply_markup }),
|
|
204
|
+
...(threadId !== undefined && { messageThreadId: threadId }),
|
|
205
|
+
...(replyTo !== undefined && { replyToMessageId: replyTo }),
|
|
206
|
+
at: Date.now(),
|
|
207
|
+
};
|
|
208
|
+
messages.push(m);
|
|
209
|
+
current.set(`${chatKey}|${messageId}`, m);
|
|
210
|
+
return messageResult(s, m);
|
|
211
|
+
};
|
|
212
|
+
const editMessageText = (s, params) => {
|
|
213
|
+
const chatId = num(params.chat_id);
|
|
214
|
+
const messageId = num(params.message_id);
|
|
215
|
+
const key = `${s.bot.token}|${chatId}|${messageId}`;
|
|
216
|
+
const before = current.get(key);
|
|
217
|
+
if (chatId === undefined || messageId === undefined || !before) {
|
|
218
|
+
throw new TelegramError(400, "Bad Request: message to edit not found");
|
|
219
|
+
}
|
|
220
|
+
const text = str(params.text) ?? "";
|
|
221
|
+
if (text === "")
|
|
222
|
+
throw new TelegramError(400, "Bad Request: message text is empty");
|
|
223
|
+
if (telegramTextLength(text, str(params.parse_mode)) > MAX_TEXT) {
|
|
224
|
+
throw new TelegramError(400, "Bad Request: message is too long");
|
|
225
|
+
}
|
|
226
|
+
const markup = params.reply_markup;
|
|
227
|
+
if (text === before.text && JSON.stringify(markup) === JSON.stringify(before.replyMarkup)) {
|
|
228
|
+
throw new TelegramError(400, "Bad Request: message is not modified");
|
|
229
|
+
}
|
|
230
|
+
const parseMode = str(params.parse_mode);
|
|
231
|
+
const m = {
|
|
232
|
+
chatId,
|
|
233
|
+
messageId,
|
|
234
|
+
text,
|
|
235
|
+
...(parseMode !== undefined && { parseMode }),
|
|
236
|
+
...(markup !== undefined && { replyMarkup: markup }),
|
|
237
|
+
...(before.messageThreadId !== undefined && { messageThreadId: before.messageThreadId }),
|
|
238
|
+
...(before.replyToMessageId !== undefined && { replyToMessageId: before.replyToMessageId }),
|
|
239
|
+
at: Date.now(),
|
|
240
|
+
};
|
|
241
|
+
edits.push(m);
|
|
242
|
+
current.set(key, m);
|
|
243
|
+
return { ...messageResult(s, m), edit_date: nowSec() };
|
|
244
|
+
};
|
|
245
|
+
const messageResult = (s, m) => ({
|
|
246
|
+
message_id: m.messageId,
|
|
247
|
+
from: botUser(s.bot),
|
|
248
|
+
chat: { id: m.chatId, type: m.chatId > 0 ? "private" : "supergroup" },
|
|
249
|
+
date: Math.floor(m.at / 1000),
|
|
250
|
+
text: m.text,
|
|
251
|
+
...(m.messageThreadId !== undefined && { message_thread_id: m.messageThreadId }),
|
|
252
|
+
...(m.replyMarkup !== undefined && { reply_markup: m.replyMarkup }),
|
|
253
|
+
});
|
|
254
|
+
const handle = async (req, res, token, name) => {
|
|
255
|
+
const url = new URL(req.url ?? "/", "http://x");
|
|
256
|
+
let params;
|
|
257
|
+
try {
|
|
258
|
+
params = parseParams(url, await readBody(req), req.headers["content-type"]);
|
|
259
|
+
}
|
|
260
|
+
catch (e) {
|
|
261
|
+
if (e instanceof TelegramError)
|
|
262
|
+
return fail(res, e.code, e.message);
|
|
263
|
+
throw e;
|
|
264
|
+
}
|
|
265
|
+
const s = states.get(token);
|
|
266
|
+
if (!s)
|
|
267
|
+
return fail(res, 401, "Unauthorized");
|
|
268
|
+
calls.push({ method: name, token, params, at: Date.now() });
|
|
269
|
+
const method = name.toLowerCase();
|
|
270
|
+
const wait = delays.get(method) ?? 0;
|
|
271
|
+
if (wait > 0) {
|
|
272
|
+
await new Promise((resolve) => {
|
|
273
|
+
const timer = setTimeout(() => {
|
|
274
|
+
delayTimers.delete(timer);
|
|
275
|
+
resolve();
|
|
276
|
+
}, wait);
|
|
277
|
+
delayTimers.set(timer, resolve);
|
|
278
|
+
});
|
|
279
|
+
if (closed)
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const f = failures.find((x) => x.method === method && x.left > 0);
|
|
283
|
+
if (f) {
|
|
284
|
+
f.left--;
|
|
285
|
+
const { status, errorCode, description, retryAfter, migrateToChatId } = f.failure;
|
|
286
|
+
const parameters = {
|
|
287
|
+
...(retryAfter !== undefined && { retry_after: retryAfter }),
|
|
288
|
+
...(migrateToChatId !== undefined && { migrate_to_chat_id: migrateToChatId }),
|
|
289
|
+
};
|
|
290
|
+
return reply(res, status, {
|
|
291
|
+
ok: false,
|
|
292
|
+
error_code: errorCode ?? status,
|
|
293
|
+
description,
|
|
294
|
+
...(Object.keys(parameters).length > 0 && { parameters }),
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
switch (method) {
|
|
299
|
+
case "getme":
|
|
300
|
+
return ok(res, {
|
|
301
|
+
...botUser(s.bot),
|
|
302
|
+
can_join_groups: true,
|
|
303
|
+
can_read_all_group_messages: s.bot.canReadAllGroupMessages ?? false,
|
|
304
|
+
supports_inline_queries: false,
|
|
305
|
+
has_topics_enabled: s.bot.hasTopicsEnabled ?? false,
|
|
306
|
+
});
|
|
307
|
+
case "getwebhookinfo":
|
|
308
|
+
return ok(res, {
|
|
309
|
+
url: s.webhook,
|
|
310
|
+
has_custom_certificate: false,
|
|
311
|
+
pending_update_count: s.queue.length,
|
|
312
|
+
});
|
|
313
|
+
case "getupdates": {
|
|
314
|
+
const { limit, timeout, ready, port } = getUpdates(s, params, req);
|
|
315
|
+
if (ready.length > 0 || timeout === 0 || closed)
|
|
316
|
+
return ok(res, ready);
|
|
317
|
+
const p = {
|
|
318
|
+
res,
|
|
319
|
+
port,
|
|
320
|
+
limit,
|
|
321
|
+
timer: setTimeout(() => {
|
|
322
|
+
removePoller(s, p);
|
|
323
|
+
ok(res, collect(s, limit));
|
|
324
|
+
}, timeout * 1000),
|
|
325
|
+
};
|
|
326
|
+
s.pollers.push(p);
|
|
327
|
+
res.on("close", () => removePoller(s, p));
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
case "sendmessage":
|
|
331
|
+
return ok(res, sendMessage(s, params));
|
|
332
|
+
case "editmessagetext":
|
|
333
|
+
return ok(res, editMessageText(s, params));
|
|
334
|
+
case "answercallbackquery":
|
|
335
|
+
callbackAnswers.push(str(params.callback_query_id) ?? "");
|
|
336
|
+
return ok(res, true);
|
|
337
|
+
default:
|
|
338
|
+
return fail(res, 404, "Not Found");
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
catch (e) {
|
|
342
|
+
if (e instanceof TelegramError)
|
|
343
|
+
return fail(res, e.code, e.message);
|
|
344
|
+
throw e;
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
const server = createServer((req, res) => {
|
|
348
|
+
void (async () => {
|
|
349
|
+
const path = new URL(req.url ?? "/", "http://x").pathname;
|
|
350
|
+
const m = /^\/bot([^/]+)\/([A-Za-z]+)$/.exec(path);
|
|
351
|
+
if (!m || (req.method !== "GET" && req.method !== "POST")) {
|
|
352
|
+
return fail(res, 404, "Not Found");
|
|
353
|
+
}
|
|
354
|
+
return handle(req, res, decodeURIComponent(m[1]), m[2]);
|
|
355
|
+
})().catch(() => {
|
|
356
|
+
if (!res.headersSent)
|
|
357
|
+
res.writeHead(500);
|
|
358
|
+
res.end();
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
|
362
|
+
const url = `http://127.0.0.1:${server.address().port}`;
|
|
363
|
+
return {
|
|
364
|
+
url,
|
|
365
|
+
apiUrl: url,
|
|
366
|
+
bot: first,
|
|
367
|
+
bots,
|
|
368
|
+
messages,
|
|
369
|
+
edits,
|
|
370
|
+
calls,
|
|
371
|
+
callbackAnswers,
|
|
372
|
+
push(update, token) {
|
|
373
|
+
const s = stateOf(token);
|
|
374
|
+
const id = s.nextUpdateId++;
|
|
375
|
+
s.queue.push({ update_id: id, ...update });
|
|
376
|
+
for (const p of [...s.pollers]) {
|
|
377
|
+
const ready = collect(s, p.limit);
|
|
378
|
+
if (ready.length === 0)
|
|
379
|
+
continue;
|
|
380
|
+
removePoller(s, p);
|
|
381
|
+
ok(p.res, ready);
|
|
382
|
+
}
|
|
383
|
+
return id;
|
|
384
|
+
},
|
|
385
|
+
confirmedOffset: (token) => stateOf(token).confirmed,
|
|
386
|
+
pending: (token) => stateOf(token).queue.length,
|
|
387
|
+
activePollers: (token) => stateOf(token).pollers.length,
|
|
388
|
+
maxConcurrentPollers: (token) => stateOf(token).peakPollers,
|
|
389
|
+
pollerPeerPorts: (token) => stateOf(token).pollers.flatMap((p) => (p.port === undefined ? [] : [p.port])),
|
|
390
|
+
setWebhook(webhookUrl, token) {
|
|
391
|
+
stateOf(token).webhook = webhookUrl ?? "";
|
|
392
|
+
},
|
|
393
|
+
failNext(method, failure, count = 1) {
|
|
394
|
+
failures.push({ method: method.toLowerCase(), failure, left: count });
|
|
395
|
+
},
|
|
396
|
+
delay(method, ms) {
|
|
397
|
+
delays.set(method.toLowerCase(), ms);
|
|
398
|
+
},
|
|
399
|
+
async close() {
|
|
400
|
+
closed = true;
|
|
401
|
+
for (const [timer, release] of delayTimers) {
|
|
402
|
+
clearTimeout(timer);
|
|
403
|
+
release();
|
|
404
|
+
}
|
|
405
|
+
delayTimers.clear();
|
|
406
|
+
for (const s of states.values())
|
|
407
|
+
for (const p of [...s.pollers])
|
|
408
|
+
removePoller(s, p);
|
|
409
|
+
server.closeAllConnections();
|
|
410
|
+
await new Promise((r) => server.close(() => r()));
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
let seq = 0;
|
|
415
|
+
const nextMessageId = () => 1000 + ++seq;
|
|
416
|
+
const userOf = (u) => ({
|
|
417
|
+
id: u.id,
|
|
418
|
+
is_bot: u.is_bot ?? false,
|
|
419
|
+
first_name: u.first_name,
|
|
420
|
+
...(u.last_name !== undefined && { last_name: u.last_name }),
|
|
421
|
+
...(u.username !== undefined && { username: u.username }),
|
|
422
|
+
});
|
|
423
|
+
/** A `bot_command` entity when the text starts with `/command`. */
|
|
424
|
+
const commandEntities = (text) => {
|
|
425
|
+
const m = /^\/[A-Za-z0-9_]+(@[A-Za-z0-9_]+)?/.exec(text);
|
|
426
|
+
return m ? [{ type: "bot_command", offset: 0, length: m[0].length }] : [];
|
|
427
|
+
};
|
|
428
|
+
/** An update with a private (direct) message from `from`. */
|
|
429
|
+
export function telegramPrivateMessage(from, text, o = {}) {
|
|
430
|
+
const entities = commandEntities(text);
|
|
431
|
+
return {
|
|
432
|
+
message: {
|
|
433
|
+
message_id: o.messageId ?? nextMessageId(),
|
|
434
|
+
date: o.date ?? nowSec(),
|
|
435
|
+
chat: {
|
|
436
|
+
id: from.id,
|
|
437
|
+
type: "private",
|
|
438
|
+
first_name: from.first_name,
|
|
439
|
+
...(from.last_name !== undefined && { last_name: from.last_name }),
|
|
440
|
+
...(from.username !== undefined && { username: from.username }),
|
|
441
|
+
},
|
|
442
|
+
from: userOf(from),
|
|
443
|
+
text,
|
|
444
|
+
...(entities.length > 0 && { entities }),
|
|
445
|
+
},
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* An update with a group message. `mention` (with or without `@`) adds a `mention` entity at its
|
|
450
|
+
* UTF-16 offset, prefixing `@<mention> ` when the text lacks it; `replyTo` sets `reply_to_message`
|
|
451
|
+
* (from the bot when `fromBot` is given); `messageThreadId` sets the thread, with
|
|
452
|
+
* `is_topic_message` defaulting to the chat's `is_forum`; `caption` turns the message into a photo
|
|
453
|
+
* whose caption carries the text and entities.
|
|
454
|
+
*/
|
|
455
|
+
export function telegramGroupMessage(chat, from, text, o = {}) {
|
|
456
|
+
let body = text;
|
|
457
|
+
const entities = commandEntities(text);
|
|
458
|
+
if (o.mention !== undefined) {
|
|
459
|
+
const handle = o.mention.startsWith("@") ? o.mention : `@${o.mention}`;
|
|
460
|
+
if (!body.includes(handle))
|
|
461
|
+
body = `${handle} ${body}`;
|
|
462
|
+
entities.splice(0, entities.length, ...commandEntities(body));
|
|
463
|
+
entities.push({ type: "mention", offset: body.indexOf(handle), length: handle.length });
|
|
464
|
+
}
|
|
465
|
+
const date = nowSec();
|
|
466
|
+
const isTopic = o.isTopicMessage ?? (chat.is_forum === true ? true : undefined);
|
|
467
|
+
const r = o.replyTo;
|
|
468
|
+
const replyFrom = r?.fromBot
|
|
469
|
+
? {
|
|
470
|
+
id: r.fromBot.id,
|
|
471
|
+
is_bot: true,
|
|
472
|
+
first_name: r.fromBot.firstName ?? r.fromBot.username,
|
|
473
|
+
username: r.fromBot.username,
|
|
474
|
+
}
|
|
475
|
+
: userOf(from);
|
|
476
|
+
return {
|
|
477
|
+
message: {
|
|
478
|
+
message_id: o.messageId ?? nextMessageId(),
|
|
479
|
+
date,
|
|
480
|
+
chat,
|
|
481
|
+
from: userOf(from),
|
|
482
|
+
...(o.messageThreadId !== undefined && { message_thread_id: o.messageThreadId }),
|
|
483
|
+
...(o.messageThreadId !== undefined &&
|
|
484
|
+
isTopic !== undefined && { is_topic_message: isTopic }),
|
|
485
|
+
...(r && {
|
|
486
|
+
reply_to_message: {
|
|
487
|
+
message_id: r.messageId,
|
|
488
|
+
date: date - 60,
|
|
489
|
+
chat,
|
|
490
|
+
from: replyFrom,
|
|
491
|
+
text: r.text ?? "",
|
|
492
|
+
...(o.messageThreadId !== undefined && { message_thread_id: o.messageThreadId }),
|
|
493
|
+
},
|
|
494
|
+
}),
|
|
495
|
+
...(o.caption
|
|
496
|
+
? {
|
|
497
|
+
photo: [
|
|
498
|
+
{
|
|
499
|
+
file_id: "fake-photo-small",
|
|
500
|
+
file_unique_id: "fps",
|
|
501
|
+
width: 90,
|
|
502
|
+
height: 90,
|
|
503
|
+
file_size: 1200,
|
|
504
|
+
},
|
|
505
|
+
{
|
|
506
|
+
file_id: "fake-photo-large",
|
|
507
|
+
file_unique_id: "fpl",
|
|
508
|
+
width: 800,
|
|
509
|
+
height: 800,
|
|
510
|
+
file_size: 64000,
|
|
511
|
+
},
|
|
512
|
+
],
|
|
513
|
+
caption: body,
|
|
514
|
+
...(entities.length > 0 && { caption_entities: entities }),
|
|
515
|
+
}
|
|
516
|
+
: { text: body, ...(entities.length > 0 && { entities }) }),
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
/** An update with a callback query: `from` pressed an inline button with `data` on a bot message. */
|
|
521
|
+
export function telegramCallback(from, message, data, o = {}) {
|
|
522
|
+
return {
|
|
523
|
+
callback_query: {
|
|
524
|
+
id: o.id ?? `cbq-${++seq}`,
|
|
525
|
+
from: userOf(from),
|
|
526
|
+
chat_instance: `ci${Math.abs(message.chatId)}`,
|
|
527
|
+
data,
|
|
528
|
+
message: {
|
|
529
|
+
message_id: message.messageId,
|
|
530
|
+
date: nowSec(),
|
|
531
|
+
chat: {
|
|
532
|
+
id: message.chatId,
|
|
533
|
+
type: message.chatType ?? (message.chatId > 0 ? "private" : "supergroup"),
|
|
534
|
+
},
|
|
535
|
+
...(message.messageThreadId !== undefined && {
|
|
536
|
+
message_thread_id: message.messageThreadId,
|
|
537
|
+
}),
|
|
538
|
+
},
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
/** Finds an inline keyboard button in a `reply_markup` (object or JSON string). */
|
|
543
|
+
export function findTelegramButton(replyMarkup, pred) {
|
|
544
|
+
let markup = replyMarkup;
|
|
545
|
+
if (typeof markup === "string") {
|
|
546
|
+
try {
|
|
547
|
+
markup = JSON.parse(markup);
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const rows = markup?.inline_keyboard;
|
|
554
|
+
if (!Array.isArray(rows))
|
|
555
|
+
return undefined;
|
|
556
|
+
for (const row of rows) {
|
|
557
|
+
if (!Array.isArray(row))
|
|
558
|
+
continue;
|
|
559
|
+
for (const b of row) {
|
|
560
|
+
if (pred(b))
|
|
561
|
+
return b;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return undefined;
|
|
565
|
+
}
|
|
566
|
+
/** The headers Telegram sends to a webhook set with `secret_token`. */
|
|
567
|
+
export function telegramWebhookHeaders(secret) {
|
|
568
|
+
return { "content-type": "application/json", "x-telegram-bot-api-secret-token": secret };
|
|
569
|
+
}
|
package/dist/fixtures.d.ts
CHANGED
|
@@ -10,19 +10,36 @@
|
|
|
10
10
|
* | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`; deployment config `allowInsecureLoopback` (default true), `inspectAuth` (`bearer` / `api_key`), `kind` (default `fake`; `mcp` lets clients that know only the official kinds drive it) |
|
|
11
11
|
* | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`; deployment config `allowInsecureLoopback` (default true) |
|
|
12
12
|
* | `fake-object-store` | `object-store@1` on the `startTestS3()` container (deployment config as `TestS3` gives it; POST-policy presign) |
|
|
13
|
-
* | `fake-tools-ui` |
|
|
13
|
+
* | `fake-tools-ui` | tools `write` and `web-only` (`sources` web and channel_dm; returns its call context), view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
|
|
14
14
|
* | `fake-storage-user` | tools `note` / `read_note` through `ctx.storage` (`permissions.storage`) |
|
|
15
|
+
* | `fake-lifecycle` | observes `org.member_removed`, `agent.deleted` and `org.deleted`; a migration with tables `calls` (every call) and `deliveries` (every call that succeeded), each row the mount and the payload; deployment config `failTimes` (default 0): the first `failTimes` calls of each (mount, payload) throw, and `label` (optional, at most 10 characters, overridable per org: an invalid org copy) |
|
|
15
16
|
* | `fake-embed` | embeds `panel` (page) and `panel-conv` (conversation), static `/ui/panel.js`, token-checked routes, SSE over `ctx.bus` |
|
|
16
17
|
* | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
|
|
17
18
|
* | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
|
|
18
19
|
* | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
|
|
19
20
|
* | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
|
|
21
|
+
* | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
|
|
22
|
+
* | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
|
|
23
|
+
* | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
|
|
24
|
+
* | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
|
|
25
|
+
* | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
|
|
20
26
|
*/
|
|
21
|
-
export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im"];
|
|
27
|
+
export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-lifecycle", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im", "fake-web", "fake-web-2", "fake-context", "fake-config-form", "fake-client", "fake-client-broken"];
|
|
28
|
+
/**
|
|
29
|
+
* Fake plugins without an extension (declarative: they live in `fixtures/plugins/<name>`, same
|
|
30
|
+
* pack layout).
|
|
31
|
+
*
|
|
32
|
+
* | name | provides / covers |
|
|
33
|
+
* |---|---|
|
|
34
|
+
* | `fake-theme` | themes `neon-grid` (dark only, wordmark, font `FakeSans`, logo) and `paper` (light and dark); passes `capybara-plugin check` |
|
|
35
|
+
*/
|
|
36
|
+
export declare const FAKE_PLUGINS: readonly ["fake-theme"];
|
|
37
|
+
/** The name of a fake plugin. */
|
|
38
|
+
export type FakePluginName = (typeof FAKE_PLUGINS)[number];
|
|
22
39
|
/** The name of a fake extension (also its plugin and extension name). */
|
|
23
40
|
export type FakeExtensionName = (typeof FAKE_EXTENSIONS)[number];
|
|
24
41
|
/** The plugin directory of a fake (pack layout), for `packFixture` or a packer of your own. */
|
|
25
|
-
export declare function fakeExtensionDir(name: FakeExtensionName): string;
|
|
42
|
+
export declare function fakeExtensionDir(name: FakeExtensionName | FakePluginName): string;
|
|
26
43
|
/**
|
|
27
44
|
* The extension entry `src/index.ts` of a fake, for kernel configs that load extensions by path
|
|
28
45
|
* (`extensions: [fakeExtensionEntry("fake-connector")]`). `createDualReplicaHarness` loads it in
|
|
@@ -46,4 +63,4 @@ export interface PackedFixture {
|
|
|
46
63
|
* skills and templates), writes it to `outDir` and returns its path, bytes and sha256. Packing
|
|
47
64
|
* leaves no files in the fixture directory.
|
|
48
65
|
*/
|
|
49
|
-
export declare function packFixture(name: FakeExtensionName, outDir: string): Promise<PackedFixture>;
|
|
66
|
+
export declare function packFixture(name: FakeExtensionName | FakePluginName, outDir: string): Promise<PackedFixture>;
|