@effect/chat-discord 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 (132) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +27 -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/DiscordChat.d.ts +530 -0
  88. package/dist/DiscordChat.d.ts.map +1 -0
  89. package/dist/DiscordChat.js +574 -0
  90. package/dist/DiscordChat.js.map +1 -0
  91. package/dist/index.d.ts +10 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +11 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/internal/adapter.d.ts +2 -0
  96. package/dist/internal/adapter.d.ts.map +1 -0
  97. package/dist/internal/adapter.js +492 -0
  98. package/dist/internal/adapter.js.map +1 -0
  99. package/dist/internal/errors.d.ts +2 -0
  100. package/dist/internal/errors.d.ts.map +1 -0
  101. package/dist/internal/errors.js +236 -0
  102. package/dist/internal/errors.js.map +1 -0
  103. package/dist/internal/interactions.d.ts +2 -0
  104. package/dist/internal/interactions.d.ts.map +1 -0
  105. package/dist/internal/interactions.js +490 -0
  106. package/dist/internal/interactions.js.map +1 -0
  107. package/dist/internal/length.d.ts +2 -0
  108. package/dist/internal/length.d.ts.map +1 -0
  109. package/dist/internal/length.js +31 -0
  110. package/dist/internal/length.js.map +1 -0
  111. package/dist/internal/mentions.d.ts +2 -0
  112. package/dist/internal/mentions.d.ts.map +1 -0
  113. package/dist/internal/mentions.js +93 -0
  114. package/dist/internal/mentions.js.map +1 -0
  115. package/dist/internal/normalize.d.ts +2 -0
  116. package/dist/internal/normalize.d.ts.map +1 -0
  117. package/dist/internal/normalize.js +322 -0
  118. package/dist/internal/normalize.js.map +1 -0
  119. package/dist/internal/options.d.ts +2 -0
  120. package/dist/internal/options.d.ts.map +1 -0
  121. package/dist/internal/options.js +25 -0
  122. package/dist/internal/options.js.map +1 -0
  123. package/package.json +63 -1
  124. package/src/DiscordChat.ts +703 -0
  125. package/src/index.ts +12 -0
  126. package/src/internal/adapter.ts +653 -0
  127. package/src/internal/errors.ts +184 -0
  128. package/src/internal/interactions.ts +451 -0
  129. package/src/internal/length.ts +33 -0
  130. package/src/internal/mentions.ts +101 -0
  131. package/src/internal/normalize.ts +363 -0
  132. package/src/internal/options.ts +29 -0
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
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 DiscordChat from "./DiscordChat.ts"
@@ -0,0 +1,653 @@
1
+ import type { DiscordREST } from "dfx/DiscordREST"
2
+ import * as Generated from "dfx/DiscordREST/Generated"
3
+ import type * as Discord from "dfx/types"
4
+ import * as Cache from "effect/Cache"
5
+ import {
6
+ type ChatAdapter,
7
+ checkMessageLength,
8
+ type Descriptor,
9
+ type File,
10
+ type Posted,
11
+ retrySafe,
12
+ type ThreadInfo,
13
+ type User
14
+ } from "effect/chat/ChatAdapter"
15
+ import {
16
+ type ChatError,
17
+ type ChatErrorReason,
18
+ fileRefused,
19
+ interactionExpired,
20
+ NotFound,
21
+ TooLarge
22
+ } from "effect/chat/ChatError"
23
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
24
+ import type { ChatMessage } from "effect/chat/ChatMessage"
25
+ import type * as ChatThread from "effect/chat/ChatThread"
26
+ import type { Action } from "effect/chat/ChatUi"
27
+ import * as Clock from "effect/Clock"
28
+ import * as DateTime from "effect/DateTime"
29
+ import * as Duration from "effect/Duration"
30
+ import * as Effect from "effect/Effect"
31
+ import * as Exit from "effect/Exit"
32
+ import { flow } from "effect/Function"
33
+ import * as HttpClient from "effect/http/HttpClient"
34
+ import * as HttpClientRequest from "effect/http/HttpClientRequest"
35
+ import * as Option from "effect/Option"
36
+ import { isObject } from "effect/Predicate"
37
+ import * as Schema from "effect/Schema"
38
+ import * as Stream from "effect/Stream"
39
+ import type { DiscordPostOptions } from "../DiscordChat.ts"
40
+ import * as Errors from "./errors.ts"
41
+ import * as Interactions from "./interactions.ts"
42
+ import * as Length from "./length.ts"
43
+ import * as Normalize from "./normalize.ts"
44
+ import { nonEmpty, optional, UserFields } from "./normalize.ts"
45
+ import { allowedMentions, CurrentPostOptions, flags } from "./options.ts"
46
+
47
+ type Json = Schema.Json
48
+ type Rest = DiscordREST["Service"]
49
+
50
+ /** @internal */
51
+ export const descriptor: Descriptor = {
52
+ platform: Normalize.platform,
53
+ capabilities: new Set([
54
+ "edit",
55
+ "delete",
56
+ "fetchMessage",
57
+ "history",
58
+ "download",
59
+ "files",
60
+ "replyTo",
61
+ "startThread",
62
+ "getThread",
63
+ "opener",
64
+ "getUser",
65
+ "buttons",
66
+ "selects",
67
+ "modals",
68
+ "commands",
69
+ "ephemeral"
70
+ ]),
71
+ // Components sit beside `content`, so the elements cost nothing here.
72
+ measure: (markdown) => Length.codePoints(markdown),
73
+ limits: {
74
+ messageLength: Length.messageLength,
75
+ filesPerMessage: 10,
76
+ uploadBytes: 10 * 1024 * 1024,
77
+ minWriteInterval: Duration.millis(1500),
78
+ followUpAge: Duration.minutes(15),
79
+ ...Interactions.limits
80
+ }
81
+ }
82
+
83
+ const pageSize = 100
84
+
85
+ /** Discord's code for "a thread has already been created for this message". */
86
+ const THREAD_ALREADY_CREATED = 160004
87
+ /** Discord's code for "cannot execute action on this channel type". */
88
+ const WRONG_CHANNEL_TYPE = 50024
89
+ /** Discord's code for "unknown interaction": a callback after the 3 seconds. */
90
+ const UNKNOWN_INTERACTION = 10062
91
+ /**
92
+ * Discord's codes for an interaction token it no longer takes. After 15
93
+ * minutes it answered 401 with 50027 "Invalid Webhook Token", recorded in
94
+ * EFF-3802. 10015 "Unknown Webhook" is from the docs' list and was not seen.
95
+ */
96
+ const SPENT_TOKEN = [50027, 10015]
97
+
98
+ const ChannelFields = Schema.Struct({
99
+ id: Schema.String,
100
+ type: Schema.Number,
101
+ guild_id: optional(Schema.String),
102
+ parent_id: optional(Schema.String),
103
+ name: optional(Schema.String),
104
+ topic: optional(Schema.String),
105
+ thread_metadata: optional(Schema.Struct({ create_timestamp: optional(Schema.String) }))
106
+ })
107
+
108
+ /**
109
+ * What the adapter reads from a channel.
110
+ *
111
+ * @internal
112
+ */
113
+ export type Channel = typeof ChannelFields.Type & { readonly raw: Json }
114
+
115
+ const decodeChannel = Schema.decodeUnknownOption(ChannelFields)
116
+
117
+ const decodeUser = Schema.decodeUnknownOption(UserFields)
118
+
119
+ const MemberFields = Schema.Struct({ nick: optional(Schema.String), user: optional(UserFields) })
120
+
121
+ const decodeMember = Schema.decodeUnknownOption(MemberFields)
122
+
123
+ const snowflake = /^\d{1,20}$/
124
+
125
+ /** Whether `thread` is a Discord address. */
126
+ const isAddress = (thread: ChatThread.ChatThread): boolean =>
127
+ thread.platform === Normalize.platform && snowflake.test(thread.id)
128
+
129
+ /**
130
+ * Discord's API, as dfx's `DiscordConfig` has it by default.
131
+ *
132
+ * @internal
133
+ */
134
+ export const defaultBaseUrl = "https://discord.com/api/v10"
135
+
136
+ /** @internal */
137
+ export const make = Effect.fnUntraced(function*(options: {
138
+ readonly rest: Rest
139
+ readonly http: HttpClient.HttpClient
140
+ readonly baseUrl: string
141
+ readonly botUserId: Effect.Effect<string, ChatError>
142
+ }) {
143
+ const { rest } = options
144
+
145
+ /**
146
+ * dfx's requests for the interaction webhook, over the plain `HttpClient`.
147
+ * dfx's own client sends a request again after a 429, which for
148
+ * `followUp` could land past the 15 minutes the expiry check ran on. The
149
+ * webhook takes the interaction's token and no bot token.
150
+ */
151
+ const webhooks = Generated.make(
152
+ HttpClient.mapRequest(
153
+ options.http,
154
+ flow(
155
+ HttpClientRequest.prependUrl(options.baseUrl),
156
+ HttpClientRequest.setHeader("User-Agent", "DiscordBot (https://effect.website, 1)")
157
+ )
158
+ )
159
+ )
160
+
161
+ const fail = (op: string, reason: ChatErrorReason) => Effect.fail(Errors.chatError(op, reason))
162
+
163
+ /** A message's elements as action rows, checked before any call. */
164
+ const components = (op: string, actions: ReadonlyArray<Action> | undefined) => {
165
+ const rows = Interactions.rows(actions ?? [])
166
+ return Array.isArray(rows) ? Effect.succeed(rows) : fail(op, rows)
167
+ }
168
+
169
+ /** One REST call, its failure mapped to a `ChatError` and retried when nothing happened. */
170
+ const call = <A, E>(op: string, effect: Effect.Effect<A, E>, write = false): Effect.Effect<A, ChatError> =>
171
+ retrySafe(Effect.mapError(effect, (error) => Errors.chatError(op, Errors.reasonForRestError(error, { write }))))
172
+
173
+ const resolve = (op: string, thread: ChatThread.ChatThread): Effect.Effect<string, ChatError> =>
174
+ isAddress(thread) ? Effect.succeed(thread.id) : fail(op, Errors.invalidRequest("invalid_thread"))
175
+
176
+ const getChannel = (op: string, id: string): Effect.Effect<Channel, ChatError> =>
177
+ Effect.flatMap(call(op, rest.getChannel(id)), (raw: unknown) =>
178
+ Option.match(decodeChannel(raw), {
179
+ onNone: () => fail(op, Errors.invalidResponse(false, "invalid_channel")),
180
+ onSome: (fields) => Effect.succeed({ ...fields, raw: raw as Json })
181
+ }))
182
+
183
+ /** Channels by id, for their type, parent and guild, none of which change. Failures are not kept. */
184
+ const channels = yield* Cache.makeWith(
185
+ (id: string) => getChannel("getChannel", id),
186
+ {
187
+ capacity: 1024,
188
+ timeToLive: (exit) => Exit.isSuccess(exit) ? Duration.hours(1) : Duration.zero
189
+ }
190
+ )
191
+
192
+ const channel = (op: string, id: string): Effect.Effect<Channel, ChatError> =>
193
+ Cache.get(channels, id).pipe(
194
+ Effect.mapError((error) => error.op === op ? error : Errors.chatError(op, error.reason))
195
+ )
196
+
197
+ const toMessage = (raw: unknown, botUserId: string): ChatMessage | undefined => {
198
+ const fields = Normalize.decodeMessageFields(raw)
199
+ return fields === undefined ? undefined : Normalize.message(raw as Json, fields, { botUserId })
200
+ }
201
+
202
+ const getMessage = (op: string, channelId: string, messageId: string): Effect.Effect<Json, ChatError> =>
203
+ call(op, rest.getMessage(channelId, messageId)).pipe(Effect.map((raw) => raw as unknown as Json))
204
+
205
+ const fetchMessage: ChatAdapter["fetchMessage"] = Effect.fnUntraced(function*(thread, messageId) {
206
+ const op = "fetchMessage"
207
+ const channelId = yield* resolve(op, thread)
208
+ const botUserId = yield* options.botUserId
209
+ const raw = yield* getMessage(op, channelId, messageId)
210
+ const message = toMessage(raw, botUserId)
211
+ return message === undefined ? yield* fail(op, Errors.notFound("not_a_message")) : message
212
+ })
213
+
214
+ /** The `interaction_expired` failure, with the reason Discord gave as its `cause`. */
215
+ const expired = (op: string, cause?: ChatErrorReason) =>
216
+ Errors.chatError(op, new NotFound({ detail: interactionExpired, ...(cause === undefined ? {} : { cause }) }))
217
+
218
+ /** An optional read: none when the message is gone or the bot may not read it. */
219
+ const orNone = <A>(effect: Effect.Effect<A, ChatError>): Effect.Effect<Option.Option<A>, ChatError> =>
220
+ effect.pipe(
221
+ Effect.map(Option.some),
222
+ Effect.catchIf(
223
+ (error) => error.reason._tag === "NotFound" || error.reason._tag === "Forbidden",
224
+ () => Effect.succeed(Option.none())
225
+ )
226
+ )
227
+
228
+ // Writes
229
+
230
+ /**
231
+ * A write's message, after the checks every write makes before a call.
232
+ * `components` is absent when there are none.
233
+ */
234
+ const messageBody = Effect.fnUntraced(function*(
235
+ op: string,
236
+ content: { readonly markdown: string; readonly actions?: ReadonlyArray<Action> | undefined },
237
+ postOptions: DiscordPostOptions
238
+ ) {
239
+ const rows = yield* components(op, content.actions)
240
+ yield* checkMessageLength(descriptor, op, content.markdown)
241
+ return {
242
+ content: content.markdown,
243
+ allowed_mentions: allowedMentions(postOptions.notify),
244
+ flags: flags(postOptions),
245
+ ...(rows.length === 0 ? {} : { components: rows })
246
+ }
247
+ })
248
+
249
+ const toFile = (file: File) =>
250
+ new globalThis.File([file.content as Uint8Array<ArrayBuffer>], file.name, { type: file.contentType })
251
+
252
+ const post: ChatAdapter["post"] = Effect.fnUntraced(function*(thread, content) {
253
+ const op = "post"
254
+ const channelId = yield* resolve(op, thread)
255
+ const postOptions = yield* CurrentPostOptions
256
+ const body = yield* messageBody(op, content, postOptions)
257
+ const files = content.files ?? []
258
+ // The adapter's own count and size check refuses the file the way Discord would.
259
+ if (
260
+ files.length > descriptor.limits.filesPerMessage ||
261
+ files.reduce((total, file) => total + file.content.length, 0) > descriptor.limits.uploadBytes
262
+ ) {
263
+ return yield* fail(op, new TooLarge({ subject: "files", detail: fileRefused }))
264
+ }
265
+ const create = rest.createMessage(channelId, {
266
+ ...body,
267
+ ...(content.replyTo === undefined ? {} : {
268
+ message_reference: {
269
+ message_id: content.replyTo.messageId,
270
+ ...(postOptions.failIfNotExists === false ? { fail_if_not_exists: false } : {})
271
+ }
272
+ }),
273
+ ...(files.length === 0 ? {} : { attachments: files.map((file, i) => ({ id: String(i), filename: file.name })) })
274
+ })
275
+ const answer = yield* (files.length === 0
276
+ ? call(op, create, true)
277
+ // Discord creates the message and its files in one request, so a denied answer left nothing posted.
278
+ : call(op, rest.withFiles(files.map(toFile))(create), true).pipe(
279
+ Effect.mapError((error) => Errors.chatError(op, Errors.fileRefused(error.reason)))
280
+ ))
281
+ if (typeof answer.id !== "string" || typeof answer.timestamp !== "string") {
282
+ return yield* fail(op, Errors.invalidResponse(true, "missing_id"))
283
+ }
284
+ const timestamp = DateTime.make(answer.timestamp)
285
+ if (Option.isNone(timestamp)) return yield* fail(op, Errors.invalidResponse(true, "invalid_timestamp"))
286
+ return { id: answer.id, thread, timestamp: DateTime.toUtc(timestamp.value) } satisfies Posted
287
+ })
288
+
289
+ const edit: ChatAdapter["edit"] = Effect.fnUntraced(function*(thread, messageId, content) {
290
+ const op = "edit"
291
+ const channelId = yield* resolve(op, thread)
292
+ const body = yield* messageBody(op, content, yield* CurrentPostOptions)
293
+ // Send empty components to clear existing elements.
294
+ yield* call(op, rest.updateMessage(channelId, messageId, { ...body, components: body.components ?? [] }), true)
295
+ })
296
+
297
+ const startThread: ChatAdapter["startThread"] = Effect.fnUntraced(function*(thread, messageId, startOptions) {
298
+ const op = "startThread"
299
+ const channelId = yield* resolve(op, thread)
300
+ const postOptions = yield* CurrentPostOptions
301
+ const given = nonEmpty(startOptions?.name?.trim())
302
+ const name = given ?? (yield* Effect.map(
303
+ getMessage(op, channelId, messageId),
304
+ (raw) => {
305
+ const text = isObject(raw) && typeof raw.content === "string" ? raw.content.replace(/\s+/g, " ").trim() : ""
306
+ return text === "" ? "Thread" : Length.cut(text, 100)
307
+ }
308
+ ))
309
+ return yield* call(
310
+ op,
311
+ rest.createThreadFromMessage(channelId, messageId, {
312
+ name: Length.cut(name, 100),
313
+ ...(postOptions.autoArchiveDuration === undefined
314
+ ? {}
315
+ : { auto_archive_duration: postOptions.autoArchiveDuration })
316
+ }),
317
+ true
318
+ ).pipe(
319
+ Effect.map((answer) => Normalize.thread(typeof answer.id === "string" ? answer.id : messageId)),
320
+ // The thread under a message has the message's id.
321
+ Effect.catchIf(Errors.hasCode(THREAD_ALREADY_CREATED), () => Effect.succeed(Normalize.thread(messageId))),
322
+ // A message in a thread has no thread of its own: the thread is the answer.
323
+ Effect.catchIf(Errors.hasCode(WRONG_CHANNEL_TYPE), (error) =>
324
+ Effect.flatMap(
325
+ channel(op, channelId),
326
+ (found) => Normalize.isThreadType(found.type) ? Effect.succeed(thread) : Effect.fail(error)
327
+ ))
328
+ )
329
+ })
330
+
331
+ // Reads
332
+
333
+ /**
334
+ * A thread's messages, with the `THREAD_STARTER_MESSAGE` placeholder
335
+ * replaced by the opener from the parent channel, or dropped when the
336
+ * opener is gone.
337
+ */
338
+ const history: ChatAdapter["history"] = (thread, { direction, from }) =>
339
+ Stream.unwrap(Effect.gen(function*() {
340
+ const op = "history"
341
+ const channelId = yield* resolve(op, thread)
342
+ const botUserId = yield* options.botUserId
343
+ const page = (cursor: string | undefined) =>
344
+ call(
345
+ op,
346
+ rest.listMessages(
347
+ channelId,
348
+ direction === "backward"
349
+ ? { ...(cursor === undefined ? {} : { before: cursor }), limit: pageSize }
350
+ : { after: cursor ?? "0", limit: pageSize }
351
+ )
352
+ ).pipe(Effect.map((answer) => {
353
+ const found: ReadonlyArray<Json> = Array.isArray(answer) ? answer as ReadonlyArray<Json> : []
354
+ const sorted = [...found].sort((a, b) =>
355
+ Normalize.compareIds(idOf(a), idOf(b)) * (direction === "backward" ? -1 : 1)
356
+ )
357
+ const last = sorted.at(-1)
358
+ return [
359
+ sorted,
360
+ found.length < pageSize || last === undefined ? Option.none<string>() : Option.some(idOf(last))
361
+ ] as const
362
+ }))
363
+ const after = (message: ChatMessage) =>
364
+ from === undefined ||
365
+ (direction === "forward"
366
+ ? Normalize.compareIds(message.id, from) > 0
367
+ : Normalize.compareIds(message.id, from) < 0)
368
+ return Stream.paginate(from, page).pipe(
369
+ Stream.mapEffect((raw) => resolveStarter(op, raw, botUserId)),
370
+ Stream.filter((message): message is ChatMessage => message !== undefined && after(message))
371
+ )
372
+ }))
373
+
374
+ const idOf = (raw: Json): string => isObject(raw) && typeof raw.id === "string" ? raw.id : ""
375
+
376
+ const resolveStarter = (
377
+ op: string,
378
+ raw: Json,
379
+ botUserId: string
380
+ ): Effect.Effect<ChatMessage | undefined, ChatError> => {
381
+ const fields = Normalize.decodeMessageFields(raw)
382
+ if (fields === undefined) return Effect.succeed(undefined)
383
+ if (fields.type !== Normalize.THREAD_STARTER_MESSAGE) {
384
+ return Effect.succeed(Normalize.message(raw, fields, { botUserId }))
385
+ }
386
+ const referenced = isObject(raw) ? raw.referenced_message : undefined
387
+ if (referenced === null) return Effect.succeed(undefined)
388
+ if (referenced !== undefined) return Effect.succeed(toMessage(referenced, botUserId))
389
+ const reference = fields.message_reference
390
+ const channelId = nonEmpty(reference?.channel_id)
391
+ const messageId = nonEmpty(reference?.message_id)
392
+ if (channelId === undefined || messageId === undefined) return Effect.succeed(undefined)
393
+ return orNone(getMessage(op, channelId, messageId)).pipe(
394
+ Effect.map((found) => Option.isSome(found) ? toMessage(found.value, botUserId) : undefined)
395
+ )
396
+ }
397
+
398
+ /**
399
+ * The message whose id is the thread's: in the thread for a forum post,
400
+ * otherwise in the parent channel.
401
+ */
402
+ const opener: ChatAdapter["opener"] = Effect.fnUntraced(function*(thread) {
403
+ const op = "opener"
404
+ const channelId = yield* resolve(op, thread)
405
+ const found = yield* channel(op, channelId)
406
+ if (!Normalize.isThreadType(found.type)) return Option.none()
407
+ const botUserId = yield* options.botUserId
408
+ const inThread = yield* orNone(getMessage(op, channelId, channelId))
409
+ const parent = nonEmpty(found.parent_id)
410
+ const raw = Option.isSome(inThread) || parent === undefined
411
+ ? inThread
412
+ : yield* orNone(getMessage(op, parent, channelId))
413
+ return Option.flatMap(raw, (raw) => Option.fromUndefinedOr(toMessage(raw, botUserId)))
414
+ })
415
+
416
+ const getThread: ChatAdapter["getThread"] = Effect.fnUntraced(function*(thread) {
417
+ const op = "getThread"
418
+ const channelId = yield* resolve(op, thread)
419
+ const found = yield* getChannel(op, channelId)
420
+ const kind = Normalize.kindOf(found.type)
421
+ const name = kind === "direct" ? undefined : nonEmpty(found.name)
422
+ const topic = nonEmpty(found.topic)
423
+ const parent = kind === "thread" ? nonEmpty(found.parent_id) : undefined
424
+ const created = Option.flatMap(
425
+ Option.fromUndefinedOr(nonEmpty(found.thread_metadata?.create_timestamp)),
426
+ DateTime.make
427
+ )
428
+ const createdAt = Option.isSome(created) ? DateTime.toUtc(created.value) : Normalize.snowflakeTime(found.id)
429
+ return {
430
+ thread,
431
+ kind,
432
+ ...(name === undefined ? {} : { name }),
433
+ ...(topic === undefined ? {} : { topic }),
434
+ ...(parent === undefined ? {} : { parent: Normalize.thread(parent) }),
435
+ ...(createdAt === undefined ? {} : { createdAt }),
436
+ raw: found.raw
437
+ } satisfies ThreadInfo
438
+ })
439
+
440
+ const getUser: ChatAdapter["getUser"] = Effect.fnUntraced(function*(id, userOptions) {
441
+ const op = "getUser"
442
+ const botUserId = yield* options.botUserId
443
+ const toUser = (user: typeof UserFields.Type, nick: string | null | undefined, raw: unknown): User => ({
444
+ id: user.id,
445
+ name: nonEmpty(nick) ?? nonEmpty(user.global_name) ?? nonEmpty(user.username) ?? user.id,
446
+ isBot: user.bot === true,
447
+ isSelf: user.id === botUserId,
448
+ raw: raw as Json
449
+ })
450
+ const where = userOptions?.in
451
+ const guildId = where === undefined
452
+ ? undefined
453
+ : nonEmpty((yield* channel(op, yield* resolve(op, where))).guild_id)
454
+ if (guildId !== undefined) {
455
+ const member = yield* orNone(call(op, rest.getGuildMember(guildId, id)))
456
+ if (Option.isSome(member)) {
457
+ const fields = Option.getOrUndefined(decodeMember(member.value))
458
+ const user = fields?.user
459
+ if (fields !== undefined && user !== null && user !== undefined) return toUser(user, fields.nick, member.value)
460
+ }
461
+ }
462
+ const raw = yield* call(op, rest.getUser(id))
463
+ const user = Option.getOrUndefined(decodeUser(raw))
464
+ if (user === undefined) return yield* fail(op, Errors.invalidResponse(false, "invalid_user"))
465
+ return toUser(user, undefined, raw)
466
+ })
467
+
468
+ const download: ChatAdapter["download"] = (thread, attachment, { maxBytes }) =>
469
+ Stream.unwrap(Effect.gen(function*() {
470
+ const op = "download"
471
+ const channelId = yield* resolve(op, thread)
472
+ const tooLarge = Errors.chatError(op, new TooLarge({ subject: "files", detail: "max_bytes" }))
473
+ const transport = (error: { readonly reason: { readonly _tag: string } }) =>
474
+ Errors.chatError(op, Errors.transport(false, error.reason._tag, error))
475
+ if (attachment.size !== undefined && attachment.size > maxBytes) return yield* Effect.fail(tooLarge)
476
+ const ids = Normalize.parseAttachmentId(attachment.id)
477
+ if (ids === undefined) return yield* fail(op, Errors.invalidRequest("invalid_attachment"))
478
+ const raw = yield* getMessage(op, channelId, ids.messageId)
479
+ const list = isObject(raw) && Array.isArray(raw.attachments) ? raw.attachments : []
480
+ const found = list.find((item) => isObject(item) && item.id === ids.attachmentId)
481
+ const url = isObject(found) && typeof found.url === "string" ? found.url : undefined
482
+ if (url === undefined) return yield* fail(op, Errors.notFound("attachment_not_found"))
483
+ const response = yield* Effect.mapError(options.http.execute(HttpClientRequest.get(url)), transport)
484
+ if (response.status < 200 || response.status >= 300) {
485
+ return yield* fail(op, Errors.reasonForResponse(response.status, undefined, { write: false }))
486
+ }
487
+ let received = 0
488
+ return response.stream.pipe(
489
+ Stream.mapError(transport),
490
+ Stream.mapEffect((chunk) => {
491
+ received += chunk.length
492
+ return received > maxBytes ? Effect.fail(tooLarge) : Effect.succeed(chunk)
493
+ })
494
+ )
495
+ }))
496
+
497
+ /**
498
+ * The message a `post` of the same content sends with the default post
499
+ * options, after the same checks: no mentions and no embeds.
500
+ * `withPostOptions` does not reach a command's answer.
501
+ */
502
+ const answerBody = (
503
+ op: string,
504
+ content: { readonly markdown: string; readonly actions?: ReadonlyArray<Action> | undefined }
505
+ ) => messageBody(op, content, {})
506
+
507
+ /**
508
+ * Edits the original response of a deferred command in one HTTP request:
509
+ * not through `call`, nor dfx's client, whose retries would send again
510
+ * after the expiry check. Refused before the call past `followUpAge`,
511
+ * read from the interaction's id. A token Discord no longer takes is
512
+ * `interaction_expired` too.
513
+ */
514
+ const followUp: ChatAdapter["followUp"] = Effect.fnUntraced(function*(deferred, content) {
515
+ const op = "followUp"
516
+ const to = isAddress(deferred.command.thread) ? Interactions.followUpTo(deferred.command.raw) : undefined
517
+ if (to === undefined || !snowflake.test(to.id)) return yield* fail(op, Errors.invalidRequest("invalid_interaction"))
518
+ const now = yield* Clock.currentTimeMillis
519
+ if (now - Normalize.snowflakeMillis(to.id) >= Duration.toMillis(descriptor.limits.followUpAge!)) {
520
+ return yield* Effect.fail(expired(op))
521
+ }
522
+ const body = yield* answerBody(op, content)
523
+ yield* webhooks.updateOriginalWebhookMessage(to.applicationId, to.token, {
524
+ payload: Interactions.withVisibility(body, deferred.visibility)
525
+ }).pipe(Effect.mapError((cause) => {
526
+ const error = Errors.chatError(op, Errors.reasonForRestError(cause, { write: true }))
527
+ return SPENT_TOKEN.some((code) => Errors.hasCode(code)(error)) ? expired(op, error.reason) : error
528
+ }))
529
+ })
530
+
531
+ const adapter: ChatAdapter = {
532
+ descriptor,
533
+ post,
534
+ edit,
535
+ followUp,
536
+ delete: Effect.fnUntraced(function*(thread, messageId) {
537
+ const channelId = yield* resolve("delete", thread)
538
+ yield* call("delete", rest.deleteMessage(channelId, messageId), true)
539
+ }),
540
+ fetchMessage,
541
+ history,
542
+ download,
543
+ startThread,
544
+ getThread,
545
+ opener,
546
+ getUser
547
+ }
548
+
549
+ /** The guild a channel or thread is in, from the cached channel. */
550
+ const guild = (thread: ChatThread.ChatThread): Effect.Effect<Option.Option<string>, ChatError> =>
551
+ Effect.flatMap(
552
+ resolve("guild", thread),
553
+ (id) => Effect.map(channel("guild", id), (found) => Option.fromUndefinedOr(nonEmpty(found.guild_id)))
554
+ )
555
+
556
+ /** A channel's type, for `dispatch`. */
557
+ const channelType = (id: string): Effect.Effect<number, ChatError> =>
558
+ Effect.map(channel("dispatch", id), (found) => found.type)
559
+
560
+ // Interactions
561
+
562
+ /** One callback, Discord's answer to an interaction. */
563
+ const callback = (
564
+ op: string,
565
+ to: { readonly id: string; readonly token: string },
566
+ payload: Discord.CreateInteractionResponseRequest
567
+ ): Effect.Effect<void, ChatError> =>
568
+ Effect.asVoid(call(op, rest.createInteractionResponse(to.id, to.token, { payload }), true))
569
+
570
+ const logged = (effect: Effect.Effect<void, ChatError>) =>
571
+ Effect.catch(effect, (error) => Effect.logWarning("@effect/chat-discord: an interaction callback failed", error))
572
+
573
+ /**
574
+ * Normalises an `INTERACTION_CREATE` payload, runs the handler inside
575
+ * `deadline` and answers through the callback endpoint.
576
+ */
577
+ const interaction = (
578
+ raw: unknown,
579
+ interactionOptions?: { readonly deadline?: Duration.Duration | undefined }
580
+ ): Effect.Effect<void, never, ChatInteraction.Handler> =>
581
+ Effect.gen(function*() {
582
+ const event = Interactions.normalize(raw)
583
+ const to = Interactions.answerTo(raw)
584
+ if (Option.isNone(event) || to === undefined) return
585
+ const reply = yield* ChatInteraction.handle(event.value, interactionOptions?.deadline ?? Duration.seconds(2))
586
+ switch (reply._tag) {
587
+ // Too late to answer: Discord shows its own banner.
588
+ case "Late":
589
+ return
590
+ case "Ack":
591
+ case "Close":
592
+ // Type 6 is no answer to a command, so an unhandled one is left to whoever owns it.
593
+ if (event.value._tag === "CommandInvoked") return
594
+ return yield* logged(callback("ack", to, Interactions.ackCallback))
595
+ case "Errors":
596
+ return yield* logged(callback("errors", to, Interactions.errorsCallback(reply.errors)))
597
+ case "OpenModal": {
598
+ const from = event.value as
599
+ | ChatInteraction.ButtonClicked
600
+ | ChatInteraction.SelectChanged
601
+ | ChatInteraction.CommandInvoked
602
+ const data = Interactions.modalData(reply.modal)
603
+ if (!("custom_id" in data)) {
604
+ // A click is still answered, so the person sees no failure for a modal that could not be built.
605
+ // A command has no silent answer, so it gets none, and Discord shows its own failure.
606
+ if (from._tag !== "CommandInvoked") yield* logged(callback("ack", to, Interactions.ackCallback))
607
+ const handler = yield* ChatInteraction.Handler
608
+ return yield* handler.refused(from, Errors.chatError("openModal", data))
609
+ }
610
+ return yield* answer(from, "openModal", to, Effect.succeed(Interactions.modalCallback(data)))
611
+ }
612
+ case "Respond":
613
+ return yield* answer(
614
+ event.value as ChatInteraction.CommandInvoked,
615
+ "respond",
616
+ to,
617
+ Effect.map(answerBody("respond", reply), (body) => Interactions.respondCallback(body, reply.visibility))
618
+ )
619
+ case "Defer":
620
+ return yield* answer(
621
+ event.value as ChatInteraction.CommandInvoked,
622
+ "defer",
623
+ to,
624
+ Effect.succeed(Interactions.deferCallback(reply.visibility))
625
+ )
626
+ }
627
+ })
628
+
629
+ /**
630
+ * Sends a reply that must land, or tells `Handler.refused`: a reply that
631
+ * fails its checks sends nothing, and a callback that comes back
632
+ * `Unknown interaction` was late, which is `interaction_expired`.
633
+ */
634
+ const answer = (
635
+ event: ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged | ChatInteraction.CommandInvoked,
636
+ op: string,
637
+ to: { readonly id: string; readonly token: string },
638
+ payload: Effect.Effect<Discord.CreateInteractionResponseRequest, ChatError>
639
+ ): Effect.Effect<void, never, ChatInteraction.Handler> =>
640
+ Effect.gen(function*() {
641
+ const handler = yield* ChatInteraction.Handler
642
+ yield* Effect.flatMap(payload, (built) => callback(op, to, built)).pipe(
643
+ Effect.catch((error) =>
644
+ handler.refused(
645
+ event,
646
+ Errors.hasCode(UNKNOWN_INTERACTION)(error) ? expired(op, error.reason) : error
647
+ )
648
+ )
649
+ )
650
+ })
651
+
652
+ return { adapter, guild, channelType, interaction }
653
+ })