-
Notifications
You must be signed in to change notification settings - Fork 393
/
App.ts
1658 lines (1507 loc) · 64.6 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 type { Agent } from 'node:http';
import type { SecureContextOptions } from 'node:tls';
import util from 'node:util';
import { ConsoleLogger, LogLevel, type Logger } from '@slack/logger';
import { type ChatPostMessageArguments, WebClient, type WebClientOptions, addAppMetadata } from '@slack/web-api';
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
import type { Assistant } from './Assistant';
import {
CustomFunction,
type FunctionCompleteFn,
type FunctionFailFn,
type SlackCustomFunctionMiddlewareArgs,
createFunctionComplete,
createFunctionFail,
} from './CustomFunction';
import type { WorkflowStep } from './WorkflowStep';
import { type ConversationStore, MemoryStore, conversationContext } from './conversation-store';
import {
AppInitializationError,
type CodedError,
ErrorCode,
InvalidCustomPropertyError,
MultipleListenerError,
asCodedError,
} from './errors';
import {
IncomingEventType,
assertNever,
getTypeAndConversation,
isBodyWithTypeEnterpriseInstall,
isEventTypeToSkipAuthorize,
} from './helpers';
import {
autoAcknowledge,
ignoreSelf as ignoreSelfMiddleware,
isSlackEventMiddlewareArgsOptions,
matchCommandName,
matchConstraints,
matchEventType,
matchMessage,
onlyActions,
onlyCommands,
onlyEvents,
onlyOptions,
onlyShortcuts,
onlyViewActions,
} from './middleware/builtin';
import processMiddleware from './middleware/process';
import HTTPReceiver, { type HTTPReceiverOptions } from './receivers/HTTPReceiver';
import SocketModeReceiver from './receivers/SocketModeReceiver';
import type {
AckFn,
ActionConstraints,
AnyMiddlewareArgs,
BlockAction,
BlockElementAction,
Context,
DialogSubmitAction,
EventTypePattern,
FunctionInputs,
InteractiveAction,
InteractiveMessage,
KnownEventFromType,
KnownOptionsPayloadFromType,
Middleware,
OptionsConstraints,
OptionsSource,
Receiver,
ReceiverEvent,
RespondArguments,
RespondFn,
SayFn,
ShortcutConstraints,
SlackAction,
SlackActionMiddlewareArgs,
SlackCommandMiddlewareArgs,
SlackEventMiddlewareArgs,
SlackEventMiddlewareArgsOptions,
SlackOptionsMiddlewareArgs,
SlackShortcut,
SlackShortcutMiddlewareArgs,
SlackViewAction,
SlackViewMiddlewareArgs,
SlashCommand,
ViewConstraints,
ViewOutput,
WorkflowStepEdit,
} from './types';
import { type AllMiddlewareArgs, contextBuiltinKeys } from './types/middleware';
import { type StringIndexed, isRejected } from './types/utilities';
const packageJson = require('../package.json');
export type { ActionConstraints, OptionsConstraints, ShortcutConstraints, ViewConstraints } from './types';
// ----------------------------
// For listener registration methods
// TODO: we have types for this... consolidate
const validViewTypes = ['view_closed', 'view_submission'];
// ----------------------------
// For the constructor
const tokenUsage =
'Apps used in a single workspace can be initialized with a token. Apps used in many workspaces ' +
'should be initialized with oauth installer options 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;
deferInitialization?: boolean;
extendedErrorHandler?: boolean;
attachFunctionToken?: boolean;
}
export { LogLevel, Logger } from '@slack/logger';
/** Authorization function - seeds the middleware processing and listeners with an authorization context */
export type 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
userId?: string;
teamId?: string;
enterpriseId?: string;
// biome-ignore lint/suspicious/noExplicitAny: TODO: for better type safety, we may want to revisit this
[key: string]: any;
}
// 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 type ErrorHandler = (error: CodedError) => Promise<void>;
export type ExtendedErrorHandler = (args: ExtendedErrorHandlerArgs) => Promise<void>;
export interface AnyErrorHandler extends ErrorHandler, ExtendedErrorHandler {}
// Used only in this file
type MessageEventMiddleware<CustomContext extends StringIndexed = StringIndexed> = Middleware<
SlackEventMiddlewareArgs<'message'>,
CustomContext
>;
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<AppCustomContext extends StringIndexed = StringIndexed> {
/** 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;
// used when deferInitialization is true
private argToken?: string;
// used when deferInitialization is true
private argAuthorize?: Authorize;
// used when deferInitialization is true
private argAuthorization?: Authorization;
private tokenVerificationEnabled: boolean;
private initialized: boolean;
private attachFunctionToken: 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,
deferInitialization = false,
attachFunctionToken = true,
}: AppOptions = {}) {
/* ------------------------ Developer mode ----------------------------- */
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 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;
// Override token with functionBotAccessToken in function-related handlers
this.attachFunctionToken = attachFunctionToken;
/* ------------------------ Set 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 env vars 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) {
// SocketModeReceiver only uses a custom port number when listening for the OAuth flow.
// Therefore, 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>${escapeHtml(error.code)}</div></body></html>`);
},
};
}
this.receiver = this.initReceiver(
receiver,
signingSecret,
endpoints,
port,
customRoutes,
processBeforeResponse,
signatureVerification,
clientId,
clientSecret,
stateSecret,
redirectUri,
installationStore,
scopes,
appToken,
logger,
);
/* ------------------------ Set authorize ----------------------------- */
this.tokenVerificationEnabled = tokenVerificationEnabled;
let argAuthorization: Authorization | undefined;
if (token !== undefined) {
argAuthorization = {
botId,
botUserId,
botToken: token,
};
}
if (deferInitialization) {
this.argToken = token;
this.argAuthorize = authorize;
this.argAuthorization = argAuthorization;
this.initialized = false;
// You need to run `await app.init();` on your own
} else {
this.authorize = this.initAuthorizeInConstructor(token, authorize, argAuthorization);
this.initialized = true;
}
// 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));
}
/* ------------------------ Initialize receiver ------------------------ */
// Should be last to avoid exposing partially initialized app
this.receiver.init(this);
}
public async init(): Promise<void> {
this.initialized = true;
try {
const initializedAuthorize = this.initAuthorizeIfNoTokenIsGiven(this.argToken, this.argAuthorize);
if (initializedAuthorize !== undefined) {
this.authorize = initializedAuthorize;
return;
}
if (this.argToken !== undefined && this.argAuthorization !== undefined) {
let authorization = this.argAuthorization;
if (this.tokenVerificationEnabled) {
const authTestResult = await this.client.auth.test({ token: this.argToken });
if (authTestResult.ok) {
authorization = {
botUserId: authTestResult.user_id as string,
botId: authTestResult.bot_id as string,
botToken: this.argToken,
};
}
}
this.authorize = singleAuthorization(this.client, authorization, this.tokenVerificationEnabled);
this.initialized = true;
} else {
this.logger.error(
'Something has gone wrong. Please report this issue to the maintainers. https://github.com/slackapi/bolt-js/issues',
);
assertNever();
}
} catch (e) {
// Revert the flag change as the initialization failed
this.initialized = false;
throw e;
}
}
public get webClientOptions(): WebClientOptions {
return this.clientOptions;
}
/**
* Register a new middleware, processed in the order registered.
*
* @param m global middleware function
*/
public use<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
m: Middleware<AnyMiddlewareArgs<{ autoAcknowledge: false }>, AppCustomContext & MiddlewareCustomContext>,
): this {
this.middleware.push(m as Middleware<AnyMiddlewareArgs>);
return this;
}
/**
* Register Assistant middleware
*
* @param assistant global assistant middleware function
*/
public assistant(assistant: Assistant): this {
const m = assistant.getMiddleware();
this.middleware.push(m);
return this;
}
/**
* Register WorkflowStep middleware
*
* @param workflowStep global workflow step middleware function
* @deprecated Steps from Apps are no longer supported and support for them will be removed in the next major bolt-js
* version.
*/
public step(workflowStep: WorkflowStep): this {
const m = workflowStep.getMiddleware();
this.middleware.push(m);
return this;
}
/**
* Register CustomFunction middleware
*/
public function<Options extends SlackEventMiddlewareArgsOptions = { autoAcknowledge: true }>(
callbackId: string,
options: Options,
...listeners: Middleware<SlackCustomFunctionMiddlewareArgs<Options>>[]
): this;
public function<Options extends SlackEventMiddlewareArgsOptions = { autoAcknowledge: true }>(
callbackId: string,
...listeners: Middleware<SlackCustomFunctionMiddlewareArgs<Options>>[]
): this;
public function<Options extends SlackEventMiddlewareArgsOptions = { autoAcknowledge: true }>(
callbackId: string,
...optionOrListeners: (Options | Middleware<SlackCustomFunctionMiddlewareArgs<Options>>)[]
): this {
// TODO: fix this casting; edge case is if dev specifically sets AutoAck generic as false, this true assignment is invalid according to TS.
const options = isSlackEventMiddlewareArgsOptions(optionOrListeners[0])
? optionOrListeners[0]
: ({ autoAcknowledge: true } as Options);
const listeners = optionOrListeners.filter(
(optionOrListener): optionOrListener is Middleware<SlackCustomFunctionMiddlewareArgs<Options>> => {
return !isSlackEventMiddlewareArgsOptions(optionOrListener);
},
);
const fn = new CustomFunction<Options>(callbackId, listeners, options);
this.listeners.push(fn.getListeners());
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']> {
if (!this.initialized) {
throw new AppInitializationError(
'This App instance is not yet initialized. Call `await App#init()` before starting the app.',
);
}
// TODO: HTTPReceiver['start'] should be the actual receiver's return type
return this.receiver.start(...args) as ReturnType<HTTPReceiver['start']>;
}
// biome-ignore lint/suspicious/noExplicitAny: receivers could accept anything as arguments for stop
public stop(...args: any[]): Promise<unknown> {
return this.receiver.stop(...args);
}
// TODO: can constrain EventType here to the set of available slack event types to help autocomplete event names
public event<EventType extends string = string, MiddlewareCustomContext extends StringIndexed = StringIndexed>(
eventName: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<EventType>, AppCustomContext & MiddlewareCustomContext>[]
): void;
public event<EventType extends RegExp = RegExp, MiddlewareCustomContext extends StringIndexed = StringIndexed>(
eventName: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<string>, AppCustomContext & MiddlewareCustomContext>[]
): void;
public event<
EventType extends EventTypePattern = EventTypePattern,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
eventNameOrPattern: EventType,
...listeners: Middleware<SlackEventMiddlewareArgs<string>, AppCustomContext & MiddlewareCustomContext>[]
): void {
let invalidEventName = false;
if (typeof eventNameOrPattern === 'string') {
const name = eventNameOrPattern;
invalidEventName = name.startsWith('message.');
} else if (eventNameOrPattern instanceof RegExp) {
const name = eventNameOrPattern.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.`,
);
}
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
const _listeners = listeners as any;
this.listeners.push([
onlyEvents,
matchEventType(eventNameOrPattern),
autoAcknowledge,
..._listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
/**
*
* @param listeners Middlewares that process and react to a message event
*/
public message<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
...listeners: MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>[]
): 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<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
pattern: string | RegExp,
...listeners: MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>[]
): 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<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
filter: MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>,
pattern: string | RegExp,
...listeners: MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>[]
): 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<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
filter: MessageEventMiddleware, // TODO: why do we need this override? shouldnt ...listeners capture this too?
...listeners: MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>[]
): 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<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
...patternsOrMiddleware: (string | RegExp | MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>)[]
): void;
// TODO: expose a type parameter for overriding the MessageEvent type (just like shortcut() and action() does) https://github.com/slackapi/bolt-js/issues/796
public message<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
...patternsOrMiddleware: (string | RegExp | MessageEventMiddleware<AppCustomContext & MiddlewareCustomContext>)[]
): void {
const messageMiddleware = patternsOrMiddleware.map((patternOrMiddleware) => {
if (typeof patternOrMiddleware === 'string' || util.types.isRegExp(patternOrMiddleware)) {
return matchMessage(patternOrMiddleware);
}
return patternOrMiddleware;
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
}) as any;
this.listeners.push([
onlyEvents,
matchEventType('message'),
autoAcknowledge,
...messageMiddleware,
] as Middleware<AnyMiddlewareArgs>[]);
}
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
callbackId: string | RegExp,
...listeners: Middleware<SlackShortcutMiddlewareArgs<Shortcut>, AppCustomContext & MiddlewareCustomContext>[]
): void;
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
Constraints extends ShortcutConstraints<Shortcut> = ShortcutConstraints<Shortcut>,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
constraints: Constraints,
...listeners: Middleware<
SlackShortcutMiddlewareArgs<Extract<Shortcut, { type: Constraints['type'] }>>,
AppCustomContext & MiddlewareCustomContext
>[]
): void;
public shortcut<
Shortcut extends SlackShortcut = SlackShortcut,
Constraints extends ShortcutConstraints<Shortcut> = ShortcutConstraints<Shortcut>,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
callbackIdOrConstraints: string | RegExp | Constraints,
...listeners: Middleware<
SlackShortcutMiddlewareArgs<Extract<Shortcut, { type: Constraints['type'] }>>,
AppCustomContext & MiddlewareCustomContext
>[]
): 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) {
// TODO:event() will throw an error if you provide an invalid event name; we should align this behaviour.
this.logger.error(
`Slack listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
const _listeners = listeners as any;
this.listeners.push([
onlyShortcuts,
matchConstraints(constraints),
..._listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
public action<
Action extends SlackAction = SlackAction,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
actionId: string | RegExp,
...listeners: Middleware<SlackActionMiddlewareArgs<Action>, AppCustomContext & MiddlewareCustomContext>[]
): void;
public action<
Action extends SlackAction = SlackAction,
Constraints extends ActionConstraints<Action> = ActionConstraints<Action>,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
constraints: Constraints,
// NOTE: Extract<> is able to return the whole union when type: undefined. Why?
...listeners: Middleware<
SlackActionMiddlewareArgs<Extract<Action, { type: Constraints['type'] }>>,
AppCustomContext & MiddlewareCustomContext
>[]
): void;
public action<
Action extends SlackAction = SlackAction,
Constraints extends ActionConstraints<Action> = ActionConstraints<Action>,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
actionIdOrConstraints: string | RegExp | Constraints,
...listeners: Middleware<
SlackActionMiddlewareArgs<Extract<Action, { type: Constraints['type'] }>>,
AppCustomContext & MiddlewareCustomContext
>[]
): 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) {
// TODO:event() will throw an error if you provide an invalid event name; we should align this behaviour.
this.logger.error(
`Action listener cannot be attached using unknown constraint keys: ${unknownConstraintKeys.join(', ')}`,
);
return;
}
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
const _listeners = listeners as any;
this.listeners.push([onlyActions, matchConstraints(constraints), ..._listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public command<MiddlewareCustomContext extends StringIndexed = StringIndexed>(
commandName: string | RegExp,
...listeners: Middleware<SlackCommandMiddlewareArgs, AppCustomContext & MiddlewareCustomContext>[]
): void {
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
const _listeners = listeners as any;
this.listeners.push([
onlyCommands,
matchCommandName(commandName),
..._listeners,
] as Middleware<AnyMiddlewareArgs>[]);
}
public options<
Source extends OptionsSource = 'block_suggestion', // TODO: here, similarly to `message()`, the generic is the string `type` of the payload. in others, like `action()`, it's the entire payload. could we make this consistent?
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
actionId: string | RegExp,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>, AppCustomContext & MiddlewareCustomContext>[]
): void;
// TODO: reflect the type in constraints to Source (this relates to the above TODO, too)
public options<
Source extends OptionsSource = OptionsSource,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
constraints: OptionsConstraints, // TODO: to be able to 'link' listener arguments to the constrains, should pass the Source type in as a generic here
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>, AppCustomContext & MiddlewareCustomContext>[]
): void;
// TODO: reflect the type in constraints to Source
public options<
Source extends OptionsSource = OptionsSource,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
actionIdOrConstraints: string | RegExp | OptionsConstraints,
...listeners: Middleware<SlackOptionsMiddlewareArgs<Source>, AppCustomContext & MiddlewareCustomContext>[]
): void {
const constraints: OptionsConstraints =
typeof actionIdOrConstraints === 'string' || util.types.isRegExp(actionIdOrConstraints)
? { action_id: actionIdOrConstraints }
: actionIdOrConstraints;
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
const _listeners = listeners as any;
this.listeners.push([onlyOptions, matchConstraints(constraints), ..._listeners] as Middleware<AnyMiddlewareArgs>[]);
}
public view<
ViewActionType extends SlackViewAction = SlackViewAction,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
callbackId: string | RegExp,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>, AppCustomContext & MiddlewareCustomContext>[]
): void;
public view<
ViewActionType extends SlackViewAction = SlackViewAction,
// TODO: add a type parameter for view constraints; this way we can constrain the handler view arguments based on the type of the constraint, similar to what action() does
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
constraints: ViewConstraints,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>, AppCustomContext & MiddlewareCustomContext>[]
): void;
public view<
ViewActionType extends SlackViewAction = SlackViewAction,
MiddlewareCustomContext extends StringIndexed = StringIndexed,
>(
callbackIdOrConstraints: string | RegExp | ViewConstraints,
...listeners: Middleware<SlackViewMiddlewareArgs<ViewActionType>, AppCustomContext & MiddlewareCustomContext>[]
): 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;
}
// biome-ignore lint/suspicious/noExplicitAny: FIXME: workaround for TypeScript 4.7 breaking changes
const _listeners = listeners as any;
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;
if (type === IncomingEventType.Event && isEventTypeToSkipAuthorize(event)) {
authorizeResult = {
enterpriseId: source.enterpriseId,
teamId: source.teamId,
};
} else {
try {
authorizeResult = await this.authorize(source, bodyArg);
} catch (error) {
// biome-ignore lint/suspicious/noExplicitAny: errors can be anything
const e = error as any;
this.logger.warn('Authorization of incoming event did not succeed. No listeners will be called.');
e.code = ErrorCode.AuthorizationError;
return this.handleError({
error: e,
logger: this.logger,
body: bodyArg,
context: {
isEnterpriseInstall,
},
});
}
}
// Try to set userId from AuthorizeResult before using one from source
if (authorizeResult.userId === undefined && source.userId !== undefined) {
authorizeResult.userId = source.userId;
}
// 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,
isEnterpriseInstall,
retryNum: event.retryNum,
retryReason: event.retryReason,
};
// Extract function-related information and augment context
const { functionExecutionId, functionBotAccessToken, functionInputs } = extractFunctionContext(body);
if (functionExecutionId) {
context.functionExecutionId = functionExecutionId;
if (functionInputs) {
context.functionInputs = functionInputs;
}
}
// Attach and make available the JIT/function-related token on context