-
Notifications
You must be signed in to change notification settings - Fork 399
/
builtin.ts
371 lines (323 loc) · 10.7 KB
/
builtin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import type { ActionConstraints, OptionsConstraints, ShortcutConstraints, ViewConstraints } from '../App';
import { ContextMissingPropertyError } from '../errors';
import type {
AnyMiddlewareArgs,
BlockElementAction,
BlockSuggestion,
DialogSubmitAction,
DialogSuggestion,
EventTypePattern,
GlobalShortcut,
InteractiveMessage,
InteractiveMessageSuggestion,
MessageShortcut,
Middleware,
SlackActionMiddlewareArgs,
SlackCommandMiddlewareArgs,
SlackEventMiddlewareArgs,
SlackOptionsMiddlewareArgs,
SlackShortcutMiddlewareArgs,
SlackViewAction,
SlackViewMiddlewareArgs,
} from '../types';
/** Type predicate that can narrow payloads block action or suggestion payloads */
function isBlockPayload(
payload:
| SlackActionMiddlewareArgs['payload']
| SlackOptionsMiddlewareArgs['payload']
| SlackViewMiddlewareArgs['payload'],
): payload is BlockElementAction | BlockSuggestion {
return 'action_id' in payload && payload.action_id !== undefined;
}
type CallbackIdentifiedBody =
| InteractiveMessage
| DialogSubmitAction
| MessageShortcut
| GlobalShortcut
| InteractiveMessageSuggestion
| DialogSuggestion;
// TODO: consider exporting these type guards for use elsewhere within bolt
// TODO: is there overlap with `function_executed` event here?
function isCallbackIdentifiedBody(
body: SlackActionMiddlewareArgs['body'] | SlackOptionsMiddlewareArgs['body'] | SlackShortcutMiddlewareArgs['body'],
): body is CallbackIdentifiedBody {
return 'callback_id' in body && body.callback_id !== undefined;
}
// TODO: clarify terminology used internally: event vs. body vs. payload
/** Type predicate that can narrow event bodies to ones containing Views */
function isViewBody(
body: SlackActionMiddlewareArgs['body'] | SlackOptionsMiddlewareArgs['body'] | SlackViewMiddlewareArgs['body'],
): body is SlackViewAction {
return 'view' in body && body.view !== undefined;
}
function isEventArgs(args: AnyMiddlewareArgs): args is SlackEventMiddlewareArgs {
return 'event' in args && args.event !== undefined;
}
function isMessageEventArgs(args: AnyMiddlewareArgs): args is SlackEventMiddlewareArgs<'message'> {
return isEventArgs(args) && 'message' in args;
}
/**
* Middleware that filters out any event that isn't an action
*/
export const onlyActions: Middleware<AnyMiddlewareArgs> = async (args) => {
if ('action' in args && args.action) {
await args.next();
}
};
/**
* Middleware that filters out any event that isn't a shortcut
*/
export const onlyShortcuts: Middleware<AnyMiddlewareArgs> = async (args) => {
if ('shortcut' in args && args.shortcut) {
await args.next();
}
};
/**
* Middleware that filters out any event that isn't a command
*/
export const onlyCommands: Middleware<AnyMiddlewareArgs> = async (args) => {
if ('command' in args && args.command) {
await args.next();
}
};
/**
* Middleware that filters out any event that isn't an options
*/
export const onlyOptions: Middleware<AnyMiddlewareArgs> = async (args) => {
if ('options' in args && args.options) {
await args.next();
}
};
// TODO: event terminology here "event that isn't an event" wat
/**
* Middleware that filters out any event that isn't an event
*/
export const onlyEvents: Middleware<AnyMiddlewareArgs> = async (args) => {
if (isEventArgs(args)) {
await args.next();
}
};
// TODO: event terminology "ViewAction" is confusing since "Action" we use for block actions
/**
* Middleware that filters out any event that isn't a view_submission or view_closed event
*/
export const onlyViewActions: Middleware<AnyMiddlewareArgs> = async (args) => {
if ('view' in args) {
await args.next();
}
};
/**
* Middleware that checks for matches given constraints
*/
export function matchConstraints(
constraints: ActionConstraints | ViewConstraints | ShortcutConstraints | OptionsConstraints,
): Middleware<SlackActionMiddlewareArgs | SlackOptionsMiddlewareArgs | SlackViewMiddlewareArgs> {
return async ({ payload, body, next, context }) => {
// TODO: is putting matches in an array actually helpful? there's no way to know which of the regexps contributed
// which matches (and in which order)
let tempMatches: RegExpMatchArray | null;
// Narrow type for ActionConstraints
if ('block_id' in constraints || 'action_id' in constraints) {
if (!isBlockPayload(payload)) {
return;
}
// Check block_id
if (constraints.block_id !== undefined) {
if (typeof constraints.block_id === 'string') {
if (payload.block_id !== constraints.block_id) {
return;
}
} else {
tempMatches = payload.block_id.match(constraints.block_id);
if (tempMatches !== null) {
context.blockIdMatches = tempMatches;
} else {
return;
}
}
}
// Check action_id
if (constraints.action_id !== undefined) {
if (typeof constraints.action_id === 'string') {
if (payload.action_id !== constraints.action_id) {
return;
}
} else {
tempMatches = payload.action_id.match(constraints.action_id);
if (tempMatches !== null) {
context.actionIdMatches = tempMatches;
} else {
return;
}
}
}
}
// Check callback_id
if ('callback_id' in constraints && constraints.callback_id !== undefined) {
let callbackId = '';
if (isViewBody(body)) {
callbackId = body.view.callback_id;
} else if (isCallbackIdentifiedBody(body)) {
callbackId = body.callback_id;
} else {
return;
}
if (typeof constraints.callback_id === 'string') {
if (callbackId !== constraints.callback_id) {
return;
}
} else {
tempMatches = callbackId.match(constraints.callback_id);
if (tempMatches !== null) {
context.callbackIdMatches = tempMatches;
} else {
return;
}
}
}
// Check type
if ('type' in constraints) {
if (body.type !== constraints.type) return;
}
await next();
};
}
/*
* Middleware that filters out messages that don't match pattern
*/
export function matchMessage(
pattern: string | RegExp,
): Middleware<SlackEventMiddlewareArgs<'message' | 'app_mention'>> {
return async ({ event, context, next }) => {
let tempMatches: RegExpMatchArray | null;
if (!('text' in event) || event.text === undefined) {
return;
}
// Filter out messages or app mentions that don't contain the pattern
if (typeof pattern === 'string') {
if (!event.text.includes(pattern)) {
return;
}
} else {
tempMatches = event.text.match(pattern);
if (tempMatches !== null) {
context.matches = tempMatches;
} else {
return;
}
}
await next();
};
}
/**
* Middleware that filters out any command that doesn't match the pattern
*/
export function matchCommandName(pattern: string | RegExp): Middleware<SlackCommandMiddlewareArgs> {
return async ({ command, next }) => {
// Filter out any commands that do not match the correct command name or pattern
if (!matchesPattern(pattern, command.command)) {
return;
}
await next();
};
}
function matchesPattern(pattern: string | RegExp, candidate: string): boolean {
if (typeof pattern === 'string') {
return pattern === candidate;
}
return pattern.test(candidate);
}
/*
* Middleware that filters out events that don't match pattern
*/
export function matchEventType(pattern: EventTypePattern): Middleware<SlackEventMiddlewareArgs> {
return async ({ event, context, next }) => {
let tempMatches: RegExpMatchArray | null;
if (!('type' in event) || event.type === undefined) {
return;
}
// Filter out events that don't contain the pattern
if (typeof pattern === 'string') {
if (event.type !== pattern) {
return;
}
} else {
tempMatches = event.type.match(pattern);
if (tempMatches !== null) {
context.matches = tempMatches;
} else {
return;
}
}
await next();
};
}
/**
* Filters out any event originating from the handling app.
*/
export const ignoreSelf: Middleware<AnyMiddlewareArgs> = async (args) => {
const { botId, botUserId } = args.context;
if (isEventArgs(args)) {
if (isMessageEventArgs(args)) {
const { message } = args;
// Look for an event that is identified as a bot message from the same bot ID as this app, and return to skip
if (message.subtype === 'bot_message' && message.bot_id === botId) {
return;
}
}
// It's an Events API event that isn't of type message, but the user ID might match our own app. Filter these out.
// However, some events still must be fired, because they can make sense.
const eventsWhichShouldBeKept = ['member_joined_channel', 'member_left_channel'];
if (
botUserId !== undefined &&
'user' in args.event &&
args.event.user === botUserId &&
!eventsWhichShouldBeKept.includes(args.event.type)
) {
return;
}
}
// If all the previous checks didn't skip this message, then its okay to resume to next
await args.next();
};
// TODO: breaking change: constrain the subtype argument to be a valid message subtype
/**
* Filters out any message events whose subtype does not match the provided subtype.
*/
export function subtype(subtype1: string): Middleware<SlackEventMiddlewareArgs<'message'>> {
return async ({ message, next }) => {
if (message && message.subtype === subtype1) {
await next();
}
};
}
const slackLink = /<(?<type>[@#!])?(?<link>[^>|]+)(?:\|(?<label>[^>]+))?>/;
/**
* Filters out any message event whose text does not start with an @-mention of the handling app.
*/
export const directMention: Middleware<SlackEventMiddlewareArgs<'message'>> = async ({ message, context, next }) => {
// When context does not have a botUserId in it, then this middleware cannot perform its job. Bail immediately.
if (context.botUserId === undefined) {
throw new ContextMissingPropertyError(
'botUserId',
'Cannot match direct mentions of the app without a bot user ID. Ensure authorize callback returns a botUserId.',
);
}
if (!message || !('text' in message) || message.text === undefined) {
return;
}
// Match the message text with a user mention format
const text = message.text.trim();
const matches = slackLink.exec(text);
if (
matches === null || // stop when no matches are found
matches.index !== 0 || // stop if match isn't at the beginning
// stop if match isn't a user mention with the right user ID
matches.groups === undefined ||
matches.groups.type !== '@' ||
matches.groups.link !== context.botUserId
) {
return;
}
await next();
};