@onify/flow-extensions 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Onify
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ Onify Flow Extensions
2
+ =====================
3
+
4
+ [![Built latest](https://github.com/onify/flow-extensions/actions/workflows/build-latest.yaml/badge.svg)](https://github.com/onify/flow-extensions/actions/workflows/build-latest.yaml)
5
+
6
+ # Api
7
+
8
+ - `extensions`: Flow extensions
9
+ - `extendFn`: extend function to pass to [serializer](https://github.com/paed01/moddle-context-serializer/blob/master/API.md)
10
+
11
+ # Examples
12
+
13
+ ## Bpmn engine example
14
+
15
+ ```js
16
+ const {Engine} = require('bpmn-engine');
17
+ const {extensions} = require('@onify/flow-extensions');
18
+ const FlowScripts = require('@onify/flow-extensions/dist/src/FlowScripts');
19
+
20
+ const source = `
21
+ <definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
22
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
23
+ xmlns:camunda="http://camunda.org/schema/1.0/bpmn">
24
+ <process id="theProcess" isExecutable="true">
25
+ <serviceTask id="task1" camunda:expression="\${environment.services.serviceFn}" camunda:resultVariable="result" />
26
+ <sequenceFlow id="to-task2" sourceRef="task1" targetRef="task2" />
27
+ <scriptTask id="task2" camunda:resultVariable="out">
28
+ <script>
29
+ next(null, myContextFn());
30
+ </script>
31
+ </scriptTask>
32
+ </process>
33
+ </definitions>`;
34
+
35
+ const name = 'onify flow';
36
+ const engine = new Engine({
37
+ name,
38
+ source,
39
+ moddleOptions: {
40
+ camunda: require('camunda-bpmn-moddle/resources/camunda.json'),
41
+ },
42
+ services: {
43
+ serviceFn(scope, callback) {
44
+ callback(null, {data: 1});
45
+ }
46
+ },
47
+ extensions: {
48
+ onify: extensions,
49
+ },
50
+ scripts: new FlowScripts(name, './script-resources', {
51
+ myContextFn() {
52
+ return 2;
53
+ },
54
+ }),
55
+ });
56
+
57
+ engine.execute((err, instance) => {
58
+ if (err) throw err;
59
+ console.log(instance.name, instance.environment.output);
60
+ });
61
+ ```
62
+
63
+ ## Extract scripts with extend function
64
+
65
+ ```js
66
+ const {extendFn} = require('@onify/flow-extensions');
67
+
68
+ const BpmnModdle = require('bpmn-moddle');
69
+ const Elements = require('bpmn-elements');
70
+ const {default: Serializer, TypeResolver} = require('moddle-context-serializer');
71
+
72
+ const source = `
73
+ <definitions id="Def_0" xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
74
+ xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
75
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
76
+ targetNamespace="http://bpmn.io/schema/bpmn">
77
+ <process id="process-1" name="Onify Flow" isExecutable="true">
78
+ <serviceTask id="task1">
79
+ <extensionElements>
80
+ <camunda:connector>
81
+ <camunda:connectorId>onifyApiRequest</camunda:connectorId>
82
+ <camunda:inputOutput>
83
+ <camunda:inputParameter name="method">GET</camunda:inputParameter>
84
+ <camunda:inputParameter name="url">/my/items/workspace-1</camunda:inputParameter>
85
+ <camunda:outputParameter name="result">
86
+ <camunda:script scriptFormat="js">
87
+ next(null, {
88
+ id: content.id,
89
+ statuscode,
90
+ });
91
+ </camunda:script>
92
+ </camunda:outputParameter>
93
+ </camunda:inputOutput>
94
+ </camunda:connector>
95
+ <camunda:inputOutput>
96
+ <camunda:outputParameter name="result">\${content.output.result.statuscode}</camunda:outputParameter>
97
+ </camunda:inputOutput>
98
+ </extensionElements>
99
+ </serviceTask>
100
+ <sequenceFlow id="to-task2" sourceRef="task1" targetRef="task2" />
101
+ <scriptTask id="task2" camunda:resultVariable="out">
102
+ <script>
103
+ next(null, 2);
104
+ </script>
105
+ </scriptTask>
106
+ </process>
107
+ </definitions>`;
108
+
109
+ (async () => {
110
+ const moddle = await getModdleContext(source, {
111
+ camunda: require('camunda-bpmn-moddle/resources/camunda.json'),
112
+ });
113
+
114
+ const serialized = Serializer(moddle, TypeResolver(Elements), extendFn);
115
+ console.log(serialized.elements.scripts);
116
+ })();
117
+
118
+ function getModdleContext(source, options) {
119
+ const bpmnModdle = new BpmnModdle(options);
120
+ return bpmnModdle.fromXML(Buffer.isBuffer(source) ? source.toString() : source.trim());
121
+ }
122
+ ```
package/dist/index.js ADDED
@@ -0,0 +1,455 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.extendFn = extendFn;
7
+ exports.extensions = extensions;
8
+
9
+ var _cronParser = _interopRequireDefault(require("cron-parser"));
10
+
11
+ var _IOProperties = _interopRequireDefault(require("./src/IOProperties"));
12
+
13
+ var _IOForm = _interopRequireDefault(require("./src/IOForm"));
14
+
15
+ var _Connector = _interopRequireDefault(require("./src/Connector"));
16
+
17
+ var _ServiceExpression = _interopRequireDefault(require("./src/ServiceExpression"));
18
+
19
+ var _IO = require("./src/IO");
20
+
21
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22
+
23
+ class FormatError extends Error {
24
+ constructor(elementId, err) {
25
+ super(`<${elementId}> ${err.message}`);
26
+ this.code = 'EFLOW_FORMAT';
27
+ this.output = {
28
+ statusCode: 500
29
+ };
30
+ }
31
+
32
+ }
33
+
34
+ function extensions(element, context) {
35
+ if (element.type === 'bpmn:Process') return new OnifyProcessExtensions(element, context);
36
+ return new OnifyElementExtensions(element, context);
37
+ }
38
+
39
+ class OnifyProcessExtensions {
40
+ constructor(bp, context) {
41
+ this.process = bp;
42
+ this.context = context;
43
+ this.extensions = getExtensions(bp, context);
44
+
45
+ this._activate();
46
+ }
47
+
48
+ _activate() {
49
+ const bp = this.process;
50
+ bp.on('process.enter', elementApi => {
51
+ try {
52
+ const result = this._onEnter(elementApi);
53
+
54
+ const environment = elementApi.environment;
55
+ environment.assignVariables(result);
56
+ } catch (err) {
57
+ elementApi.broker.publish('event', 'process.error', { ...elementApi.content,
58
+ error: new FormatError(bp.id, err)
59
+ }, {
60
+ mandatory: true,
61
+ type: 'error'
62
+ });
63
+ }
64
+ }, {
65
+ consumerTag: '_onify-extension-on-enter'
66
+ });
67
+ }
68
+
69
+ _onEnter(elementApi) {
70
+ const {
71
+ format,
72
+ properties
73
+ } = this.extensions;
74
+ const result = {};
75
+ Object.assign(result, format.resolve(elementApi));
76
+ Object.assign(elementApi.content, result);
77
+
78
+ if (properties) {
79
+ Object.assign(result, properties.resolve(elementApi));
80
+ Object.assign(elementApi.content, result);
81
+ }
82
+
83
+ return result;
84
+ }
85
+
86
+ }
87
+
88
+ class OnifyElementExtensions {
89
+ constructor(activity, context) {
90
+ this.activity = activity;
91
+ this.context = context;
92
+ const {
93
+ Service
94
+ } = this.extensions = getExtensions(activity, context);
95
+
96
+ if (Service) {
97
+ activity.behaviour.Service = Service;
98
+ }
99
+ }
100
+
101
+ activate() {
102
+ const activity = this.activity;
103
+ const broker = activity.broker;
104
+ const formatQ = activity.broker.getQueue('format-run-q');
105
+ activity.on('enter', async elementApi => {
106
+ formatQ.queueMessage({
107
+ routingKey: 'run.enter.format'
108
+ }, {
109
+ endRoutingKey: 'run.enter.complete'
110
+ }, {
111
+ persistent: false
112
+ });
113
+
114
+ try {
115
+ var format = await this._onEnter(elementApi);
116
+ } catch (err) {
117
+ return broker.publish('format', 'run.enter.error', {
118
+ error: err
119
+ }, {
120
+ persistent: false
121
+ });
122
+ }
123
+
124
+ broker.publish('format', 'run.enter.complete', format, {
125
+ persistent: false
126
+ });
127
+ }, {
128
+ consumerTag: '_onify-extension-on-enter'
129
+ });
130
+ activity.on('activity.execution.completed', async elementApi => {
131
+ if (elementApi.fields.redelivered) return;
132
+ formatQ.queueMessage({
133
+ routingKey: 'run.end.error'
134
+ }, {
135
+ endRoutingKey: 'run.end.complete'
136
+ }, {
137
+ persistent: false
138
+ });
139
+
140
+ try {
141
+ var format = await this._onExecuted(elementApi);
142
+ } catch (err) {
143
+ return broker.publish('format', 'run.enter.error', {
144
+ error: err
145
+ }, {
146
+ persistent: false
147
+ });
148
+ }
149
+
150
+ broker.publish('format', 'run.end.complete', { ...format
151
+ }, {
152
+ persistent: false
153
+ });
154
+ }, {
155
+ consumerTag: '_onify-extension-on-executed'
156
+ });
157
+ }
158
+
159
+ deactivate() {
160
+ const broker = this.activity.broker;
161
+ broker.cancel('_onify-extension-on-enter');
162
+ broker.cancel('_onify-extension-on-executed');
163
+ }
164
+
165
+ async _onEnter(elementApi) {
166
+ const {
167
+ format,
168
+ properties,
169
+ io,
170
+ form
171
+ } = this.extensions;
172
+ const result = {};
173
+ Object.assign(result, format.resolve(elementApi));
174
+ Object.assign(elementApi.content, result);
175
+
176
+ if (properties) {
177
+ Object.assign(result, {
178
+ properties: properties.resolve(elementApi)
179
+ });
180
+ Object.assign(elementApi.content, result);
181
+ }
182
+
183
+ if (io) {
184
+ var _io$input, _io$output;
185
+
186
+ if ((_io$input = io.input) !== null && _io$input !== void 0 && _io$input.length) {
187
+ const input = await io.getInput(this.activity, elementApi);
188
+ Object.assign(result, {
189
+ input
190
+ });
191
+ Object.assign(elementApi.content, result);
192
+ }
193
+
194
+ if ((_io$output = io.output) !== null && _io$output !== void 0 && _io$output.length) {
195
+ result.assignToOutput = true;
196
+ }
197
+ }
198
+
199
+ if (form) {
200
+ Object.assign(result, {
201
+ form: form.resolve(elementApi)
202
+ });
203
+ }
204
+
205
+ return result;
206
+ }
207
+
208
+ async _onExecuted(elementApi) {
209
+ const {
210
+ properties,
211
+ io
212
+ } = this.extensions;
213
+ const result = {};
214
+
215
+ if (io !== null && io !== void 0 && io.output.length) {
216
+ const output = await io.getOutput(this.activity, elementApi);
217
+ Object.assign(result, {
218
+ output
219
+ });
220
+ Object.assign(elementApi.content, {
221
+ output
222
+ });
223
+ }
224
+
225
+ if (properties) {
226
+ const props = properties.resolve(elementApi);
227
+ Object.assign(result, {
228
+ properties: props
229
+ });
230
+ Object.assign(elementApi.content, {
231
+ properties: props
232
+ });
233
+ }
234
+
235
+ const {
236
+ output,
237
+ assignToOutput,
238
+ resultVariable
239
+ } = elementApi.content;
240
+ if (output === undefined || output === null) return result;
241
+
242
+ if (assignToOutput && typeof output === 'object') {
243
+ Object.assign(this.activity.environment.output, output);
244
+ } else if (resultVariable) {
245
+ elementApi.environment.output[resultVariable] = output;
246
+ }
247
+
248
+ return result;
249
+ }
250
+
251
+ }
252
+
253
+ function getExtensions(element, context) {
254
+ var _element$behaviour$ex, _ext$values, _ext$fields;
255
+
256
+ const result = {
257
+ format: element.type === 'bpmn:Process' ? new FormatProcess(element) : new FormatActivity(element)
258
+ };
259
+ const expression = element.behaviour.expression;
260
+ if (expression) result.Service = _ServiceExpression.default;
261
+ const extensions = (_element$behaviour$ex = element.behaviour.extensionElements) === null || _element$behaviour$ex === void 0 ? void 0 : _element$behaviour$ex.values;
262
+ if (!extensions) return result;
263
+
264
+ for (const ext of extensions) {
265
+ switch (ext.$type) {
266
+ case 'camunda:Properties':
267
+ if ((_ext$values = ext.values) !== null && _ext$values !== void 0 && _ext$values.length) result.properties = new _IOProperties.default(element, ext);
268
+ break;
269
+
270
+ case 'camunda:InputOutput':
271
+ result.io = new _IO.InputOutput(element.id, ext, context);
272
+ break;
273
+
274
+ case 'camunda:FormData':
275
+ if ((_ext$fields = ext.fields) !== null && _ext$fields !== void 0 && _ext$fields.length) result.form = new _IOForm.default(element, ext);
276
+ break;
277
+
278
+ case 'camunda:Connector':
279
+ {
280
+ const {
281
+ connectorId,
282
+ inputOutput
283
+ } = ext;
284
+ const io = inputOutput && new _IO.InputOutput(`${element.id}/${ext.$type.toLowerCase()}`, inputOutput, context);
285
+ result.Service = _Connector.default.bind(_Connector.default, connectorId, io);
286
+ break;
287
+ }
288
+ }
289
+ }
290
+
291
+ return result;
292
+ }
293
+
294
+ class FormatActivity {
295
+ constructor(activity) {
296
+ this.activity = activity;
297
+ this.resultVariable = activity.behaviour.resultVariable || '_' + activity.id;
298
+ let timeCycles;
299
+
300
+ if (activity.eventDefinitions) {
301
+ for (const ed of activity.eventDefinitions.filter(e => e.type === 'bpmn:TimerEventDefinition')) {
302
+ if (!('timeCycle' in ed)) continue;
303
+ timeCycles = timeCycles || [];
304
+ timeCycles.push(ed.timeCycle);
305
+ }
306
+ }
307
+
308
+ this.timeCycles = timeCycles;
309
+ }
310
+
311
+ resolve(elementApi) {
312
+ var _documentation$, _user, _groups;
313
+
314
+ let user, groups, assigneeValue, description;
315
+ const activity = this.activity;
316
+ const {
317
+ documentation,
318
+ candidateUsers,
319
+ candidateGroups,
320
+ scheduledStart,
321
+ assignee
322
+ } = activity.behaviour;
323
+ if (candidateUsers) user = resolveAndSplit(elementApi, candidateUsers);
324
+ if (candidateGroups) groups = resolveAndSplit(elementApi, candidateGroups);
325
+ if (assignee) assigneeValue = elementApi.resolveExpression(assignee);
326
+ if (documentation) description = (_documentation$ = documentation[0]) === null || _documentation$ === void 0 ? void 0 : _documentation$.text;
327
+ let expireAt;
328
+ let timeCycles = this.timeCycles;
329
+
330
+ if (timeCycles) {
331
+ for (const cycle of timeCycles) {
332
+ const cron = elementApi.resolveExpression(cycle);
333
+ if (!cron) continue;
334
+
335
+ const expireAtDt = _cronParser.default.parseExpression(cron).next().toDate();
336
+
337
+ if (!expireAt || expireAtDt < expireAt) expireAt = expireAtDt;
338
+ }
339
+ }
340
+
341
+ return {
342
+ resultVariable: this.resultVariable,
343
+ ...(scheduledStart && activity.parent.type === 'bpmn:Process' ? {
344
+ scheduledStart
345
+ } : undefined),
346
+ ...(((_user = user) === null || _user === void 0 ? void 0 : _user.length) && {
347
+ candidateUsers: user
348
+ }),
349
+ ...(((_groups = groups) === null || _groups === void 0 ? void 0 : _groups.length) && {
350
+ candidateGroups: groups
351
+ }),
352
+ ...(!elementApi.content.description && description && {
353
+ description: elementApi.resolveExpression(description)
354
+ }),
355
+ ...(expireAt && {
356
+ expireAt
357
+ }),
358
+ ...(assigneeValue && {
359
+ assignee: assigneeValue
360
+ })
361
+ };
362
+ }
363
+
364
+ }
365
+
366
+ class FormatProcess {
367
+ constructor(bp) {
368
+ this.process = bp;
369
+ }
370
+
371
+ resolve(elementApi) {
372
+ var _documentation$2, _user2, _groups2;
373
+
374
+ let user, groups, description;
375
+ const bp = this.process;
376
+ const {
377
+ documentation,
378
+ candidateStarterUsers,
379
+ candidateStarterGroups
380
+ } = bp.behaviour;
381
+ if (candidateStarterUsers) user = resolveAndSplit(elementApi, candidateStarterUsers);
382
+ if (candidateStarterGroups) groups = resolveAndSplit(elementApi, candidateStarterGroups);
383
+ if (documentation) description = (_documentation$2 = documentation[0]) === null || _documentation$2 === void 0 ? void 0 : _documentation$2.text;
384
+ return {
385
+ resultVariable: this.resultVariable,
386
+ ...(((_user2 = user) === null || _user2 === void 0 ? void 0 : _user2.length) && {
387
+ candidateStarterUsers: user
388
+ }),
389
+ ...(((_groups2 = groups) === null || _groups2 === void 0 ? void 0 : _groups2.length) && {
390
+ candidateStarterGroups: groups
391
+ }),
392
+ ...(!elementApi.content.description && description && {
393
+ description: elementApi.resolveExpression(description)
394
+ })
395
+ };
396
+ }
397
+
398
+ }
399
+
400
+ function resolveAndSplit(elementApi, str) {
401
+ if (Array.isArray(str)) return str.filter(Boolean);
402
+ if (typeof str !== 'string') return;
403
+ const resolved = elementApi.resolveExpression(str);
404
+ if (Array.isArray(resolved)) return resolved.filter(Boolean);
405
+ if (typeof resolved !== 'string') return;
406
+ return resolved.split(',').map(g => g.trim && g.trim().toLowerCase()).filter(Boolean);
407
+ }
408
+
409
+ function extendFn(behaviour, context) {
410
+ var _behaviour$extensionE;
411
+
412
+ if (behaviour.$type === 'bpmn:StartEvent' && behaviour.eventDefinitions) {
413
+ const timer = behaviour.eventDefinitions.find(({
414
+ type,
415
+ behaviour: edBehaviour
416
+ }) => edBehaviour && type === 'bpmn:TimerEventDefinition');
417
+ if (timer && timer.behaviour.timeCycle) Object.assign(behaviour, {
418
+ scheduledStart: timer.behaviour.timeCycle
419
+ });
420
+ }
421
+
422
+ if (!Array.isArray((_behaviour$extensionE = behaviour.extensionElements) === null || _behaviour$extensionE === void 0 ? void 0 : _behaviour$extensionE.values)) return;
423
+ const inputOutput = behaviour.extensionElements.values.find(el => el.$type === 'camunda:InputOutput');
424
+ const connector = behaviour.extensionElements.values.find(el => el.$type === 'camunda:Connector');
425
+ if (inputOutput) registerIOScripts(behaviour.id, context, inputOutput.$type, inputOutput);
426
+ if (connector) registerIOScripts(behaviour.id, context, connector.$type, connector.inputOutput);
427
+ }
428
+
429
+ function registerIOScripts(parentId, context, type, ioBehaviour) {
430
+ if (!ioBehaviour) return;
431
+ const {
432
+ inputParameters = [],
433
+ outputParameters = []
434
+ } = ioBehaviour;
435
+
436
+ for (const {
437
+ $type,
438
+ name,
439
+ definition
440
+ } of inputParameters.concat(outputParameters)) {
441
+ if (!definition) continue;
442
+ if (definition.$type !== 'camunda:Script') continue;
443
+ const filename = `${parentId}/${type}/${$type}/${name}`;
444
+ context.addScript(filename, {
445
+ id: filename,
446
+ scriptFormat: definition.scriptFormat,
447
+ ...(definition.value ? {
448
+ body: definition.value
449
+ } : undefined),
450
+ ...(definition.resource ? {
451
+ resource: definition.resource
452
+ } : undefined)
453
+ });
454
+ }
455
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = Connector;
7
+
8
+ class NotImplemented extends Error {
9
+ constructor(serviceId) {
10
+ super(`${serviceId} service function not found`);
11
+ this.code = 'EFLOW_NOT_IMPLEMENTED';
12
+ this.output = {
13
+ statusCode: 501
14
+ };
15
+ }
16
+
17
+ }
18
+
19
+ function Connector(connectorId, io, activity, executionMessage) {
20
+ if (!(this instanceof Connector)) return new Connector(connectorId, io, activity, executionMessage);
21
+ this.connectorId = connectorId;
22
+ this.io = io;
23
+ this.activity = activity;
24
+ this.executionMessage = executionMessage;
25
+ }
26
+
27
+ Connector.prototype.execute = async function execute(...args) {
28
+ const callback = args.pop();
29
+ args.push(formatCallback);
30
+ const activity = this.activity;
31
+ const io = this.io;
32
+ const environment = activity.environment;
33
+ const connectorId = this.connectorId;
34
+ const executionMessage = this.executionMessage;
35
+ const serviceFunction = environment.services[connectorId];
36
+ if (!serviceFunction) return callback(new NotImplemented(connectorId));
37
+
38
+ try {
39
+ const input = io && (await io.getInput(activity, executionMessage));
40
+ await serviceFunction.call(activity, input, ...args);
41
+ } catch (err) {
42
+ return callback(err);
43
+ }
44
+
45
+ async function formatCallback(serviceErr, result) {
46
+ if (serviceErr) return callback(serviceErr);
47
+ if (!(io !== null && io !== void 0 && io.output.length)) return callback(null, result);
48
+
49
+ try {
50
+ const formattedResult = await io.getOutput(activity, { ...executionMessage,
51
+ ...result
52
+ });
53
+ return callback(null, formattedResult);
54
+ } catch (err) {
55
+ return callback(err);
56
+ }
57
+ }
58
+ };