forked from slackapi/bolt-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorkflowStep.ts
373 lines (320 loc) · 10.6 KB
/
WorkflowStep.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
KnownBlock,
Block,
ViewsOpenResponse,
WorkflowsUpdateStepResponse,
WorkflowsStepCompletedResponse,
WorkflowsStepFailedResponse,
} from '@slack/web-api';
import {
Middleware,
AllMiddlewareArgs,
AnyMiddlewareArgs,
SlackActionMiddlewareArgs,
SlackViewMiddlewareArgs,
WorkflowStepEdit,
Context,
SlackEventMiddlewareArgs,
ViewWorkflowStepSubmitAction,
WorkflowStepExecuteEvent,
} from './types';
import processMiddleware from './middleware/process';
import { WorkflowStepInitializationError } from './errors';
/** Interfaces */
export interface StepConfigureArguments {
blocks: (KnownBlock | Block)[];
private_metadata?: string;
submit_disabled?: boolean;
external_id?: string;
}
export interface StepUpdateArguments {
inputs?: {
[key: string]: {
value: any;
skip_variable_replacement?: boolean;
variables?: {
[key: string]: any;
};
};
};
outputs?: {
name: string;
type: string;
label: string;
}[];
step_name?: string;
step_image_url?: string;
}
export interface StepCompleteArguments {
outputs?: {
[key: string]: any;
};
}
export interface StepFailArguments {
error: {
message: string;
};
}
export interface StepConfigureFn {
(params: StepConfigureArguments): Promise<ViewsOpenResponse>;
}
export interface StepUpdateFn {
(params?: StepUpdateArguments): Promise<WorkflowsUpdateStepResponse>;
}
export interface StepCompleteFn {
(params?: StepCompleteArguments): Promise<WorkflowsStepCompletedResponse>;
}
export interface StepFailFn {
(params: StepFailArguments): Promise<WorkflowsStepFailedResponse>;
}
export interface WorkflowStepConfig {
edit: WorkflowStepEditMiddleware | WorkflowStepEditMiddleware[];
save: WorkflowStepSaveMiddleware | WorkflowStepSaveMiddleware[];
execute: WorkflowStepExecuteMiddleware | WorkflowStepExecuteMiddleware[];
}
export interface WorkflowStepEditMiddlewareArgs extends SlackActionMiddlewareArgs<WorkflowStepEdit> {
step: WorkflowStepEdit['workflow_step'];
configure: StepConfigureFn;
}
export interface WorkflowStepSaveMiddlewareArgs extends SlackViewMiddlewareArgs<ViewWorkflowStepSubmitAction> {
step: ViewWorkflowStepSubmitAction['workflow_step'];
update: StepUpdateFn;
}
export interface WorkflowStepExecuteMiddlewareArgs extends SlackEventMiddlewareArgs<'workflow_step_execute'> {
step: WorkflowStepExecuteEvent['workflow_step'];
complete: StepCompleteFn;
fail: StepFailFn;
}
/** Types */
export type SlackWorkflowStepMiddlewareArgs =
| WorkflowStepEditMiddlewareArgs
| WorkflowStepSaveMiddlewareArgs
| WorkflowStepExecuteMiddlewareArgs;
export type WorkflowStepEditMiddleware = Middleware<WorkflowStepEditMiddlewareArgs>;
export type WorkflowStepSaveMiddleware = Middleware<WorkflowStepSaveMiddlewareArgs>;
export type WorkflowStepExecuteMiddleware = Middleware<WorkflowStepExecuteMiddlewareArgs>;
export type WorkflowStepMiddleware =
| WorkflowStepEditMiddleware[]
| WorkflowStepSaveMiddleware[]
| WorkflowStepExecuteMiddleware[];
export type AllWorkflowStepMiddlewareArgs<T extends SlackWorkflowStepMiddlewareArgs = SlackWorkflowStepMiddlewareArgs> =
T & AllMiddlewareArgs;
/** Constants */
const VALID_PAYLOAD_TYPES = new Set(['workflow_step_edit', 'workflow_step', 'workflow_step_execute']);
/** Class */
export class WorkflowStep {
/** Step callback_id */
private callbackId: string;
/** Step Add/Edit :: 'workflow_step_edit' action */
private edit: WorkflowStepEditMiddleware[];
/** Step Config Save :: 'view_submission' */
private save: WorkflowStepSaveMiddleware[];
/** Step Executed/Run :: 'workflow_step_execute' event */
private execute: WorkflowStepExecuteMiddleware[];
public constructor(callbackId: string, config: WorkflowStepConfig) {
validate(callbackId, config);
const { save, edit, execute } = config;
this.callbackId = callbackId;
this.save = Array.isArray(save) ? save : [save];
this.edit = Array.isArray(edit) ? edit : [edit];
this.execute = Array.isArray(execute) ? execute : [execute];
}
public getMiddleware(): Middleware<AnyMiddlewareArgs> {
return async (args): Promise<any> => {
if (isStepEvent(args) && this.matchesConstraints(args)) {
return this.processEvent(args);
}
return args.next();
};
}
private matchesConstraints(args: SlackWorkflowStepMiddlewareArgs): boolean {
return args.payload.callback_id === this.callbackId;
}
private async processEvent(args: AllWorkflowStepMiddlewareArgs): Promise<void> {
const { payload } = args;
const stepArgs = prepareStepArgs(args);
const stepMiddleware = this.getStepMiddleware(payload);
return processStepMiddleware(stepArgs, stepMiddleware);
}
private getStepMiddleware(payload: AllWorkflowStepMiddlewareArgs['payload']): WorkflowStepMiddleware {
switch (payload.type) {
case 'workflow_step_edit':
return this.edit;
case 'workflow_step':
return this.save;
case 'workflow_step_execute':
return this.execute;
default:
return [];
}
}
}
/** Helper Functions */
export function validate(callbackId: string, config: WorkflowStepConfig): void {
// Ensure callbackId is valid
if (typeof callbackId !== 'string') {
const errorMsg = 'WorkflowStep expects a callback_id as the first argument';
throw new WorkflowStepInitializationError(errorMsg);
}
// Ensure step config object is passed in
if (typeof config !== 'object') {
const errorMsg = 'WorkflowStep expects a configuration object as the second argument';
throw new WorkflowStepInitializationError(errorMsg);
}
// Check for missing required keys
const requiredKeys: (keyof WorkflowStepConfig)[] = ['save', 'edit', 'execute'];
const missingKeys: (keyof WorkflowStepConfig)[] = [];
requiredKeys.forEach((key) => {
if (config[key] === undefined) {
missingKeys.push(key);
}
});
if (missingKeys.length > 0) {
const errorMsg = `WorkflowStep is missing required keys: ${missingKeys.join(', ')}`;
throw new WorkflowStepInitializationError(errorMsg);
}
// Ensure a callback or an array of callbacks is present
const requiredFns: (keyof WorkflowStepConfig)[] = ['save', 'edit', 'execute'];
requiredFns.forEach((fn) => {
if (typeof config[fn] !== 'function' && !Array.isArray(config[fn])) {
const errorMsg = `WorkflowStep ${fn} property must be a function or an array of functions`;
throw new WorkflowStepInitializationError(errorMsg);
}
});
}
/**
* `processStepMiddleware()` invokes each callback for lifecycle event
* @param args workflow_step_edit action
*/
export async function processStepMiddleware(
args: AllWorkflowStepMiddlewareArgs,
middleware: WorkflowStepMiddleware,
): Promise<void> {
const { context, client, logger } = args;
// TODO :: revisit type used below (look into contravariance)
const callbacks = [...middleware] as Middleware<AnyMiddlewareArgs>[];
const lastCallback = callbacks.pop();
if (lastCallback !== undefined) {
await processMiddleware(
callbacks, args, context, client, logger,
async () => lastCallback({ ...args, context, client, logger }),
);
}
}
export function isStepEvent(args: AnyMiddlewareArgs): args is AllWorkflowStepMiddlewareArgs {
return VALID_PAYLOAD_TYPES.has(args.payload.type);
}
function selectToken(context: Context): string | undefined {
return context.botToken !== undefined ? context.botToken : context.userToken;
}
/**
* Factory for `configure()` utility
* @param args workflow_step_edit action
*/
function createStepConfigure(args: AllWorkflowStepMiddlewareArgs<WorkflowStepEditMiddlewareArgs>): StepConfigureFn {
const {
context,
client,
body: { callback_id, trigger_id },
} = args;
const token = selectToken(context);
return (params: Parameters<StepConfigureFn>[0]) => client.views.open({
token,
trigger_id,
view: {
callback_id,
type: 'workflow_step',
...params,
},
});
}
/**
* Factory for `update()` utility
* @param args view_submission event
*/
function createStepUpdate(args: AllWorkflowStepMiddlewareArgs<WorkflowStepSaveMiddlewareArgs>): StepUpdateFn {
const {
context,
client,
body: {
workflow_step: { workflow_step_edit_id },
},
} = args;
const token = selectToken(context);
return (params: Parameters<StepUpdateFn>[0] = {}) => client.workflows.updateStep({
token,
workflow_step_edit_id,
...params,
});
}
/**
* Factory for `complete()` utility
* @param args workflow_step_execute event
*/
function createStepComplete(args: AllWorkflowStepMiddlewareArgs<WorkflowStepExecuteMiddlewareArgs>): StepCompleteFn {
const {
context,
client,
payload: {
workflow_step: { workflow_step_execute_id },
},
} = args;
const token = selectToken(context);
return (params: Parameters<StepCompleteFn>[0] = {}) => client.workflows.stepCompleted({
token,
workflow_step_execute_id,
...params,
});
}
/**
* Factory for `fail()` utility
* @param args workflow_step_execute event
*/
function createStepFail(args: AllWorkflowStepMiddlewareArgs<WorkflowStepExecuteMiddlewareArgs>): StepFailFn {
const {
context,
client,
payload: {
workflow_step: { workflow_step_execute_id },
},
} = args;
const token = selectToken(context);
return (params: Parameters<StepFailFn>[0]) => {
const { error } = params;
return client.workflows.stepFailed({
token,
workflow_step_execute_id,
error,
});
};
}
/**
* `prepareStepArgs()` takes in a workflow step's args and:
* 1. removes the next() passed in from App-level middleware processing
* - events will *not* continue down global middleware chain to subsequent listeners
* 2. augments args with step lifecycle-specific properties/utilities
* */
// TODO :: refactor to incorporate a generic parameter
export function prepareStepArgs(args: any): AllWorkflowStepMiddlewareArgs {
const { next: _next, ...stepArgs } = args;
const preparedArgs: any = { ...stepArgs };
switch (preparedArgs.payload.type) {
case 'workflow_step_edit':
preparedArgs.step = preparedArgs.action.workflow_step;
preparedArgs.configure = createStepConfigure(preparedArgs);
break;
case 'workflow_step':
preparedArgs.step = preparedArgs.body.workflow_step;
preparedArgs.update = createStepUpdate(preparedArgs);
break;
case 'workflow_step_execute':
preparedArgs.step = preparedArgs.event.workflow_step;
preparedArgs.complete = createStepComplete(preparedArgs);
preparedArgs.fail = createStepFail(preparedArgs);
break;
default:
break;
}
return preparedArgs;
}