@effect/chat-telegram 0.0.0 → 4.1.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 (157) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +122 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/TelegramBotApi.d.ts +153 -0
  88. package/dist/TelegramBotApi.d.ts.map +1 -0
  89. package/dist/TelegramBotApi.js +219 -0
  90. package/dist/TelegramBotApi.js.map +1 -0
  91. package/dist/TelegramChat.d.ts +390 -0
  92. package/dist/TelegramChat.d.ts.map +1 -0
  93. package/dist/TelegramChat.js +359 -0
  94. package/dist/TelegramChat.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +88 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +309 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +26 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/commands.d.ts +2 -0
  112. package/dist/internal/commands.d.ts.map +1 -0
  113. package/dist/internal/commands.js +30 -0
  114. package/dist/internal/commands.js.map +1 -0
  115. package/dist/internal/errors.d.ts +2 -0
  116. package/dist/internal/errors.d.ts.map +1 -0
  117. package/dist/internal/errors.js +136 -0
  118. package/dist/internal/errors.js.map +1 -0
  119. package/dist/internal/markdown.d.ts +9 -0
  120. package/dist/internal/markdown.d.ts.map +1 -0
  121. package/dist/internal/markdown.js +708 -0
  122. package/dist/internal/markdown.js.map +1 -0
  123. package/dist/internal/normalize.d.ts +2 -0
  124. package/dist/internal/normalize.d.ts.map +1 -0
  125. package/dist/internal/normalize.js +276 -0
  126. package/dist/internal/normalize.js.map +1 -0
  127. package/dist/internal/options.d.ts +2 -0
  128. package/dist/internal/options.d.ts.map +1 -0
  129. package/dist/internal/options.js +6 -0
  130. package/dist/internal/options.js.map +1 -0
  131. package/dist/internal/polling.d.ts +2 -0
  132. package/dist/internal/polling.d.ts.map +1 -0
  133. package/dist/internal/polling.js +68 -0
  134. package/dist/internal/polling.js.map +1 -0
  135. package/dist/internal/receive.d.ts +2 -0
  136. package/dist/internal/receive.d.ts.map +1 -0
  137. package/dist/internal/receive.js +183 -0
  138. package/dist/internal/receive.js.map +1 -0
  139. package/dist/internal/webhook.d.ts +2 -0
  140. package/dist/internal/webhook.d.ts.map +1 -0
  141. package/dist/internal/webhook.js +61 -0
  142. package/dist/internal/webhook.js.map +1 -0
  143. package/package.json +65 -1
  144. package/src/TelegramBotApi.ts +282 -0
  145. package/src/TelegramChat.ts +542 -0
  146. package/src/index.ts +18 -0
  147. package/src/internal/actions.ts +95 -0
  148. package/src/internal/adapter.ts +319 -0
  149. package/src/internal/address.ts +33 -0
  150. package/src/internal/commands.ts +37 -0
  151. package/src/internal/errors.ts +148 -0
  152. package/src/internal/markdown.ts +805 -0
  153. package/src/internal/normalize.ts +283 -0
  154. package/src/internal/options.ts +12 -0
  155. package/src/internal/polling.ts +86 -0
  156. package/src/internal/receive.ts +268 -0
  157. package/src/internal/webhook.ts +85 -0
@@ -0,0 +1,283 @@
1
+ import * as ChatEvent from "effect/chat/ChatEvent"
2
+ import type * as ChatMessage from "effect/chat/ChatMessage"
3
+ import type { ChatThread } from "effect/chat/ChatThread"
4
+ import * as DateTime from "effect/DateTime"
5
+ import * as Predicate from "effect/Predicate"
6
+ import type * as Schema from "effect/Schema"
7
+ import * as Address from "./address.ts"
8
+
9
+ /** @internal */
10
+ export type JsonObject = { readonly [key: string]: Schema.Json }
11
+
12
+ /** @internal */
13
+ export const isObject = (u: unknown): u is JsonObject => Predicate.isObject(u)
14
+
15
+ const field = (o: unknown, key: string): unknown => isObject(o) ? o[key] : undefined
16
+
17
+ /** The object at `key` of `o`, when `o` is an object. @internal */
18
+ export const object = (o: unknown, key: string): JsonObject | undefined => {
19
+ const value = field(o, key)
20
+ return isObject(value) ? value : undefined
21
+ }
22
+
23
+ /** @internal */
24
+ export const string = (o: unknown, key: string): string | undefined => {
25
+ const value = field(o, key)
26
+ return typeof value === "string" ? value : undefined
27
+ }
28
+
29
+ /** @internal */
30
+ export const integer = (o: unknown, key: string): number | undefined => {
31
+ const value = field(o, key)
32
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined
33
+ }
34
+
35
+ /** What normalising needs to know about the bot. @internal */
36
+ export interface Context {
37
+ readonly botId: string
38
+ /** The bot's username, without `@`, from `getMe`. */
39
+ readonly botUsername?: string | undefined
40
+ readonly environment?: "production" | "test" | undefined
41
+ }
42
+
43
+ /**
44
+ * Whether a message belongs to a context v1 leaves out: a business
45
+ * connection, a channel's direct messages chat, or guest mode.
46
+ *
47
+ * @internal
48
+ */
49
+ export const isExcluded = (message: JsonObject): boolean =>
50
+ "business_connection_id" in message ||
51
+ "guest_query_id" in message ||
52
+ "guest_bot_caller_user" in message ||
53
+ "guest_bot_caller_chat" in message ||
54
+ "direct_messages_topic" in message ||
55
+ object(message, "chat")?.is_direct_messages === true
56
+
57
+ /** Whether a message is a private answer or input: `message_id` 0 with an `ephemeral_message_id`. @internal */
58
+ export const isEphemeral = (message: JsonObject): boolean =>
59
+ integer(message, "message_id") === 0 && integer(message, "ephemeral_message_id") !== undefined
60
+
61
+ /** The address and kind of the chat a message is in. @internal */
62
+ export const threadOf = (
63
+ message: JsonObject
64
+ ): { readonly thread: ChatThread; readonly kind: ChatEvent.ThreadKind } | undefined => {
65
+ const chat = object(message, "chat")
66
+ const chatId = integer(chat, "id")
67
+ if (chat === undefined || chatId === undefined) return undefined
68
+ const topic = message.is_topic_message === true ? integer(message, "message_thread_id") : undefined
69
+ if (topic !== undefined) return { thread: Address.thread(chatId, topic), kind: "thread" }
70
+ return { thread: Address.thread(chatId), kind: chat.type === "private" ? "direct" : "channel" }
71
+ }
72
+
73
+ /** A message's id as events carry it: the real id, or `e{ephemeral_message_id}.{date}` for a private one. @internal */
74
+ export const messageIdOf = (message: JsonObject): string | undefined => {
75
+ const id = integer(message, "message_id")
76
+ if (id === undefined) return undefined
77
+ if (id !== 0) return String(id)
78
+ const ephemeral = integer(message, "ephemeral_message_id")
79
+ return ephemeral === undefined ? undefined : `${Address.ephemeralPrefix}${ephemeral}.${integer(message, "date") ?? 0}`
80
+ }
81
+
82
+ /** A user's or private chat's first and last name, `""` without either. @internal */
83
+ export const fullName = (o: unknown): string =>
84
+ [string(o, "first_name"), string(o, "last_name")].filter((part) => part !== undefined).join(" ")
85
+
86
+ /** A user's full name, else their username. @internal */
87
+ export const displayName = (user: JsonObject): string | undefined => fullName(user) || string(user, "username")
88
+
89
+ const authorOf = (message: JsonObject, context: Context): ChatMessage.Author | undefined => {
90
+ const senderChat = object(message, "sender_chat")
91
+ const senderChatId = integer(senderChat, "id")
92
+ if (senderChat !== undefined && senderChatId !== undefined) {
93
+ const title = string(senderChat, "title")
94
+ return { id: String(senderChatId), ...(title === undefined ? {} : { name: title }), isBot: false, isSelf: false }
95
+ }
96
+ const from = object(message, "from")
97
+ const fromId = integer(from, "id")
98
+ if (from === undefined || fromId === undefined) return undefined
99
+ const name = displayName(from)
100
+ return {
101
+ id: String(fromId),
102
+ ...(name === undefined ? {} : { name }),
103
+ isBot: from.is_bot === true,
104
+ isSelf: String(fromId) === context.botId
105
+ }
106
+ }
107
+
108
+ const mentionsOf = (text: string, entities: ReadonlyArray<Schema.Json>, context: Context) => {
109
+ const mentions: Array<ChatMessage.Mention> = []
110
+ const self = context.botUsername?.toLowerCase()
111
+ for (const entity of entities) {
112
+ if (!isObject(entity)) continue
113
+ const start = integer(entity, "offset")
114
+ const length = integer(entity, "length")
115
+ if (start === undefined || length === undefined || start < 0 || start + length > text.length) continue
116
+ const end = start + length
117
+ if (entity.type === "text_mention") {
118
+ const user = integer(object(entity, "user"), "id")
119
+ if (user !== undefined) {
120
+ mentions.push({ kind: "user", id: String(user), start, end, isSelf: String(user) === context.botId })
121
+ }
122
+ } else if (entity.type === "mention" && self !== undefined && text.slice(start + 1, end).toLowerCase() === self) {
123
+ mentions.push({ kind: "user", id: context.botId, start, end, isSelf: true })
124
+ }
125
+ }
126
+ return mentions
127
+ }
128
+
129
+ const attachmentsOf = (message: JsonObject): Array<ChatMessage.Attachment> => {
130
+ const out: Array<ChatMessage.Attachment> = []
131
+ const add = (file: JsonObject | undefined) => {
132
+ const id = string(file, "file_id")
133
+ if (id === undefined) return
134
+ const name = string(file, "file_name")
135
+ const contentType = string(file, "mime_type")
136
+ const size = integer(file, "file_size")
137
+ out.push({
138
+ id,
139
+ ...(name === undefined ? {} : { name }),
140
+ ...(contentType === undefined ? {} : { contentType }),
141
+ ...(size === undefined ? {} : { size })
142
+ })
143
+ }
144
+ // An animation comes with a copy of itself as `document`, for older clients.
145
+ const animation = object(message, "animation")
146
+ add(animation ?? object(message, "document"))
147
+ for (const key of ["audio", "video", "voice"]) add(object(message, key))
148
+ const photo = message.photo
149
+ if (Array.isArray(photo) && photo.length > 0) {
150
+ let largest: JsonObject | undefined
151
+ for (const size of photo) {
152
+ if (!isObject(size)) continue
153
+ const area = (integer(size, "width") ?? 0) * (integer(size, "height") ?? 0)
154
+ const best = (integer(largest, "width") ?? 0) * (integer(largest, "height") ?? 0)
155
+ if (largest === undefined || area > best) largest = size
156
+ }
157
+ add(largest)
158
+ }
159
+ return out
160
+ }
161
+
162
+ const replyToOf = (message: JsonObject, context: Context): ChatMessage.ReplyTo | undefined => {
163
+ const reply = object(message, "reply_to_message")
164
+ const id = integer(reply, "message_id")
165
+ if (reply === undefined || id === undefined || id === 0) return undefined
166
+ // A message in a topic replies to the topic's creation message, which is not a reply.
167
+ if (
168
+ message.is_topic_message === true &&
169
+ (id === integer(message, "message_thread_id") || "forum_topic_created" in reply)
170
+ ) {
171
+ return undefined
172
+ }
173
+ const author = integer(object(reply, "from"), "id")
174
+ return author === undefined
175
+ ? { messageId: String(id) }
176
+ : { messageId: String(id), authorId: String(author), isSelf: String(author) === context.botId }
177
+ }
178
+
179
+ /** The message of an update that carries one: `message` or `channel_post`. @internal */
180
+ export const messageOf = (update: unknown): JsonObject | undefined =>
181
+ object(update, "message") ?? object(update, "channel_post")
182
+
183
+ /** The text of a message, verbatim, and its entities. @internal */
184
+ export const textOf = (
185
+ message: JsonObject
186
+ ): { readonly text: string; readonly entities: ReadonlyArray<Schema.Json> } => {
187
+ const text = string(message, "text")
188
+ if (text !== undefined) return { text, entities: Array.isArray(message.entities) ? message.entities : [] }
189
+ const caption = string(message, "caption") ?? ""
190
+ return { text: caption, entities: Array.isArray(message.caption_entities) ? message.caption_entities : [] }
191
+ }
192
+
193
+ /**
194
+ * The `MessageCreated` of an update's message, or undefined for one that
195
+ * gives none: an excluded context, a private (ephemeral) message, a message
196
+ * with no id, and a service message, with no text, caption, file or rich
197
+ * content. `invalid` is a message that should give one and can't be read.
198
+ *
199
+ * @internal
200
+ */
201
+ export const messageCreated = (
202
+ update: JsonObject,
203
+ context: Context
204
+ ): ChatEvent.MessageCreated | "none" | "invalid" => {
205
+ const message = messageOf(update)
206
+ if (message === undefined || isExcluded(message) || integer(message, "message_id") === 0) return "none"
207
+ const { entities, text } = textOf(message)
208
+ const attachments = attachmentsOf(message)
209
+ if (text === "" && attachments.length === 0 && !("rich_message" in message)) return "none"
210
+ const at = threadOf(message)
211
+ const id = messageIdOf(message)
212
+ const author = authorOf(message, context)
213
+ const date = integer(message, "date")
214
+ if (at === undefined || id === undefined || author === undefined || date === undefined) return "invalid"
215
+ const replyTo = replyToOf(message, context)
216
+ return ChatEvent.MessageCreated.make({
217
+ thread: at.thread,
218
+ kind: at.kind,
219
+ message: {
220
+ id,
221
+ thread: at.thread,
222
+ author,
223
+ text,
224
+ mentions: mentionsOf(text, entities, context),
225
+ ...(replyTo === undefined ? {} : { replyTo }),
226
+ attachments,
227
+ timestamp: DateTime.makeUnsafe(date * 1000),
228
+ raw: message
229
+ },
230
+ raw: update
231
+ })
232
+ }
233
+
234
+ /** A command typed as a message: its lowercased name and what follows it. @internal */
235
+ export interface Command {
236
+ readonly id: string
237
+ readonly text: string
238
+ }
239
+
240
+ /**
241
+ * The command a message holds: its first entity is a `bot_command` at
242
+ * offset 0, naming this bot or no bot. `undefined` when a command names a
243
+ * bot and the bot's username is not known.
244
+ *
245
+ * @internal
246
+ */
247
+ export const commandOf = (message: JsonObject, context: Context): Command | undefined => {
248
+ const { entities, text } = textOf(message)
249
+ const first = entities[0]
250
+ if (!isObject(first) || first.type !== "bot_command" || integer(first, "offset") !== 0) return undefined
251
+ const length = integer(first, "length")
252
+ if (length === undefined || length < 2 || length > text.length) return undefined
253
+ // The entity's length is Telegram's: it never covers a `-`, which `commandRequests` refuses.
254
+ const match = /^\/([A-Za-z0-9_-]{1,32})(?:@([A-Za-z0-9_]+))?$/.exec(text.slice(0, length))
255
+ if (match === null) return undefined
256
+ if (match[2] !== undefined && match[2].toLowerCase() !== context.botUsername?.toLowerCase()) return undefined
257
+ let rest = text.slice(length)
258
+ if (rest.startsWith(" ") || rest.startsWith("\n")) rest = rest.slice(1)
259
+ return { id: match[1].toLowerCase(), text: rest }
260
+ }
261
+
262
+ /** The date of an update's message or callback message, 0 when there is none. */
263
+ const dateOf = (update: unknown): number =>
264
+ integer(messageOf(update), "date") ?? integer(object(object(update, "callback_query"), "message"), "date") ?? 0
265
+
266
+ /**
267
+ * The delivery id of an update: `{botId}.{update_id}.{date}`, with `test.`
268
+ * in front in the test environment.
269
+ *
270
+ * @internal
271
+ */
272
+ export const deliveryId = (update: unknown, context: Pick<Context, "botId" | "environment">): string | undefined => {
273
+ const id = integer(update, "update_id")
274
+ if (id === undefined) return undefined
275
+ return `${context.environment === "test" ? "test." : ""}${context.botId}.${id}.${dateOf(update)}`
276
+ }
277
+
278
+ /** The events of an update, as `TelegramChat.normalize` gives them. @internal */
279
+ export const normalize = (update: unknown, context: Context): ReadonlyArray<ChatEvent.ChatEvent> => {
280
+ if (!isObject(update)) return []
281
+ const event = messageCreated(update, context)
282
+ return typeof event === "string" ? [] : [event]
283
+ }
@@ -0,0 +1,12 @@
1
+ import * as Context from "effect/Context"
2
+
3
+ /** @internal */
4
+ export interface PostOptions {
5
+ readonly notify?: { readonly users?: ReadonlyArray<string> | undefined } | undefined
6
+ readonly silent?: boolean | undefined
7
+ }
8
+
9
+ /** @internal */
10
+ export const CurrentPostOptions = Context.Reference<PostOptions>("@effect/chat-telegram/CurrentPostOptions", {
11
+ defaultValue: () => ({})
12
+ })
@@ -0,0 +1,86 @@
1
+ import type { ChatError } from "effect/chat/ChatError"
2
+ import * as Duration from "effect/Duration"
3
+ import * as Effect from "effect/Effect"
4
+ import type { TelegramBotApi } from "../TelegramBotApi.ts"
5
+ import * as Errors from "./errors.ts"
6
+ import { integer } from "./normalize.ts"
7
+ import { allowedUpdates, type Outcome } from "./receive.ts"
8
+
9
+ /** @internal */
10
+ export interface Options {
11
+ readonly api: TelegramBotApi["Service"]
12
+ readonly timeout: Duration.Duration
13
+ readonly maxAttempts: number
14
+ readonly receive: (update: unknown) => Effect.Effect<Outcome>
15
+ }
16
+
17
+ const isConflict = (error: ChatError) => error.reason._tag === "InvalidRequest" && error.reason.detail === "conflict"
18
+
19
+ /** One `getUpdates`, from `offset`. @internal */
20
+ export const getUpdates = (api: TelegramBotApi["Service"], offset: number | undefined, timeout: Duration.Duration) =>
21
+ api.call("getUpdates", {
22
+ ...(offset === undefined ? {} : { offset }),
23
+ timeout: Math.floor(Duration.toSeconds(timeout)),
24
+ allowed_updates: allowedUpdates
25
+ }).pipe(Effect.map((result) => Array.isArray(result) ? result : []))
26
+
27
+ /**
28
+ * Runs one update, retrying `notAccepted` and `invalid` up to
29
+ * `maxAttempts` times with a backoff from one second. Then it is logged
30
+ * and skipped: `getUpdates` is one ordered queue, and retrying forever
31
+ * would stall every chat.
32
+ *
33
+ * @internal
34
+ */
35
+ export const runUpdate = (update: unknown, options: Options): Effect.Effect<void> =>
36
+ Effect.gen(function*() {
37
+ for (let attempt = 1;; attempt++) {
38
+ const outcome = yield* options.receive(update)
39
+ if (outcome === "accepted" || outcome === "unhandled") return
40
+ if (attempt >= options.maxAttempts) {
41
+ return yield* Effect.logError("telegram polling: an update was not accepted, skipped").pipe(
42
+ Effect.annotateLogs({ "telegram.update_id": integer(update, "update_id") })
43
+ )
44
+ }
45
+ yield* Effect.sleep(Duration.seconds(2 ** (attempt - 1)))
46
+ }
47
+ })
48
+
49
+ /**
50
+ * The polling loop. `first` is the answer of the call the layer made
51
+ * itself. Each update's offset is confirmed by the next call only once the
52
+ * update was run, so a process that dies part way sees it again.
53
+ *
54
+ * @internal
55
+ */
56
+ export const loop = (first: ReadonlyArray<unknown>, options: Options): Effect.Effect<void> =>
57
+ Effect.gen(function*() {
58
+ let batch = first
59
+ let offset: number | undefined
60
+ for (;;) {
61
+ for (const update of batch) {
62
+ yield* runUpdate(update, options)
63
+ const id = integer(update, "update_id")
64
+ if (id !== undefined) offset = id + 1
65
+ }
66
+ const next = yield* Effect.result(getUpdates(options.api, offset, options.timeout))
67
+ if (next._tag === "Success") {
68
+ batch = next.success
69
+ continue
70
+ }
71
+ batch = []
72
+ if (isConflict(next.failure)) {
73
+ return yield* Effect.logError(
74
+ "telegram polling: getUpdates answered 409, another poller or a webhook is active; polling stopped"
75
+ )
76
+ }
77
+ yield* Effect.logWarning("telegram polling: getUpdates failed, retrying").pipe(
78
+ Effect.annotateLogs({ "chat.error.reason": next.failure.reason._tag })
79
+ )
80
+ yield* Effect.sleep(Duration.seconds(5))
81
+ }
82
+ })
83
+
84
+ /** The error the layer fails with on a 409 at start. @internal */
85
+ export const conflict = (error: ChatError): ChatError =>
86
+ isConflict(error) ? Errors.chatError("layerPolling", Errors.invalidRequest("conflict")) : error
@@ -0,0 +1,268 @@
1
+ import type { Capability, ChatError } from "effect/chat/ChatError"
2
+ import type * as ChatEvent from "effect/chat/ChatEvent"
3
+ import type { NotAccepted } from "effect/chat/ChatHandler"
4
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
5
+ import * as Duration from "effect/Duration"
6
+ import * as Effect from "effect/Effect"
7
+ import * as Option from "effect/Option"
8
+ import type * as Schema from "effect/Schema"
9
+ import type { TelegramBotApi } from "../TelegramBotApi.ts"
10
+ import * as Actions from "./actions.ts"
11
+ import type { Made } from "./adapter.ts"
12
+ import { originOf } from "./adapter.ts"
13
+ import * as Errors from "./errors.ts"
14
+ import {
15
+ commandOf,
16
+ type Context,
17
+ integer,
18
+ isEphemeral,
19
+ isExcluded,
20
+ isObject,
21
+ type JsonObject,
22
+ messageCreated,
23
+ messageIdOf,
24
+ messageOf,
25
+ object,
26
+ string,
27
+ threadOf
28
+ } from "./normalize.ts"
29
+
30
+ /**
31
+ * What became of one update.
32
+ *
33
+ * - `accepted`: its event was accepted, or its interaction was answered.
34
+ * - `unhandled`: it gave nothing, and went to `onUnhandled`.
35
+ * - `notAccepted`: the `ChatHandler` refused its event, or it passed the deadline.
36
+ * - `invalid`: it should give an event and could not be read.
37
+ *
38
+ * @internal
39
+ */
40
+ export type Outcome = "accepted" | "unhandled" | "notAccepted" | "invalid"
41
+
42
+ /** @internal */
43
+ export const defaults = {
44
+ deadline: Duration.seconds(10),
45
+ clickDeadline: Duration.millis(2500),
46
+ commandDeadline: Duration.seconds(10)
47
+ } as const
48
+
49
+ /** The update types the adapter reads, for `allowed_updates`. @internal */
50
+ export const allowedUpdates = ["message", "channel_post", "callback_query"] as const
51
+
52
+ /** @internal */
53
+ export interface Options {
54
+ readonly onUnhandled?: ((update: Schema.Json) => Effect.Effect<void>) | undefined
55
+ readonly deadline?: Duration.Input | undefined
56
+ readonly clickDeadline?: Duration.Input | undefined
57
+ readonly commandDeadline?: Duration.Input | undefined
58
+ }
59
+
60
+ /** @internal */
61
+ export interface Environment {
62
+ readonly api: TelegramBotApi["Service"]
63
+ readonly capabilities: ReadonlySet<Capability>
64
+ readonly answer: Made["answer"]
65
+ /** The bot's username, read once from `getMe`. */
66
+ readonly username: Effect.Effect<string, ChatError>
67
+ }
68
+
69
+ const duration = (input: Duration.Input | undefined, fallback: Duration.Duration) =>
70
+ input === undefined ? fallback : Duration.fromInputUnsafe(input)
71
+
72
+ /** Modals are not in this version: an `OpenModal` reply is refused. */
73
+ const refuseModal = (
74
+ handler: ChatInteraction.Handler["Service"],
75
+ event: ChatInteraction.ButtonClicked | ChatInteraction.CommandInvoked
76
+ ) => handler.refused(event, Errors.chatError("openModal", Errors.unsupported("modals")))
77
+
78
+ const answerQuery = (api: TelegramBotApi["Service"], id: string) =>
79
+ api.call("answerCallbackQuery", { callback_query_id: id }, { write: true, retry: false }).pipe(
80
+ Effect.catch((error) =>
81
+ Effect.logWarning("telegram: answerCallbackQuery failed").pipe(
82
+ Effect.annotateLogs({ "chat.error.reason": error.reason._tag })
83
+ )
84
+ )
85
+ )
86
+
87
+ /** A callback the adapter leaves alone: inline mode, a game, or an excluded context. */
88
+ const isForeignCallback = (query: JsonObject): boolean => {
89
+ const message = object(query, "message")
90
+ return message === undefined || typeof query.data !== "string" || isExcluded(message)
91
+ }
92
+
93
+ /**
94
+ * The click of a `callback_query`, only when its `data` is the
95
+ * `callback_data` of a button in Telegram's own copy of the message:
96
+ * `data` comes from the client and can be anything. Undefined for an
97
+ * inaccessible message, a message with no keyboard, or a mismatch.
98
+ *
99
+ * @internal
100
+ */
101
+ export const clickEvent = (update: JsonObject): ChatInteraction.ButtonClicked | undefined => {
102
+ const query = object(update, "callback_query")
103
+ const message = object(query, "message")
104
+ const data = string(query, "data")
105
+ if (query === undefined || message === undefined || data === undefined || isForeignCallback(query)) return undefined
106
+ const user = integer(object(query, "from"), "id")
107
+ const at = threadOf(message)
108
+ const messageId = messageIdOf(message)
109
+ if (
110
+ integer(message, "date") === 0 || !Actions.keyboardData(message.reply_markup).has(data) ||
111
+ user === undefined || at === undefined || messageId === undefined
112
+ ) return undefined
113
+ const parsed = Actions.parseData(data)
114
+ return ChatInteraction.ButtonClicked.make({
115
+ id: parsed.id,
116
+ ...(parsed.value === undefined ? {} : { value: parsed.value }),
117
+ thread: at.thread,
118
+ messageId,
119
+ userId: String(user),
120
+ raw: update
121
+ })
122
+ }
123
+
124
+ /** A click. Every click is answered, since the client shows a progress bar until it is. */
125
+ const click = (
126
+ update: JsonObject,
127
+ id: string,
128
+ env: Environment,
129
+ options: Options,
130
+ handler: Option.Option<ChatInteraction.Handler["Service"]>
131
+ ): Effect.Effect<void> =>
132
+ Effect.gen(function*() {
133
+ const answer = answerQuery(env.api, id)
134
+ if (Option.isNone(handler) || !env.capabilities.has("buttons")) return yield* answer
135
+ const event = clickEvent(update)
136
+ if (event === undefined) {
137
+ yield* Effect.logWarning("telegram: a click matched no button on its message, answered and dropped").pipe(
138
+ Effect.annotateLogs({ "chat.interaction.reason": "InvalidValue" })
139
+ )
140
+ return yield* answer
141
+ }
142
+ const reply = yield* Effect.provideService(
143
+ ChatInteraction.handle(event, duration(options.clickDeadline, defaults.clickDeadline)),
144
+ ChatInteraction.Handler,
145
+ handler.value
146
+ )
147
+ yield* answer
148
+ if (reply._tag === "OpenModal") yield* refuseModal(handler.value, event)
149
+ })
150
+
151
+ /** The command of a message update, for this bot. @internal */
152
+ export const commandEvent = (update: JsonObject, context: Context): ChatInteraction.CommandInvoked | undefined => {
153
+ const message = messageOf(update)
154
+ if (message === undefined || isExcluded(message)) return undefined
155
+ const found = commandOf(message, context)
156
+ const at = threadOf(message)
157
+ // As in `normalize`: an anonymous admin's `from` is Telegram's shared stand-in, the chat is the sender.
158
+ const user = integer(object(message, "sender_chat"), "id") ?? integer(object(message, "from"), "id")
159
+ if (found === undefined || at === undefined || user === undefined) return undefined
160
+ return ChatInteraction.CommandInvoked.make({
161
+ id: found.id,
162
+ text: found.text,
163
+ thread: at.thread,
164
+ userId: String(user),
165
+ raw: update
166
+ })
167
+ }
168
+
169
+ /**
170
+ * A command. `false` when it was not handled: no handler, no
171
+ * `commands`, or an `Ack`, which means no definition matched.
172
+ */
173
+ const command = (
174
+ event: ChatInteraction.CommandInvoked,
175
+ env: Environment,
176
+ options: Options,
177
+ handler: Option.Option<ChatInteraction.Handler["Service"]>
178
+ ): Effect.Effect<boolean> =>
179
+ Effect.gen(function*() {
180
+ if (Option.isNone(handler) || !env.capabilities.has("commands")) return false
181
+ const reply = yield* Effect.provideService(
182
+ ChatInteraction.handle(event, duration(options.commandDeadline, defaults.commandDeadline)),
183
+ ChatInteraction.Handler,
184
+ handler.value
185
+ )
186
+ switch (reply._tag) {
187
+ case "Ack":
188
+ return false
189
+ case "Late":
190
+ case "Defer":
191
+ return true
192
+ case "OpenModal":
193
+ yield* refuseModal(handler.value, event)
194
+ return true
195
+ case "Respond": {
196
+ // No `ephemeral` in this version: a private answer is refused, never posted.
197
+ if (reply.visibility === "ephemeral") {
198
+ yield* handler.value.refused(event, Errors.chatError("respond", Errors.unsupported("ephemeral")))
199
+ return true
200
+ }
201
+ const origin = originOf(event)
202
+ if (origin === undefined) return true
203
+ yield* env.answer("respond", origin, {
204
+ markdown: reply.markdown,
205
+ ...(reply.actions === undefined ? {} : { actions: reply.actions })
206
+ }).pipe(Effect.catch((error) => handler.value.refused(event, error)))
207
+ return true
208
+ }
209
+ }
210
+ })
211
+
212
+ /**
213
+ * One update, as both transports run it.
214
+ *
215
+ * - A click goes to `ChatInteraction.Handler` and is answered.
216
+ * - An ephemeral message only ever takes the command path. Whatever its
217
+ * answer, it never reaches `ChatHandler` or `onUnhandled`.
218
+ * - A command goes to `ChatInteraction.Handler`. One answered `Ack`
219
+ * continues as an ordinary message.
220
+ * - A message with content becomes `MessageCreated` for `ChatHandler`,
221
+ * within `deadline`.
222
+ * - Anything else, including the excluded contexts, goes to `onUnhandled`.
223
+ *
224
+ * @internal
225
+ */
226
+ export const receive = (
227
+ update: unknown,
228
+ env: Environment,
229
+ options: Options,
230
+ handle: (event: ChatEvent.ChatEvent) => Effect.Effect<void, NotAccepted>
231
+ ): Effect.Effect<Outcome> =>
232
+ Effect.gen(function*() {
233
+ if (!isObject(update) || integer(update, "update_id") === undefined) return "invalid"
234
+ const unhandled = Effect.as(options.onUnhandled?.(update) ?? Effect.void, "unhandled" as const)
235
+ const handler = yield* Effect.serviceOption(ChatInteraction.Handler)
236
+ const query = object(update, "callback_query")
237
+ if (query !== undefined) {
238
+ const id = string(query, "id")
239
+ if (isForeignCallback(query)) {
240
+ // A business chat's button is answered, so its client stops waiting, but never dispatched.
241
+ const message = object(query, "message")
242
+ if (id !== undefined && message !== undefined && isExcluded(message)) yield* answerQuery(env.api, id)
243
+ return yield* unhandled
244
+ }
245
+ if (id === undefined) return "invalid"
246
+ return yield* Effect.as(click(update, id, env, options, handler), "accepted" as const)
247
+ }
248
+ const message = messageOf(update)
249
+ if (message === undefined || isExcluded(message)) return yield* unhandled
250
+ const username = yield* Effect.option(env.username)
251
+ if (Option.isNone(username)) return "invalid"
252
+ const context: Context = { botId: env.api.botId, botUsername: username.value, environment: env.api.environment }
253
+ const found = commandEvent(update, context)
254
+ if (isEphemeral(message)) {
255
+ if (found !== undefined) yield* command(found, env, options, handler)
256
+ return "accepted"
257
+ }
258
+ if (integer(message, "message_id") === 0) return yield* unhandled
259
+ if (found !== undefined && (yield* command(found, env, options, handler))) return "accepted"
260
+ const event = messageCreated(update, context)
261
+ if (event === "none") return yield* unhandled
262
+ if (event === "invalid") return "invalid"
263
+ return yield* handle(event).pipe(
264
+ Effect.timeoutOption(duration(options.deadline, defaults.deadline)),
265
+ Effect.map(Option.match({ onNone: () => "notAccepted" as const, onSome: () => "accepted" as const })),
266
+ Effect.catchTag("NotAccepted", () => Effect.succeed("notAccepted" as const))
267
+ )
268
+ })