@effect/chat-slack 0.0.0-stage → 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 (182) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +46 -2
  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/SlackChat.d.ts +500 -0
  88. package/dist/SlackChat.d.ts.map +1 -0
  89. package/dist/SlackChat.js +512 -0
  90. package/dist/SlackChat.js.map +1 -0
  91. package/dist/SlackWebApi.d.ts +74 -0
  92. package/dist/SlackWebApi.d.ts.map +1 -0
  93. package/dist/SlackWebApi.js +96 -0
  94. package/dist/SlackWebApi.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 +169 -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 +836 -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 +36 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/emoji.d.ts +2 -0
  112. package/dist/internal/emoji.d.ts.map +1 -0
  113. package/dist/internal/emoji.js +207 -0
  114. package/dist/internal/emoji.js.map +1 -0
  115. package/dist/internal/emojiData.d.ts +54 -0
  116. package/dist/internal/emojiData.d.ts.map +1 -0
  117. package/dist/internal/emojiData.js +1965 -0
  118. package/dist/internal/emojiData.js.map +1 -0
  119. package/dist/internal/errors.d.ts +2 -0
  120. package/dist/internal/errors.d.ts.map +1 -0
  121. package/dist/internal/errors.js +190 -0
  122. package/dist/internal/errors.js.map +1 -0
  123. package/dist/internal/escape.d.ts +14 -0
  124. package/dist/internal/escape.d.ts.map +1 -0
  125. package/dist/internal/escape.js +413 -0
  126. package/dist/internal/escape.js.map +1 -0
  127. package/dist/internal/interactions.d.ts +2 -0
  128. package/dist/internal/interactions.d.ts.map +1 -0
  129. package/dist/internal/interactions.js +389 -0
  130. package/dist/internal/interactions.js.map +1 -0
  131. package/dist/internal/json.d.ts +2 -0
  132. package/dist/internal/json.d.ts.map +1 -0
  133. package/dist/internal/json.js +30 -0
  134. package/dist/internal/json.js.map +1 -0
  135. package/dist/internal/length.d.ts +2 -0
  136. package/dist/internal/length.d.ts.map +1 -0
  137. package/dist/internal/length.js +33 -0
  138. package/dist/internal/length.js.map +1 -0
  139. package/dist/internal/mentions.d.ts +2 -0
  140. package/dist/internal/mentions.d.ts.map +1 -0
  141. package/dist/internal/mentions.js +229 -0
  142. package/dist/internal/mentions.js.map +1 -0
  143. package/dist/internal/normalize.d.ts +2 -0
  144. package/dist/internal/normalize.d.ts.map +1 -0
  145. package/dist/internal/normalize.js +211 -0
  146. package/dist/internal/normalize.js.map +1 -0
  147. package/dist/internal/options.d.ts +2 -0
  148. package/dist/internal/options.d.ts.map +1 -0
  149. package/dist/internal/options.js +6 -0
  150. package/dist/internal/options.js.map +1 -0
  151. package/dist/internal/richText.d.ts +2 -0
  152. package/dist/internal/richText.d.ts.map +1 -0
  153. package/dist/internal/richText.js +346 -0
  154. package/dist/internal/richText.js.map +1 -0
  155. package/dist/internal/text.d.ts +2 -0
  156. package/dist/internal/text.d.ts.map +1 -0
  157. package/dist/internal/text.js +239 -0
  158. package/dist/internal/text.js.map +1 -0
  159. package/dist/internal/webhook.d.ts +2 -0
  160. package/dist/internal/webhook.d.ts.map +1 -0
  161. package/dist/internal/webhook.js +142 -0
  162. package/dist/internal/webhook.js.map +1 -0
  163. package/package.json +59 -3
  164. package/src/SlackChat.ts +640 -0
  165. package/src/SlackWebApi.ts +135 -0
  166. package/src/index.ts +18 -0
  167. package/src/internal/actions.ts +203 -0
  168. package/src/internal/adapter.ts +961 -0
  169. package/src/internal/address.ts +50 -0
  170. package/src/internal/emoji.ts +223 -0
  171. package/src/internal/emojiData.ts +1965 -0
  172. package/src/internal/errors.ts +192 -0
  173. package/src/internal/escape.ts +428 -0
  174. package/src/internal/interactions.ts +391 -0
  175. package/src/internal/json.ts +35 -0
  176. package/src/internal/length.ts +41 -0
  177. package/src/internal/mentions.ts +224 -0
  178. package/src/internal/normalize.ts +221 -0
  179. package/src/internal/options.ts +22 -0
  180. package/src/internal/richText.ts +367 -0
  181. package/src/internal/text.ts +252 -0
  182. package/src/internal/webhook.ts +199 -0
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Slack's side of buttons, selects, modals and slash commands: the checks on
3
+ * a message's elements, the view a modal opens as, and the interactivity
4
+ * payloads and command forms.
5
+ */
6
+ import {
7
+ type ChatError,
8
+ type ChatErrorReason,
9
+ interactionExpired,
10
+ InvalidRequest,
11
+ NotFound,
12
+ TooLarge
13
+ } from "effect/chat/ChatError"
14
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
15
+ import type * as ChatUi from "effect/chat/ChatUi"
16
+ import * as Duration from "effect/Duration"
17
+ import * as Effect from "effect/Effect"
18
+ import * as Option from "effect/Option"
19
+ import * as Schema from "effect/Schema"
20
+ import type { SlackWebApi } from "../SlackWebApi.ts"
21
+ import * as Actions from "./actions.ts"
22
+ import * as Address from "./address.ts"
23
+ import * as Errors from "./errors.ts"
24
+ import { isObject, type JsonObject, object, setOwn, string } from "./json.ts"
25
+ import { codePoints } from "./length.ts"
26
+
27
+ type Json = Schema.Json
28
+
29
+ /** @internal */
30
+ export const limits = {
31
+ actionsPerMessage: 25,
32
+ actionDataLength: 2_000,
33
+ modalMetadataLength: 2_800,
34
+ modalFields: 100
35
+ } as const
36
+
37
+ /** Slack's limit on an `action_id` and a `callback_id`, in code points. */
38
+ const idLength = 255
39
+ /** Slack's limit on a modal's title. */
40
+ const titleLength = 24
41
+ /** Slack's limit on an input's label. */
42
+ const labelLength = 2_000
43
+
44
+ /** The submit label when the modal has none: Slack needs one on a view with inputs. */
45
+ const defaultSubmitLabel = "Submit"
46
+
47
+ /** The handler's share of Slack's 3 seconds. @internal */
48
+ export const defaultDeadline = Duration.millis(2_500)
49
+
50
+ /**
51
+ * Why a message's elements can't go, if they can't: more than 25, an id
52
+ * holding the join or longer than 255, or an id plus a value longer than
53
+ * 2,000. All count code points.
54
+ *
55
+ * @internal
56
+ */
57
+ export const checkActions = (actions: ReadonlyArray<ChatUi.Action>): ChatErrorReason | undefined => {
58
+ if (actions.length > limits.actionsPerMessage) return new TooLarge({ detail: "too_many_actions" })
59
+ for (const action of actions) {
60
+ if (action._tag === "LinkButton") continue
61
+ if (action.id.includes(Actions.join)) return new InvalidRequest({ detail: "invalid_action_id" })
62
+ const id = codePoints(action.id)
63
+ if (id > idLength) return new TooLarge({ detail: "action_id_too_long" })
64
+ const values = action._tag === "Button" ? [action.value ?? ""] : action.options.map((option) => option.value)
65
+ if (values.some((value) => id + codePoints(value) > limits.actionDataLength)) {
66
+ return new TooLarge({ detail: "action_data_too_long" })
67
+ }
68
+ }
69
+ return undefined
70
+ }
71
+
72
+ // Modals
73
+
74
+ /** Marks a `private_metadata` the adapter packed. */
75
+ const metadataTag = "chat1"
76
+
77
+ /** Where a click or a command happened, which a submit gives back. A command has no message. */
78
+ interface Origin {
79
+ readonly channel: string
80
+ readonly threadTs?: string | undefined
81
+ readonly messageId?: string | undefined
82
+ }
83
+
84
+ /**
85
+ * Consumer metadata is last so it may contain the join delimiter.
86
+ */
87
+ const packMetadata = (origin: Origin, metadata: string | undefined): string =>
88
+ [
89
+ metadataTag,
90
+ origin.channel,
91
+ origin.threadTs ?? "",
92
+ origin.messageId ?? "",
93
+ ...(metadata === undefined ? [] : [metadata])
94
+ ].join(Actions.join)
95
+
96
+ const unpackMetadata = (
97
+ packed: string
98
+ ): { readonly origin: Origin; readonly metadata: string | undefined } | undefined => {
99
+ const parts = packed.split(Actions.join)
100
+ if (parts.length < 4 || parts[0] !== metadataTag || parts[1] === "") return undefined
101
+ return {
102
+ origin: {
103
+ channel: parts[1],
104
+ threadTs: parts[2] === "" ? undefined : parts[2],
105
+ messageId: parts[3] === "" ? undefined : parts[3]
106
+ },
107
+ metadata: parts.length === 4 ? undefined : parts.slice(4).join(Actions.join)
108
+ }
109
+ }
110
+
111
+ const inputBlock = (element: ChatUi.TextInput | ChatUi.SelectInput) => ({
112
+ type: "input",
113
+ block_id: element.id,
114
+ label: Actions.plainText(element.label),
115
+ optional: element.optional === true,
116
+ element: element._tag === "TextInput"
117
+ ? {
118
+ type: "plain_text_input",
119
+ action_id: element.id,
120
+ multiline: element.multiline === true,
121
+ ...(element.placeholder === undefined ? {} : { placeholder: Actions.plainText(element.placeholder) }),
122
+ ...(element.initial === undefined ? {} : { initial_value: element.initial }),
123
+ ...(element.minLength === undefined ? {} : { min_length: element.minLength }),
124
+ ...(element.maxLength === undefined ? {} : { max_length: element.maxLength })
125
+ }
126
+ : Actions.elements([{
127
+ _tag: "Select",
128
+ id: element.id,
129
+ options: element.options,
130
+ ...(element.placeholder === undefined ? {} : { placeholder: element.placeholder }),
131
+ ...(element.initial === undefined ? {} : { selected: element.initial })
132
+ }])[0]
133
+ })
134
+
135
+ /**
136
+ * The view that opens `modal` from `from`, or why it can't open.
137
+ *
138
+ * - Inputs are `input` blocks whose `block_id` is the field id, and a
139
+ * `Text` is a `section` of plain text.
140
+ * - The modal's id is the `callback_id`. `private_metadata` holds the
141
+ * click's channel, thread and message beside the consumer's metadata. For
142
+ * a command the message slot is empty.
143
+ * - The modal's id plus its metadata is held to 2,800 code points, the id to
144
+ * 255, the title to 24 and each label to 2,000.
145
+ *
146
+ * @internal
147
+ */
148
+ export const view = (
149
+ modal: ChatUi.Modal,
150
+ from: ChatInteraction.ButtonClicked | ChatInteraction.SelectChanged | ChatInteraction.CommandInvoked
151
+ ): { readonly view: Readonly<Record<string, unknown>> } | { readonly refusal: ChatErrorReason } => {
152
+ const refuse = (refusal: ChatErrorReason) => ({ refusal })
153
+ const id = codePoints(modal.id)
154
+ if (id + codePoints(modal.metadata ?? "") > limits.modalMetadataLength) {
155
+ return refuse(new TooLarge({ detail: "modal_metadata_too_long" }))
156
+ }
157
+ if (id > idLength) return refuse(new TooLarge({ detail: "modal_id_too_long" }))
158
+ if (modal.elements.length > limits.modalFields) return refuse(new TooLarge({ detail: "too_many_fields" }))
159
+ if (codePoints(modal.title) > titleLength) return refuse(new TooLarge({ detail: "title_too_long" }))
160
+ const parts = Address.parts(from.thread)
161
+ if (Option.isNone(parts)) return refuse(new InvalidRequest({ detail: "invalid_thread" }))
162
+ const blocks: Array<unknown> = []
163
+ for (const element of modal.elements) {
164
+ if (element._tag === "Text") {
165
+ blocks.push({ type: "section", text: Actions.plainText(element.text) })
166
+ continue
167
+ }
168
+ if (codePoints(element.label) > labelLength) return refuse(new TooLarge({ detail: "label_too_long" }))
169
+ blocks.push(inputBlock(element))
170
+ }
171
+ return {
172
+ view: {
173
+ type: "modal",
174
+ callback_id: modal.id,
175
+ title: Actions.plainText(modal.title),
176
+ submit: Actions.plainText(modal.submitLabel ?? defaultSubmitLabel),
177
+ private_metadata: packMetadata(
178
+ { ...parts.value, messageId: from._tag === "CommandInvoked" ? undefined : from.messageId },
179
+ modal.metadata
180
+ ),
181
+ blocks
182
+ }
183
+ }
184
+ }
185
+
186
+ // Inbound
187
+
188
+ const isJson = Schema.is(Schema.Json)
189
+
190
+ /** The payload without its verification `token`. */
191
+ const raw = (payload: JsonObject): Json => {
192
+ const { token: _, ...rest } = payload
193
+ return rest
194
+ }
195
+
196
+ const threadOf = (teamId: string, origin: Origin) =>
197
+ Address.thread({
198
+ team: teamId,
199
+ channel: origin.channel,
200
+ threadTs: origin.threadTs === origin.messageId ? undefined : origin.threadTs
201
+ })
202
+
203
+ const clicked = (payload: JsonObject, teamId: string): Option.Option<ChatInteraction.Interaction> => {
204
+ const actions = payload.actions
205
+ const action = Array.isArray(actions) && actions.length === 1 && isObject(actions[0]) ? actions[0] : undefined
206
+ const id = string(action, "action_id")
207
+ // Only an element in the adapter's own block, and not a link button, whose click carries nothing.
208
+ if (action === undefined || id === undefined || action.block_id !== Actions.blockId || id.startsWith(Actions.join)) {
209
+ return Option.none()
210
+ }
211
+ const container = object(payload, "container")
212
+ const message = object(payload, "message")
213
+ const channel = string(container, "channel_id") ?? string(object(payload, "channel"), "id")
214
+ const messageId = string(container, "message_ts") ?? string(message, "ts")
215
+ const userId = string(object(payload, "user"), "id")
216
+ if (channel === undefined || messageId === undefined || userId === undefined) return Option.none()
217
+ const threadTs = string(message, "thread_ts") ?? string(container, "thread_ts")
218
+ const origin = { thread: threadOf(teamId, { channel, threadTs, messageId }), messageId, userId, raw: raw(payload) }
219
+ if (action.type === "button") {
220
+ const value = typeof action.value === "string" ? action.value : undefined
221
+ return Option.some(ChatInteraction.ButtonClicked.make({ id, ...(value === undefined ? {} : { value }), ...origin }))
222
+ }
223
+ const value = object(action, "selected_option")?.value
224
+ return action.type === "static_select" && typeof value === "string"
225
+ ? Option.some(ChatInteraction.SelectChanged.make({ id, value, ...origin }))
226
+ : Option.none()
227
+ }
228
+
229
+ /** The value of one input in `view.state.values`, or nothing for an empty one. */
230
+ const inputValue = (input: Json): string | undefined => {
231
+ if (!isObject(input)) return undefined
232
+ const value = input.type === "static_select" ? object(input, "selected_option")?.value : input.value
233
+ return typeof value === "string" && value !== "" ? value : undefined
234
+ }
235
+
236
+ const submitted = (payload: JsonObject, teamId: string): Option.Option<ChatInteraction.Interaction> => {
237
+ const view = object(payload, "view")
238
+ const id = string(view, "callback_id")
239
+ const packed = string(view, "private_metadata")
240
+ const unpacked = packed === undefined ? undefined : unpackMetadata(packed)
241
+ const userId = string(object(payload, "user"), "id")
242
+ if (id === undefined || unpacked === undefined || userId === undefined) return Option.none()
243
+ const values: Record<string, string> = {}
244
+ const state = object(object(view, "state"), "values") ?? {}
245
+ for (const blockId of Object.keys(state)) {
246
+ const inputs = object(state, blockId)
247
+ if (inputs === undefined) continue
248
+ for (const input of Object.values(inputs)) {
249
+ const value = inputValue(input)
250
+ if (value !== undefined) setOwn(values, blockId, value)
251
+ }
252
+ }
253
+ const { metadata, origin } = unpacked
254
+ return Option.some(ChatInteraction.ModalSubmitted.make({
255
+ id,
256
+ ...(metadata === undefined ? {} : { metadata }),
257
+ values,
258
+ thread: threadOf(teamId, origin),
259
+ ...(origin.messageId === undefined ? {} : { messageId: origin.messageId }),
260
+ userId,
261
+ raw: raw(payload)
262
+ }))
263
+ }
264
+
265
+ /** Whether `payload` is a slash command's fields: a `command` and no `type`. @internal */
266
+ export const isCommand = (payload: unknown): boolean =>
267
+ isObject(payload) && payload.type === undefined && typeof payload.command === "string"
268
+
269
+ const invoked = (payload: JsonObject, teamId: string): Option.Option<ChatInteraction.Interaction> => {
270
+ const command = string(payload, "command")
271
+ const channel = string(payload, "channel_id")
272
+ const userId = string(payload, "user_id")
273
+ const id = command?.startsWith("/") === true ? command.slice(1) : command
274
+ if (id === undefined || id === "" || channel === undefined || userId === undefined) return Option.none()
275
+ const text = typeof payload.text === "string" ? payload.text : ""
276
+ return Option.some(ChatInteraction.CommandInvoked.make({
277
+ id,
278
+ text,
279
+ // A command can't be typed in a thread, so its address is the channel's.
280
+ thread: Address.thread({ team: teamId, channel }),
281
+ userId,
282
+ raw: raw(payload)
283
+ }))
284
+ }
285
+
286
+ /**
287
+ * The interaction a decoded `payload` is: a click on a button or select in
288
+ * an `actions` block the adapter built, a submit of a view it opened, or a
289
+ * slash command's fields. Anything else, a link button's click and a value
290
+ * that is not JSON included, is none.
291
+ *
292
+ * @internal
293
+ */
294
+ export const normalize = (
295
+ payload: unknown,
296
+ context: { readonly teamId: string }
297
+ ): Option.Option<ChatInteraction.Interaction> => {
298
+ if (!isObject(payload) || !isJson(payload)) return Option.none()
299
+ if (payload.type === "block_actions") return clicked(payload, context.teamId)
300
+ if (payload.type === "view_submission") return submitted(payload, context.teamId)
301
+ if (isCommand(payload)) return invoked(payload, context.teamId)
302
+ return Option.none()
303
+ }
304
+
305
+ /** A trigger past its 3 seconds is the same refusal `handle` gives a late click. */
306
+ const expired = (error: ChatError): ChatError =>
307
+ error.reason.detail === "expired_trigger_id"
308
+ ? Errors.chatError("openModal", new NotFound({ detail: interactionExpired, cause: error.reason }))
309
+ : error
310
+
311
+ /**
312
+ * `SlackChat.interaction`: normalises, calls the handler through
313
+ * `ChatInteraction.handle` and gives the body to answer with.
314
+ *
315
+ * - An ack, a close, a late click, a deferral and a payload that is not the
316
+ * adapter's give `undefined`, an empty answer.
317
+ * - `errors` gives `response_action: "errors"`, keyed by field id.
318
+ * - A late submit or command gives `Late`.
319
+ * - `OpenModal` calls `views.open` with the click's or command's
320
+ * `trigger_id` before answering. A modal that can't be built, or that
321
+ * Slack refuses, goes to `Handler.refused`, and the click is still acked.
322
+ * - `Respond` gives the message as the body, with its `response_type`. One
323
+ * that fails the checks of a `post` goes to `Handler.refused` and gives
324
+ * an empty answer.
325
+ *
326
+ * @internal
327
+ */
328
+ export const make = (options: {
329
+ readonly api: SlackWebApi["Service"]
330
+ readonly teamId: string
331
+ readonly answer: (
332
+ op: string,
333
+ content: { readonly markdown: string; readonly actions?: ReadonlyArray<ChatUi.Action> | undefined },
334
+ visibility: ChatInteraction.Visibility
335
+ ) => Effect.Effect<Readonly<Record<string, unknown>>, ChatError>
336
+ }) =>
337
+ (
338
+ payload: unknown,
339
+ interactionOptions?: { readonly deadline?: Duration.Duration | undefined }
340
+ ): Effect.Effect<Json | undefined | ChatInteraction.Late, never, ChatInteraction.Handler> =>
341
+ Effect.gen(function*() {
342
+ const event = normalize(payload, { teamId: options.teamId })
343
+ if (Option.isNone(event)) return undefined
344
+ const reply = yield* ChatInteraction.handle(event.value, interactionOptions?.deadline ?? defaultDeadline)
345
+ switch (reply._tag) {
346
+ case "Late":
347
+ // A late click is acked: its handler runs on and `handle` refuses a modal it opens.
348
+ return event.value._tag === "ButtonClicked" || event.value._tag === "SelectChanged" ? undefined : reply
349
+ case "Ack":
350
+ case "Close":
351
+ case "Defer":
352
+ return undefined
353
+ case "Errors":
354
+ return { response_action: "errors", errors: reply.errors }
355
+ case "Respond": {
356
+ const command = event.value as ChatInteraction.CommandInvoked
357
+ const handler = yield* ChatInteraction.Handler
358
+ return yield* options.answer("respond", reply, reply.visibility).pipe(
359
+ // The body is a post's, which is JSON.
360
+ Effect.map((body): Json | undefined => body as Json),
361
+ Effect.catch((error) => Effect.as(handler.refused(command, error), undefined))
362
+ )
363
+ }
364
+ case "OpenModal": {
365
+ const click = event.value as
366
+ | ChatInteraction.ButtonClicked
367
+ | ChatInteraction.SelectChanged
368
+ | ChatInteraction.CommandInvoked
369
+ const handler = yield* ChatInteraction.Handler
370
+ const built = view(reply.modal, click)
371
+ if ("refusal" in built) {
372
+ yield* handler.refused(click, Errors.chatError("openModal", built.refusal))
373
+ return undefined
374
+ }
375
+ const triggerId = string(payload, "trigger_id")
376
+ if (triggerId === undefined) {
377
+ yield* handler.refused(click, Errors.chatError("openModal", new InvalidRequest({ detail: "no_trigger_id" })))
378
+ return undefined
379
+ }
380
+ yield* options.api.call("views.open", { trigger_id: triggerId, view: built.view }, {
381
+ write: true,
382
+ retry: false
383
+ })
384
+ .pipe(
385
+ Effect.mapError(Errors.withOp("openModal")),
386
+ Effect.catch((error) => handler.refused(click, expired(error)))
387
+ )
388
+ return undefined
389
+ }
390
+ }
391
+ })
@@ -0,0 +1,35 @@
1
+ import * as Predicate from "effect/Predicate"
2
+ import type * as Schema from "effect/Schema"
3
+
4
+ /** @internal */
5
+ export type JsonObject = { readonly [key: string]: Schema.Json }
6
+
7
+ /** `Predicate.isObject`, narrowed to the JSON a payload holds. @internal */
8
+ export const isObject = (u: unknown): u is JsonObject => Predicate.isObject(u)
9
+
10
+ const field = (object: unknown, key: string): unknown => isObject(object) ? object[key] : undefined
11
+
12
+ /** A non-empty string field of `object`, when it is an object. @internal */
13
+ export const string = (object: unknown, key: string): string | undefined => {
14
+ const value = field(object, key)
15
+ return typeof value === "string" && value.length > 0 ? value : undefined
16
+ }
17
+
18
+ /** An object field of `object`, when it is an object. @internal */
19
+ export const object = (object: unknown, key: string): JsonObject | undefined => {
20
+ const value = field(object, key)
21
+ return isObject(value) ? value : undefined
22
+ }
23
+
24
+ /** The parsed JSON, or `undefined` when `text` is not JSON. @internal */
25
+ export const parse = (text: string): unknown => {
26
+ try {
27
+ return JSON.parse(text)
28
+ } catch {
29
+ return undefined
30
+ }
31
+ }
32
+
33
+ /** An own property, so a key such as `__proto__` stays a field. @internal */
34
+ export const setOwn = (record: Record<string, string>, key: string, value: string) =>
35
+ Object.defineProperty(record, key, { value, enumerable: true, writable: true, configurable: true })
@@ -0,0 +1,41 @@
1
+ import type { Action } from "effect/chat/ChatUi"
2
+ import * as Actions from "./actions.ts"
3
+ import { blocksCost } from "./emoji.ts"
4
+
5
+ /** `msg_too_long`: code points of `markdown_text` as sent, inclusive. @internal */
6
+ export const messageLength = 12_000
7
+
8
+ /** @internal */
9
+ export const codePoints = (text: string): number => {
10
+ let count = 0
11
+ for (let i = 0; i < text.length; i++) {
12
+ const code = text.charCodeAt(i)
13
+ if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
14
+ const low = text.charCodeAt(i + 1)
15
+ if (low >= 0xdc00 && low <= 0xdfff) i++
16
+ }
17
+ count++
18
+ }
19
+ return count
20
+ }
21
+
22
+ const lessThan = (text: string): number => {
23
+ let count = 0
24
+ for (let i = text.indexOf("<"); i !== -1; i = text.indexOf("<", i + 1)) count++
25
+ return count
26
+ }
27
+
28
+ /**
29
+ * What a Markdown string and the elements beside it cost against
30
+ * `messageLength`, as an upper bound that adds up. It is the larger of two
31
+ * counts: code points plus three for every `<`, which may be sent as
32
+ * `&lt;`, and Slack's 13,200 count, scaled to 12,000, of the text with each
33
+ * emoji as its shortcode plus the `actions` block's stored JSON.
34
+ *
35
+ * @internal
36
+ */
37
+ export const measure = (markdown: string, actions?: ReadonlyArray<Action>): number =>
38
+ Math.max(
39
+ codePoints(markdown) + 3 * lessThan(markdown),
40
+ Math.ceil((blocksCost(markdown) + Actions.cost(Actions.elements(actions ?? []))) * 10 / 11)
41
+ )
@@ -0,0 +1,224 @@
1
+ import type { Mention } from "effect/chat/ChatMessage"
2
+ import { isObject } from "effect/Predicate"
3
+
4
+ type Kind = Mention["kind"]
5
+
6
+ interface Target {
7
+ readonly kind: Kind
8
+ readonly id: string
9
+ }
10
+
11
+ /** A mention token in `text`, as Slack writes it. */
12
+ const tokenPattern =
13
+ /<(@([UW][A-Z0-9]+)|!subteam\^([A-Z0-9]+)|#(C[A-Z0-9]+|G[A-Z0-9]+)|!(here|channel|everyone))(\|[^<>]*)?>/g
14
+
15
+ /**
16
+ * Parses one token, `<@U123>`, `<!subteam^S123|@team>`, `<#C123|name>` or
17
+ * `<!here>`, as the whole of `slice`.
18
+ *
19
+ * @internal
20
+ */
21
+ export const parseToken = (slice: string): Target | undefined => {
22
+ tokenPattern.lastIndex = 0
23
+ const match = tokenPattern.exec(slice)
24
+ if (match === null || match.index !== 0 || match[0].length !== slice.length) return undefined
25
+ return targetOf(match)
26
+ }
27
+
28
+ const targetOf = (match: RegExpExecArray): Target => {
29
+ const [, , user, group, channel, broadcast] = match
30
+ if (user !== undefined) return { kind: "user", id: user }
31
+ if (group !== undefined) return { kind: "role", id: group }
32
+ if (channel !== undefined) return { kind: "channel", id: channel }
33
+ return { kind: "broadcast", id: broadcast! }
34
+ }
35
+
36
+ interface Token extends Target {
37
+ readonly start: number
38
+ readonly end: number
39
+ }
40
+
41
+ const tokens = (text: string, skipCode: boolean): Array<Token> => {
42
+ const code: Array<readonly [number, number]> = []
43
+ if (skipCode) {
44
+ const codePattern = /```[\s\S]*?```|`[^`\n]+`/g
45
+ for (let match = codePattern.exec(text); match !== null; match = codePattern.exec(text)) {
46
+ code.push([match.index, match.index + match[0].length])
47
+ }
48
+ }
49
+ const found: Array<Token> = []
50
+ tokenPattern.lastIndex = 0
51
+ for (let match = tokenPattern.exec(text); match !== null; match = tokenPattern.exec(text)) {
52
+ const start = match.index
53
+ if (code.some(([from, to]) => start >= from && start < to)) continue
54
+ found.push({ ...targetOf(match), start, end: start + match[0].length })
55
+ }
56
+ return found
57
+ }
58
+
59
+ interface Item extends Target {
60
+ readonly real: boolean
61
+ }
62
+
63
+ /**
64
+ * The items of a message's `rich_text` blocks that a token in `text` can
65
+ * stand for, in order. A `user`, `usergroup`, `channel` or `broadcast`
66
+ * element is a real mention, unless it has code style or sits in a
67
+ * preformatted section. A token-shaped string in text elements (adjacent
68
+ * ones joined) is a literal, as is a code-styled element. `undefined` when
69
+ * the message has no `rich_text` block.
70
+ */
71
+ const richTextItems = (blocks: unknown): Array<Item> | undefined => {
72
+ if (!Array.isArray(blocks)) return undefined
73
+ const rich = blocks.filter((block) => isObject(block) && block.type === "rich_text")
74
+ if (rich.length === 0) return undefined
75
+ const items: Array<Item> = []
76
+ let pending = ""
77
+ const flushText = () => {
78
+ if (pending === "") return
79
+ for (const token of tokens(pending, false)) items.push({ kind: token.kind, id: token.id, real: false })
80
+ pending = ""
81
+ }
82
+ const walk = (element: unknown, inCode: boolean): void => {
83
+ if (!isObject(element)) return
84
+ const code = inCode || element.type === "rich_text_preformatted"
85
+ const style = element.style
86
+ const literal = code || (isObject(style) && style.code === true)
87
+ let target: Target | undefined
88
+ switch (element.type) {
89
+ case "text":
90
+ if (typeof element.text === "string") pending += element.text
91
+ return
92
+ case "user":
93
+ if (typeof element.user_id === "string") target = { kind: "user", id: element.user_id }
94
+ break
95
+ case "usergroup":
96
+ if (typeof element.usergroup_id === "string") target = { kind: "role", id: element.usergroup_id }
97
+ break
98
+ case "channel":
99
+ if (typeof element.channel_id === "string") target = { kind: "channel", id: element.channel_id }
100
+ break
101
+ case "broadcast":
102
+ if (typeof element.range === "string") target = { kind: "broadcast", id: element.range }
103
+ break
104
+ }
105
+ if (target !== undefined) {
106
+ flushText()
107
+ items.push({ ...target, real: !literal })
108
+ return
109
+ }
110
+ if (Array.isArray(element.elements)) {
111
+ flushText()
112
+ for (const child of element.elements) walk(child, code)
113
+ flushText()
114
+ }
115
+ }
116
+ for (const block of rich) walk(block, false)
117
+ flushText()
118
+ return items
119
+ }
120
+
121
+ const sameTarget = (a: Target, b: Target): boolean => a.kind === b.kind && a.id === b.id
122
+
123
+ /** Past this many item and token pairs, the alignment is skipped for the fallback. */
124
+ const maxAlignment = 1_000_000
125
+
126
+ /**
127
+ * Aligns the tokens in `text` with the block's items, in order. Every real
128
+ * item takes a token it equals, a literal item may take one or be passed
129
+ * over, and a token may stand for no item. Of the alignments, the one that
130
+ * pairs the most items wins, the earliest pairing first. Gives the token
131
+ * index of each real item, or `undefined` when no alignment pairs them all.
132
+ */
133
+ const align = (items: ReadonlyArray<Item>, found: ReadonlyArray<Token>): Array<number> | undefined => {
134
+ const n = items.length
135
+ const m = found.length
136
+ if ((n + 1) * (m + 1) > maxAlignment) return undefined
137
+ const impossible = -1
138
+ const width = m + 1
139
+ // best[i * width + j]: the most pairs for items i.. and tokens j.., or
140
+ // impossible when some real item among i.. can't be paired. Row n, no
141
+ // items left, is all zero.
142
+ const best = new Int32Array((n + 1) * width)
143
+ const pairs = (i: number, j: number): number => {
144
+ if (j === m || !sameTarget(items[i], found[j])) return impossible
145
+ const rest = best[(i + 1) * width + j + 1]
146
+ return rest === impossible ? impossible : rest + 1
147
+ }
148
+ for (let i = n - 1; i >= 0; i--) {
149
+ for (let j = m; j >= 0; j--) {
150
+ let score = pairs(i, j)
151
+ if (!items[i].real) score = Math.max(score, best[(i + 1) * width + j])
152
+ if (j < m) score = Math.max(score, best[i * width + j + 1])
153
+ best[i * width + j] = score
154
+ }
155
+ }
156
+ if (best[0] === impossible) return undefined
157
+ const out: Array<number> = []
158
+ let i = 0
159
+ let j = 0
160
+ // Every step moves i or j forward, so this ends after n + m steps.
161
+ while (i < n) {
162
+ const score = best[i * width + j]
163
+ if (pairs(i, j) === score) {
164
+ if (items[i].real) out.push(j)
165
+ i++
166
+ j++
167
+ } else if (!items[i].real && best[(i + 1) * width + j] === score) {
168
+ i++
169
+ } else if (j < m && best[i * width + j + 1] === score) {
170
+ j++
171
+ } else {
172
+ return undefined
173
+ }
174
+ }
175
+ return out
176
+ }
177
+
178
+ /**
179
+ * The mentions of a message with offsets into `text`.
180
+ *
181
+ * - With a `rich_text` block, the mentions are its real mention elements
182
+ * whose token is in `text`, since Slack decides a mention from `text`. A
183
+ * real element with no token there is not reported, however long the
184
+ * message. Offsets come from aligning the tokens in `text` with the
185
+ * block's items, in order. When no alignment places every real item,
186
+ * because `text` has fewer occurrences of a token than the block, each
187
+ * real item takes the next unused token it equals, and one with none left
188
+ * is not reported. `text` never adds a mention.
189
+ * - Without one, `text` is scanned, skipping backtick code spans and fences.
190
+ * That covers Block Kit posts, attachment-only posts and system messages.
191
+ *
192
+ * @internal
193
+ */
194
+ export const extract = (
195
+ text: string,
196
+ blocks: unknown,
197
+ botUserId: string
198
+ ): Array<Mention> => {
199
+ const toMention = (token: Token): Mention => ({
200
+ kind: token.kind,
201
+ id: token.id,
202
+ start: token.start,
203
+ end: token.end,
204
+ isSelf: token.kind === "user" && token.id === botUserId
205
+ })
206
+ const items = richTextItems(blocks)
207
+ if (items === undefined) return tokens(text, true).map(toMention)
208
+ const found = tokens(text, false)
209
+ const aligned = align(items, found)
210
+ if (aligned !== undefined) return aligned.map((index) => toMention(found[index]))
211
+ const used = new Set<number>()
212
+ const mentions: Array<Mention> = []
213
+ let from = 0
214
+ for (const item of items) {
215
+ if (!item.real) continue
216
+ let index = found.findIndex((token, k) => k >= from && !used.has(k) && sameTarget(item, token))
217
+ if (index < 0) index = found.findIndex((token, k) => !used.has(k) && sameTarget(item, token))
218
+ if (index < 0) continue
219
+ used.add(index)
220
+ from = index + 1
221
+ mentions.push(toMention(found[index]))
222
+ }
223
+ return mentions.sort((x, y) => x.start - y.start)
224
+ }