@dual-os/telegram 0.0.0-stage → 8.0.5

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 (53) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +65 -2
  3. package/Runner.js +5539 -0
  4. package/Runner.js.map +59 -0
  5. package/bundle-inventory.json +1 -0
  6. package/dist/Telegram.d.ts +5291 -0
  7. package/dist/Telegram.d.ts.map +1 -0
  8. package/dist/TelegramClient.d.ts +203 -0
  9. package/dist/TelegramClient.d.ts.map +1 -0
  10. package/dist/TelegramClient.js +28 -0
  11. package/dist/TelegramClient.js.map +9 -0
  12. package/dist/TelegramDefinition.d.ts +1556 -0
  13. package/dist/TelegramDefinition.d.ts.map +1 -0
  14. package/dist/channel/telegram-bot-client.d.ts +45 -0
  15. package/dist/channel/telegram-bot-client.d.ts.map +1 -0
  16. package/dist/channel/telegram-bot-definition.d.ts +155 -0
  17. package/dist/channel/telegram-bot-definition.d.ts.map +1 -0
  18. package/dist/channel/telegram-bot-webhook.d.ts +62 -0
  19. package/dist/channel/telegram-bot-webhook.d.ts.map +1 -0
  20. package/dist/channel/telegram-bot.d.ts +111 -0
  21. package/dist/channel/telegram-bot.d.ts.map +1 -0
  22. package/dist/definition.d.ts +1114 -0
  23. package/dist/definition.d.ts.map +1 -0
  24. package/dist/definition.js +20 -0
  25. package/dist/definition.js.map +9 -0
  26. package/dist/index.d.ts +3 -0
  27. package/dist/index.js +17 -0
  28. package/dist/index.js.map +9 -0
  29. package/dist/internal/TelegramSchemas.d.ts +375 -0
  30. package/dist/internal/TelegramSchemas.d.ts.map +1 -0
  31. package/dist/plugin.d.ts +3282 -0
  32. package/dist/plugin.d.ts.map +1 -0
  33. package/dist/plugin.js +26 -0
  34. package/dist/plugin.js.map +9 -0
  35. package/dual-plugin.json +1 -0
  36. package/index-68np0qzt.js +224 -0
  37. package/index-68np0qzt.js.map +11 -0
  38. package/index-hpjyc5yq.js +847 -0
  39. package/index-hpjyc5yq.js.map +14 -0
  40. package/index-pm1rw9n0.js +1301 -0
  41. package/index-pm1rw9n0.js.map +18 -0
  42. package/index-ppnnem2q.js +5473 -0
  43. package/index-ppnnem2q.js.map +56 -0
  44. package/index-sdgqen8s.js +13975 -0
  45. package/index-sdgqen8s.js.map +111 -0
  46. package/index-xc47zv2c.js +251 -0
  47. package/index-xc47zv2c.js.map +10 -0
  48. package/licenses/@dual-os_sdk@0.9.0/LICENSE +4 -0
  49. package/licenses/@effect_platform-node-shared@4.1.2/LICENSE +21 -0
  50. package/licenses/@effect_platform-node@4.1.2/LICENSE +21 -0
  51. package/licenses/effect@4.1.2/LICENSE +21 -0
  52. package/package.json +1 -6
  53. package/plugin.json +8 -0
@@ -0,0 +1,847 @@
1
+ // @bun
2
+ import {
3
+ __exportAll
4
+ } from "./index-68np0qzt.js";
5
+ import {
6
+ TelegramClient2,
7
+ layer2
8
+ } from "./index-xc47zv2c.js";
9
+ import {
10
+ toLowerCase,
11
+ slice,
12
+ isEmpty,
13
+ split,
14
+ startsWith,
15
+ endsWith,
16
+ RequestInit,
17
+ layer4,
18
+ Action_exports,
19
+ AgentChannel_exports,
20
+ Plugin_exports
21
+ } from "./index-ppnnem2q.js";
22
+ import {
23
+ telegramAccessToken2,
24
+ TelegramUpdateV22,
25
+ telegramPluginBase2,
26
+ userKey,
27
+ chatKey,
28
+ telegramBotToken,
29
+ messagesChannel,
30
+ telegramBotPluginBase,
31
+ telegramPluginBase3
32
+ } from "./index-pm1rw9n0.js";
33
+ import {
34
+ pipe,
35
+ flow,
36
+ Service2,
37
+ toEntries,
38
+ fromIterable,
39
+ isReadonlyArrayEmpty,
40
+ isReadonlyArrayNonEmpty,
41
+ contains2,
42
+ map2,
43
+ filter2,
44
+ some2,
45
+ join,
46
+ effect,
47
+ provide,
48
+ succeed4,
49
+ void_2,
50
+ gen2,
51
+ fail5,
52
+ mapError,
53
+ timeout,
54
+ provideService,
55
+ fnUntraced,
56
+ fn,
57
+ makeUnsafe4,
58
+ formatIso,
59
+ is,
60
+ decodeUnknownEffect,
61
+ decodeEffect,
62
+ optionalKey,
63
+ Literal,
64
+ String3,
65
+ Boolean2,
66
+ Struct,
67
+ ArraySchema,
68
+ Union,
69
+ isPattern,
70
+ isLessThanOrEqualTo,
71
+ isBetween2,
72
+ isInt,
73
+ Int,
74
+ Natural,
75
+ NonEmptyString,
76
+ fromJsonString,
77
+ NumberFromString,
78
+ TaggedError2,
79
+ post,
80
+ acceptJson,
81
+ prependUrl,
82
+ bodyJson,
83
+ schemaBodyJson,
84
+ HttpClient,
85
+ mapRequest
86
+ } from "./index-sdgqen8s.js";
87
+
88
+ // dist/Telegram.js
89
+ import { createHmac, randomUUID, timingSafeEqual } from "crypto";
90
+ var fromTelegramApiFailure = (error) => {
91
+ const fields = {
92
+ cause: error,
93
+ details: {
94
+ operation: error.operation,
95
+ reason: "TelegramApiError"
96
+ },
97
+ message: error.message,
98
+ status: error.status
99
+ };
100
+ return error.status === 429 || error.status >= 500 ? new Action_exports.RetryableActionHandlerError(fields) : new Action_exports.ActionHandlerError(fields);
101
+ };
102
+ var orTelegramFailure = fn("Telegram.orTelegramFailure")(function* (effect) {
103
+ return yield* mapError(effect, (error) => error._tag === "TelegramApiError" ? fromTelegramApiFailure(error) : Action_exports.fromHttpClientFailure(error));
104
+ });
105
+ var baseUrlOf = (context) => context.auth.match({ "access-token": (b) => b.value.baseUrl ?? "https://api.telegram.org" });
106
+ var tokenOf = (context) => context.auth.match({ "access-token": (b) => b.value.accessToken });
107
+ var connOf = (context) => ({
108
+ baseUrl: baseUrlOf(context),
109
+ token: tokenOf(context)
110
+ });
111
+ var deriveSecretToken = (token, webhookUrl) => createHmac("sha256", token).update(webhookUrl).digest("hex");
112
+ var secretTokenOf = (config, webhookUrl, token) => config.secretToken ?? deriveSecretToken(token, webhookUrl);
113
+ var isSecretTokenValid = (request, expected) => {
114
+ if (expected === "")
115
+ return false;
116
+ const provided = request.headers?.["x-telegram-bot-api-secret-token"] ?? "";
117
+ const expectedBuf = Buffer.from(expected);
118
+ const providedBuf = Buffer.from(provided);
119
+ return expectedBuf.length === providedBuf.length && timingSafeEqual(expectedBuf, providedBuf);
120
+ };
121
+ var allowedUpdatesOf = (updates) => updates ?? [];
122
+ var updateChatId = (update) => {
123
+ const candidates = [
124
+ update["message"],
125
+ update["edited_message"],
126
+ update["channel_post"],
127
+ update["edited_channel_post"]
128
+ ];
129
+ for (const candidate of candidates)
130
+ if (typeof candidate === "object" && candidate !== null) {
131
+ const chat = candidate.chat;
132
+ if (typeof chat === "object" && chat !== null) {
133
+ const id = chat.id;
134
+ if (id !== undefined && id !== null)
135
+ return String(id);
136
+ }
137
+ }
138
+ const cb = update["callback_query"];
139
+ if (typeof cb === "object" && cb !== null) {
140
+ const message = cb.message;
141
+ if (typeof message === "object" && message !== null) {
142
+ const chat = message.chat;
143
+ if (typeof chat === "object" && chat !== null) {
144
+ const id = chat.id;
145
+ if (id !== undefined && id !== null)
146
+ return String(id);
147
+ }
148
+ }
149
+ }
150
+ };
151
+ var updateUserId = (update) => {
152
+ const sources = [
153
+ update["message"],
154
+ update["edited_message"],
155
+ update["channel_post"],
156
+ update["edited_channel_post"],
157
+ update["callback_query"],
158
+ update["inline_query"],
159
+ update["pre_checkout_query"],
160
+ update["shipping_query"]
161
+ ];
162
+ for (const source of sources)
163
+ if (typeof source === "object" && source !== null) {
164
+ const from = source.from;
165
+ if (typeof from === "object" && from !== null) {
166
+ const id = from.id;
167
+ if (id !== undefined && id !== null)
168
+ return String(id);
169
+ }
170
+ }
171
+ };
172
+ var activateUpdateV2 = fnUntraced(function* (config, webhookUrl, context) {
173
+ const client = yield* TelegramClient2;
174
+ const connection = connOf(context);
175
+ const registrationUrl = new URL(webhookUrl);
176
+ registrationUrl.searchParams.set("__dual_telegram_registration", randomUUID());
177
+ yield* orTelegramFailure(client.setWebhook({
178
+ ...connection,
179
+ allowedUpdates: allowedUpdatesOf(config.updates),
180
+ secretToken: secretTokenOf(config, webhookUrl, connection.token),
181
+ url: registrationUrl.href
182
+ }));
183
+ return { state: {
184
+ lastUpdateId: null,
185
+ registrationUrl: registrationUrl.href
186
+ } };
187
+ });
188
+ var verifyUpdate = (input, webhookUrl, context, status) => isSecretTokenValid(input.request, secretTokenOf(input.config, webhookUrl, tokenOf(context))) ? void_2 : fail5(new Action_exports.ActionHandlerError({
189
+ message: "invalid Telegram secret token",
190
+ status
191
+ }));
192
+ var deactivateUpdateV2 = fnUntraced(function* (state, context) {
193
+ if (state?.registrationUrl === undefined)
194
+ return;
195
+ const client = yield* TelegramClient2;
196
+ const connection = connOf(context);
197
+ if ((yield* decodeUnknownEffect(Struct({ url: String3 }))(yield* orTelegramFailure(client.getWebhookInfo(connection)))).url !== state.registrationUrl)
198
+ return;
199
+ yield* orTelegramFailure(client.deleteWebhook(connection));
200
+ });
201
+ var parseUpdateV2 = fnUntraced(function* (input, webhookUrl, context) {
202
+ yield* verifyUpdate(input, webhookUrl, context, 401);
203
+ const body = yield* decodeUnknownEffect(TelegramUpdateV22)(input.request.body);
204
+ const state = {
205
+ ...input.state,
206
+ lastUpdateId: body.update_id
207
+ };
208
+ if (isReadonlyArrayNonEmpty(input.config.updates ?? []) && !some2(input.config.updates ?? [], (kind) => body[kind] !== undefined))
209
+ return {
210
+ events: [],
211
+ state
212
+ };
213
+ const chatId = body.chat_member?.chat.id ?? body.my_chat_member?.chat.id ?? body.message_reaction?.chat.id ?? body.message_reaction_count?.chat.id;
214
+ const userId = body.chat_member?.from.id ?? body.my_chat_member?.from.id ?? body.message_reaction?.user?.id;
215
+ if (isReadonlyArrayNonEmpty(input.config.chatIds ?? [])) {
216
+ const id = chatId === undefined ? updateChatId(body) : String(chatId);
217
+ if (id === undefined || !contains2(input.config.chatIds ?? [], id))
218
+ return {
219
+ events: [],
220
+ state
221
+ };
222
+ }
223
+ if (isReadonlyArrayNonEmpty(input.config.userIds ?? [])) {
224
+ const id = userId === undefined ? updateUserId(body) : String(userId);
225
+ if (id === undefined || !contains2(input.config.userIds ?? [], id))
226
+ return {
227
+ events: [],
228
+ state
229
+ };
230
+ }
231
+ return {
232
+ events: [{
233
+ key: `update:${body.update_id}`,
234
+ payload: body
235
+ }],
236
+ state
237
+ };
238
+ });
239
+ var TelegramLive2 = Plugin_exports.toLayer(telegramPluginBase2, (pluginHandlers) => pluginHandlers.group("callback", (handlers) => handlers.action("answer-inline-query", fn("@dual-os/telegram/callback.answer-inline-query")(function* (input, context) {
240
+ const client = yield* TelegramClient2;
241
+ return yield* orTelegramFailure(client.answerInlineQuery({
242
+ ...connOf(context),
243
+ ...input
244
+ }));
245
+ })).action("answer-query", fn("@dual-os/telegram/callback.answer-query")(function* (input, context) {
246
+ const client = yield* TelegramClient2;
247
+ return yield* orTelegramFailure(client.answerCallbackQuery({
248
+ ...connOf(context),
249
+ ...input
250
+ }));
251
+ }))).group("chat", (handlers) => handlers.action("administrators", fn("@dual-os/telegram/chat.administrators")(function* (input, context) {
252
+ const client = yield* TelegramClient2;
253
+ return yield* orTelegramFailure(client.getChatAdministrators({
254
+ ...connOf(context),
255
+ ...input
256
+ }));
257
+ })).action("get", fn("@dual-os/telegram/chat.get")(function* (input, context) {
258
+ const client = yield* TelegramClient2;
259
+ return yield* orTelegramFailure(client.getChat({
260
+ ...connOf(context),
261
+ ...input
262
+ }));
263
+ })).action("leave", fn("@dual-os/telegram/chat.leave")(function* (input, context) {
264
+ const client = yield* TelegramClient2;
265
+ return yield* orTelegramFailure(client.leaveChat({
266
+ ...connOf(context),
267
+ ...input
268
+ }));
269
+ })).action("member", fn("@dual-os/telegram/chat.member")(function* (input, context) {
270
+ const client = yield* TelegramClient2;
271
+ return yield* orTelegramFailure(client.getChatMember({
272
+ ...connOf(context),
273
+ ...input
274
+ }));
275
+ })).action("set-description", fn("@dual-os/telegram/chat.set-description")(function* (input, context) {
276
+ const client = yield* TelegramClient2;
277
+ return yield* orTelegramFailure(client.setChatDescription({
278
+ ...connOf(context),
279
+ ...input
280
+ }));
281
+ })).action("set-title", fn("@dual-os/telegram/chat.set-title")(function* (input, context) {
282
+ const client = yield* TelegramClient2;
283
+ return yield* orTelegramFailure(client.setChatTitle({
284
+ ...connOf(context),
285
+ ...input
286
+ }));
287
+ }))).group("file", (handlers) => handlers.action("get", fn("@dual-os/telegram/file.get")(function* (input, context) {
288
+ const client = yield* TelegramClient2;
289
+ return yield* orTelegramFailure(client.getFile({
290
+ ...connOf(context),
291
+ ...input
292
+ }));
293
+ }))).group("message", (handlers) => handlers.action("delete-message", fn("@dual-os/telegram/message.delete-message")(function* (input, context) {
294
+ const client = yield* TelegramClient2;
295
+ return yield* orTelegramFailure(client.deleteMessage({
296
+ ...connOf(context),
297
+ ...input
298
+ }));
299
+ })).action("edit-message-text", fn("@dual-os/telegram/message.edit-message-text")(function* (input, context) {
300
+ const client = yield* TelegramClient2;
301
+ return yield* orTelegramFailure(client.editMessageText({
302
+ ...connOf(context),
303
+ ...input
304
+ }));
305
+ })).action("pin-chat-message", fn("@dual-os/telegram/message.pin-chat-message")(function* (input, context) {
306
+ const client = yield* TelegramClient2;
307
+ return yield* orTelegramFailure(client.pinChatMessage({
308
+ ...connOf(context),
309
+ ...input
310
+ }));
311
+ })).action("send-animation", fn("@dual-os/telegram/message.send-animation")(function* (input, context) {
312
+ const client = yield* TelegramClient2;
313
+ return yield* orTelegramFailure(client.sendAnimation({
314
+ ...connOf(context),
315
+ ...input
316
+ }));
317
+ })).action("send-audio", fn("@dual-os/telegram/message.send-audio")(function* (input, context) {
318
+ const client = yield* TelegramClient2;
319
+ return yield* orTelegramFailure(client.sendAudio({
320
+ ...connOf(context),
321
+ ...input
322
+ }));
323
+ })).action("send-chat-action", fn("@dual-os/telegram/message.send-chat-action")(function* (input, context) {
324
+ const client = yield* TelegramClient2;
325
+ return yield* orTelegramFailure(client.sendChatAction({
326
+ ...connOf(context),
327
+ ...input
328
+ }));
329
+ })).action("send-document", fn("@dual-os/telegram/message.send-document")(function* (input, context) {
330
+ const client = yield* TelegramClient2;
331
+ return yield* orTelegramFailure(client.sendDocument({
332
+ ...connOf(context),
333
+ ...input
334
+ }));
335
+ })).action("send-location", fn("@dual-os/telegram/message.send-location")(function* (input, context) {
336
+ const client = yield* TelegramClient2;
337
+ return yield* orTelegramFailure(client.sendLocation({
338
+ ...connOf(context),
339
+ ...input
340
+ }));
341
+ })).action("send-media-group", fn("@dual-os/telegram/message.send-media-group")(function* (input, context) {
342
+ const client = yield* TelegramClient2;
343
+ return yield* orTelegramFailure(client.sendMediaGroup({
344
+ ...connOf(context),
345
+ ...input
346
+ }));
347
+ })).action("send-message", fn("@dual-os/telegram/message.send-message")(function* (input, context) {
348
+ const client = yield* TelegramClient2;
349
+ return yield* orTelegramFailure(client.sendMessage({
350
+ ...connOf(context),
351
+ ...input
352
+ }));
353
+ })).action("send-photo", fn("@dual-os/telegram/message.send-photo")(function* (input, context) {
354
+ const client = yield* TelegramClient2;
355
+ return yield* orTelegramFailure(client.sendPhoto({
356
+ ...connOf(context),
357
+ ...input
358
+ }));
359
+ })).action("send-sticker", fn("@dual-os/telegram/message.send-sticker")(function* (input, context) {
360
+ const client = yield* TelegramClient2;
361
+ return yield* orTelegramFailure(client.sendSticker({
362
+ ...connOf(context),
363
+ ...input
364
+ }));
365
+ })).action("send-video", fn("@dual-os/telegram/message.send-video")(function* (input, context) {
366
+ const client = yield* TelegramClient2;
367
+ return yield* orTelegramFailure(client.sendVideo({
368
+ ...connOf(context),
369
+ ...input
370
+ }));
371
+ })).action("unpin-chat-message", fn("@dual-os/telegram/message.unpin-chat-message")(function* (input, context) {
372
+ const client = yield* TelegramClient2;
373
+ return yield* orTelegramFailure(client.unpinChatMessage({
374
+ ...connOf(context),
375
+ ...input
376
+ }));
377
+ }))).trigger("update", {
378
+ activate: (input, context) => activateUpdateV2(input.config, input.webhookUrl, context),
379
+ deactivate: (input, context) => deactivateUpdateV2(input.state, context),
380
+ parse: (input, context) => parseUpdateV2(input, input.webhookUrl, context),
381
+ verify: (input, context) => verifyUpdate(input, input.webhookUrl, context, 401)
382
+ }));
383
+ var telegramPlugin = telegramPluginBase2.pipe(Plugin_exports.provide(TelegramLive2), Plugin_exports.provide(layer2), Plugin_exports.provide(layer4));
384
+
385
+ // dist/channel/telegram-bot-client.js
386
+ var numericId = Int.check(isBetween2({
387
+ minimum: 1,
388
+ maximum: 9007199254740991
389
+ }));
390
+ var bot = Struct({
391
+ id: numericId,
392
+ is_bot: Literal(true),
393
+ username: NonEmptyString
394
+ });
395
+ var webhook = Struct({ url: String3 });
396
+ var sentMessage = Struct({
397
+ chat: Struct({ id: Int }),
398
+ message_id: numericId,
399
+ message_thread_id: optionalKey(numericId)
400
+ });
401
+ var failure = Struct({
402
+ description: String3,
403
+ error_code: Int,
404
+ ok: Literal(false),
405
+ parameters: optionalKey(Struct({ retry_after: optionalKey(Natural) }))
406
+ });
407
+ var TelegramBotFailure = class extends TaggedError2()("TelegramBotFailure", {
408
+ code: AgentChannel_exports.FailureCode,
409
+ retryAfterSeconds: optionalKey(Natural)
410
+ }) {
411
+ };
412
+ function uncertainCode(createsMessage) {
413
+ if (createsMessage)
414
+ return "unknown_completion";
415
+ return "unavailable";
416
+ }
417
+ function errorCode(status, createsMessage) {
418
+ if (status === 429)
419
+ return "rate_limited";
420
+ if (status === 401 || status === 403)
421
+ return "unauthorized";
422
+ if (status >= 500)
423
+ return uncertainCode(createsMessage);
424
+ return "rejected";
425
+ }
426
+ function retryDelay(parameters) {
427
+ if (parameters?.retry_after === undefined)
428
+ return {};
429
+ return { retryAfterSeconds: parameters.retry_after };
430
+ }
431
+ var make = gen2(function* () {
432
+ const transport = yield* HttpClient;
433
+ const client = pipe(transport, mapRequest(flow(prependUrl("https://api.telegram.org"), acceptJson)));
434
+ const call = fn("TelegramBotClient.call")(function* (auth, method, body, result, createsMessage = false) {
435
+ const request = yield* pipe(post(`/bot${auth.botToken}/${method}`), bodyJson(body), mapError(() => TelegramBotFailure.make({ code: "rejected" })));
436
+ const response = yield* pipe(client.execute(request), provideService(RequestInit, { redirect: "manual" }), timeout("30 seconds"), mapError(() => TelegramBotFailure.make({ code: uncertainCode(createsMessage) })));
437
+ const envelope = Union([Struct({
438
+ ok: Literal(true),
439
+ result
440
+ }), failure]);
441
+ const decoded = yield* pipe(schemaBodyJson(envelope)(response), timeout("30 seconds"), mapError((error) => {
442
+ if (response.status >= 200 && response.status < 300) {
443
+ if (createsMessage)
444
+ return TelegramBotFailure.make({ code: "unknown_completion" });
445
+ if (error._tag === "TimeoutError" || error._tag === "HttpClientError")
446
+ return TelegramBotFailure.make({ code: "unavailable" });
447
+ }
448
+ return TelegramBotFailure.make({ code: errorCode(response.status, createsMessage) });
449
+ }));
450
+ if (decoded.ok && response.status >= 200 && response.status < 300)
451
+ return decoded.result;
452
+ if (!decoded.ok) {
453
+ if (response.status >= 500)
454
+ return yield* TelegramBotFailure.make({ code: uncertainCode(createsMessage) });
455
+ return yield* TelegramBotFailure.make({
456
+ code: errorCode(decoded.error_code, createsMessage),
457
+ ...retryDelay(decoded.parameters)
458
+ });
459
+ }
460
+ return yield* TelegramBotFailure.make({ code: uncertainCode(createsMessage) });
461
+ });
462
+ return {
463
+ deleteMessage: (auth, body) => call(auth, "deleteMessage", body, Literal(true)),
464
+ deleteWebhook: (auth) => call(auth, "deleteWebhook", { drop_pending_updates: false }, Literal(true)),
465
+ editMessageText: (auth, body) => call(auth, "editMessageText", body, sentMessage),
466
+ getMe: (auth) => call(auth, "getMe", {}, bot),
467
+ getWebhookInfo: (auth) => call(auth, "getWebhookInfo", {}, webhook),
468
+ sendChatAction: (auth, body) => call(auth, "sendChatAction", body, Literal(true)),
469
+ sendMessage: (auth, body) => call(auth, "sendMessage", body, sentMessage, true),
470
+ setMessageReaction: (auth, body) => call(auth, "setMessageReaction", body, Literal(true)),
471
+ setWebhook: (auth, url) => call(auth, "setWebhook", {
472
+ allowed_updates: ["message"],
473
+ drop_pending_updates: false,
474
+ secret_token: auth.webhookSecret,
475
+ url
476
+ }, Literal(true))
477
+ };
478
+ });
479
+ var TelegramBotClient = class extends Service2()("@dual-os/telegram-bot/telegram-bot-client/TelegramBotClient") {
480
+ static layer = effect(this, make);
481
+ };
482
+
483
+ // dist/channel/telegram-bot-webhook.js
484
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
485
+ var positiveId = Int.check(isBetween2({
486
+ minimum: 1,
487
+ maximum: 9007199254740991
488
+ }));
489
+ var user = Struct({
490
+ id: positiveId,
491
+ is_bot: Boolean2
492
+ });
493
+ var chat = Struct({
494
+ id: Int.check(isBetween2({
495
+ minimum: -9007199254740991,
496
+ maximum: 9007199254740991
497
+ })),
498
+ type: String3
499
+ });
500
+ var entity = Struct({
501
+ length: Natural,
502
+ offset: Natural,
503
+ type: String3,
504
+ user: optionalKey(user)
505
+ });
506
+ var message = Struct({
507
+ business_connection_id: optionalKey(String3),
508
+ chat,
509
+ date: Natural.check(isLessThanOrEqualTo(253402300799)),
510
+ entities: optionalKey(ArraySchema(entity)),
511
+ from: optionalKey(user),
512
+ forward_origin: optionalKey(Struct({ type: String3 })),
513
+ is_automatic_forward: optionalKey(Boolean2),
514
+ message_id: positiveId,
515
+ message_thread_id: optionalKey(positiveId),
516
+ reply_to_message: optionalKey(Struct({
517
+ chat,
518
+ from: optionalKey(user),
519
+ message_id: positiveId,
520
+ message_thread_id: optionalKey(positiveId)
521
+ })),
522
+ sender_chat: optionalKey(chat),
523
+ text: optionalKey(String3)
524
+ });
525
+ var addressedCommand = String3.check(isPattern(/^\/[a-z0-9_]+@[a-z0-9_]+$/u));
526
+ var update = Struct({
527
+ edited_message: optionalKey(message),
528
+ message: optionalKey(message),
529
+ update_id: Natural
530
+ });
531
+ function verify(request, secret) {
532
+ const headers = filter2(toEntries(request.headers), (entry) => toLowerCase(entry[0]) === "x-telegram-bot-api-secret-token");
533
+ const received = headers[0]?.[1];
534
+ if (request.method !== "POST" || headers.length !== 1 || received === undefined)
535
+ return fail5(AgentChannel_exports.HandlerError.make({ code: "unauthorized" }));
536
+ const actual = new TextEncoder().encode(received);
537
+ const expected = new TextEncoder().encode(secret);
538
+ if (actual.byteLength !== expected.byteLength || !timingSafeEqual2(actual, expected))
539
+ return fail5(AgentChannel_exports.HandlerError.make({ code: "unauthorized" }));
540
+ return succeed4({ verified: true });
541
+ }
542
+ function messageKey(destination, id) {
543
+ return `${destination.conversationKey}/${destination.threadKey ?? "main"}/${id}`;
544
+ }
545
+ function chatKind(type) {
546
+ if (type === "private")
547
+ return "direct";
548
+ return "group";
549
+ }
550
+ function threadKey(id) {
551
+ if (id === undefined)
552
+ return {};
553
+ return { threadKey: `${id}` };
554
+ }
555
+ function replyKey(destination, reply) {
556
+ if (reply === undefined)
557
+ return {};
558
+ return { replyToMessageKey: messageKey(destination, reply.message_id) };
559
+ }
560
+ function inScope(conversation, settings) {
561
+ if (conversation.kind === "direct")
562
+ return settings.directMessages;
563
+ return isReadonlyArrayEmpty(settings.chatIds) || contains2(settings.chatIds, conversation.conversationKey) || conversation.threadKey !== undefined && contains2(settings.chatIds, `${conversation.conversationKey}/${conversation.threadKey}`);
564
+ }
565
+ var receive = fn("TelegramBot.receive")(function* (body, state, settings) {
566
+ const input = yield* pipe(decodeEffect(fromJsonString(update))(body), mapError(() => AgentChannel_exports.HandlerError.make({ code: "rejected" })));
567
+ const source = input.message;
568
+ if (source === undefined || input.edited_message !== undefined || source.from === undefined || source.from.is_bot || `${source.from.id}` === state.botId || source.sender_chat !== undefined || source.business_connection_id !== undefined || source.forward_origin !== undefined || source.is_automatic_forward === true || source.text === undefined || isEmpty(source.text) || source.chat.type !== "private" && source.chat.type !== "group" && source.chat.type !== "supergroup")
569
+ return [];
570
+ const conversation = {
571
+ conversationKey: `${source.chat.id}`,
572
+ kind: chatKind(source.chat.type),
573
+ ...threadKey(source.message_thread_id)
574
+ };
575
+ if (!inScope(conversation, settings))
576
+ return [];
577
+ const text = source.text;
578
+ const entities = source.entities ?? [];
579
+ const addressed = filter2(entities, (item) => item.length > 0 && item.offset + item.length <= text.length && !some2(entities, (span) => (span.type === "blockquote" || span.type === "expandable_blockquote" || span.type === "code" || span.type === "pre") && item.offset < span.offset + span.length && item.offset + item.length > span.offset));
580
+ const username = toLowerCase(state.botUsername);
581
+ const explicit = some2(addressed, (item) => {
582
+ const value = toLowerCase(slice(item.offset, item.offset + item.length)(text));
583
+ return item.type === "mention" && value === `@${username}` || item.type === "text_mention" && `${item.user?.id}` === state.botId || item.type === "bot_command" && item.offset === 0 && is(addressedCommand)(value) && endsWith(`@${username}`)(value);
584
+ });
585
+ const reply = source.reply_to_message;
586
+ const replyToBot = reply !== undefined && `${reply.from?.id}` === state.botId && reply.from?.is_bot === true && reply.chat.id === source.chat.id && reply.message_thread_id === source.message_thread_id;
587
+ const respond = conversation.kind === "direct" || explicit || replyToBot || settings.respondTo === "all_messages";
588
+ const stop = some2(addressed, (item) => {
589
+ if (item.type !== "bot_command" || item.offset !== 0)
590
+ return false;
591
+ const command = toLowerCase(slice(0, item.length)(text));
592
+ return command === "/stop" || command === `/stop@${username}`;
593
+ });
594
+ const identity = {
595
+ conversation,
596
+ eventKey: `${input.update_id}`,
597
+ senderKey: `${source.from.id}`,
598
+ timestamp: formatIso(makeUnsafe4(source.date * 1000))
599
+ };
600
+ if (stop && respond)
601
+ return [{
602
+ ...identity,
603
+ kind: "stop"
604
+ }];
605
+ return [{
606
+ ...identity,
607
+ content: {
608
+ text,
609
+ ...replyKey(conversation, reply)
610
+ },
611
+ kind: "message",
612
+ messageKey: messageKey(conversation, source.message_id),
613
+ respond
614
+ }];
615
+ });
616
+
617
+ // dist/channel/telegram-bot.js
618
+ var numericKey = NumberFromString.check(isInt(), isBetween2({
619
+ minimum: 1,
620
+ maximum: 9007199254740991
621
+ }));
622
+ function validDestination(destination) {
623
+ if (!is(chatKey)(destination.conversationKey))
624
+ return false;
625
+ if (destination.threadKey !== undefined && !is(userKey)(destination.threadKey))
626
+ return false;
627
+ if (destination.kind === "direct")
628
+ return !startsWith("-")(destination.conversationKey);
629
+ return startsWith("-")(destination.conversationKey);
630
+ }
631
+ function checkAccess(identity, context) {
632
+ if (!validDestination(identity.conversation) || !inScope(identity.conversation, context.deploymentSettings) || !is(userKey)(identity.senderKey) || identity.conversation.kind === "direct" && identity.conversation.conversationKey !== identity.senderKey || identity.senderKey === split(":")(context.auth.value.botToken)[0] || context.deploymentSettings.access === "restricted" && !contains2(context.deploymentSettings.allowedSenderKeys, identity.senderKey))
633
+ return succeed4({ decision: "deny" });
634
+ return succeed4({ decision: "allow" });
635
+ }
636
+ function installed(command, context) {
637
+ if (command.installationKey !== command.state.botId || command.state.botId !== split(":")(context.auth.value.botToken)[0])
638
+ return fail5(AgentChannel_exports.HandlerError.make({ code: "unauthorized" }));
639
+ return void_2;
640
+ }
641
+ var activate = fn("TelegramBot.activate")(function* (command, context) {
642
+ const client = yield* TelegramBotClient;
643
+ const bot = yield* client.getMe(context.auth.value);
644
+ const botId = `${bot.id}`;
645
+ if (botId !== split(":")(context.auth.value.botToken)[0] || command.state !== undefined && (command.state.botId !== botId || command.state.ingressUrl !== command.ingressUrl))
646
+ return yield* AgentChannel_exports.HandlerError.make({ code: "unauthorized" });
647
+ const url = new URL(command.ingressUrl);
648
+ if (url.protocol !== "https:")
649
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
650
+ url.searchParams.set("__dual_telegram_registration", command.operationKey);
651
+ const state = {
652
+ botId,
653
+ botUsername: bot.username,
654
+ ingressUrl: command.ingressUrl,
655
+ registrationUrl: url.href
656
+ };
657
+ if (command.state !== undefined && command.state.registrationUrl !== state.registrationUrl)
658
+ return yield* AgentChannel_exports.HandlerError.make({ code: "unauthorized" });
659
+ if (command.state === undefined) {
660
+ yield* client.getWebhookInfo(context.auth.value);
661
+ return {
662
+ checkpoint: true,
663
+ installationKey: botId,
664
+ kind: "activate",
665
+ operationKey: command.operationKey,
666
+ state
667
+ };
668
+ }
669
+ yield* client.setWebhook(context.auth.value, state.registrationUrl);
670
+ if ((yield* client.getWebhookInfo(context.auth.value)).url !== state.registrationUrl)
671
+ return yield* AgentChannel_exports.HandlerError.make({ code: "unavailable" });
672
+ return {
673
+ installationKey: botId,
674
+ kind: "activate",
675
+ operationKey: command.operationKey,
676
+ state
677
+ };
678
+ });
679
+ function referenceId(destination, reference) {
680
+ const prefix = `${destination.conversationKey}/${destination.threadKey ?? "main"}/`;
681
+ if (reference === undefined || !startsWith(prefix)(reference))
682
+ return fail5(AgentChannel_exports.HandlerError.make({ code: "rejected" }));
683
+ const id = slice(prefix.length)(reference);
684
+ if (!is(userKey)(id))
685
+ return fail5(AgentChannel_exports.HandlerError.make({ code: "rejected" }));
686
+ return pipe(decodeEffect(numericKey)(id), mapError(() => AgentChannel_exports.HandlerError.make({ code: "rejected" })));
687
+ }
688
+ var topicParameters = fn("TelegramBot.topicParameters")(function* (destination) {
689
+ if (destination.threadKey === undefined)
690
+ return {};
691
+ return { message_thread_id: yield* pipe(decodeEffect(numericKey)(destination.threadKey), mapError(() => AgentChannel_exports.HandlerError.make({ code: "rejected" }))) };
692
+ });
693
+ function sameTopic(destination, id) {
694
+ if (id === undefined)
695
+ return destination.threadKey === undefined;
696
+ return `${id}` === destination.threadKey;
697
+ }
698
+ function outcomeText(operation) {
699
+ if (operation.kind === "present_outcome" && operation.options !== undefined)
700
+ return join([operation.text, ...map2(operation.options, (option, index) => `${index + 1}. ${option}`)], `
701
+ `);
702
+ return operation.text;
703
+ }
704
+ var reactions = {
705
+ confused: "\uD83E\uDD14",
706
+ eyes: "\uD83D\uDC40",
707
+ heart: "\u2764",
708
+ hooray: "\uD83C\uDF89",
709
+ laugh: "\uD83D\uDE01",
710
+ rocket: "\uD83D\uDE80",
711
+ thumbs_down: "\uD83D\uDC4E",
712
+ thumbs_up: "\uD83D\uDC4D"
713
+ };
714
+ function desiredReaction(operation) {
715
+ if (!operation.active)
716
+ return [];
717
+ return [{
718
+ type: "emoji",
719
+ emoji: reactions[operation.reaction]
720
+ }];
721
+ }
722
+ function reactionReference(operation, activationMessageKey) {
723
+ if (operation.target.kind === "activation")
724
+ return activationMessageKey;
725
+ return operation.target.reference;
726
+ }
727
+ var performOutput = fn("TelegramBot.performOutput")(function* (command, context) {
728
+ const destination = command.destination;
729
+ if (!validDestination(destination))
730
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
731
+ const client = yield* TelegramBotClient;
732
+ const auth = context.auth.value;
733
+ const target = { chat_id: destination.conversationKey };
734
+ const operation = command.operation;
735
+ if (operation.kind === "set_activity") {
736
+ if (operation.activity.kind === "working") {
737
+ const topic = yield* topicParameters(destination);
738
+ yield* client.sendChatAction(auth, {
739
+ ...target,
740
+ ...topic,
741
+ action: "typing"
742
+ });
743
+ }
744
+ return command.deliveryKey;
745
+ }
746
+ if (operation.kind === "set_reaction") {
747
+ const id = yield* referenceId(destination, reactionReference(operation, command.activationMessageKey));
748
+ yield* client.setMessageReaction(auth, {
749
+ ...target,
750
+ message_id: id,
751
+ reaction: desiredReaction(operation)
752
+ });
753
+ return messageKey(destination, id);
754
+ }
755
+ if (operation.kind === "delete_message") {
756
+ const id = yield* referenceId(destination, operation.reference);
757
+ yield* client.deleteMessage(auth, {
758
+ ...target,
759
+ message_id: id
760
+ });
761
+ return operation.reference;
762
+ }
763
+ if (operation.kind === "update_message") {
764
+ if (fromIterable(operation.text).length > 4096)
765
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
766
+ const id = yield* referenceId(destination, operation.reference);
767
+ const edited = yield* client.editMessageText(auth, {
768
+ ...target,
769
+ message_id: id,
770
+ text: operation.text
771
+ });
772
+ if (`${edited.chat.id}` !== destination.conversationKey || edited.message_id !== id || !sameTopic(destination, edited.message_thread_id))
773
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
774
+ return operation.reference;
775
+ }
776
+ if (operation.kind === "present_outcome" || operation.kind === "create_message") {
777
+ const text = outcomeText(operation);
778
+ if (fromIterable(text).length > 4096)
779
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
780
+ if (isEmpty(text))
781
+ return command.deliveryKey;
782
+ const topic = yield* topicParameters(destination);
783
+ const sent = yield* client.sendMessage(auth, {
784
+ ...target,
785
+ ...topic,
786
+ text
787
+ });
788
+ if (`${sent.chat.id}` !== destination.conversationKey || !sameTopic(destination, sent.message_thread_id))
789
+ return yield* AgentChannel_exports.HandlerError.make({ code: "unknown_completion" });
790
+ return messageKey(destination, sent.message_id);
791
+ }
792
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
793
+ });
794
+ var execute = fn("TelegramBot.execute")(function* (command, context) {
795
+ if (command.kind === "activate")
796
+ return yield* activate(command, context);
797
+ yield* installed(command, context);
798
+ if (command.kind === "deactivate") {
799
+ const client = yield* TelegramBotClient;
800
+ if ((yield* client.getWebhookInfo(context.auth.value)).url === command.state.registrationUrl)
801
+ yield* client.deleteWebhook(context.auth.value);
802
+ return {
803
+ kind: "deactivate",
804
+ operationKey: command.operationKey
805
+ };
806
+ }
807
+ if (command.kind === "deliver")
808
+ return {
809
+ deliveryKey: command.deliveryKey,
810
+ kind: "deliver",
811
+ operationKey: command.operationKey,
812
+ providerDeliveryKey: yield* performOutput(command, context),
813
+ status: "succeeded"
814
+ };
815
+ if (command.kind !== "receive")
816
+ return yield* AgentChannel_exports.HandlerError.make({ code: "rejected" });
817
+ return {
818
+ events: yield* receive(command.request.body, command.state, context.deploymentSettings),
819
+ kind: "receive",
820
+ operationKey: command.operationKey,
821
+ response: {
822
+ body: "",
823
+ status: 200
824
+ },
825
+ verified: true
826
+ };
827
+ }, mapError((error) => AgentChannel_exports.HandlerError.make({ code: error.code })));
828
+ var telegramBotHandlers = Plugin_exports.toLayer(telegramBotPluginBase, (handlers) => handlers.channel("messages", {
829
+ checkAccess,
830
+ execute,
831
+ verify: (request, context) => verify(request, context.auth.value.webhookSecret)
832
+ }));
833
+ var telegramChannelLayer = telegramBotHandlers.pipe(provide(TelegramBotClient.layer), provide(layer4));
834
+
835
+ // dist/plugin.js
836
+ var plugin_exports2 = /* @__PURE__ */ __exportAll({
837
+ TelegramLive: () => TelegramLive2,
838
+ layer: () => layer2,
839
+ telegramAccessToken: () => telegramAccessToken2,
840
+ telegramPlugin: () => telegramPlugin2,
841
+ telegramPluginBase: () => telegramPluginBase3
842
+ });
843
+ var telegramPlugin2 = telegramPlugin.pipe(Plugin_exports.withAuthMethod(telegramBotToken), Plugin_exports.withAgentChannel(messagesChannel), Plugin_exports.provide(telegramChannelLayer));
844
+ export { TelegramLive2, plugin_exports2, telegramPlugin2 };
845
+
846
+ //# debugId=CF09747DEAF2115164756E2164756E21
847
+ //# sourceMappingURL=index-hpjyc5yq.js.map