-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
219 lines (196 loc) · 5.79 KB
/
index.js
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
/* eslint-disable no-use-before-define */
import enumerate from '@js-bits/enumerate';
import { Executor } from '@js-bits/executor';
const KEYS = enumerate.ts(`
OPERATION
SWITCH_KEY
SWITCH_OPTIONS
INPUT
OUTPUT
EXIT
`);
/**
* @param {any} value
* @returns {string}
*/
const getType = value => {
if (value === null) return 'null';
if (typeof value === 'object') return String(value);
return typeof value;
};
/**
* @param {any} value
* @returns {boolean}
*/
const isObject = value => !!(value && typeof value === 'object' && value.constructor === Object);
/**
* Fixes issues with aws-xray-sdk wrapping global Promise
* @param {any} value
* @returns {boolean}
*/
const isPromise = value => value instanceof Promise || value instanceof Process.noop.constructor;
/**
* @param {any} value
* @param {typeof KEYS[Exclude<keyof KEYS, symbol>]} key
* @returns
*/
const validate = (value, key) => {
/** @type {boolean} */
let isValid = false;
/** @type {typeof ERRORS[Exclude<keyof ERRORS, symbol>]} */
let errorName = ERRORS.InitializationError;
// eslint-disable-next-line default-case
switch (key) {
case KEYS.OPERATION:
isValid = value instanceof Process || isPromise(value) || typeof value === 'function';
break;
case KEYS.SWITCH_KEY:
isValid = typeof value === 'string';
break;
case KEYS.SWITCH_OPTIONS:
isValid = isObject(value);
break;
case KEYS.INPUT:
case KEYS.OUTPUT:
isValid = value === undefined || isObject(value);
errorName = ERRORS.ExecutionError;
break;
}
if (isValid) return true;
const error = new Error(`Invalid "${key.description?.toLowerCase()}" type: ${getType(value)}`);
error.name = errorName;
throw error;
};
/**
* @param {import('./types').Operation} operation
* @param {import('./types').Input} [input]
* @returns {Promise<import('./types').Output>}
*/
const execute = async (operation, input) => {
let output;
if (operation instanceof Process) {
output = await operation.start(input);
} else if (isPromise(operation)) {
output = await operation;
} else if (operation === exit) {
output = exit(); // exit code
} else {
output = await /** @type {import('./types').FunctionStep} */ (operation)(input); // supposed be a function
}
if (output === exit) output = exit(); // exit code
validate(output, KEYS.OUTPUT);
return output;
};
/**
* @param {object} previousOutput
* @param {object} currentOutput
* @returns
*/
const mixOutput = (previousOutput, currentOutput) => {
if (previousOutput && currentOutput) {
const overlappingProps = Object.keys(previousOutput).filter(key =>
Object.prototype.hasOwnProperty.call(currentOutput, key)
);
if (overlappingProps.length) {
const error = new Error(`Conflicting step results for: "${overlappingProps.join('", "')}"`);
error.name = Process.ExecutionError;
throw error;
}
}
return { ...previousOutput, ...currentOutput };
};
/**
* @param {import('./types').Output} [output]
* @returns {import('./types').Output & { [KEYS.EXIT]: true }}
*/
const exit = output => {
validate(output, KEYS.OUTPUT);
return { ...output, [KEYS.EXIT]: true };
};
/**
* @template T
* @extends {Executor<T>}
*/
class Process extends Executor {
// eslint-disable-next-line class-methods-use-this
get [Symbol.toStringTag]() {
return Process.name;
}
/**
* @param {(import('./types').Operation | import('./types').Operation[])[]} args
*/
constructor(...args) {
// prepare steps
const steps = args.map(operation => {
if (Array.isArray(operation)) {
// wrap into a process
return new Process(...operation);
}
validate(operation, KEYS.OPERATION);
return operation;
});
super(async (resolve, reject, input) => {
try {
resolve(
await steps.reduce(async (previousStep, currentStep) => {
const previousOutput = await previousStep;
if (previousOutput && previousOutput[KEYS.EXIT]) return previousOutput;
const currentInput = { .../** @type {import('./types').Input} */ (input), ...previousOutput };
const currentOutput = await execute(currentStep, currentInput);
return mixOutput(previousOutput, currentOutput);
}, Promise.resolve())
);
} catch (error) {
reject(error);
}
});
}
/**
* @param {import('./types').Input} [input]
* @returns {this}
*/
execute(input) {
validate(input, KEYS.INPUT);
return super.execute(input);
}
/**
* Just an alias of {@link Process#execute} method
*/
start = this.execute;
/**
* Just a shortcut for `new Process(...steps).start(input)`
* @param {import('./types').Operation[]} list
* @returns {import('./types').FunctionStep}
*/
static steps(...list) {
return /** @type {import('./types').FunctionStep} */ input => new Process(...list).start(input);
}
/**
* @param {string} key
* @param {{ [key: string]: import('./types').Operation | import('./types').Operation[]}} options
* @param {import('./types').Operation} fallback
* @returns
*/
static switch(key, options, fallback = Process.noop) {
validate(key, KEYS.SWITCH_KEY);
validate(options, KEYS.SWITCH_OPTIONS);
return /** @type {import('./types').FunctionStep} */ input =>
new Process((input && options[/** @type {string} */ (input[key])]) || fallback).start(input);
}
/**
* @type {Promise<void>}
*/
static noop = Promise.resolve();
static exit = exit;
}
const ERRORS = enumerate.ts(
`
InitializationError
ExecutionError
`,
`${Process.name}|`
);
// Assigning properties like this helps typescript to declare the namespace properly
Process.ExecutionError = ERRORS.ExecutionError;
Process.InitializationError = ERRORS.InitializationError;
export default Process;