-
Notifications
You must be signed in to change notification settings - Fork 402
/
Copy pathApp.ts
1303 lines (1177 loc) · 49.7 KB
/
App.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Agent } from 'http';
import { SecureContextOptions } from 'tls';
import util from 'util';
import { WebClient, ChatPostMessageArguments, addAppMetadata, WebClientOptions } from '@slack/web-api';
import { Logger, LogLevel, ConsoleLogger } from '@slack/logger';
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import SocketModeReceiver from './receivers/SocketModeReceiver';
import HTTPReceiver, { HTTPReceiverOptions } from './receivers/HTTPReceiver';
import {
ignoreSelf as ignoreSelfMiddleware,
onlyActions,
matchConstraints,
onlyCommands,
matchCommandName,
onlyOptions,
onlyShortcuts,
onlyEvents,
matchEventType,
matchMessage,
onlyViewActions,
} from './middleware/builtin';
import processMiddleware from './middleware/process';
import { ConversationStore, conversationContext, MemoryStore } from './conversation-store';
import { WorkflowStep } from './WorkflowStep';
import {
Middleware,
AnyMiddlewareArgs,
SlackActionMiddlewareArgs,
SlackCommandMiddlewareArgs,
SlackEventMiddlewareArgs,
SlackOptionsMiddlewareArgs,
SlackShortcutMiddlewareArgs,
SlackViewMiddlewareArgs,
SlackAction,
EventTypePattern,
SlackShortcut,
Context,
SayFn,
AckFn,
RespondFn,
OptionsSource,
BlockAction,
InteractiveMessage,
SlackViewAction,
Receiver,
ReceiverEvent,
RespondArguments,
DialogSubmitAction,
BlockElementAction,
InteractiveAction,
ViewOutput,
KnownOptionsPayloadFromType,
KnownEventFromType,
SlashCommand,
WorkflowStepEdit,
} from './types';
import { IncomingEventType, getTypeAndConversation, assertNever } from './helpers';
import { CodedError, asCodedError, AppInitializationError, MultipleListenerError, ErrorCode, InvalidCustomPropertyError } from './errors';
import { AllMiddlewareArgs, contextBuiltinKeys } from './types/middleware';
import { StringIndexed } from './types/helpers';
// eslint-disable-next-line import/order
import allSettled = require('promise.allsettled'); // eslint-disable-line @typescript-eslint/no-require-imports
// eslint-disable-next-line @typescript-eslint/no-require-imports, import/no-commonjs
const packageJson = require('../package.json'); // eslint-disable-line @typescript-eslint/no-var-requires
// ----------------------------
// For listener registration methods
const validViewTypes = ['view_closed', 'view_submission'];
// ----------------------------
// For the constructor
const tokenUsage = 'Apps used in one workspace should be initialized with a token. Apps used in many workspaces ' +
'should be initialized with oauth installer or authorize.';
/** App initialization options */
export interface AppOptions {
signingSecret?: HTTPReceiverOptions['signingSecret'];
endpoints?: HTTPReceiverOptions['endpoints'];
port?: HTTPReceiverOptions['port'];
customRoutes?: HTTPReceiverOptions['customRoutes'];
processBeforeResponse?: HTTPReceiverOptions['processBeforeResponse'];
signatureVerification?: HTTPReceiverOptions['signatureVerification'];
clientId?: HTTPReceiverOptions['clientId'];
clientSecret?: HTTPReceiverOptions['clientSecret'];
stateSecret?: HTTPReceiverOptions['stateSecret']; // required when using default stateStore
redirectUri?: HTTPReceiverOptions['redirectUri']
installationStore?: HTTPReceiverOptions['installationStore']; // default MemoryInstallationStore
scopes?: HTTPReceiverOptions['scopes'];
installerOptions?: HTTPReceiverOptions['installerOptions'];
agent?: Agent;
clientTls?: Pick<SecureContextOptions, 'pfx' | 'key' | 'passphrase' | 'cert' | 'ca'>;
convoStore?: ConversationStore | false;
token?: AuthorizeResult['botToken']; // either token or authorize
appToken?: string; // TODO should this be included in AuthorizeResult
botId?: AuthorizeResult['botId']; // only used when authorize is not defined, shortcut for fetching
botUserId?: AuthorizeResult['botUserId']; // only used when authorize is not defined, shortcut for fetching
authorize?: Authorize<boolean>; // either token or authorize
receiver?: Receiver;
logger?: Logger;
logLevel?: LogLevel;
ignoreSelf?: boolean;
clientOptions?: Pick<WebClientOptions, 'slackApiUrl'>;
socketMode?: boolean;
developerMode?: boolean;
tokenVerificationEnabled?: boolean;
extendedErrorHandler?: boolean;
}
export { LogLevel, Logger } from '@slack/logger';
/** Authorization function - seeds the middleware processing and listeners with an authorization context */
export interface Authorize<IsEnterpriseInstall extends boolean = false> {
(source: AuthorizeSourceData<IsEnterpriseInstall>, body?: AnyMiddlewareArgs['body']): Promise<AuthorizeResult>;
}
/** Authorization function inputs - authenticated data about an event for the authorization function */
export interface AuthorizeSourceData<IsEnterpriseInstall extends boolean = false> {
teamId: IsEnterpriseInstall extends true ? string | undefined : string;
enterpriseId: IsEnterpriseInstall extends true ? string : string | undefined;
userId?: string;
conversationId?: string;
isEnterpriseInstall: IsEnterpriseInstall;
}
/** Authorization function outputs - data that will be available as part of event processing */
export interface AuthorizeResult {
// one of either botToken or userToken are required
botToken?: string; // used by `say` (preferred over userToken)
userToken?: string; // used by `say` (overridden by botToken)
botId?: string; // required for `ignoreSelf` global middleware
botUserId?: string; // optional but allows `ignoreSelf` global middleware be more filter more than just message events
teamId?: string;
enterpriseId?: string;
// TODO: for better type safety, we may want to reivit this
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}
export interface ActionConstraints<A extends SlackAction = SlackAction> {
type?: A['type'];
block_id?: A extends BlockAction ? string | RegExp : never;
action_id?: A extends BlockAction ? string | RegExp : never;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback_id?: Extract<A, { callback_id?: string }> extends any ? string | RegExp : never;
}
export interface ShortcutConstraints<S extends SlackShortcut = SlackShortcut> {
type?: S['type'];
callback_id?: string | RegExp;
}
export interface ViewConstraints {
callback_id?: string | RegExp;
type?: 'view_closed' | 'view_submission';
}
// Passed internally to the handleError method
interface AllErrorHandlerArgs {
error: Error; // Error is not necessarily a CodedError
logger: Logger;
body: AnyMiddlewareArgs['body'];
context: Context;
}
// Passed into the error handler when extendedErrorHandler is true
export interface ExtendedErrorHandlerArgs extends AllErrorHandlerArgs {
error: CodedError; // asCodedError has been called
}
export interface ErrorHandler {
(error: CodedError): Promise<void>;
}
export interface ExtendedErrorHandler {
(args: ExtendedErrorHandlerArgs): Promise<void>;
}
export interface AnyErrorHandler extends ErrorHandler, ExtendedErrorHandler {
}
// Used only in this file
type MessageEventMiddleware = Middleware<SlackEventMiddlewareArgs<'message'>>;
class WebClientPool {
private pool: { [token: string]: WebClient } = {};
public getOrCreate(token: string, clientOptions: WebClientOptions): WebClient {
const cachedClient = this.pool[token];
if (typeof cachedClient !== 'undefined') {
return cachedClient;
}
const client = new WebClient(token, clientOptions);
this.pool[token] = client;
return client;
}
}
/**
* A Slack App
*/
export default class App {
/** Slack Web API client */
public client: WebClient;
private clientOptions: WebClientOptions;
// Some payloads don't have teamId anymore. So we use EnterpriseId in those scenarios
private clients: { [teamOrEnterpriseId: string]: WebClientPool } = {};
/** Receiver - ingests events from the Slack platform */
private receiver: Receiver;
/** Logger */
private logger: Logger;
/** Log Level */
private logLevel: LogLevel;
/** Authorize */
private authorize!: Authorize<boolean>;
/** Global middleware chain */
private middleware: Middleware<AnyMiddlewareArgs>[];
/** Listener middleware chains */
private listeners: Middleware<AnyMiddlewareArgs>[][];
private errorHandler: AnyErrorHandler;
private axios: AxiosInstance;
private installerOptions: HTTPReceiverOptions['installerOptions'];
private socketMode: boolean;
private developerMode: boolean;
private extendedErrorHandler: boolean;
private hasCustomErrorHandler: boolean;
public constructor({
signingSecret = undefined,
endpoints = undefined,
port = undefined,
customRoutes = undefined,
agent = undefined,
clientTls = undefined,
receiver = undefined,
convoStore = undefined,
token = undefined,
appToken = undefined,
botId = undefined,
botUserId = undefined,
authorize = undefined,
logger = undefined,
logLevel = undefined,
ignoreSelf = true,
clientOptions = undefined,
processBeforeResponse = false,
signatureVerification = true,
clientId = undefined,
clientSecret = undefined,
stateSecret = undefined,
redirectUri = undefined,
installationStore = undefined,
scopes = undefined,
installerOptions = undefined,
socketMode = undefined,
developerMode = false,
tokenVerificationEnabled = true,
extendedErrorHandler = false,
}: AppOptions = {}) {
// this.logLevel = logLevel;
this.developerMode = developerMode;
if (developerMode) {
// Set logLevel to Debug in Developer Mode if one wasn't passed in
this.logLevel = logLevel ?? LogLevel.DEBUG;
// Set SocketMode to true if one wasn't passed in
this.socketMode = socketMode ?? true;
} else {
// If devs aren't using Developer Mode or Socket Mode, set it to false
this.socketMode = socketMode ?? false;
// Set logLevel to Info if one wasn't passed in
this.logLevel = logLevel ?? LogLevel.INFO;
}
// Set up logger
if (typeof logger === 'undefined') {
// Initialize with the default logger
const consoleLogger = new ConsoleLogger();
consoleLogger.setName('bolt-app');
this.logger = consoleLogger;
} else {
this.logger = logger;
}
if (typeof this.logLevel !== 'undefined' && this.logger.getLevel() !== this.logLevel) {
this.logger.setLevel(this.logLevel);
}
// Error-related properties used to later determine args passed into the error handler
this.hasCustomErrorHandler = false;
this.errorHandler = defaultErrorHandler(this.logger) as AnyErrorHandler;
this.extendedErrorHandler = extendedErrorHandler;
// Set up client options
this.clientOptions = clientOptions !== undefined ? clientOptions : {};
if (agent !== undefined && this.clientOptions.agent === undefined) {
this.clientOptions.agent = agent;
}
if (clientTls !== undefined && this.clientOptions.tls === undefined) {
this.clientOptions.tls = clientTls;
}
if (logLevel !== undefined && logger === undefined) {
// only logLevel is passed
this.clientOptions.logLevel = logLevel;
} else {
// Since v3.4, WebClient starts sharing logger with App
this.clientOptions.logger = this.logger;
}
// The public WebClient instance (app.client)
// Since v3.4, it can have the passed token in the case of single workspace installation.
this.client = new WebClient(token, this.clientOptions);
this.axios = axios.create({
httpAgent: agent,
httpsAgent: agent,
// disabling axios' automatic proxy support:
// axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations.
// for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other
// protocols), users of this package should use the `agent` option to configure a proxy.
proxy: false,
...clientTls,
});
this.middleware = [];
this.listeners = [];
// Add clientOptions to InstallerOptions to pass them to @slack/oauth
this.installerOptions = {
clientOptions: this.clientOptions,
...installerOptions,
};
if (socketMode && port !== undefined && this.installerOptions.port === undefined) {
// As SocketModeReceiver uses a custom port number to listen on only for the OAuth flow,
// only installerOptions.port is available in the constructor arguments.
this.installerOptions.port = port;
}
if (
this.developerMode &&
this.installerOptions &&
(typeof this.installerOptions.callbackOptions === 'undefined' ||
(typeof this.installerOptions.callbackOptions !== 'undefined' &&
typeof this.installerOptions.callbackOptions.failure === 'undefined'))
) {
// add a custom failure callback for Developer Mode in case they are using OAuth
this.logger.debug('adding Developer Mode custom OAuth failure handler');
this.installerOptions.callbackOptions = {
failure: (error, _installOptions, _req, res) => {
this.logger.debug(error);
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end(`<html><body><h1>OAuth failed!</h1><div>${error}</div></body></html>`);
},
};
}
// Initialize receiver
if (receiver !== undefined) {
// Custom receiver
if (this.socketMode) {
throw new AppInitializationError('receiver cannot be passed when socketMode is set to true');
}
this.receiver = receiver;
} else if (this.socketMode) {
if (appToken === undefined) {
throw new AppInitializationError('You must provide an appToken when using Socket Mode');
}
this.logger.debug('Initializing SocketModeReceiver');
// Create default SocketModeReceiver
this.receiver = new SocketModeReceiver({
appToken,
clientId,
clientSecret,
stateSecret,
redirectUri,
installationStore,
scopes,
logger,
logLevel: this.logLevel,
installerOptions: this.installerOptions,
customRoutes,
});
} else if (signatureVerification && signingSecret === undefined) {
// No custom receiver
throw new AppInitializationError(
'Signing secret not found, so could not initialize the default receiver. Set a signing secret or use a ' +
'custom receiver.',
);
} else {
this.logger.debug('Initializing HTTPReceiver');
// Create default HTTPReceiver
this.receiver = new HTTPReceiver({
signingSecret: signingSecret || '',
endpoints,
port,
customRoutes,
processBeforeResponse,
signatureVerification,
clientId,
clientSecret,
stateSecret,
redirectUri,
installationStore,
scopes,
logger,
logLevel: this.logLevel,
installerOptions: this.installerOptions,
});
}
let usingOauth = false;
const httpReceiver = (this.receiver as HTTPReceiver);
if (
httpReceiver.installer !== undefined &&
httpReceiver.installer.authorize !== undefined
) {
// This supports using the built in HTTPReceiver, declaring your own HTTPReceiver
// and theoretically, doing a fully custom (non express) receiver that implements OAuth
usingOauth = true;
}
if (token !== undefined) {
if (authorize !== undefined || usingOauth) {
throw new AppInitializationError(
`token as well as authorize or oauth installer options were provided. ${tokenUsage}`,
);
}
this.authorize = singleAuthorization(
this.client,
{
botId,
botUserId,
botToken: token,
},
tokenVerificationEnabled,
);
} else if (authorize === undefined && !usingOauth) {
throw new AppInitializationError(
`No token, no authorize, and no oauth installer options provided. ${tokenUsage}`,
);
} else if (authorize !== undefined && usingOauth) {
throw new AppInitializationError(`Both authorize options and oauth installer options provided. ${tokenUsage}`);
} else if (authorize === undefined && usingOauth) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.authorize = httpReceiver.installer!.authorize;
} else if (authorize !== undefined && !usingOauth) {
this.authorize = authorize;
} else {
this.logger.error('Never should have reached this point, please report to the team');
assertNever();
}
// Conditionally use a global middleware that ignores events (including messages) that are sent from this app
if (ignoreSelf) {
this.use(ignoreSelfMiddleware());
}
// Use conversation state global middleware
if (convoStore !== false) {
// Use the memory store by default, or another store if provided
const store: ConversationStore = convoStore === undefined ? new MemoryStore() : convoStore;
this.use(conversationContext(store));
}
// Should be last to avoid exposing partially initialized app
this.receiver.init(this);
}
/**
* Register a new middleware, processed in the order registered.
*
* @param m global middleware function
*/
public use(m: Middleware<AnyMiddlewareArgs>): this {
this.middleware.push(m);
return this;
}
/**
* Register WorkflowStep middleware
*
* @param workflowStep global workflow step middleware function
*/
public step(workflowStep: WorkflowStep): this {
const m = workflowStep.getMiddleware();
this.middleware.push(m);
return this;
}
/**
* Convenience method to call start on the receiver
*
* TODO: should replace HTTPReceiver in type definition with a generic that is constrained to Receiver
*
* @param args receiver-specific start arguments
*/
public start(
...args: Parameters<HTTPReceiver['start'] | SocketModeReceiver['start']>
): ReturnType<HTTPReceiver['start']> {
// TODO: HTTPReceiver['start'] should be the actual receiver's return type
return this.receiver.start(...args) as ReturnType<HTTPReceiver['start']>;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public stop(...args: any[]): Promise<unknown> {
return this.receiver.stop(...args);
}
public event<EventType extends string = string>(
eventName: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<EventType>>[]
): void;
public event<EventType extends RegExp = RegExp>(
eventName: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<string>>[]
): void;
public event<EventType extends EventTypePattern = EventTypePattern>(
eventNameOrPattern: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<string>>[]
): void {
let invalidEventName = false;
if (typeof eventNameOrPattern === 'string') {
const name = eventNameOrPattern as string;
invalidEventName = name.startsWith('message.');
} else if (eventNameOrPattern instanceof RegExp) {
const name = (eventNameOrPattern as RegExp).source;
invalidEventName = name.startsWith('message\\.');
}
if (invalidEventName) {
throw new AppInitializationError(
`Although the document mentions "${eventNameOrPattern}",` +
'it is not a valid event type. Use "message" instead. ' +
'If you want to filter message events, you can use event.channel_type for it.',
);
}
this.listeners.push([
onlyEvents,
matchEventType(eventNameOrPattern),
...listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
/**
*
* @param listeners Middlewares that process and react to a message event
*/
public message(...listeners: MessageEventMiddleware[]): void;
/**
*
* @param pattern Used for filtering out messages that don't match.
* Strings match via {@link String.prototype.includes}.
* @param listeners Middlewares that process and react to the message events that matched the provided patterns.
*/
public message(pattern: string | RegExp, ...listeners: MessageEventMiddleware[]): void;
/**
*
* @param filter Middleware that can filter out messages. Generally this is done by returning before
* calling {@link AllMiddlewareArgs.next} if there is no match. See {@link directMention} for an example.
* @param pattern Used for filtering out messages that don't match the pattern. Strings match
* via {@link String.prototype.includes}.
* @param listeners Middlewares that process and react to the message events that matched the provided pattern.
*/
public message(
filter: MessageEventMiddleware, pattern: string | RegExp, ...listeners: MessageEventMiddleware[]
): void;
/**
*
* @param filter Middleware that can filter out messages. Generally this is done by returning before calling
* {@link AllMiddlewareArgs.next} if there is no match. See {@link directMention} for an example.
* @param listeners Middlewares that process and react to the message events that matched the provided patterns.
*/
public message(filter: MessageEventMiddleware, ...listeners: MessageEventMiddleware[]): void;
/**
* This allows for further control of the filtering and response logic. Patterns and middlewares are processed in
* the order provided. If any patterns do not match, or a middleware does not call {@link AllMiddlewareArgs.next},
* all remaining patterns and middlewares will be skipped.
* @param patternsOrMiddleware A mix of patterns and/or middlewares.
*/
public message(...patternsOrMiddleware: (string | RegExp | MessageEventMiddleware)[]): void;
public message(...patternsOrMiddleware: (string | RegExp | MessageEventMiddleware)[]): void {
const messageMiddleware = patternsOrMiddleware.map((patternOrMiddleware) => {
if (typeof patternOrMiddleware === 'string' || util.types.isRegExp(patternOrMiddleware)) {
return matchMessage(patternOrMiddleware);
}
return patternOrMiddleware;
});
this.listeners.push([
onlyEvents,
matchEventType('message'),
...messageMiddleware,
] as Middleware<AnyMiddlewareArgs>[]);
}
public shortcut<Shortcut extends SlackShortcut = SlackShortcut>(
callbackId: string | RegExp,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Shortcut>>[]
): void;
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
Constraints extends ShortcutConstraints<Shortcut> = ShortcutConstraints<Shortcut>,
>(
constraints: Constraints,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Extract<Shortcut, { type: Constraints['type'] }>>>[]
): void;
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
Constraints extends ShortcutConstraints<Shortcut> = ShortcutConstraints<Shortcut>,
>(
callbackIdOrConstraints: string | RegExp | Constraints,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Extract<Shortcut, { type: Constraints['type'] }>>>[]
): void {
const constraints: ShortcutConstraints = typeof callbackIdOrConstraints === 'string' || util.types.isRegExp(callbackIdOrConstraints) ?
{ callback_id: callbackIdOrConstraints } :
callbackIdOrConstraints;
// Fail early if the constraints contain invalid keys
const unknownConstraintKeys = Object.keys(constraints).filter((k) => k !== 'callback_id' && k !== 'type');
if (unknownConstraintKeys.length > 0) {
this.logger.error(
`Slack listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
this.listeners.push([
onlyShortcuts,
matchConstraints(constraints),
...listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
// NOTE: this is what's called a convenience generic, so that types flow more easily without casting.
// https://basarat.gitbooks.io/typescript/docs/types/generics.html#design-pattern-convenience-generic
public action<Action extends SlackAction = SlackAction>(
actionId: string | RegExp,
...listeners: Middleware<SlackActionMiddlewareArgs<Action>>[]
): void;
public action<
Action extends SlackAction = SlackAction,
Constraints extends ActionConstraints<Action> = ActionConstraints<Action>,
>(
constraints: Constraints,
// NOTE: Extract<> is able to return the whole union when type: undefined. Why?
...listeners: Middleware<SlackActionMiddlewareArgs<Extract<Action, { type: Constraints['type'] }>>>[]
): void;
public action<
Action extends SlackAction = SlackAction,
Constraints extends ActionConstraints<Action> = ActionConstraints<Action>,
>(
actionIdOrConstraints: string | RegExp | Constraints,
...listeners: Middleware<SlackActionMiddlewareArgs<Extract<Action, { type: Constraints['type'] }>>>[]
): void {
// Normalize Constraints
const constraints: ActionConstraints = typeof actionIdOrConstraints === 'string' || util.types.isRegExp(actionIdOrConstraints) ?
{ action_id: actionIdOrConstraints } :
actionIdOrConstraints;
// Fail early if the constraints contain invalid keys
const unknownConstraintKeys = Object.keys(constraints).filter(
(k) => k !== 'action_id' && k !== 'block_id' && k !== 'callback_id' && k !== 'type',
);
if (unknownConstraintKeys.length > 0) {
this.logger.error(
`Action listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
this.listeners.push([onlyActions, matchConstraints(constraints), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public command(commandName: string | RegExp, ...listeners: Middleware<SlackCommandMiddlewareArgs>[]): void {
this.listeners.push([onlyCommands, matchCommandName(commandName), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public options<Source extends OptionsSource = 'block_suggestion'>(
actionId: string | RegExp,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
): void;
// TODO: reflect the type in constraits to Source
public options<Source extends OptionsSource = OptionsSource>(
constraints: ActionConstraints,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
): void;
// TODO: reflect the type in constraits to Source
public options<Source extends OptionsSource = OptionsSource>(
actionIdOrConstraints: string | RegExp | ActionConstraints,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>>[]
): void {
const constraints: ActionConstraints = typeof actionIdOrConstraints === 'string' || util.types.isRegExp(actionIdOrConstraints) ?
{ action_id: actionIdOrConstraints } :
actionIdOrConstraints;
this.listeners.push([onlyOptions, matchConstraints(constraints), ...listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public view<ViewActionType extends SlackViewAction = SlackViewAction>(
callbackId: string | RegExp,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>>[]
): void;
public view<ViewActionType extends SlackViewAction = SlackViewAction>(
constraints: ViewConstraints,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>>[]
): void;
public view<ViewActionType extends SlackViewAction = SlackViewAction>(
callbackIdOrConstraints: string | RegExp | ViewConstraints,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>>[]
): void {
const constraints: ViewConstraints = typeof callbackIdOrConstraints === 'string' || util.types.isRegExp(callbackIdOrConstraints) ?
{ callback_id: callbackIdOrConstraints, type: 'view_submission' } :
callbackIdOrConstraints;
// Fail early if the constraints contain invalid keys
const unknownConstraintKeys = Object.keys(constraints).filter((k) => k !== 'callback_id' && k !== 'type');
if (unknownConstraintKeys.length > 0) {
this.logger.error(
`View listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
if (constraints.type !== undefined && !validViewTypes.includes(constraints.type)) {
this.logger.error(`View listener cannot be attached using unknown view event type: ${constraints.type}`);
return;
}
this.listeners.push([
onlyViewActions,
matchConstraints(constraints),
...listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
// Error handler args dependent on extendedErrorHandler property
public error(errorHandler: ErrorHandler): void;
public error(errorHandler: ExtendedErrorHandler): void;
public error(errorHandler: AnyErrorHandler): void {
this.errorHandler = errorHandler;
this.hasCustomErrorHandler = true;
}
/**
* Handles events from the receiver
*/
public async processEvent(event: ReceiverEvent): Promise<void> {
const { body, ack } = event;
if (this.developerMode) {
// log the body of the event
// this may contain sensitive info like tokens
this.logger.debug(JSON.stringify(body));
}
// TODO: when generating errors (such as in the say utility) it may become useful to capture the current context,
// or even all of the args, as properties of the error. This would give error handling code some ability to deal
// with "finally" type error situations.
// Introspect the body to determine what type of incoming event is being handled, and any channel context
const { type, conversationId } = getTypeAndConversation(body);
// If the type could not be determined, warn and exit
if (type === undefined) {
this.logger.warn('Could not determine the type of an incoming event. No listeners will be called.');
return;
}
// From this point on, we assume that body is not just a key-value map, but one of the types of bodies we expect
const bodyArg = body as AnyMiddlewareArgs['body'];
// Check if type event with the authorizations object or if it has a top level is_enterprise_install property
const isEnterpriseInstall = isBodyWithTypeEnterpriseInstall(bodyArg, type);
const source = buildSource(type, conversationId, bodyArg, isEnterpriseInstall);
let authorizeResult: AuthorizeResult;
try {
if (source.isEnterpriseInstall) {
authorizeResult = await this.authorize(source as AuthorizeSourceData<true>, bodyArg);
} else {
authorizeResult = await this.authorize(source as AuthorizeSourceData<false>, bodyArg);
}
} catch (error) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const e = error as any;
this.logger.warn('Authorization of incoming event did not succeed. No listeners will be called.');
e.code = ErrorCode.AuthorizationError;
// disabling due to https://github.com/typescript-eslint/typescript-eslint/issues/1277
// eslint-disable-next-line consistent-return
return this.handleError({
error: e,
logger: this.logger,
body: bodyArg,
context: {},
});
}
// Try to set teamId from AuthorizeResult before using one from source
if (authorizeResult.teamId === undefined && source.teamId !== undefined) {
authorizeResult.teamId = source.teamId;
}
// Try to set enterpriseId from AuthorizeResult before using one from source
if (authorizeResult.enterpriseId === undefined && source.enterpriseId !== undefined) {
authorizeResult.enterpriseId = source.enterpriseId;
}
if (typeof event.customProperties !== 'undefined') {
const customProps: StringIndexed = event.customProperties;
const builtinKeyDetected = contextBuiltinKeys.find((key) => key in customProps);
if (typeof builtinKeyDetected !== 'undefined') {
throw new InvalidCustomPropertyError('customProperties cannot have the same names with the built-in ones');
}
}
const context: Context = {
...authorizeResult,
...event.customProperties,
retryNum: event.retryNum,
retryReason: event.retryReason,
};
// Factory for say() utility
const createSay = (channelId: string): SayFn => {
const token = selectToken(context);
return (message: Parameters<SayFn>[0]) => {
const postMessageArguments: ChatPostMessageArguments = typeof message === 'string' ?
{ token, text: message, channel: channelId } :
{ ...message, token, channel: channelId };
return this.client.chat.postMessage(postMessageArguments);
};
};
// Set body and payload
// TODO: this value should eventually conform to AnyMiddlewareArgs
let payload: DialogSubmitAction | WorkflowStepEdit | SlackShortcut | KnownEventFromType<string> | SlashCommand
| KnownOptionsPayloadFromType<string> | BlockElementAction | ViewOutput | InteractiveAction;
switch (type) {
case IncomingEventType.Event:
payload = (bodyArg as SlackEventMiddlewareArgs['body']).event;
break;
case IncomingEventType.ViewAction:
payload = (bodyArg as SlackViewMiddlewareArgs['body']).view;
break;
case IncomingEventType.Shortcut:
payload = (bodyArg as SlackShortcutMiddlewareArgs['body']);
break;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Fallthrough case in switch
case IncomingEventType.Action:
if (isBlockActionOrInteractiveMessageBody(bodyArg as SlackActionMiddlewareArgs['body'])) {
const { actions } = (bodyArg as SlackActionMiddlewareArgs<BlockAction | InteractiveMessage>['body']);
[payload] = actions;
break;
}
// If above conditional does not hit, fall through to fallback payload in default block below
default:
payload = (bodyArg as (
| Exclude<
AnyMiddlewareArgs,
SlackEventMiddlewareArgs | SlackActionMiddlewareArgs | SlackViewMiddlewareArgs
>
| SlackActionMiddlewareArgs<Exclude<SlackAction, BlockAction | InteractiveMessage>>
)['body']);
break;
}
// NOTE: the following doesn't work because... distributive?
// const listenerArgs: Partial<AnyMiddlewareArgs> = {
const listenerArgs: Pick<AnyMiddlewareArgs, 'body' | 'payload'> & {
/** Say function might be set below */
say?: SayFn;
/** Respond function might be set below */
respond?: RespondFn;
/** Ack function might be set below */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ack?: AckFn<any>;
} = {
body: bodyArg,
payload,
};
// Set aliases
if (type === IncomingEventType.Event) {
const eventListenerArgs = listenerArgs as SlackEventMiddlewareArgs;
eventListenerArgs.event = eventListenerArgs.payload;
if (eventListenerArgs.event.type === 'message') {
const messageEventListenerArgs = eventListenerArgs as SlackEventMiddlewareArgs<'message'>;
messageEventListenerArgs.message = messageEventListenerArgs.payload;
}
} else if (type === IncomingEventType.Action) {
const actionListenerArgs = listenerArgs as SlackActionMiddlewareArgs;
actionListenerArgs.action = actionListenerArgs.payload;
} else if (type === IncomingEventType.Command) {
const commandListenerArgs = listenerArgs as SlackCommandMiddlewareArgs;
commandListenerArgs.command = commandListenerArgs.payload;
} else if (type === IncomingEventType.Options) {
const optionListenerArgs = listenerArgs as SlackOptionsMiddlewareArgs<OptionsSource>;
optionListenerArgs.options = optionListenerArgs.payload;
} else if (type === IncomingEventType.ViewAction) {
const viewListenerArgs = listenerArgs as SlackViewMiddlewareArgs;
viewListenerArgs.view = viewListenerArgs.payload;
} else if (type === IncomingEventType.Shortcut) {
const shortcutListenerArgs = listenerArgs as SlackShortcutMiddlewareArgs;
shortcutListenerArgs.shortcut = shortcutListenerArgs.payload;
}
// Set say() utility
if (conversationId !== undefined && type !== IncomingEventType.Options) {
listenerArgs.say = createSay(conversationId);
}
// Set respond() utility
if (body.response_url) {
listenerArgs.respond = buildRespondFn(this.axios, body.response_url);
} else if (typeof body.response_urls !== 'undefined' && body.response_urls.length > 0) {
// This can exist only when view_submission payloads - response_url_enabled: true
listenerArgs.respond = buildRespondFn(this.axios, body.response_urls[0].response_url);
}
// Set ack() utility
if (type !== IncomingEventType.Event) {
listenerArgs.ack = ack;
} else {
// Events API requests are acknowledged right away, since there's no data expected
await ack();
}
// Get the client arg
let { client } = this;
const token = selectToken(context);
if (token !== undefined) {
let pool;
const clientOptionsCopy = { ...this.clientOptions };
if (authorizeResult.teamId !== undefined) {
pool = this.clients[authorizeResult.teamId];
if (pool === undefined) {
// eslint-disable-next-line no-multi-assign
pool = this.clients[authorizeResult.teamId] = new WebClientPool();
}
// Add teamId to clientOptions so it can be automatically added to web-api calls
clientOptionsCopy.teamId = authorizeResult.teamId;
} else if (authorizeResult.enterpriseId !== undefined) {
pool = this.clients[authorizeResult.enterpriseId];
if (pool === undefined) {
// eslint-disable-next-line no-multi-assign
pool = this.clients[authorizeResult.enterpriseId] = new WebClientPool();
}
}
if (pool !== undefined) {
client = pool.getOrCreate(token, clientOptionsCopy);
}
}
// Dispatch event through the global middleware chain
try {
await processMiddleware(
this.middleware,
listenerArgs as AnyMiddlewareArgs,
context,
client,
this.logger,
async () => {
// Dispatch the event through the listener middleware chains and aggregate their results
// TODO: change the name of this.middleware and this.listeners to help this make more sense
const listenerResults = this.listeners.map(async (origListenerMiddleware) => {
// Copy the array so modifications don't affect the original
const listenerMiddleware = [...origListenerMiddleware];
// Don't process the last item in the listenerMiddleware array - it shouldn't get a next fn
const listener = listenerMiddleware.pop();
if (listener === undefined) {
return undefined;
}
return processMiddleware(
listenerMiddleware,
listenerArgs as AnyMiddlewareArgs,
context,
client,
this.logger,
// When all of the listener middleware are done processing,
// `listener` here will be called without a `next` execution
async () => listener({
...(listenerArgs as AnyMiddlewareArgs),
context,
client,
logger: this.logger,
// `next` is already set in the outer processMiddleware
} as AnyMiddlewareArgs & AllMiddlewareArgs),
);