@effect/chat-telegram 0.0.0 → 4.1.6

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,542 @@
1
+ /**
2
+ * The Telegram adapter for `effect/chat`, over the Bot API: the `Registry`
3
+ * layer, the webhook and polling transports, the pure normaliser and the
4
+ * address helpers.
5
+ *
6
+ * **Details**
7
+ *
8
+ * - Raw REST over `HttpClient`, through `TelegramBotApi`, which keeps the
9
+ * bot token out of spans and errors.
10
+ * - Posts and edits are rich messages (`sendRichMessage`,
11
+ * `editMessageText` with `rich_message`), in Markdown escaped so that
12
+ * consumer text reaches no raw HTML, image, math, spoiler or non-web
13
+ * link.
14
+ * - The base live checks ran against production. Files, buttons and
15
+ * commands need further checks, so they are behind `unverified`
16
+ * options, off by default.
17
+ * - There is no `ephemeral`: a private answer to a command is refused
18
+ * through `Handler.refused`, never posted. `fetchMessage`, `history`,
19
+ * `opener`, `startThread`, selects, modals, native streams and reaction
20
+ * events are not in this version.
21
+ *
22
+ * @stability unstable
23
+ * @since 4.1.5
24
+ */
25
+ import * as ByteSize from "effect/ByteSize"
26
+ import { Registry } from "effect/chat/ChatAdapter"
27
+ import type { ChatError } from "effect/chat/ChatError"
28
+ import type { ChatEvent } from "effect/chat/ChatEvent"
29
+ import { ChatHandler } from "effect/chat/ChatHandler"
30
+ import type * as ChatInteraction from "effect/chat/ChatInteraction"
31
+ import type { ParseMention } from "effect/chat/ChatTest"
32
+ import type { ChatThread } from "effect/chat/ChatThread"
33
+ import * as Context from "effect/Context"
34
+ import * as Duration from "effect/Duration"
35
+ import * as Effect from "effect/Effect"
36
+ import { dual } from "effect/Function"
37
+ import type * as HttpClient from "effect/http/HttpClient"
38
+ import * as HttpRouter from "effect/http/HttpRouter"
39
+ import * as Layer from "effect/Layer"
40
+ import * as Option from "effect/Option"
41
+ import type * as Redacted from "effect/Redacted"
42
+ import type * as Schema from "effect/Schema"
43
+ import * as Adapter from "./internal/adapter.ts"
44
+ import * as Address from "./internal/address.ts"
45
+ import * as Commands from "./internal/commands.ts"
46
+ import * as Errors from "./internal/errors.ts"
47
+ import * as Normalize from "./internal/normalize.ts"
48
+ import { CurrentPostOptions } from "./internal/options.ts"
49
+ import * as Polling from "./internal/polling.ts"
50
+ import * as Receive from "./internal/receive.ts"
51
+ import * as Webhook from "./internal/webhook.ts"
52
+ import * as TelegramBotApi from "./TelegramBotApi.ts"
53
+
54
+ /**
55
+ * Capabilities that are built but stay off until their live checks pass.
56
+ *
57
+ * **Details**
58
+ *
59
+ * - `files`: rich-message media sent as multipart `attach://` parts,
60
+ * up to 10 per post and 50 MB each.
61
+ * - `buttons`: inline keyboards. A click is dispatched only when its
62
+ * `data` matches a button in Telegram's copy of the message.
63
+ * - `commands`: messages that start with a `bot_command` for this bot.
64
+ *
65
+ * @stability unstable
66
+ * @category models
67
+ * @since 4.1.5
68
+ */
69
+ export interface Unverified {
70
+ readonly files?: boolean | undefined
71
+ readonly buttons?: boolean | undefined
72
+ readonly commands?: boolean | undefined
73
+ }
74
+
75
+ /**
76
+ * What became of one update given to `receive`.
77
+ *
78
+ * **Details**
79
+ *
80
+ * - `accepted`: its event was accepted, or its click or command was
81
+ * answered, refused or not.
82
+ * - `unhandled`: it gave nothing and went to `onUnhandled`.
83
+ * - `notAccepted`: the `ChatHandler` failed `NotAccepted` or passed
84
+ * `deadline`.
85
+ * - `invalid`: it is not an update, or it should give an event and could
86
+ * not be read.
87
+ *
88
+ * @stability unstable
89
+ * @category models
90
+ * @since 4.1.5
91
+ */
92
+ export type Outcome = "accepted" | "unhandled" | "notAccepted" | "invalid"
93
+
94
+ /**
95
+ * Options for running updates.
96
+ *
97
+ * @stability unstable
98
+ * @category models
99
+ * @since 4.1.5
100
+ */
101
+ export interface ReceiveOptions {
102
+ /** Updates that give no event, the excluded contexts among them. */
103
+ readonly onUnhandled?: ((update: Schema.Json) => Effect.Effect<void>) | undefined
104
+ /** How long `ChatHandler.handle` has before the update is `notAccepted`. Default 10 seconds. */
105
+ readonly deadline?: Duration.Input | undefined
106
+ /**
107
+ * How long a click handler has before the click is answered. Default 2.5
108
+ * seconds. The handler then keeps running, detached, and the update is
109
+ * `accepted`: Telegram does not send it again.
110
+ */
111
+ readonly clickDeadline?: Duration.Input | undefined
112
+ /**
113
+ * How long a command handler has. Default 10 seconds. The handler is then
114
+ * interrupted, and the update is `accepted`: Telegram does not send it
115
+ * again.
116
+ */
117
+ readonly commandDeadline?: Duration.Input | undefined
118
+ }
119
+
120
+ /**
121
+ * The Telegram adapter's own service.
122
+ *
123
+ * **Details**
124
+ *
125
+ * - `botId` is the numeric id in front of the token's colon.
126
+ * - `receive` runs one update, already authenticated and parsed, as both
127
+ * transports do, for a consumer's own transport. It needs a
128
+ * `ChatHandler`. Clicks and commands go to `ChatInteraction.Handler`
129
+ * when there is one in context: without it a click is answered and
130
+ * dropped, and a command is an ordinary message.
131
+ *
132
+ * @stability unstable
133
+ * @category services
134
+ * @since 4.1.5
135
+ */
136
+ export class TelegramChat extends Context.Service<TelegramChat, {
137
+ readonly botId: string
138
+ readonly environment: TelegramBotApi.Environment
139
+ readonly receive: (
140
+ update: unknown,
141
+ options?: ReceiveOptions | undefined
142
+ ) => Effect.Effect<Outcome, never, ChatHandler>
143
+ }>()("@effect/chat-telegram/TelegramChat") {}
144
+
145
+ /**
146
+ * Registers the Telegram adapter in the `Registry` and provides the
147
+ * `TelegramChat` and `TelegramBotApi` services.
148
+ *
149
+ * **Details**
150
+ *
151
+ * - The descriptor has `edit`, `delete`, `replyTo`, `download`,
152
+ * `getThread` and `getUser`, beside `post`, and whatever `unverified`
153
+ * turns on.
154
+ * - `environment: "test"` uses Telegram's test environment.
155
+ * - `apiUrl` is for a local Bot API server and is privileged configuration.
156
+ * - Fails `Unauthenticated` when the token has no bot id. The token is not
157
+ * checked against Telegram here; the first call does that.
158
+ * - The bot's username, which commands and `@` mentions need, is read with
159
+ * `getMe` on the first message and kept. While it can't be read, a
160
+ * message update is `invalid`, and Telegram sends it again.
161
+ *
162
+ * @stability unstable
163
+ * @category layers
164
+ * @since 4.1.5
165
+ */
166
+ export const layer = (options: {
167
+ readonly token: Redacted.Redacted<string>
168
+ readonly environment?: TelegramBotApi.Environment | undefined
169
+ readonly apiUrl?: string | undefined
170
+ readonly unverified?: Unverified | undefined
171
+ }): Layer.Layer<TelegramChat | TelegramBotApi.TelegramBotApi, ChatError, HttpClient.HttpClient | Registry> =>
172
+ Layer.effect(
173
+ TelegramChat,
174
+ Effect.gen(function*() {
175
+ const api = yield* TelegramBotApi.TelegramBotApi
176
+ const registry = yield* Registry
177
+ const capabilities = Adapter.capabilitiesOf(options.unverified ?? {})
178
+ const { adapter, answer } = Adapter.make({ api, capabilities })
179
+ yield* registry.register(adapter)
180
+ let username: string | undefined
181
+ const env: Receive.Environment = {
182
+ api,
183
+ capabilities,
184
+ answer,
185
+ username: Effect.suspend(() =>
186
+ username !== undefined ? Effect.succeed(username) : api.call("getMe").pipe(
187
+ Effect.flatMap((me) => {
188
+ const name = Normalize.string(me, "username")
189
+ if (name === undefined) return Errors.fail("getMe", Errors.invalidResponse(false, "missing_username"))
190
+ username = name
191
+ return Effect.succeed(name)
192
+ })
193
+ )
194
+ )
195
+ }
196
+ return TelegramChat.of({
197
+ botId: api.botId,
198
+ environment: api.environment,
199
+ receive: Effect.fnUntraced(function*(update, receiveOptions) {
200
+ const handler = yield* ChatHandler
201
+ return yield* Receive.receive(update, env, receiveOptions ?? {}, handler.handle)
202
+ })
203
+ })
204
+ })
205
+ ).pipe(Layer.provideMerge(TelegramBotApi.layer(options)))
206
+
207
+ /** `TelegramChat.receive` with the layer's `ChatHandler`, as a transport runs it. */
208
+ const transportReceive = Effect.fnUntraced(function*(options: ReceiveOptions) {
209
+ const telegram = yield* TelegramChat
210
+ const context = yield* Effect.context<ChatHandler>()
211
+ return (update: unknown) => Effect.provideContext(telegram.receive(update, options), context)
212
+ })
213
+
214
+ /**
215
+ * The header Telegram sends the webhook secret in. An app that records
216
+ * server request headers must add it to `Headers.CurrentRedactedNames`,
217
+ * keeping the names already there, in the layer it serves:
218
+ * `Layer.provideMerge` reaches the server span, `Layer.provide` on the
219
+ * webhook alone does not. The README has the setup.
220
+ *
221
+ * @stability unstable
222
+ * @category constants
223
+ * @since 4.1.5
224
+ */
225
+ export const secretHeader: string = Webhook.secretHeader
226
+
227
+ /**
228
+ * `POST {path}`: the bot's webhook.
229
+ *
230
+ * **Details**
231
+ *
232
+ * - The `X-Telegram-Bot-Api-Secret-Token` header must equal
233
+ * `secretToken`, compared in constant time. Otherwise the answer is 401
234
+ * and the body is not read. The layer fails unless `secretToken` is 32 to
235
+ * 256 characters of `A-Za-z0-9_-`.
236
+ * - 413 past `maxBodyBytes` (1 MiB by default), 400 for a body that can't
237
+ * be read or is not an update. `maxBodyBytes` must be a non-negative safe
238
+ * integer; another value is a defect when the layer is built.
239
+ * - The update goes through `receive`: 200 for `accepted` and
240
+ * `unhandled`, 503 for `notAccepted` and `invalid`, which Telegram
241
+ * sends again. A click or command is answered 200 after its reply
242
+ * attempt.
243
+ *
244
+ * @stability unstable
245
+ * @category layers
246
+ * @since 4.1.5
247
+ */
248
+ export const layerWebhook = (
249
+ options: ReceiveOptions & {
250
+ readonly path: `/${string}`
251
+ readonly secretToken: Redacted.Redacted<string>
252
+ readonly maxBodyBytes?: number | undefined
253
+ }
254
+ ): Layer.Layer<never, ChatError, HttpRouter.HttpRouter | TelegramChat | ChatHandler> =>
255
+ HttpRouter.use(Effect.fnUntraced(function*(router) {
256
+ const secret = new TextEncoder().encode(yield* Webhook.secretToken("layerWebhook", options.secretToken))
257
+ const maxBodySize = ByteSize.bytes(options.maxBodyBytes ?? 1024 * 1024)
258
+ const receive = yield* transportReceive(options)
259
+ yield* router.add(
260
+ "POST",
261
+ options.path,
262
+ (request) => Webhook.handleRequest(request, { secret, maxBodySize, receive })
263
+ )
264
+ }))
265
+
266
+ /**
267
+ * Long polling with `getUpdates`, for a long-running process.
268
+ *
269
+ * **Details**
270
+ *
271
+ * - Updates run one at a time, in order, through `receive`. An update is
272
+ * confirmed only after it ran, so a process that dies part way sees it
273
+ * again.
274
+ * - `notAccepted` and `invalid` are retried up to `maxAttempts` times (3
275
+ * by default) with a backoff, then logged as an error and skipped:
276
+ * `getUpdates` is one queue, and retrying forever would stall the bot.
277
+ * - The layer fails with `InvalidRequest` and detail `conflict` when
278
+ * Telegram answers 409 at start: a webhook is set, or another process
279
+ * polls. It never deletes a webhook itself. A later 409 stops polling
280
+ * with an error log.
281
+ *
282
+ * @stability unstable
283
+ * @category layers
284
+ * @since 4.1.5
285
+ */
286
+ export const layerPolling = (options: ReceiveOptions & {
287
+ /** The long-poll timeout. Default 30 seconds. */
288
+ readonly timeout?: Duration.Input | undefined
289
+ readonly maxAttempts?: number | undefined
290
+ } = {}): Layer.Layer<never, ChatError, TelegramChat | TelegramBotApi.TelegramBotApi | ChatHandler> =>
291
+ Layer.effectDiscard(Effect.gen(function*() {
292
+ const api = yield* TelegramBotApi.TelegramBotApi
293
+ const pollingOptions: Polling.Options = {
294
+ api,
295
+ timeout: options.timeout === undefined ? Duration.seconds(30) : Duration.fromInputUnsafe(options.timeout),
296
+ maxAttempts: Math.max(1, options.maxAttempts ?? 3),
297
+ receive: yield* transportReceive(options)
298
+ }
299
+ const first = yield* Polling.getUpdates(api, undefined, Duration.zero).pipe(Effect.mapError(Polling.conflict))
300
+ yield* Effect.forkScoped(Polling.loop(first, pollingOptions))
301
+ }))
302
+
303
+ /**
304
+ * Registers the webhook with exactly the `allowed_updates` the adapter
305
+ * reads. It is never called by the adapter itself.
306
+ *
307
+ * @stability unstable
308
+ * @category webhooks
309
+ * @since 4.1.5
310
+ */
311
+ export const setWebhook = (options: {
312
+ readonly url: string
313
+ readonly secretToken: Redacted.Redacted<string>
314
+ readonly maxConnections?: number | undefined
315
+ readonly dropPendingUpdates?: boolean | undefined
316
+ }): Effect.Effect<void, ChatError, TelegramBotApi.TelegramBotApi> =>
317
+ Effect.gen(function*() {
318
+ const secret = yield* Webhook.secretToken("setWebhook", options.secretToken)
319
+ const api = yield* TelegramBotApi.TelegramBotApi
320
+ yield* api.call("setWebhook", {
321
+ url: options.url,
322
+ secret_token: secret,
323
+ allowed_updates: Receive.allowedUpdates,
324
+ ...(options.maxConnections === undefined ? {} : { max_connections: options.maxConnections }),
325
+ ...(options.dropPendingUpdates === undefined ? {} : { drop_pending_updates: options.dropPendingUpdates })
326
+ }, { write: true })
327
+ })
328
+
329
+ /**
330
+ * The `setMyCommands` payload for a group's commands.
331
+ *
332
+ * **Details**
333
+ *
334
+ * - Fails `InvalidRequest` with detail `invalid_command_names` when a
335
+ * command id is not `[a-z0-9_]{1,32}`. The portable rule allows `-`;
336
+ * Telegram does not.
337
+ * - An `argument` has no Telegram counterpart and is appended to the
338
+ * description.
339
+ * - Commands are registered as ordinary, not ephemeral: this version has
340
+ * no `ephemeral`.
341
+ *
342
+ * @stability unstable
343
+ * @category commands
344
+ * @since 4.1.5
345
+ */
346
+ export const commandRequests = (
347
+ group: ChatInteraction.Group<any>
348
+ ): Effect.Effect<
349
+ { readonly commands: ReadonlyArray<{ readonly command: string; readonly description: string }> },
350
+ ChatError
351
+ > => {
352
+ const result = Commands.botCommands(group)
353
+ return "invalid" in result
354
+ ? Errors.fail("commandRequests", Errors.invalidRequest("invalid_command_names"))
355
+ : Effect.succeed(result)
356
+ }
357
+
358
+ /**
359
+ * Sends a group's commands with `setMyCommands`.
360
+ *
361
+ * @stability unstable
362
+ * @category commands
363
+ * @since 4.1.5
364
+ */
365
+ export const setCommands = (
366
+ group: ChatInteraction.Group<any>,
367
+ options?: { readonly scope?: Schema.Json | undefined; readonly languageCode?: string | undefined }
368
+ ): Effect.Effect<void, ChatError, TelegramBotApi.TelegramBotApi> =>
369
+ Effect.gen(function*() {
370
+ const payload = yield* commandRequests(group)
371
+ const api = yield* TelegramBotApi.TelegramBotApi
372
+ yield* api.call("setMyCommands", {
373
+ commands: payload.commands,
374
+ ...(options?.scope === undefined ? {} : { scope: options.scope }),
375
+ ...(options?.languageCode === undefined ? {} : { language_code: options.languageCode })
376
+ }, { write: true })
377
+ })
378
+
379
+ /**
380
+ * The address of a chat, or of a forum topic in it.
381
+ *
382
+ * @stability unstable
383
+ * @category constructors
384
+ * @since 4.1.5
385
+ */
386
+ export const thread: (chatId: string | number, messageThreadId?: string | number | undefined) => ChatThread =
387
+ Address.thread
388
+
389
+ /**
390
+ * The parts of a Telegram address, or `None` for another platform's or a
391
+ * malformed one.
392
+ *
393
+ * @stability unstable
394
+ * @category destructors
395
+ * @since 4.1.5
396
+ */
397
+ export const parts: (thread: ChatThread) => Option.Option<{
398
+ readonly chatId: string
399
+ readonly messageThreadId?: string | undefined
400
+ }> = Address.parts
401
+
402
+ /**
403
+ * What the normalisers need to know about the bot.
404
+ *
405
+ * @stability unstable
406
+ * @category models
407
+ * @since 4.1.5
408
+ */
409
+ export interface NormalizeContext {
410
+ readonly botId: string
411
+ /** The bot's username without `@`, from `getMe`. */
412
+ readonly botUsername: string
413
+ readonly environment?: TelegramBotApi.Environment | undefined
414
+ }
415
+
416
+ /**
417
+ * The normaliser, for a consumer's own transport. It checks no secret:
418
+ * that is the transport's job.
419
+ *
420
+ * **Details**
421
+ *
422
+ * - A `message` or `channel_post` with text, a caption, a file or rich
423
+ * content gives a `MessageCreated`. `text` is verbatim, and empty for
424
+ * an inbound rich message, whose content is only in `raw`.
425
+ * - `text_mention` entities are mentions by id. An `@username` is a
426
+ * mention only when it names the bot.
427
+ * - The author is `sender_chat` when there is one, else `from`.
428
+ * - A private (ephemeral) message, a service message, and anything from a
429
+ * business connection, a channel's direct messages or guest mode give
430
+ * none, as does every other update. Commands are messages here too:
431
+ * `receive` is what routes them.
432
+ * - `raw` is the update.
433
+ *
434
+ * @stability unstable
435
+ * @category normalization
436
+ * @since 4.1.5
437
+ */
438
+ export const normalize: (update: unknown, context: NormalizeContext) => ReadonlyArray<ChatEvent> = Normalize.normalize
439
+
440
+ /**
441
+ * The click or command of an update, as `receive` would dispatch it.
442
+ *
443
+ * **Details**
444
+ *
445
+ * A click is given only when its `data` is the `callback_data` of a button
446
+ * in Telegram's own copy of the message. That proves the bot put the button
447
+ * there, not that it is still current or that this user may press it.
448
+ *
449
+ * @stability unstable
450
+ * @category normalization
451
+ * @since 4.1.5
452
+ */
453
+ export const normalizeInteraction = (
454
+ update: unknown,
455
+ context: NormalizeContext
456
+ ): Option.Option<ChatInteraction.ButtonClicked | ChatInteraction.CommandInvoked> => {
457
+ if (!Normalize.isObject(update)) return Option.none()
458
+ return Option.fromUndefinedOr(Receive.clickEvent(update) ?? Receive.commandEvent(update, context))
459
+ }
460
+
461
+ /**
462
+ * The delivery key of an update, or of an event or interaction whose `raw`
463
+ * is one: `{botId}.{update_id}.{date}`, with `test.` in front in the test
464
+ * environment. Telegram sends an update again until it gets a 200 (or an
465
+ * offset moves past it), clicks and commands included, so a handler whose
466
+ * work must not be lost or run twice commits this key and a recoverable
467
+ * work item in one transaction before it returns. A click or command
468
+ * past its deadline counts as answered and is not sent again, so that
469
+ * holds only for a commit within the deadline. The README has the recipe.
470
+ *
471
+ * @stability unstable
472
+ * @category normalization
473
+ * @since 4.1.5
474
+ */
475
+ export const deliveryKey = (
476
+ raw: unknown,
477
+ context: { readonly botId: string; readonly environment?: TelegramBotApi.Environment | undefined }
478
+ ): Option.Option<string> => Option.fromUndefinedOr(Normalize.deliveryId(raw, context))
479
+
480
+ /**
481
+ * Reads a mention for `ChatTest`. A mention's text is a display name or an
482
+ * `@username`, neither of which holds the id, so this is always `None`;
483
+ * a message's `mentions` come from its entities.
484
+ *
485
+ * @stability unstable
486
+ * @category testing
487
+ * @since 4.1.5
488
+ */
489
+ export const parseMention: ParseMention = () => Option.none()
490
+
491
+ /**
492
+ * Telegram options for every write inside an effect.
493
+ *
494
+ * @stability unstable
495
+ * @category models
496
+ * @since 4.1.5
497
+ */
498
+ export interface TelegramPostOptions {
499
+ /**
500
+ * Users whose `[name](tg://user?id=…)` links in the Markdown stay links.
501
+ * Any other `tg://` link becomes text. Default: none.
502
+ */
503
+ readonly notify?: { readonly users?: ReadonlyArray<string> | undefined } | undefined
504
+ /** Sends posts with `disable_notification`. */
505
+ readonly silent?: boolean | undefined
506
+ }
507
+
508
+ /**
509
+ * Scoped Telegram options for every write inside `effect`. Nested calls
510
+ * merge, the inner one winning field by field. Answers to commands and
511
+ * follow-ups ignore them.
512
+ *
513
+ * @stability unstable
514
+ * @category combinators
515
+ * @since 4.1.5
516
+ */
517
+ export const withPostOptions: {
518
+ /**
519
+ * Scoped Telegram options for every write inside `effect`. Nested calls
520
+ * merge, the inner one winning field by field. Answers to commands and
521
+ * follow-ups ignore them.
522
+ *
523
+ * @stability unstable
524
+ * @category combinators
525
+ * @since 4.1.5
526
+ */
527
+ (options: TelegramPostOptions): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
528
+ /**
529
+ * Scoped Telegram options for every write inside `effect`. Nested calls
530
+ * merge, the inner one winning field by field. Answers to commands and
531
+ * follow-ups ignore them.
532
+ *
533
+ * @stability unstable
534
+ * @category combinators
535
+ * @since 4.1.5
536
+ */
537
+ <A, E, R>(effect: Effect.Effect<A, E, R>, options: TelegramPostOptions): Effect.Effect<A, E, R>
538
+ } = dual(
539
+ 2,
540
+ <A, E, R>(effect: Effect.Effect<A, E, R>, options: TelegramPostOptions): Effect.Effect<A, E, R> =>
541
+ Effect.updateService(effect, CurrentPostOptions, (current) => ({ ...current, ...options }))
542
+ )
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @stability unstable
3
+ * @since 4.1.5
4
+ */
5
+
6
+ // @barrel: Auto-generated exports. Do not edit manually.
7
+
8
+ /**
9
+ * @stability unstable
10
+ * @since 4.1.5
11
+ */
12
+ export * as TelegramBotApi from "./TelegramBotApi.ts"
13
+
14
+ /**
15
+ * @stability unstable
16
+ * @since 4.1.5
17
+ */
18
+ export * as TelegramChat from "./TelegramChat.ts"
@@ -0,0 +1,95 @@
1
+ import type { ChatErrorReason } from "effect/chat/ChatError"
2
+ import type * as ChatUi from "effect/chat/ChatUi"
3
+ import * as Predicate from "effect/Predicate"
4
+ import * as Errors from "./errors.ts"
5
+ import { string } from "./normalize.ts"
6
+
7
+ /** The adapter's own cap, as Telegram publishes no button count. @internal */
8
+ export const actionsPerMessage = 100
9
+
10
+ /** `callback_data` is 1 to 64 bytes, less the separator. @internal */
11
+ export const actionDataLength = 63
12
+
13
+ /** Between a button's id and its value in `callback_data`. @internal */
14
+ export const separator = "\u001f"
15
+
16
+ const encoder = new TextEncoder()
17
+
18
+ const bytes = (s: string) => encoder.encode(s).length
19
+
20
+ /** A button's `callback_data`: its id, and its value after the separator when it has one. @internal */
21
+ export const callbackData = (button: { readonly id: string; readonly value?: string | undefined }): string =>
22
+ button.value === undefined ? button.id : button.id + separator + button.value
23
+
24
+ /** The id and value of `callback_data`. @internal */
25
+ export const parseData = (data: string): { readonly id: string; readonly value?: string | undefined } => {
26
+ const at = data.indexOf(separator)
27
+ return at === -1 ? { id: data } : { id: data.slice(0, at), value: data.slice(at + 1) }
28
+ }
29
+
30
+ /** A label short enough to share a row with two others. */
31
+ const shortLabel = 12
32
+
33
+ const perRow = 3
34
+
35
+ type KeyboardButton =
36
+ | { readonly text: string; readonly callback_data: string; readonly style?: string }
37
+ | { readonly text: string; readonly url: string }
38
+
39
+ /**
40
+ * The inline keyboard of a message's actions, or the reason it can't be
41
+ * sent: a select (`Unsupported`), too many elements, data past 63 bytes,
42
+ * an id holding the separator, or a link that is not http or https.
43
+ *
44
+ * @internal
45
+ */
46
+ export const keyboard = (
47
+ actions: ReadonlyArray<ChatUi.Action>
48
+ ): { readonly inline_keyboard: ReadonlyArray<ReadonlyArray<KeyboardButton>> } | ChatErrorReason => {
49
+ if (actions.some((action) => action._tag === "Select")) return Errors.unsupported("selects")
50
+ if (actions.length > actionsPerMessage) return Errors.tooLarge(undefined, "too_many_actions")
51
+ const buttons: Array<KeyboardButton> = []
52
+ for (const action of actions) {
53
+ if (action._tag === "Button") {
54
+ if (action.id.includes(separator)) return Errors.invalidRequest("invalid_action_id")
55
+ if (bytes(action.id) + bytes(action.value ?? "") > actionDataLength) {
56
+ return Errors.tooLarge(undefined, "action_data_too_long")
57
+ }
58
+ buttons.push({
59
+ text: action.label,
60
+ callback_data: callbackData(action),
61
+ ...(action.style === "primary" || action.style === "danger" ? { style: action.style } : {})
62
+ })
63
+ } else if (action._tag === "LinkButton") {
64
+ if (!/^https?:\/\//i.test(action.url)) return Errors.invalidRequest("untrusted_url")
65
+ buttons.push({ text: action.label, url: action.url })
66
+ }
67
+ }
68
+ const rows: Array<Array<KeyboardButton>> = []
69
+ let row: Array<KeyboardButton> = []
70
+ for (const button of buttons) {
71
+ const short = button.text.length <= shortLabel
72
+ if (!short || row.length === perRow || row.some((b) => b.text.length > shortLabel)) {
73
+ if (row.length > 0) rows.push(row)
74
+ row = []
75
+ }
76
+ row.push(button)
77
+ }
78
+ if (row.length > 0) rows.push(row)
79
+ return { inline_keyboard: rows }
80
+ }
81
+
82
+ /** Every `callback_data` in a message's `reply_markup`. @internal */
83
+ export const keyboardData = (replyMarkup: unknown): ReadonlySet<string> => {
84
+ const data = new Set<string>()
85
+ const rows = Predicate.isObject(replyMarkup) ? replyMarkup.inline_keyboard : undefined
86
+ if (!Array.isArray(rows)) return data
87
+ for (const row of rows) {
88
+ if (!Array.isArray(row)) continue
89
+ for (const button of row) {
90
+ const value = string(button, "callback_data")
91
+ if (value !== undefined) data.add(value)
92
+ }
93
+ }
94
+ return data
95
+ }