@yaebal/test 0.1.0 → 0.2.1

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.
Files changed (107) hide show
  1. package/README.md +334 -160
  2. package/lib/api.d.ts +82 -0
  3. package/lib/api.d.ts.map +1 -0
  4. package/lib/api.js +183 -0
  5. package/lib/api.js.map +1 -0
  6. package/lib/api.test.d.ts +2 -0
  7. package/lib/api.test.d.ts.map +1 -0
  8. package/lib/api.test.js +131 -0
  9. package/lib/api.test.js.map +1 -0
  10. package/lib/bot-messages.d.ts +42 -0
  11. package/lib/bot-messages.d.ts.map +1 -0
  12. package/lib/bot-messages.js +72 -0
  13. package/lib/bot-messages.js.map +1 -0
  14. package/lib/chat-actor.d.ts +45 -0
  15. package/lib/chat-actor.d.ts.map +1 -0
  16. package/lib/chat-actor.js +72 -0
  17. package/lib/chat-actor.js.map +1 -0
  18. package/lib/clock.d.ts +22 -0
  19. package/lib/clock.d.ts.map +1 -0
  20. package/lib/clock.js +72 -0
  21. package/lib/clock.js.map +1 -0
  22. package/lib/clock.test.d.ts +2 -0
  23. package/lib/clock.test.d.ts.map +1 -0
  24. package/lib/clock.test.js +69 -0
  25. package/lib/clock.test.js.map +1 -0
  26. package/lib/env.d.ts +100 -0
  27. package/lib/env.d.ts.map +1 -0
  28. package/lib/env.js +164 -0
  29. package/lib/env.js.map +1 -0
  30. package/lib/env.test.d.ts +2 -0
  31. package/lib/env.test.d.ts.map +1 -0
  32. package/lib/env.test.js +302 -0
  33. package/lib/env.test.js.map +1 -0
  34. package/lib/fetch.d.ts +3 -0
  35. package/lib/fetch.d.ts.map +1 -0
  36. package/lib/fetch.js +12 -0
  37. package/lib/fetch.js.map +1 -0
  38. package/lib/index.d.ts +19 -205
  39. package/lib/index.d.ts.map +1 -1
  40. package/lib/index.js +19 -391
  41. package/lib/index.js.map +1 -1
  42. package/lib/internal.d.ts +25 -0
  43. package/lib/internal.d.ts.map +1 -0
  44. package/lib/internal.js +19 -0
  45. package/lib/internal.js.map +1 -0
  46. package/lib/keyboard.d.ts +15 -0
  47. package/lib/keyboard.d.ts.map +1 -0
  48. package/lib/keyboard.js +25 -0
  49. package/lib/keyboard.js.map +1 -0
  50. package/lib/keyboard.test.d.ts +2 -0
  51. package/lib/keyboard.test.d.ts.map +1 -0
  52. package/lib/keyboard.test.js +31 -0
  53. package/lib/keyboard.test.js.map +1 -0
  54. package/lib/normalize.d.ts +10 -0
  55. package/lib/normalize.d.ts.map +1 -0
  56. package/lib/normalize.js +27 -0
  57. package/lib/normalize.js.map +1 -0
  58. package/lib/reactions.d.ts +3 -0
  59. package/lib/reactions.d.ts.map +1 -0
  60. package/lib/reactions.js +17 -0
  61. package/lib/reactions.js.map +1 -0
  62. package/lib/updates.d.ts +126 -0
  63. package/lib/updates.d.ts.map +1 -0
  64. package/lib/updates.js +200 -0
  65. package/lib/updates.js.map +1 -0
  66. package/lib/updates.test.d.ts +2 -0
  67. package/lib/updates.test.d.ts.map +1 -0
  68. package/lib/updates.test.js +72 -0
  69. package/lib/updates.test.js.map +1 -0
  70. package/lib/user-actor.d.ts +188 -0
  71. package/lib/user-actor.d.ts.map +1 -0
  72. package/lib/user-actor.js +465 -0
  73. package/lib/user-actor.js.map +1 -0
  74. package/lib/webhook.d.ts +18 -0
  75. package/lib/webhook.d.ts.map +1 -0
  76. package/lib/webhook.js +25 -0
  77. package/lib/webhook.js.map +1 -0
  78. package/lib/webhook.test.d.ts +2 -0
  79. package/lib/webhook.test.d.ts.map +1 -0
  80. package/lib/webhook.test.js +36 -0
  81. package/lib/webhook.test.js.map +1 -0
  82. package/package.json +7 -5
  83. package/src/api.test.ts +180 -0
  84. package/src/api.ts +281 -0
  85. package/src/bot-messages.ts +117 -0
  86. package/src/chat-actor.ts +101 -0
  87. package/src/clock.test.ts +80 -0
  88. package/src/clock.ts +118 -0
  89. package/src/env.test.ts +370 -0
  90. package/src/env.ts +235 -0
  91. package/src/fetch.ts +11 -0
  92. package/src/index.ts +79 -630
  93. package/src/internal.ts +43 -0
  94. package/src/keyboard.test.ts +35 -0
  95. package/src/keyboard.ts +38 -0
  96. package/src/normalize.ts +34 -0
  97. package/src/reactions.ts +18 -0
  98. package/src/updates.test.ts +107 -0
  99. package/src/updates.ts +354 -0
  100. package/src/user-actor.ts +702 -0
  101. package/src/webhook.test.ts +54 -0
  102. package/src/webhook.ts +48 -0
  103. package/lib/index.test.d.ts +0 -2
  104. package/lib/index.test.d.ts.map +0 -1
  105. package/lib/index.test.js +0 -213
  106. package/lib/index.test.js.map +0 -1
  107. package/src/index.test.ts +0 -320
package/src/index.ts CHANGED
@@ -1,634 +1,83 @@
1
1
  /**
2
- * @yaebal/test — testing utilities for yaebal bots, with zero dependency on any
3
- * test runner or assertion library. Works with `node:test`, vitest, bun:test,
4
- * jest, ava — anything that can `await` a promise and call `assert`.
2
+ * @yaebal/test — an actor-driven test framework for yaebal bots, with zero dependency on any
3
+ * test runner or assertion library. Works with `node:test`, vitest, bun:test, jest, ava —
4
+ * anything that can `await` a promise and call `assert`.
5
5
  *
6
- * every plugin test used to hand-build fake updates and a mock api. this package
7
- * extracts that boilerplate: {@link mockApi} records every call (and can drive
8
- * real `before`/`after`/`onError` hooks and simulate failures), the `*Update`
9
- * factories produce real {@link Update} shapes for every update kind, and
10
- * {@link createContext} wraps one in a core {@link Context}.
11
- */
12
-
13
- import {
14
- type AfterHook,
15
- type Api,
16
- type BeforeHook,
17
- type Composer,
18
- Context,
19
- type ErrorAction,
20
- type ErrorHook,
21
- type Message,
22
- type NextFn,
23
- type Update,
24
- type UpdateName,
25
- type UpdateSink,
26
- } from "@yaebal/core";
27
-
28
- /** the payload type for a given update kind — reuses core's `Update` shape, no extra types package needed. */
29
- type Payload<K extends UpdateName> = NonNullable<Update[K]>;
30
-
31
- /** a single recorded api call: the method name and the params it was given. */
32
- export interface RecordedCall {
33
- method: string;
34
- params: Record<string, unknown> | undefined;
35
- }
36
-
37
- /** a canned result for one method: a static value, an `Error` to throw, or a function of `(params, attempt)`. */
38
- export type MockResult =
39
- | unknown
40
- | Error
41
- | ((params: Record<string, unknown> | undefined, attempt: number) => unknown);
42
-
43
- export interface MockApiOptions {
44
- /**
45
- * per-method canned results/errors, keyed by method name — overrides the
46
- * built-in defaults. a function receives `attempt`, a 1-based count of how
47
- * many times that method has been called (including retries), so you can
48
- * simulate "fails twice, then succeeds": `sendMessage: (p, a) => a <= 2 ? new
49
- * TelegramError(...) : { message_id: 1 }`.
50
- */
51
- results?: Record<string, MockResult>;
52
- }
53
-
54
- /** result of {@link mockApi}: the fake `api`, its recorded calls, and inspection helpers. */
55
- export interface MockApi {
56
- api: Api;
57
- calls: RecordedCall[];
58
- /** hooks registered on `api` via `before`/`after`/`onError` — inspect them or invoke them yourself. */
59
- hooks: { before: BeforeHook[]; after: AfterHook[]; onError: ErrorHook[] };
60
- /** the most recent recorded call, optionally filtered to a method. */
61
- lastCall(method?: string): RecordedCall | undefined;
62
- /** every recorded call to a given method, in call order. */
63
- callsTo(method: string): RecordedCall[];
64
- /** set (or replace) the canned result/error for a method after creation. */
65
- setResult(method: string, result: MockResult): void;
66
- /** clear recorded calls and per-method attempt counters. keeps hooks and result overrides. */
67
- reset(): void;
68
- }
69
-
70
- /** default results for known methods; everything else resolves to `{}`. */
71
- function builtinResult(method: string, nextMessageId: () => number): unknown {
72
- if (method.startsWith("send") || method === "copyMessage" || method === "forwardMessage") {
73
- return { message_id: nextMessageId() };
74
- }
75
-
76
- if (method === "answerCallbackQuery") return true;
77
- if (method === "getMe") return { id: 1, is_bot: true, first_name: "bot", username: "bot" };
78
-
79
- return {};
80
- }
81
-
82
- /**
83
- * a fake {@link Api} whose every method records `{ method, params }` into `calls`
84
- * and resolves to a sensible default (auto-incrementing `message_id` for `send*`,
85
- * `true` for `answerCallbackQuery`, `{}` otherwise) — or to whatever `options.results`
86
- * says. `before`/`after`/`onError` are real hook registrars (not no-ops): register
87
- * a hook the same way you would on the production `Api` and it actually runs,
88
- * including retries requested by an `onError` hook. the mock never actually waits
89
- * on a requested `delayMs` — retries settle instantly, so tests stay fast.
90
- */
91
- export function mockApi(options: MockApiOptions = {}): MockApi {
92
- const calls: RecordedCall[] = [];
93
- const overrides: Record<string, MockResult> = { ...options.results };
94
- const attempts = new Map<string, number>();
95
- let nextMessageId = 1;
96
-
97
- const hooks = {
98
- before: [] as BeforeHook[],
99
- after: [] as AfterHook[],
100
- onError: [] as ErrorHook[],
101
- };
102
-
103
- function resolveResult(method: string, params: Record<string, unknown> | undefined): unknown {
104
- const attempt = (attempts.get(method) ?? 0) + 1;
105
- attempts.set(method, attempt);
106
-
107
- const override = overrides[method];
108
- if (typeof override === "function") {
109
- return (override as (p: typeof params, a: number) => unknown)(params, attempt);
110
- }
111
-
112
- return override !== undefined ? override : builtinResult(method, () => nextMessageId++);
113
- }
114
-
115
- const call = async (method: string, params?: Record<string, unknown>): Promise<never> => {
116
- let p = params;
117
- for (const hook of hooks.before) {
118
- const next = await hook(method, p);
119
- if (next !== undefined) p = next;
120
- }
121
-
122
- for (let attempt = 1; ; attempt++) {
123
- calls.push({ method, params: p });
124
-
125
- let result: unknown;
126
- try {
127
- result = resolveResult(method, p);
128
- if (result instanceof Error) throw result;
129
- } catch (error) {
130
- let retry: ErrorAction | undefined;
131
- for (const hook of hooks.onError) {
132
- const action = await hook(method, error, attempt);
133
- if (action?.retry) {
134
- retry = action;
135
- break;
136
- }
137
- }
138
-
139
- if (!retry) throw error;
140
- continue; // the mock never actually waits on retry.delayMs
141
- }
142
-
143
- for (const hook of hooks.after) {
144
- const next = await hook(method, p, result);
145
- if (next !== undefined) result = next;
146
- }
147
-
148
- return result as never;
149
- }
150
- };
151
-
152
- const registrar: Record<string, unknown> = {
153
- call: (method: string, params?: Record<string, unknown>) => call(method, params),
154
- fileUrl: (filePath: string) => `https://example.invalid/file/${filePath}`,
155
- before(hook: BeforeHook) {
156
- hooks.before.push(hook);
157
- return api;
158
- },
159
- after(hook: AfterHook) {
160
- hooks.after.push(hook);
161
- return api;
162
- },
163
- onError(hook: ErrorHook) {
164
- hooks.onError.push(hook);
165
- return api;
166
- },
167
- };
168
-
169
- const api = new Proxy(registrar, {
170
- get(obj, prop: string) {
171
- if (prop in obj) return obj[prop];
172
-
173
- const method = (params?: Record<string, unknown>) => call(prop, params);
174
- obj[prop] = method;
175
-
176
- return method;
177
- },
178
- }) as unknown as Api;
179
-
180
- return {
181
- api,
182
- calls,
183
- hooks,
184
- lastCall: (method) =>
185
- method ? [...calls].reverse().find((c) => c.method === method) : calls.at(-1),
186
- callsTo: (method) => calls.filter((c) => c.method === method),
187
- setResult: (method, result) => {
188
- overrides[method] = result;
189
- },
190
- reset: () => {
191
- calls.length = 0;
192
- attempts.clear();
193
- nextMessageId = 1;
194
- },
195
- };
196
- }
197
-
198
- let updateIdCounter = 0;
199
-
200
- /** build an {@link Update} from a partial, filling in a fresh `update_id`. */
201
- export function createUpdate(partial: Partial<Update> = {}): Update {
202
- return { update_id: ++updateIdCounter, ...partial };
203
- }
204
-
205
- const stubUser = (id: number) => ({ id, is_bot: false, first_name: "u" });
206
-
207
- /** options shared by the message-shaped factories (`message`, `edited_message`, `channel_post`, ...). */
208
- export interface MessageUpdateOptions {
209
- text?: string;
210
- chatId?: number;
211
- fromId?: number;
212
- chatType?: "private" | "group" | "supergroup" | "channel";
213
- }
214
-
215
- function buildMessage(
216
- options: MessageUpdateOptions,
217
- defaultChatType: NonNullable<MessageUpdateOptions["chatType"]>,
218
- ): Message {
219
- const { text = "", chatId = 1, fromId = chatId, chatType = defaultChatType } = options;
220
-
221
- return {
222
- message_id: 1,
223
- date: 0,
224
- chat: { id: chatId, type: chatType },
225
- from: stubUser(fromId),
226
- text,
227
- };
228
- }
229
-
230
- /** build a `message` {@link Update}. */
231
- export function messageUpdate(options: MessageUpdateOptions = {}): Update {
232
- return createUpdate({ message: buildMessage(options, "private") });
233
- }
234
-
235
- /** build an `edited_message` {@link Update}. */
236
- export function editedMessageUpdate(options: MessageUpdateOptions = {}): Update {
237
- return createUpdate({ edited_message: buildMessage(options, "private") });
238
- }
239
-
240
- /** build a `channel_post` {@link Update}. */
241
- export function channelPostUpdate(options: MessageUpdateOptions = {}): Update {
242
- return createUpdate({ channel_post: buildMessage(options, "channel") });
243
- }
244
-
245
- /** build an `edited_channel_post` {@link Update}. */
246
- export function editedChannelPostUpdate(options: MessageUpdateOptions = {}): Update {
247
- return createUpdate({ edited_channel_post: buildMessage(options, "channel") });
248
- }
249
-
250
- /** options for {@link callbackUpdate}. */
251
- export interface CallbackUpdateOptions {
252
- data?: string;
253
- chatId?: number;
254
- fromId?: number;
255
- }
256
-
257
- /** build a `callback_query` {@link Update}. */
258
- export function callbackUpdate(options: CallbackUpdateOptions = {}): Update {
259
- const { data = "", chatId = 1, fromId = chatId } = options;
260
-
261
- return createUpdate({
262
- callback_query: {
263
- id: "1",
264
- chat_instance: "0",
265
- from: stubUser(fromId),
266
- message: {
267
- message_id: 1,
268
- date: 0,
269
- chat: { id: chatId, type: "private" },
270
- },
271
- data,
272
- },
273
- });
274
- }
275
-
276
- /** options for {@link inlineQueryUpdate}. */
277
- export interface InlineQueryUpdateOptions {
278
- query?: string;
279
- fromId?: number;
280
- id?: string;
281
- offset?: string;
282
- chatType?: Payload<"inline_query">["chat_type"];
283
- }
284
-
285
- /** build an `inline_query` {@link Update}. */
286
- export function inlineQueryUpdate(options: InlineQueryUpdateOptions = {}): Update {
287
- const { query = "", fromId = 1, id = "1", offset = "", chatType } = options;
288
-
289
- return createUpdate({
290
- inline_query: {
291
- id,
292
- from: stubUser(fromId),
293
- query,
294
- offset,
295
- ...(chatType ? { chat_type: chatType } : {}),
296
- },
297
- });
298
- }
299
-
300
- /** options for {@link chosenInlineResultUpdate}. */
301
- export interface ChosenInlineResultUpdateOptions {
302
- resultId?: string;
303
- fromId?: number;
304
- query?: string;
305
- inlineMessageId?: string;
306
- }
307
-
308
- /** build a `chosen_inline_result` {@link Update}. */
309
- export function chosenInlineResultUpdate(options: ChosenInlineResultUpdateOptions = {}): Update {
310
- const { resultId = "1", fromId = 1, query = "", inlineMessageId } = options;
311
-
312
- return createUpdate({
313
- chosen_inline_result: {
314
- result_id: resultId,
315
- from: stubUser(fromId),
316
- query,
317
- ...(inlineMessageId ? { inline_message_id: inlineMessageId } : {}),
318
- },
319
- });
320
- }
321
-
322
- /** options for {@link shippingQueryUpdate}. */
323
- export interface ShippingQueryUpdateOptions {
324
- id?: string;
325
- fromId?: number;
326
- invoicePayload?: string;
327
- shippingAddress?: Partial<Payload<"shipping_query">["shipping_address"]>;
328
- }
329
-
330
- /** build a `shipping_query` {@link Update}. */
331
- export function shippingQueryUpdate(options: ShippingQueryUpdateOptions = {}): Update {
332
- const { id = "1", fromId = 1, invoicePayload = "", shippingAddress = {} } = options;
333
-
334
- return createUpdate({
335
- shipping_query: {
336
- id,
337
- from: stubUser(fromId),
338
- invoice_payload: invoicePayload,
339
- shipping_address: {
340
- country_code: "US",
341
- state: "",
342
- city: "New York",
343
- street_line1: "",
344
- street_line2: "",
345
- post_code: "10001",
346
- ...shippingAddress,
347
- },
348
- },
349
- });
350
- }
351
-
352
- /** options for {@link preCheckoutQueryUpdate}. */
353
- export interface PreCheckoutQueryUpdateOptions {
354
- id?: string;
355
- fromId?: number;
356
- currency?: string;
357
- totalAmount?: number;
358
- invoicePayload?: string;
359
- }
360
-
361
- /** build a `pre_checkout_query` {@link Update}. */
362
- export function preCheckoutQueryUpdate(options: PreCheckoutQueryUpdateOptions = {}): Update {
363
- const {
364
- id = "1",
365
- fromId = 1,
366
- currency = "USD",
367
- totalAmount = 100,
368
- invoicePayload = "",
369
- } = options;
370
-
371
- return createUpdate({
372
- pre_checkout_query: {
373
- id,
374
- from: stubUser(fromId),
375
- currency,
376
- total_amount: totalAmount,
377
- invoice_payload: invoicePayload,
378
- },
379
- });
380
- }
381
-
382
- /** options for {@link pollUpdate}. */
383
- export interface PollUpdateOptions {
384
- id?: string;
385
- question?: string;
386
- options?: string[];
387
- isClosed?: boolean;
388
- }
389
-
390
- /** build a `poll` {@link Update}. */
391
- export function pollUpdate(options: PollUpdateOptions = {}): Update {
392
- const { id = "1", question = "", options: choices = ["yes", "no"], isClosed = false } = options;
393
-
394
- return createUpdate({
395
- poll: {
396
- id,
397
- question,
398
- options: choices.map((text, i) => ({ persistent_id: String(i), text, voter_count: 0 })),
399
- total_voter_count: 0,
400
- is_closed: isClosed,
401
- is_anonymous: true,
402
- type: "regular",
403
- allows_multiple_answers: false,
404
- allows_revoting: false,
405
- members_only: false,
406
- },
407
- });
408
- }
409
-
410
- /** options for {@link pollAnswerUpdate}. */
411
- export interface PollAnswerUpdateOptions {
412
- pollId?: string;
413
- fromId?: number;
414
- optionIds?: number[];
415
- }
416
-
417
- /** build a `poll_answer` {@link Update}. */
418
- export function pollAnswerUpdate(options: PollAnswerUpdateOptions = {}): Update {
419
- const { pollId = "1", fromId = 1, optionIds = [0] } = options;
420
-
421
- return createUpdate({
422
- poll_answer: {
423
- poll_id: pollId,
424
- user: stubUser(fromId),
425
- option_ids: optionIds,
426
- option_persistent_ids: optionIds.map(String),
427
- },
428
- });
429
- }
430
-
431
- /** options for {@link myChatMemberUpdate} / {@link chatMemberUpdate}. */
432
- export interface ChatMemberUpdateOptions {
433
- chatId?: number;
434
- fromId?: number;
435
- userId?: number;
436
- oldStatus?: string;
437
- newStatus?: string;
438
- }
439
-
440
- function buildChatMemberUpdate(options: ChatMemberUpdateOptions): Payload<"my_chat_member"> {
441
- const {
442
- chatId = 1,
443
- fromId = chatId,
444
- userId = fromId,
445
- oldStatus = "member",
446
- newStatus = "member",
447
- } = options;
448
- const user = stubUser(userId);
449
-
450
- return {
451
- chat: { id: chatId, type: "group" },
452
- from: stubUser(fromId),
453
- date: 0,
454
- old_chat_member: { status: oldStatus, user },
455
- new_chat_member: { status: newStatus, user },
456
- };
457
- }
458
-
459
- /** build a `my_chat_member` {@link Update} (the bot's own membership changed). */
460
- export function myChatMemberUpdate(options: ChatMemberUpdateOptions = {}): Update {
461
- return createUpdate({ my_chat_member: buildChatMemberUpdate(options) });
462
- }
463
-
464
- /** build a `chat_member` {@link Update} (another member's membership changed). */
465
- export function chatMemberUpdate(options: ChatMemberUpdateOptions = {}): Update {
466
- return createUpdate({ chat_member: buildChatMemberUpdate(options) });
467
- }
468
-
469
- /** options for {@link chatJoinRequestUpdate}. */
470
- export interface ChatJoinRequestUpdateOptions {
471
- chatId?: number;
472
- fromId?: number;
473
- userChatId?: number;
474
- bio?: string;
475
- }
476
-
477
- /** build a `chat_join_request` {@link Update}. */
478
- export function chatJoinRequestUpdate(options: ChatJoinRequestUpdateOptions = {}): Update {
479
- const { chatId = 1, fromId = 1, userChatId = fromId, bio } = options;
480
-
481
- return createUpdate({
482
- chat_join_request: {
483
- chat: { id: chatId, type: "group" },
484
- from: stubUser(fromId),
485
- user_chat_id: userChatId,
486
- date: 0,
487
- ...(bio ? { bio } : {}),
488
- },
489
- });
490
- }
491
-
492
- /** infer which payload key an update carries; defaults to `"message"`. */
493
- export function detectUpdateType(update: Update): UpdateName {
494
- if (update.message) return "message";
495
- if (update.edited_message) return "edited_message";
496
- if (update.channel_post) return "channel_post";
497
- if (update.callback_query) return "callback_query";
498
-
499
- const bag = update as unknown as Record<string, unknown>;
500
- for (const key of Object.keys(bag)) {
501
- if (key !== "update_id" && bag[key] !== undefined) return key as UpdateName;
502
- }
503
-
504
- return "message";
505
- }
506
-
507
- /**
508
- * wrap an {@link Update} in a core {@link Context}. the api defaults to a fresh
509
- * {@link mockApi}; pass `updateType` to override the auto-detected one.
510
- */
511
- export function createContext(update: Update, api?: Api, updateType?: UpdateName): Context {
512
- return new Context({
513
- api: api ?? mockApi().api,
514
- update,
515
- updateType: updateType ?? detectUpdateType(update),
516
- });
517
- }
518
-
519
- /** shortcut: build a `message` update and wrap it in a {@link Context} in one call. */
520
- export function messageContext(options: MessageUpdateOptions = {}, api?: Api): Context {
521
- return createContext(messageUpdate(options), api);
522
- }
523
-
524
- /** shortcut: build a `callback_query` update and wrap it in a {@link Context} in one call. */
525
- export function callbackContext(options: CallbackUpdateOptions = {}, api?: Api): Context {
526
- return createContext(callbackUpdate(options), api);
527
- }
528
-
529
- const noop: NextFn = async () => {};
530
-
531
- /** run a composer's middleware against a context. resolves when the chain settles. */
532
- export async function runMiddleware<C extends Context>(
533
- composer: Composer<C>,
534
- ctx: C,
535
- ): Promise<void> {
536
- await composer.toMiddleware()(ctx, noop);
537
- }
538
-
539
- /** an inline keyboard button found by {@link findButton}, with its position. */
540
- export interface FoundButton {
541
- text: string;
542
- row: number;
543
- col: number;
544
- [key: string]: unknown;
545
- }
546
-
547
- /**
548
- * search an inline keyboard (a `reply_markup`-shaped object, e.g. from a
549
- * recorded `sendMessage` call's params) for a button whose text matches a
550
- * string or regex. returns the button (plus its `row`/`col`) or `undefined`.
6
+ * {@link createTestEnv} wraps your bot and hands you {@link UserActor}/{@link ChatActor} actors
7
+ * that send it real updates messages, commands, media, reactions, button clicks, joins,
8
+ * payments — the way real Telegram users would. every outgoing api call is intercepted and
9
+ * recorded (no real HTTP), with sensible auto-stubs, `onApi`/`apiError` overrides for the rest,
10
+ * a virtual clock for TTL/retry tests, and satellite-plugin test packs.
11
+ *
12
+ * fixture builders ({@link messageUpdate} & co.), {@link webhookRequest}/{@link collectUpdates},
13
+ * and {@link withFetch} remain as the escape hatch beneath the actor api — reach for them when
14
+ * you need a raw update shape or full control.
551
15
  */
552
- export function findButton(
553
- markup: { inline_keyboard?: Array<Array<Record<string, unknown>>> } | undefined,
554
- match: string | RegExp,
555
- ): FoundButton | undefined {
556
- const rows = markup?.inline_keyboard ?? [];
557
-
558
- for (let row = 0; row < rows.length; row++) {
559
- const cols = rows[row] ?? [];
560
-
561
- for (let col = 0; col < cols.length; col++) {
562
- const button = cols[col];
563
- if (!button) continue;
564
-
565
- const text = typeof button.text === "string" ? button.text : "";
566
- const matches = typeof match === "string" ? text === match : match.test(text);
567
-
568
- if (matches) return { ...button, text, row, col };
569
- }
570
- }
571
-
572
- return undefined;
573
- }
574
-
575
- /** result of {@link collectUpdates}: an {@link UpdateSink} plus the updates it received, in order. */
576
- export interface UpdateCollector {
577
- sink: UpdateSink;
578
- updates: Update[];
579
- }
580
-
581
- /** a minimal {@link UpdateSink} (the `{ handleUpdate }` shape `webhookCallback`/runners expect) that just records. */
582
- export function collectUpdates(): UpdateCollector {
583
- const updates: Update[] = [];
584
-
585
- return {
586
- sink: {
587
- handleUpdate: async (update) => {
588
- updates.push(update);
589
- },
590
- },
591
- updates,
592
- };
593
- }
594
-
595
- /** options for {@link webhookRequest}. */
596
- export interface WebhookRequestOptions {
597
- url?: string;
598
- method?: string;
599
- secretToken?: string;
600
- headers?: Record<string, string>;
601
- }
602
-
603
- /** build a `Request` carrying `update` as JSON, as telegram would POST it to a webhook handler. */
604
- export function webhookRequest(update: Update, options: WebhookRequestOptions = {}): Request {
605
- const {
606
- url = "https://example.invalid/webhook",
607
- method = "POST",
608
- secretToken,
609
- headers = {},
610
- } = options;
611
-
612
- const finalHeaders: Record<string, string> = { "content-type": "application/json", ...headers };
613
- if (secretToken) finalHeaders["x-telegram-bot-api-secret-token"] = secretToken;
614
-
615
- return new Request(url, {
616
- method,
617
- headers: finalHeaders,
618
- body: method === "GET" || method === "HEAD" ? undefined : JSON.stringify(update),
619
- });
620
- }
621
-
622
- /** stub `globalThis.fetch` for the duration of `fn`, restoring the original afterwards (even on throw). */
623
- export async function withFetch<T>(handler: typeof fetch, fn: () => T | Promise<T>): Promise<T> {
624
- const realFetch = globalThis.fetch;
625
- globalThis.fetch = handler;
626
-
627
- try {
628
- return await fn();
629
- } finally {
630
- globalThis.fetch = realFetch;
631
- }
632
- }
633
16
 
634
- export type { Message };
17
+ export { type MockApi, type MockApiOptions, mockApi } from "./api.js";
18
+ export {
19
+ type ApiErrorSentinel,
20
+ apiError,
21
+ type BotMessage,
22
+ ChatActor,
23
+ type ChatMembership,
24
+ type ChatType,
25
+ type CreateChatOptions,
26
+ createTestEnv,
27
+ installTestClock,
28
+ isApiErrorSentinel,
29
+ type LastBotMessageQuery,
30
+ type MediaOptions,
31
+ type MessageOptions,
32
+ type MockResult,
33
+ type OnApiOptions,
34
+ type RecordedCall,
35
+ TestApiError,
36
+ type TestClock,
37
+ TestEnv,
38
+ type TestEnvOptions,
39
+ type TestPack,
40
+ UserActor,
41
+ UserInChatScope,
42
+ UserOnMessageScope,
43
+ } from "./env.js";
44
+ export { withFetch } from "./fetch.js";
45
+
46
+ export { type FoundButton, findButton } from "./keyboard.js";
47
+ export { toPlain } from "./normalize.js";
48
+ export {
49
+ type BuildUserOptions,
50
+ buildUser,
51
+ type CallbackUpdateOptions,
52
+ type ChatJoinRequestUpdateOptions,
53
+ type ChatMemberUpdateOptions,
54
+ type ChosenInlineResultUpdateOptions,
55
+ callbackUpdate,
56
+ channelPostUpdate,
57
+ chatJoinRequestUpdate,
58
+ chatMemberUpdate,
59
+ chosenInlineResultUpdate,
60
+ createUpdate,
61
+ detectUpdateType,
62
+ editedChannelPostUpdate,
63
+ editedMessageUpdate,
64
+ type InlineQueryUpdateOptions,
65
+ inlineQueryUpdate,
66
+ type MessageUpdateOptions,
67
+ messageUpdate,
68
+ myChatMemberUpdate,
69
+ type PollAnswerUpdateOptions,
70
+ type PollUpdateOptions,
71
+ type PreCheckoutQueryUpdateOptions,
72
+ pollAnswerUpdate,
73
+ pollUpdate,
74
+ preCheckoutQueryUpdate,
75
+ type ShippingQueryUpdateOptions,
76
+ shippingQueryUpdate,
77
+ } from "./updates.js";
78
+ export {
79
+ collectUpdates,
80
+ type UpdateCollector,
81
+ type WebhookRequestOptions,
82
+ webhookRequest,
83
+ } from "./webhook.js";