@emaarco/bpmn-js-data-simulation 0.0.0-stage → 0.1.0

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.
Files changed (71) hide show
  1. package/README.md +98 -2
  2. package/dist/assets/bpmn-js-data-simulation.css +127 -0
  3. package/dist/domain/model.d.ts +32 -0
  4. package/dist/domain/model.d.ts.map +1 -0
  5. package/dist/domain/routing.d.ts +4 -0
  6. package/dist/domain/routing.d.ts.map +1 -0
  7. package/dist/domain/scenario.d.ts +13 -0
  8. package/dist/domain/scenario.d.ts.map +1 -0
  9. package/dist/domain/startFields.d.ts +31 -0
  10. package/dist/domain/startFields.d.ts.map +1 -0
  11. package/dist/domain/variables.d.ts +4 -0
  12. package/dist/domain/variables.d.ts.map +1 -0
  13. package/dist/engines/camunda7/camunda7Engine.d.ts +3 -0
  14. package/dist/engines/camunda7/camunda7Engine.d.ts.map +1 -0
  15. package/dist/engines/camunda7/juel.d.ts +32 -0
  16. package/dist/engines/camunda7/juel.d.ts.map +1 -0
  17. package/dist/engines/index.d.ts +7 -0
  18. package/dist/engines/index.d.ts.map +1 -0
  19. package/dist/engines/moddle.d.ts +8 -0
  20. package/dist/engines/moddle.d.ts.map +1 -0
  21. package/dist/engines/types.d.ts +21 -0
  22. package/dist/engines/types.d.ts.map +1 -0
  23. package/dist/engines/zeebe/zeebeEngine.d.ts +3 -0
  24. package/dist/engines/zeebe/zeebeEngine.d.ts.map +1 -0
  25. package/dist/index.cjs +1965 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.ts +13 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +1951 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/integration/DataGateways.d.ts +20 -0
  32. package/dist/integration/DataGateways.d.ts.map +1 -0
  33. package/dist/integration/DataSimulation.d.ts +34 -0
  34. package/dist/integration/DataSimulation.d.ts.map +1 -0
  35. package/dist/integration/DataSimulationOverlays.d.ts +23 -0
  36. package/dist/integration/DataSimulationOverlays.d.ts.map +1 -0
  37. package/dist/integration/DataSimulationPanel.d.ts +11 -0
  38. package/dist/integration/DataSimulationPanel.d.ts.map +1 -0
  39. package/dist/integration/DataSimulationToggle.d.ts +11 -0
  40. package/dist/integration/DataSimulationToggle.d.ts.map +1 -0
  41. package/dist/integration/DataStartForm.d.ts +18 -0
  42. package/dist/integration/DataStartForm.d.ts.map +1 -0
  43. package/dist/integration/behaviors/DataContextPads.d.ts +24 -0
  44. package/dist/integration/behaviors/DataContextPads.d.ts.map +1 -0
  45. package/dist/integration/behaviors/DataGatewayBehaviors.d.ts +11 -0
  46. package/dist/integration/behaviors/DataGatewayBehaviors.d.ts.map +1 -0
  47. package/dist/integration/behaviors/DataGatewaySettings.d.ts +16 -0
  48. package/dist/integration/behaviors/DataGatewaySettings.d.ts.map +1 -0
  49. package/dist/integration/index.d.ts +7 -0
  50. package/dist/integration/index.d.ts.map +1 -0
  51. package/dist/integration/tokenSimulation.d.ts +98 -0
  52. package/dist/integration/tokenSimulation.d.ts.map +1 -0
  53. package/dist/simulation/DataSimulationStore.d.ts +85 -0
  54. package/dist/simulation/DataSimulationStore.d.ts.map +1 -0
  55. package/dist/ui/SimpleStartForm.d.ts +3 -0
  56. package/dist/ui/SimpleStartForm.d.ts.map +1 -0
  57. package/dist/ui/StartDialog.d.ts +16 -0
  58. package/dist/ui/StartDialog.d.ts.map +1 -0
  59. package/dist/ui/VariablesPanel.d.ts +30 -0
  60. package/dist/ui/VariablesPanel.d.ts.map +1 -0
  61. package/dist/ui/dom.d.ts +5 -0
  62. package/dist/ui/dom.d.ts.map +1 -0
  63. package/dist/ui/overlayContent.d.ts +5 -0
  64. package/dist/ui/overlayContent.d.ts.map +1 -0
  65. package/dist/ui/popoverPlacement.d.ts +18 -0
  66. package/dist/ui/popoverPlacement.d.ts.map +1 -0
  67. package/dist/ui/shadow.d.ts +2 -0
  68. package/dist/ui/shadow.d.ts.map +1 -0
  69. package/dist/ui/startForm.d.ts +18 -0
  70. package/dist/ui/startForm.d.ts.map +1 -0
  71. package/package.json +85 -4
package/dist/index.js ADDED
@@ -0,0 +1,1951 @@
1
+ import { parseExpression, evaluate } from 'feelin';
2
+
3
+ function routeGateway(kind, outgoing, evaluateCondition) {
4
+ const conditional = outgoing.filter(flow => !flow.isDefault);
5
+ const defaultFlow = outgoing.find(flow => flow.isDefault);
6
+ const evaluations = [];
7
+ for (const flow of conditional) {
8
+ const alreadyDecided = kind === 'exclusive' && evaluations.some(isDecisive);
9
+ evaluations.push(alreadyDecided ? { flow, outcome: 'skipped' } : evaluateFlow(flow, evaluateCondition));
10
+ }
11
+ const failed = evaluations.find(evaluation => evaluation.outcome === 'error');
12
+ if (failed) {
13
+ return stuck(evaluations, defaultFlow, `Condition of "${failed.flow.name ?? failed.flow.id}" failed: ${failed.reason}`);
14
+ }
15
+ const taken = evaluations.filter(evaluation => evaluation.outcome === 'taken');
16
+ if (taken.length) {
17
+ return withDefault(evaluations, defaultFlow, 'not-taken', taken.map(evaluation => evaluation.flow.id));
18
+ }
19
+ if (defaultFlow) {
20
+ return withDefault(evaluations, defaultFlow, 'taken', [defaultFlow.id]);
21
+ }
22
+ return stuck(evaluations, defaultFlow, 'No condition is true and there is no default flow');
23
+ }
24
+ function evaluateFlow(flow, evaluateCondition) {
25
+ if (flow.expression === undefined) {
26
+ return { flow, outcome: 'error', reason: 'Missing condition' };
27
+ }
28
+ const evaluation = evaluateCondition(flow.expression);
29
+ if (!evaluation.ok) {
30
+ return { flow, outcome: 'error', reason: evaluation.reason };
31
+ }
32
+ if (typeof evaluation.value !== 'boolean') {
33
+ return {
34
+ flow,
35
+ outcome: 'error',
36
+ value: evaluation.value,
37
+ reason: `Expected a boolean but got ${describe(evaluation.value)}`,
38
+ };
39
+ }
40
+ return { flow, outcome: evaluation.value ? 'taken' : 'not-taken', value: evaluation.value };
41
+ }
42
+ function isDecisive(evaluation) {
43
+ return evaluation.outcome === 'taken' || evaluation.outcome === 'error';
44
+ }
45
+ function withDefault(evaluations, defaultFlow, defaultOutcome, takenFlowIds) {
46
+ const flows = defaultFlow ? [...evaluations, { flow: defaultFlow, outcome: defaultOutcome }] : evaluations;
47
+ return { flows, takenFlowIds };
48
+ }
49
+ function stuck(evaluations, defaultFlow, stuckReason) {
50
+ return { ...withDefault(evaluations, defaultFlow, 'skipped', []), stuckReason };
51
+ }
52
+ function describe(value) {
53
+ if (value === null || value === undefined)
54
+ return 'null';
55
+ return `${typeof value} ${JSON.stringify(value)}`;
56
+ }
57
+
58
+ function setVariable(variables, path, value) {
59
+ const [head, ...rest] = path.split('.');
60
+ if (!rest.length) {
61
+ return { ...variables, [head]: value };
62
+ }
63
+ const nested = variables[head];
64
+ const nestedVariables = isVariables(nested) ? nested : {};
65
+ return { ...variables, [head]: setVariable(nestedVariables, rest.join('.'), value) };
66
+ }
67
+ function isVariables(value) {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
69
+ }
70
+
71
+ class ScenarioError extends Error {
72
+ constructor() {
73
+ super(...arguments);
74
+ this.name = 'ScenarioError';
75
+ }
76
+ }
77
+ function parseScenarios(input) {
78
+ const list = isVariables(input) ? input.scenarios : input;
79
+ if (!Array.isArray(list)) {
80
+ throw new ScenarioError('Expected an array of scenarios or an object with a "scenarios" array');
81
+ }
82
+ const scenarios = list.map(parseScenario);
83
+ assertUniqueIds(scenarios);
84
+ return scenarios;
85
+ }
86
+ function parseScenario(raw, index) {
87
+ if (!isVariables(raw)) {
88
+ throw new ScenarioError(`Scenario #${index + 1} must be an object`);
89
+ }
90
+ const { id, name, description, variables = {}, taskResults = {} } = raw;
91
+ const label = typeof id === 'string' ? `"${id}"` : `#${index + 1}`;
92
+ if (typeof id !== 'string' || !id) {
93
+ throw new ScenarioError(`Scenario ${label} needs a non-empty string "id"`);
94
+ }
95
+ if (name !== undefined && typeof name !== 'string') {
96
+ throw new ScenarioError(`Scenario ${label}: "name" must be a string`);
97
+ }
98
+ if (description !== undefined && typeof description !== 'string') {
99
+ throw new ScenarioError(`Scenario ${label}: "description" must be a string`);
100
+ }
101
+ if (!isVariables(variables)) {
102
+ throw new ScenarioError(`Scenario ${label}: "variables" must be an object`);
103
+ }
104
+ if (!isVariables(taskResults) || !Object.values(taskResults).every(isVariables)) {
105
+ throw new ScenarioError(`Scenario ${label}: "taskResults" must map element ids to objects`);
106
+ }
107
+ return {
108
+ id,
109
+ name: name ?? id,
110
+ ...(description === undefined ? {} : { description }),
111
+ variables,
112
+ taskResults: taskResults,
113
+ };
114
+ }
115
+ function assertUniqueIds(scenarios) {
116
+ const seen = new Set();
117
+ for (const { id } of scenarios) {
118
+ if (seen.has(id)) {
119
+ throw new ScenarioError(`Duplicate scenario id "${id}"`);
120
+ }
121
+ seen.add(id);
122
+ }
123
+ }
124
+
125
+ function deriveStartFields(usages, { examples = [], taskResultNames = [] } = {}) {
126
+ const written = new Set([...usages.flatMap(usage => usage.outputTargets.map(topLevelName)), ...taskResultNames]);
127
+ const usedBy = new Map();
128
+ for (const usage of usages) {
129
+ const localNames = new Set(usage.inputTargets.map(topLevelName));
130
+ for (const name of [...usage.conditionReads, ...usage.inputReads, ...usage.outputReads]) {
131
+ if (written.has(name) || localNames.has(name))
132
+ continue;
133
+ if (!usedBy.has(name))
134
+ usedBy.set(name, new Set());
135
+ usedBy.get(name).add(usage.elementName);
136
+ }
137
+ }
138
+ return [...usedBy.entries()].map(([name, elements]) => ({
139
+ name,
140
+ type: inferType(examples.map(example => example[name]).find(value => value !== undefined)),
141
+ usedBy: [...elements],
142
+ }));
143
+ }
144
+ function parseFieldValue(field, raw) {
145
+ if (typeof raw === 'boolean')
146
+ return { ok: true, value: raw };
147
+ const text = raw.trim();
148
+ if (!text)
149
+ return { ok: true, value: undefined };
150
+ switch (field.type) {
151
+ case 'number': {
152
+ const value = Number(text);
153
+ return Number.isNaN(value) ? { ok: false, reason: `${field.name} must be a number` } : { ok: true, value };
154
+ }
155
+ case 'json':
156
+ try {
157
+ return { ok: true, value: JSON.parse(text) };
158
+ }
159
+ catch {
160
+ return { ok: false, reason: `${field.name} must be valid JSON` };
161
+ }
162
+ case 'auto':
163
+ try {
164
+ return { ok: true, value: JSON.parse(text) };
165
+ }
166
+ catch {
167
+ return { ok: true, value: raw };
168
+ }
169
+ default:
170
+ return { ok: true, value: raw };
171
+ }
172
+ }
173
+ function formatFieldValue(field, value) {
174
+ if (field.type === 'boolean')
175
+ return value === true;
176
+ if (value === undefined || value === null)
177
+ return '';
178
+ if (typeof value === 'string' && field.type !== 'json')
179
+ return value;
180
+ return field.type === 'number' ? String(value) : JSON.stringify(value);
181
+ }
182
+ function applyFieldValues(base, values) {
183
+ const variables = { ...base };
184
+ for (const [name, value] of Object.entries(values)) {
185
+ if (value === undefined)
186
+ delete variables[name];
187
+ else
188
+ variables[name] = value;
189
+ }
190
+ return variables;
191
+ }
192
+ function topLevelName(path) {
193
+ return path.split('.')[0];
194
+ }
195
+ function inferType(example) {
196
+ if (typeof example === 'number')
197
+ return 'number';
198
+ if (typeof example === 'boolean')
199
+ return 'boolean';
200
+ if (typeof example === 'string')
201
+ return 'text';
202
+ if (Array.isArray(example) || isVariables(example))
203
+ return 'json';
204
+ return 'auto';
205
+ }
206
+
207
+ function findExtension(element, type) {
208
+ const extensionElements = element.extensionElements;
209
+ return extensionElements?.values?.find(value => value.$type === type);
210
+ }
211
+ function listProperty(element, property) {
212
+ const value = element?.[property];
213
+ return Array.isArray(value) ? value : [];
214
+ }
215
+ function readConditionExpression(sequenceFlow) {
216
+ const condition = sequenceFlow.conditionExpression;
217
+ if (!condition)
218
+ return undefined;
219
+ return {
220
+ body: typeof condition.body === 'string' ? condition.body : undefined,
221
+ language: typeof condition.language === 'string' ? condition.language : undefined,
222
+ };
223
+ }
224
+
225
+ class JuelError extends Error {
226
+ constructor() {
227
+ super(...arguments);
228
+ this.name = 'JuelError';
229
+ }
230
+ }
231
+ const KEYWORD_OPERATORS = {
232
+ and: '&&',
233
+ or: '||',
234
+ not: '!',
235
+ eq: '==',
236
+ ne: '!=',
237
+ lt: '<',
238
+ gt: '>',
239
+ le: '<=',
240
+ ge: '>=',
241
+ div: '/',
242
+ mod: '%',
243
+ empty: 'empty',
244
+ };
245
+ const SYMBOL_OPERATORS = [
246
+ '==',
247
+ '!=',
248
+ '<=',
249
+ '>=',
250
+ '&&',
251
+ '||',
252
+ '<',
253
+ '>',
254
+ '!',
255
+ '+',
256
+ '-',
257
+ '*',
258
+ '/',
259
+ '%',
260
+ '(',
261
+ ')',
262
+ '[',
263
+ ']',
264
+ '.',
265
+ '?',
266
+ ':',
267
+ ];
268
+ function parseJuelTemplate(text) {
269
+ const parts = [];
270
+ let cursor = 0;
271
+ while (cursor < text.length) {
272
+ const start = findExpressionStart(text, cursor);
273
+ if (start === -1) {
274
+ parts.push(text.slice(cursor));
275
+ break;
276
+ }
277
+ if (start > cursor)
278
+ parts.push(text.slice(cursor, start));
279
+ const end = findExpressionEnd(text, start + 2);
280
+ parts.push(parseJuelExpression(text.slice(start + 2, end)));
281
+ cursor = end + 1;
282
+ }
283
+ return parts;
284
+ }
285
+ function evaluateJuelTemplate(template, variables) {
286
+ if (template.length === 1 && typeof template[0] !== 'string') {
287
+ return evaluateNode(template[0], variables);
288
+ }
289
+ return template
290
+ .map(part => (typeof part === 'string' ? part : coerceToString(evaluateNode(part, variables))))
291
+ .join('');
292
+ }
293
+ function readJuelVariableNames(template) {
294
+ const names = new Set();
295
+ const visit = (node) => {
296
+ if (node.type === 'identifier')
297
+ names.add(node.name);
298
+ if (node.type === 'member') {
299
+ visit(node.object);
300
+ visit(node.property);
301
+ }
302
+ if (node.type === 'unary')
303
+ visit(node.operand);
304
+ if (node.type === 'binary') {
305
+ visit(node.left);
306
+ visit(node.right);
307
+ }
308
+ if (node.type === 'conditional') {
309
+ visit(node.test);
310
+ visit(node.consequent);
311
+ visit(node.alternate);
312
+ }
313
+ };
314
+ template.forEach(part => typeof part !== 'string' && visit(part));
315
+ return [...names];
316
+ }
317
+ function findExpressionStart(text, from) {
318
+ const dollar = text.indexOf('${', from);
319
+ const hash = text.indexOf('#{', from);
320
+ if (dollar === -1)
321
+ return hash;
322
+ if (hash === -1)
323
+ return dollar;
324
+ return Math.min(dollar, hash);
325
+ }
326
+ function findExpressionEnd(text, from) {
327
+ let quote = null;
328
+ for (let index = from; index < text.length; index++) {
329
+ const char = text[index];
330
+ if (quote) {
331
+ if (char === '\\')
332
+ index++;
333
+ else if (char === quote)
334
+ quote = null;
335
+ }
336
+ else if (char === "'" || char === '"') {
337
+ quote = char;
338
+ }
339
+ else if (char === '}') {
340
+ return index;
341
+ }
342
+ }
343
+ throw new JuelError('Unterminated expression, missing "}"');
344
+ }
345
+ function parseJuelExpression(source) {
346
+ const parser = new Parser(tokenize(source));
347
+ const node = parser.parseExpression();
348
+ parser.expectEnd();
349
+ return node;
350
+ }
351
+ function tokenize(source) {
352
+ const tokens = [];
353
+ let index = 0;
354
+ while (index < source.length) {
355
+ const char = source[index];
356
+ if (/\s/.test(char)) {
357
+ index++;
358
+ }
359
+ else if (/[0-9]/.test(char) || (char === '.' && /[0-9]/.test(source[index + 1] ?? ''))) {
360
+ const match = /^[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/.exec(source.slice(index));
361
+ tokens.push({ kind: 'number', text: match[0], value: Number(match[0]) });
362
+ index += match[0].length;
363
+ }
364
+ else if (char === "'" || char === '"') {
365
+ const { value, length } = readString(source, index);
366
+ tokens.push({ kind: 'string', text: source.slice(index, index + length), value });
367
+ index += length;
368
+ }
369
+ else if (/[A-Za-z_$]/.test(char)) {
370
+ const match = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(source.slice(index));
371
+ const word = match[0];
372
+ const keywordOperator = hasOwn(KEYWORD_OPERATORS, word) ? KEYWORD_OPERATORS[word] : undefined;
373
+ tokens.push(keywordOperator ? { kind: 'operator', text: keywordOperator } : { kind: 'identifier', text: word });
374
+ index += word.length;
375
+ }
376
+ else {
377
+ const operator = SYMBOL_OPERATORS.find(candidate => source.startsWith(candidate, index));
378
+ if (!operator)
379
+ throw new JuelError(`Unexpected character "${char}"`);
380
+ tokens.push({ kind: 'operator', text: operator });
381
+ index += operator.length;
382
+ }
383
+ }
384
+ return tokens;
385
+ }
386
+ function readString(source, start) {
387
+ const quote = source[start];
388
+ let value = '';
389
+ for (let index = start + 1; index < source.length; index++) {
390
+ const char = source[index];
391
+ if (char === '\\') {
392
+ value += source[index + 1] ?? '';
393
+ index++;
394
+ }
395
+ else if (char === quote) {
396
+ return { value, length: index - start + 1 };
397
+ }
398
+ else {
399
+ value += char;
400
+ }
401
+ }
402
+ throw new JuelError('Unterminated string literal');
403
+ }
404
+ class Parser {
405
+ constructor(tokens) {
406
+ this.tokens = tokens;
407
+ this.position = 0;
408
+ }
409
+ parseExpression() {
410
+ const test = this.parseBinary(0);
411
+ if (!this.accept('?'))
412
+ return test;
413
+ const consequent = this.parseExpression();
414
+ this.expect(':');
415
+ const alternate = this.parseExpression();
416
+ return { type: 'conditional', test, consequent, alternate };
417
+ }
418
+ expectEnd() {
419
+ const token = this.peek();
420
+ if (token)
421
+ throw new JuelError(`Unexpected "${token.text}"`);
422
+ }
423
+ parseBinary(level) {
424
+ if (level === Parser.PRECEDENCE.length)
425
+ return this.parseUnary();
426
+ let left = this.parseBinary(level + 1);
427
+ let operator = this.acceptAny(Parser.PRECEDENCE[level]);
428
+ while (operator) {
429
+ const right = this.parseBinary(level + 1);
430
+ left = { type: 'binary', operator, left, right };
431
+ operator = this.acceptAny(Parser.PRECEDENCE[level]);
432
+ }
433
+ return left;
434
+ }
435
+ parseUnary() {
436
+ const operator = this.acceptAny(['!', '-', 'empty']);
437
+ if (operator)
438
+ return { type: 'unary', operator, operand: this.parseUnary() };
439
+ return this.parseMember();
440
+ }
441
+ parseMember() {
442
+ let node = this.parsePrimary();
443
+ for (;;) {
444
+ if (this.accept('.')) {
445
+ const property = this.next();
446
+ if (property?.kind !== 'identifier')
447
+ throw new JuelError('Expected a property name after "."');
448
+ node = { type: 'member', object: node, property: { type: 'literal', value: property.text } };
449
+ }
450
+ else if (this.accept('[')) {
451
+ node = { type: 'member', object: node, property: this.parseExpression() };
452
+ this.expect(']');
453
+ }
454
+ else if (this.peek()?.text === '(') {
455
+ throw new JuelError('Method calls are not supported');
456
+ }
457
+ else {
458
+ return node;
459
+ }
460
+ }
461
+ }
462
+ parsePrimary() {
463
+ const token = this.next();
464
+ if (!token)
465
+ throw new JuelError('Unexpected end of expression');
466
+ if (token.kind === 'number' || token.kind === 'string')
467
+ return { type: 'literal', value: token.value };
468
+ if (token.kind === 'identifier')
469
+ return identifierOrLiteral(token.text);
470
+ if (token.text === '(') {
471
+ const node = this.parseExpression();
472
+ this.expect(')');
473
+ return node;
474
+ }
475
+ throw new JuelError(`Unexpected "${token.text}"`);
476
+ }
477
+ peek() {
478
+ return this.tokens[this.position];
479
+ }
480
+ next() {
481
+ return this.tokens[this.position++];
482
+ }
483
+ accept(text) {
484
+ if (this.peek()?.kind !== 'operator' || this.peek()?.text !== text)
485
+ return false;
486
+ this.position++;
487
+ return true;
488
+ }
489
+ acceptAny(operators) {
490
+ return operators.find(operator => this.accept(operator));
491
+ }
492
+ expect(text) {
493
+ if (!this.accept(text))
494
+ throw new JuelError(`Expected "${text}"`);
495
+ }
496
+ }
497
+ Parser.PRECEDENCE = [
498
+ ['||'],
499
+ ['&&'],
500
+ ['==', '!='],
501
+ ['<', '>', '<=', '>='],
502
+ ['+', '-'],
503
+ ['*', '/', '%'],
504
+ ];
505
+ function identifierOrLiteral(name) {
506
+ if (name === 'true')
507
+ return { type: 'literal', value: true };
508
+ if (name === 'false')
509
+ return { type: 'literal', value: false };
510
+ if (name === 'null')
511
+ return { type: 'literal', value: null };
512
+ return { type: 'identifier', name };
513
+ }
514
+ function evaluateNode(node, variables) {
515
+ switch (node.type) {
516
+ case 'literal':
517
+ return node.value;
518
+ case 'identifier':
519
+ if (!hasOwn(variables, node.name))
520
+ throw new JuelError(`Unknown property used in expression: ${node.name}`);
521
+ return variables[node.name];
522
+ case 'member':
523
+ return readMember(evaluateNode(node.object, variables), evaluateNode(node.property, variables));
524
+ case 'unary':
525
+ return evaluateUnary(node.operator, evaluateNode(node.operand, variables));
526
+ case 'conditional':
527
+ return coerceToBoolean(evaluateNode(node.test, variables))
528
+ ? evaluateNode(node.consequent, variables)
529
+ : evaluateNode(node.alternate, variables);
530
+ case 'binary':
531
+ return evaluateBinary(node, variables);
532
+ }
533
+ }
534
+ function readMember(object, property) {
535
+ if (object === null || object === undefined)
536
+ return null;
537
+ const key = Array.isArray(object) ? Number(property) : String(property);
538
+ return hasOwn(object, key) ? (object[key] ?? null) : null;
539
+ }
540
+ function hasOwn(object, key) {
541
+ return Object.prototype.hasOwnProperty.call(object, key);
542
+ }
543
+ function evaluateUnary(operator, operand) {
544
+ if (operator === '!')
545
+ return !coerceToBoolean(operand);
546
+ if (operator === '-')
547
+ return -coerceToNumber(operand);
548
+ return isEmpty(operand);
549
+ }
550
+ function evaluateBinary(node, variables) {
551
+ const { operator } = node;
552
+ if (operator === '&&') {
553
+ return coerceToBoolean(evaluateNode(node.left, variables)) && coerceToBoolean(evaluateNode(node.right, variables));
554
+ }
555
+ if (operator === '||') {
556
+ return coerceToBoolean(evaluateNode(node.left, variables)) || coerceToBoolean(evaluateNode(node.right, variables));
557
+ }
558
+ const left = evaluateNode(node.left, variables);
559
+ const right = evaluateNode(node.right, variables);
560
+ switch (operator) {
561
+ case '==':
562
+ return areEqual(left, right);
563
+ case '!=':
564
+ return !areEqual(left, right);
565
+ case '<':
566
+ return isNull(left) || isNull(right) ? false : compare(left, right) < 0;
567
+ case '>':
568
+ return isNull(left) || isNull(right) ? false : compare(left, right) > 0;
569
+ case '<=':
570
+ return isNull(left) || isNull(right) ? isNull(left) && isNull(right) : compare(left, right) <= 0;
571
+ case '>=':
572
+ return isNull(left) || isNull(right) ? isNull(left) && isNull(right) : compare(left, right) >= 0;
573
+ case '+':
574
+ return coerceToNumber(left) + coerceToNumber(right);
575
+ case '-':
576
+ return coerceToNumber(left) - coerceToNumber(right);
577
+ case '*':
578
+ return coerceToNumber(left) * coerceToNumber(right);
579
+ case '/':
580
+ return coerceToNumber(left) / coerceToNumber(right);
581
+ default:
582
+ return coerceToNumber(left) % coerceToNumber(right);
583
+ }
584
+ }
585
+ function isNull(value) {
586
+ return value === null || value === undefined;
587
+ }
588
+ function areEqual(left, right) {
589
+ if (left === right)
590
+ return true;
591
+ if (isNull(left) || isNull(right))
592
+ return isNull(left) && isNull(right);
593
+ if (typeof left === 'number' || typeof right === 'number')
594
+ return coerceToNumber(left) === coerceToNumber(right);
595
+ if (typeof left === 'boolean' || typeof right === 'boolean')
596
+ return coerceToBoolean(left) === coerceToBoolean(right);
597
+ if (typeof left === 'object' || typeof right === 'object')
598
+ return deepEqual(left, right);
599
+ return String(left) === String(right);
600
+ }
601
+ function deepEqual(left, right) {
602
+ if (left === right)
603
+ return true;
604
+ if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null)
605
+ return false;
606
+ if (Array.isArray(left) !== Array.isArray(right))
607
+ return false;
608
+ const leftKeys = Object.keys(left);
609
+ const rightKeys = Object.keys(right);
610
+ return (leftKeys.length === rightKeys.length &&
611
+ leftKeys.every(key => hasOwn(right, key) &&
612
+ deepEqual(left[key], right[key])));
613
+ }
614
+ function compare(left, right) {
615
+ if (typeof left === 'string' && typeof right === 'string')
616
+ return left < right ? -1 : left > right ? 1 : 0;
617
+ return coerceToNumber(left) - coerceToNumber(right);
618
+ }
619
+ function coerceToNumber(value) {
620
+ if (value === null || value === undefined || value === '')
621
+ return 0;
622
+ const number = typeof value === 'number' ? value : Number(value);
623
+ if (typeof value === 'boolean' || Number.isNaN(number)) {
624
+ throw new JuelError(`Cannot coerce ${JSON.stringify(value)} to a number`);
625
+ }
626
+ return number;
627
+ }
628
+ function coerceToBoolean(value) {
629
+ if (typeof value === 'boolean')
630
+ return value;
631
+ if (value === null || value === undefined || value === '')
632
+ return false;
633
+ if (typeof value === 'string')
634
+ return value.toLowerCase() === 'true';
635
+ throw new JuelError(`Cannot coerce ${JSON.stringify(value)} to a boolean`);
636
+ }
637
+ function coerceToString(value) {
638
+ if (value === null || value === undefined)
639
+ return '';
640
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
641
+ }
642
+ function isEmpty(value) {
643
+ if (value === null || value === undefined || value === '')
644
+ return true;
645
+ if (Array.isArray(value))
646
+ return value.length === 0;
647
+ if (typeof value === 'object')
648
+ return Object.keys(value).length === 0;
649
+ return false;
650
+ }
651
+
652
+ const camunda7Engine = {
653
+ id: 'camunda7',
654
+ label: 'Camunda 7',
655
+ expressionLanguage: 'JUEL',
656
+ taskResultPropagation: 'always',
657
+ writeVariable: (variables, target, value) => ({ ...variables, [target]: value }),
658
+ readInputMappings: element => readMappings$1(element, 'inputParameters'),
659
+ readOutputMappings: element => readMappings$1(element, 'outputParameters'),
660
+ readCondition,
661
+ canEvaluate,
662
+ evaluate: evaluateCamundaExpression,
663
+ readVariableNames: readVariableNames$1,
664
+ };
665
+ function readMappings$1(element, property) {
666
+ const inputOutput = findExtension(element, 'camunda:InputOutput');
667
+ return listProperty(inputOutput, property)
668
+ .filter(parameter => typeof parameter.name === 'string' && parameter.name && !parameter.definition)
669
+ .map(parameter => ({
670
+ source: typeof parameter.value === 'string' ? parameter.value : '',
671
+ target: parameter.name,
672
+ }));
673
+ }
674
+ function readCondition(sequenceFlow) {
675
+ const condition = readConditionExpression(sequenceFlow);
676
+ const isJuel = !condition?.language || condition.language.toLowerCase() === 'juel';
677
+ return isJuel ? condition?.body?.trim() || undefined : undefined;
678
+ }
679
+ function canEvaluate(expression) {
680
+ try {
681
+ parseJuelTemplate(expression);
682
+ return true;
683
+ }
684
+ catch {
685
+ return false;
686
+ }
687
+ }
688
+ function readVariableNames$1(expression) {
689
+ try {
690
+ return readJuelVariableNames(parseJuelTemplate(expression));
691
+ }
692
+ catch {
693
+ return [];
694
+ }
695
+ }
696
+ function evaluateCamundaExpression(expression, variables) {
697
+ if (!expression) {
698
+ return { ok: true, value: null };
699
+ }
700
+ try {
701
+ return { ok: true, value: evaluateJuelTemplate(parseJuelTemplate(expression), variables) };
702
+ }
703
+ catch (error) {
704
+ return { ok: false, reason: error.message };
705
+ }
706
+ }
707
+
708
+ const EXPRESSION_PREFIX = '=';
709
+ const zeebeEngine = {
710
+ id: 'zeebe',
711
+ label: 'Zeebe',
712
+ expressionLanguage: 'FEEL',
713
+ taskResultPropagation: 'without-output-mappings',
714
+ writeVariable: setVariable,
715
+ readInputMappings: element => readMappings(element, 'inputParameters'),
716
+ readOutputMappings: element => readMappings(element, 'outputParameters'),
717
+ readCondition: sequenceFlow => readConditionExpression(sequenceFlow)?.body?.trim() || undefined,
718
+ canEvaluate: expression => isFeel(expression) && parsesAsFeel(expression),
719
+ evaluate: evaluateZeebeExpression,
720
+ readVariableNames,
721
+ };
722
+ function readMappings(element, property) {
723
+ const ioMapping = findExtension(element, 'zeebe:IoMapping');
724
+ return listProperty(ioMapping, property)
725
+ .filter(parameter => typeof parameter.target === 'string' && parameter.target)
726
+ .map(parameter => ({ source: String(parameter.source ?? ''), target: parameter.target }));
727
+ }
728
+ function evaluateZeebeExpression(expression, variables) {
729
+ if (!isFeel(expression)) {
730
+ return { ok: true, value: expression };
731
+ }
732
+ try {
733
+ const { value, warnings } = evaluate(feelBody(expression), variables);
734
+ const missingVariable = warnings.find(warning => warning.type === 'NO_VARIABLE_FOUND');
735
+ if (value === null && missingVariable) {
736
+ return { ok: false, reason: missingVariable.message };
737
+ }
738
+ return { ok: true, value: toVariableValue(value) };
739
+ }
740
+ catch (error) {
741
+ return { ok: false, reason: `Invalid FEEL: ${error.message}` };
742
+ }
743
+ }
744
+ function readVariableNames(expression) {
745
+ if (!isFeel(expression))
746
+ return [];
747
+ const body = feelBody(expression);
748
+ const read = new Set();
749
+ const bound = new Set();
750
+ parseExpression(body, {}, undefined).iterate({
751
+ enter(node) {
752
+ const text = body.slice(node.from, node.to);
753
+ if (node.name === 'Name')
754
+ bound.add(text);
755
+ if (node.name !== 'VariableName')
756
+ return;
757
+ const isCallee = node.node.parent?.name === 'FunctionInvocation' && node.node.prevSibling === null;
758
+ if (!isCallee)
759
+ read.add(text);
760
+ },
761
+ });
762
+ return [...read].filter(name => !bound.has(name));
763
+ }
764
+ function toVariableValue(value) {
765
+ if (value === undefined)
766
+ return null;
767
+ return typeof value === 'object' && value !== null ? JSON.parse(JSON.stringify(value)) : value;
768
+ }
769
+ function parsesAsFeel(expression) {
770
+ try {
771
+ evaluate(feelBody(expression), {});
772
+ return true;
773
+ }
774
+ catch {
775
+ return false;
776
+ }
777
+ }
778
+ function isFeel(expression) {
779
+ return expression.trimStart().startsWith(EXPRESSION_PREFIX);
780
+ }
781
+ function feelBody(expression) {
782
+ return expression.trimStart().slice(EXPRESSION_PREFIX.length);
783
+ }
784
+
785
+ const ENGINES = {
786
+ zeebe: zeebeEngine,
787
+ camunda7: camunda7Engine,
788
+ };
789
+ function resolveEngine(engine) {
790
+ if (typeof engine !== 'string')
791
+ return engine;
792
+ const adapter = ENGINES[engine];
793
+ if (!adapter) {
794
+ throw new Error(`Unknown engine "${engine}", expected one of: ${Object.keys(ENGINES).join(', ')}`);
795
+ }
796
+ return adapter;
797
+ }
798
+
799
+ class DataSimulationStore {
800
+ constructor() {
801
+ this.engineLabel = '';
802
+ this.expressionLanguage = '';
803
+ this.scenarios = [];
804
+ this.selectedScenarioId = null;
805
+ this.startVariables = {};
806
+ this.instances = new Map();
807
+ this.selectedInstanceId = null;
808
+ this.log = [];
809
+ this.nextLogId = 1;
810
+ this.listeners = new Set();
811
+ }
812
+ setEngine(label, expressionLanguage) {
813
+ this.engineLabel = label;
814
+ this.expressionLanguage = expressionLanguage;
815
+ this.emit();
816
+ }
817
+ setScenarios(scenarios) {
818
+ this.scenarios = scenarios;
819
+ this.selectScenario(scenarios[0]?.id ?? null);
820
+ }
821
+ selectScenario(scenarioId) {
822
+ const scenario = this.scenarios.find(candidate => candidate.id === scenarioId);
823
+ this.selectedScenarioId = scenario?.id ?? null;
824
+ this.startVariables = scenario ? structuredClone(scenario.variables) : {};
825
+ this.emit();
826
+ }
827
+ setStartVariables(variables) {
828
+ this.startVariables = structuredClone(variables);
829
+ this.emit();
830
+ }
831
+ startInstance(id, processName) {
832
+ this.instances.set(id, {
833
+ id,
834
+ number: this.instances.size + 1,
835
+ processName,
836
+ scenarioId: this.selectedScenarioId,
837
+ status: 'running',
838
+ variables: structuredClone(this.startVariables),
839
+ waiting: [],
840
+ });
841
+ this.selectedInstanceId = id;
842
+ this.emit();
843
+ }
844
+ selectInstance(instanceId) {
845
+ if (!this.instances.has(instanceId))
846
+ return;
847
+ this.selectedInstanceId = instanceId;
848
+ this.emit();
849
+ }
850
+ completeInstance(id) {
851
+ this.updateInstance(id, instance => ({ ...instance, status: 'completed', waiting: [] }));
852
+ }
853
+ hasInstance(id) {
854
+ return this.instances.has(id);
855
+ }
856
+ getTaskResult(instanceId, elementId) {
857
+ const scenarioId = this.instances.get(instanceId)?.scenarioId;
858
+ return this.scenarios.find(scenario => scenario.id === scenarioId)?.taskResults[elementId];
859
+ }
860
+ getVariables(instanceId) {
861
+ return this.instances.get(instanceId)?.variables ?? {};
862
+ }
863
+ setVariables(instanceId, variables) {
864
+ this.updateInstance(instanceId, instance => ({ ...instance, variables: structuredClone(variables) }));
865
+ }
866
+ addWaiting(instanceId, waiting) {
867
+ this.updateInstance(instanceId, instance => ({ ...instance, waiting: [...instance.waiting, waiting] }));
868
+ }
869
+ removeWaiting(scopeId) {
870
+ const instance = [...this.instances.values()].find(candidate => candidate.waiting.some(waiting => waiting.scopeId === scopeId));
871
+ if (!instance)
872
+ return;
873
+ this.updateInstance(instance.id, current => ({
874
+ ...current,
875
+ waiting: current.waiting.filter(waiting => waiting.scopeId !== scopeId),
876
+ }));
877
+ }
878
+ record(entry) {
879
+ this.log = [...this.log, { ...entry, id: this.nextLogId++ }];
880
+ this.emit();
881
+ }
882
+ reset() {
883
+ this.instances.clear();
884
+ this.selectedInstanceId = null;
885
+ this.log = [];
886
+ this.emit();
887
+ }
888
+ getSnapshot() {
889
+ return {
890
+ engineLabel: this.engineLabel,
891
+ expressionLanguage: this.expressionLanguage,
892
+ scenarios: this.scenarios,
893
+ selectedScenarioId: this.selectedScenarioId,
894
+ startVariables: this.startVariables,
895
+ instances: [...this.instances.values()].map(withStatus),
896
+ selectedInstanceId: this.selectedInstanceId,
897
+ log: this.log,
898
+ };
899
+ }
900
+ subscribe(listener) {
901
+ this.listeners.add(listener);
902
+ return () => this.listeners.delete(listener);
903
+ }
904
+ updateInstance(id, update) {
905
+ const instance = this.instances.get(id);
906
+ if (!instance)
907
+ return;
908
+ this.instances.set(id, update(instance));
909
+ this.emit();
910
+ }
911
+ emit() {
912
+ const snapshot = this.getSnapshot();
913
+ for (const listener of [...this.listeners])
914
+ listener(snapshot);
915
+ }
916
+ }
917
+ function withStatus(instance) {
918
+ if (instance.status === 'completed')
919
+ return instance;
920
+ return { ...instance, status: instance.waiting.length ? 'waiting' : 'running' };
921
+ }
922
+
923
+ function h(tag, attributes = {}, ...children) {
924
+ const element = document.createElement(tag);
925
+ for (const [name, value] of Object.entries(attributes)) {
926
+ if (name === 'className')
927
+ element.className = value;
928
+ else
929
+ element.setAttribute(name, value);
930
+ }
931
+ for (const child of children) {
932
+ if (child)
933
+ element.append(child);
934
+ }
935
+ return element;
936
+ }
937
+ function formatValue(value) {
938
+ if (value === undefined)
939
+ return 'undefined';
940
+ return JSON.stringify(value) ?? String(value);
941
+ }
942
+
943
+ const simpleStartFormRenderer = {
944
+ render(container, fields, values) {
945
+ const inputs = new Map();
946
+ const form = h('div', { className: 'bds-form' });
947
+ for (const field of fields) {
948
+ const input = createInput(field);
949
+ inputs.set(field.name, input);
950
+ form.append(renderField(field, input));
951
+ }
952
+ for (const field of fields)
953
+ writeInput(inputs.get(field.name), formatFieldValue(field, values[field.name]));
954
+ container.append(form);
955
+ return {
956
+ readValues() {
957
+ const result = {};
958
+ for (const field of fields) {
959
+ const input = inputs.get(field.name);
960
+ const parsed = parseFieldValue(field, input.type === 'checkbox' ? input.checked : input.value);
961
+ if (!parsed.ok)
962
+ return parsed;
963
+ result[field.name] = parsed.value;
964
+ }
965
+ return { ok: true, values: result };
966
+ },
967
+ focus() {
968
+ inputs.values().next().value?.focus();
969
+ },
970
+ destroy() {
971
+ form.remove();
972
+ },
973
+ };
974
+ },
975
+ };
976
+ function renderField(field, input) {
977
+ const id = `bds-field-${field.name}`;
978
+ input.id = id;
979
+ const hint = h('span', { className: 'bds-field-hint' }, `Used by ${field.usedBy.join(', ')}`);
980
+ if (field.type === 'boolean') {
981
+ return h('div', { className: 'bds-field bds-field--checkbox' }, h('label', { className: 'bds-checkbox', for: id }, input, h('span', { className: 'bds-field-name' }, field.name)), hint);
982
+ }
983
+ return h('div', { className: 'bds-field' }, h('label', { className: 'bds-field-name', for: id }, field.name), input, hint);
984
+ }
985
+ function createInput(field) {
986
+ if (field.type === 'boolean')
987
+ return h('input', { type: 'checkbox', name: field.name });
988
+ if (field.type === 'json') {
989
+ return h('textarea', { className: 'bds-input bds-json', name: field.name, rows: '2', spellcheck: 'false' });
990
+ }
991
+ const type = field.type === 'number' ? 'number' : 'text';
992
+ return h('input', { className: 'bds-input', type, name: field.name, step: 'any', autocomplete: 'off' });
993
+ }
994
+ function writeInput(input, value) {
995
+ if (typeof value === 'boolean')
996
+ input.checked = value;
997
+ else
998
+ input.value = value;
999
+ }
1000
+
1001
+ const FLOW_CHOICE_TYPES = ['bpmn:ExclusiveGateway', 'bpmn:InclusiveGateway'];
1002
+ const TRIGGER_TYPE = 'bpmn:Event';
1003
+ class DataContextPads {
1004
+ constructor(contextPads, dataGateways, startForm, dataSimulation) {
1005
+ for (const { handler, type } of contextPads._handlers) {
1006
+ if (FLOW_CHOICE_TYPES.includes(type))
1007
+ hideOnDataDrivenGateways(handler, dataGateways);
1008
+ if (type === TRIGGER_TYPE)
1009
+ openStartFormOnProcessStart(handler, startForm, dataSimulation);
1010
+ }
1011
+ }
1012
+ }
1013
+ DataContextPads.$inject = ['contextPads', 'dataGateways', 'dataStartForm', 'dataSimulation'];
1014
+ function hideOnDataDrivenGateways(handler, dataGateways) {
1015
+ const createContextPads = handler.createContextPads.bind(handler);
1016
+ handler.createContextPads = element => (dataGateways.isDataDriven(element) ? undefined : createContextPads(element));
1017
+ }
1018
+ function openStartFormOnProcessStart(handler, startForm, dataSimulation) {
1019
+ const createContextPads = handler.createContextPads.bind(handler);
1020
+ handler.createContextPads = element => {
1021
+ const pads = createContextPads(element);
1022
+ if (!dataSimulation.isEnabled() || !startForm.isProcessStart(element))
1023
+ return pads;
1024
+ return []
1025
+ .concat(pads)
1026
+ .map(pad => pad?.action
1027
+ ? { ...pad, action: (contexts) => startForm.open(element, () => pad.action(contexts)) }
1028
+ : pad);
1029
+ };
1030
+ }
1031
+
1032
+ class DataGatewayBehaviors {
1033
+ constructor(exclusive, inclusive, dataGateways) {
1034
+ routeByData(exclusive, 'exclusive', dataGateways);
1035
+ routeByData(inclusive, 'inclusive', dataGateways);
1036
+ }
1037
+ }
1038
+ DataGatewayBehaviors.$inject = ['exclusiveGatewayBehavior', 'inclusiveGatewayBehavior', 'dataGateways'];
1039
+ function routeByData(behavior, kind, dataGateways) {
1040
+ const exitByClick = behavior.exit.bind(behavior);
1041
+ behavior.exit = context => {
1042
+ if (dataGateways.isDataDriven(context.element)) {
1043
+ dataGateways.exit(context, kind);
1044
+ }
1045
+ else {
1046
+ dataGateways.recordClickDecision(context, kind);
1047
+ exitByClick(context);
1048
+ }
1049
+ };
1050
+ }
1051
+
1052
+ class DataGatewaySettings {
1053
+ constructor(exclusive, inclusive, dataGateways) {
1054
+ const onlyForClickGateways = (method) => {
1055
+ return (gateway, ...rest) => {
1056
+ if (!dataGateways.isDataDriven(gateway))
1057
+ method(gateway, ...rest);
1058
+ };
1059
+ };
1060
+ exclusive.setSequenceFlow = onlyForClickGateways(exclusive.setSequenceFlow.bind(exclusive));
1061
+ inclusive._setGatewayDefaults = onlyForClickGateways(inclusive._setGatewayDefaults.bind(inclusive));
1062
+ inclusive.toggleSequenceFlow = onlyForClickGateways(inclusive.toggleSequenceFlow.bind(inclusive));
1063
+ }
1064
+ }
1065
+ DataGatewaySettings.$inject = ['exclusiveGatewaySettings', 'inclusiveGatewaySettings', 'dataGateways'];
1066
+
1067
+ const TOGGLE_MODE_EVENT = 'tokenSimulation.toggleMode';
1068
+ const RESET_SIMULATION_EVENT = 'tokenSimulation.resetSimulation';
1069
+ const SCOPE_CREATE_EVENT = 'tokenSimulation.simulator.createScope';
1070
+ const SCOPE_DESTROYED_EVENT = 'tokenSimulation.simulator.destroyScope';
1071
+ const TRACE_EVENT = 'tokenSimulation.simulator.trace';
1072
+ const DATA_TOGGLE_EVENT = 'dataSimulation.toggle';
1073
+ function findProcessInstance(scope) {
1074
+ let current = scope;
1075
+ while (current.parent)
1076
+ current = current.parent;
1077
+ return current;
1078
+ }
1079
+ function elementName(element) {
1080
+ const name = element.businessObject.name;
1081
+ return typeof name === 'string' && name.trim() ? name.trim() : element.id;
1082
+ }
1083
+ function is(element, type) {
1084
+ const businessObject = element.businessObject;
1085
+ return typeof businessObject?.$instanceOf === 'function' && businessObject.$instanceOf(type);
1086
+ }
1087
+
1088
+ class DataGateways {
1089
+ constructor(dataSimulation, store, simulator) {
1090
+ this.dataSimulation = dataSimulation;
1091
+ this.store = store;
1092
+ this.simulator = simulator;
1093
+ }
1094
+ isDataDriven(gateway) {
1095
+ const engine = this.dataSimulation.getEngine();
1096
+ const outgoing = this.outgoingFlows(gateway);
1097
+ return (this.dataSimulation.isEnabled() &&
1098
+ outgoing.length > 1 &&
1099
+ outgoing
1100
+ .filter(flow => !flow.isDefault)
1101
+ .every(flow => flow.expression !== undefined && engine.canEvaluate(flow.expression)));
1102
+ }
1103
+ exit(context, kind) {
1104
+ const { element: gateway, scope } = context;
1105
+ const decision = this.decide(gateway, scope, kind);
1106
+ if (decision.stuckReason) {
1107
+ this.waitForRetry(gateway, scope);
1108
+ return;
1109
+ }
1110
+ for (const flowId of decision.takenFlowIds) {
1111
+ const flow = this.sequenceFlows(gateway).find(candidate => candidate.id === flowId);
1112
+ this.simulator.enter({ element: flow, scope: scope.parent });
1113
+ }
1114
+ }
1115
+ recordClickDecision(context, kind) {
1116
+ if (!this.dataSimulation.isEnabled())
1117
+ return;
1118
+ const { element: gateway, scope } = context;
1119
+ const { activeOutgoing } = this.simulator.getConfig(gateway);
1120
+ const chosen = [].concat(activeOutgoing ?? []);
1121
+ const outgoing = this.outgoingFlows(gateway);
1122
+ if (outgoing.length < 2 || !chosen.length)
1123
+ return;
1124
+ const flows = outgoing.map(flow => chosen.some(candidate => candidate.id === flow.id)
1125
+ ? { flow, outcome: 'taken', reason: 'Chosen by click' }
1126
+ : { flow, outcome: 'skipped', reason: 'Not chosen by click' });
1127
+ const decision = {
1128
+ flows,
1129
+ takenFlowIds: flows.filter(flow => flow.outcome === 'taken').map(flow => flow.flow.id),
1130
+ };
1131
+ this.record(gateway, scope, kind, 'click', decision, []);
1132
+ }
1133
+ decide(gateway, scope, kind) {
1134
+ const engine = this.dataSimulation.getEngine();
1135
+ const variables = this.dataSimulation.getVariables(scope);
1136
+ const outgoing = this.outgoingFlows(gateway);
1137
+ const decision = routeGateway(kind, outgoing, expression => engine.evaluate(expression, variables));
1138
+ const names = outgoing.flatMap(flow => (flow.expression ? engine.readVariableNames(flow.expression) : []));
1139
+ const inputs = [...new Set(names)].map(name => ({ name, value: structuredClone(variables[name]) }));
1140
+ this.record(gateway, scope, kind, 'data', decision, inputs);
1141
+ return decision;
1142
+ }
1143
+ record(gateway, scope, gatewayKind, chosenBy, decision, inputs) {
1144
+ this.store.record({
1145
+ kind: 'decision',
1146
+ instanceId: findProcessInstance(scope).id,
1147
+ elementId: gateway.id,
1148
+ elementName: elementName(gateway),
1149
+ gatewayKind,
1150
+ chosenBy,
1151
+ decision,
1152
+ inputs,
1153
+ });
1154
+ }
1155
+ waitForRetry(gateway, scope) {
1156
+ const waitingScope = this.simulator
1157
+ .createScope({ element: gateway, parent: scope.parent, initiator: scope })
1158
+ .start();
1159
+ this.store.addWaiting(findProcessInstance(scope).id, {
1160
+ scopeId: waitingScope.id,
1161
+ gatewayId: gateway.id,
1162
+ gatewayName: elementName(gateway),
1163
+ });
1164
+ const retry = { element: gateway, type: 'continue', interrupting: false, boundary: false };
1165
+ const subscription = this.simulator.subscribe(waitingScope, retry, initiator => {
1166
+ subscription.remove();
1167
+ this.store.removeWaiting(waitingScope.id);
1168
+ this.simulator.exit({ element: gateway, scope: waitingScope, initiator });
1169
+ });
1170
+ }
1171
+ outgoingFlows(gateway) {
1172
+ const engine = this.dataSimulation.getEngine();
1173
+ const defaultFlow = gateway.businessObject.default;
1174
+ return this.sequenceFlows(gateway).map(flow => {
1175
+ const name = flow.businessObject.name;
1176
+ return {
1177
+ id: flow.id,
1178
+ ...(typeof name === 'string' && name ? { name } : {}),
1179
+ expression: engine.readCondition(flow.businessObject),
1180
+ isDefault: flow.businessObject === defaultFlow,
1181
+ };
1182
+ });
1183
+ }
1184
+ sequenceFlows(gateway) {
1185
+ return (gateway.outgoing ?? []).filter(flow => is(flow, 'bpmn:SequenceFlow'));
1186
+ }
1187
+ }
1188
+ DataGateways.$inject = ['dataSimulation', 'dataSimulationStore', 'simulator'];
1189
+
1190
+ class DataSimulation {
1191
+ constructor(config, eventBus, store) {
1192
+ this.eventBus = eventBus;
1193
+ this.store = store;
1194
+ this.engine = resolveEngine(config?.engine ?? 'zeebe');
1195
+ this.enabled = config?.enabled ?? true;
1196
+ this.store.setEngine(this.engine.label, this.engine.expressionLanguage);
1197
+ if (config?.scenarios !== undefined)
1198
+ this.setScenarios(config.scenarios);
1199
+ eventBus.on(SCOPE_CREATE_EVENT, ({ scope }) => this.onScopeCreated(scope));
1200
+ eventBus.on(SCOPE_DESTROYED_EVENT, ({ scope }) => {
1201
+ this.store.completeInstance(scope.id);
1202
+ this.store.removeWaiting(scope.id);
1203
+ });
1204
+ eventBus.on(TRACE_EVENT, (event) => {
1205
+ if (event.action === 'exit')
1206
+ this.applyMappings(event.element, event.scope);
1207
+ });
1208
+ eventBus.on([RESET_SIMULATION_EVENT, TOGGLE_MODE_EVENT], () => this.store.reset());
1209
+ }
1210
+ getEngine() {
1211
+ return this.engine;
1212
+ }
1213
+ isEnabled() {
1214
+ return this.enabled;
1215
+ }
1216
+ setEnabled(enabled) {
1217
+ if (enabled === this.enabled)
1218
+ return;
1219
+ this.enabled = enabled;
1220
+ this.store.reset();
1221
+ this.eventBus.fire(DATA_TOGGLE_EVENT, { enabled });
1222
+ }
1223
+ setScenarios(input) {
1224
+ this.store.setScenarios(parseScenarios(input));
1225
+ }
1226
+ selectScenario(scenarioId) {
1227
+ this.store.selectScenario(scenarioId);
1228
+ }
1229
+ setStartVariables(variables) {
1230
+ this.store.setStartVariables(variables);
1231
+ }
1232
+ selectInstance(instanceId) {
1233
+ this.store.selectInstance(instanceId);
1234
+ }
1235
+ setInstanceVariables(instanceId, variables) {
1236
+ this.store.setVariables(instanceId, variables);
1237
+ }
1238
+ getVariables(scope) {
1239
+ return this.store.getVariables(findProcessInstance(scope).id);
1240
+ }
1241
+ getSnapshot() {
1242
+ return this.store.getSnapshot();
1243
+ }
1244
+ subscribe(listener) {
1245
+ return this.store.subscribe(listener);
1246
+ }
1247
+ onScopeCreated(scope) {
1248
+ if (!this.enabled || scope.parent || (!is(scope.element, 'bpmn:Process') && !is(scope.element, 'bpmn:Participant')))
1249
+ return;
1250
+ this.store.startInstance(scope.id, elementName(scope.element));
1251
+ }
1252
+ applyMappings(element, scope) {
1253
+ if (!is(element, 'bpmn:FlowNode') || scope.failed || scope.canceled)
1254
+ return;
1255
+ const instanceId = findProcessInstance(scope).id;
1256
+ if (!this.store.hasInstance(instanceId))
1257
+ return;
1258
+ const inputs = this.engine.readInputMappings(element.businessObject);
1259
+ const outputs = this.engine.readOutputMappings(element.businessObject);
1260
+ const taskResult = this.store.getTaskResult(instanceId, element.id);
1261
+ if (!inputs.length && !outputs.length && !taskResult)
1262
+ return;
1263
+ const processVariables = this.store.getVariables(instanceId);
1264
+ const localVariables = this.evaluateMappings(element, instanceId, inputs, {}, current => ({
1265
+ ...processVariables,
1266
+ ...current,
1267
+ }));
1268
+ const context = { ...processVariables, ...localVariables, ...taskResult };
1269
+ const propagatesTaskResult = taskResult && (this.engine.taskResultPropagation === 'always' || !outputs.length);
1270
+ const withTaskResult = propagatesTaskResult
1271
+ ? { ...processVariables, ...withoutKeys(taskResult, Object.keys(localVariables)) }
1272
+ : processVariables;
1273
+ this.store.setVariables(instanceId, this.evaluateMappings(element, instanceId, outputs, withTaskResult, () => context));
1274
+ }
1275
+ evaluateMappings(element, instanceId, mappings, target, contextOf) {
1276
+ let result = target;
1277
+ for (const mapping of mappings) {
1278
+ const evaluation = this.engine.evaluate(mapping.source, contextOf(result));
1279
+ if (evaluation.ok) {
1280
+ result = this.engine.writeVariable(result, mapping.target, evaluation.value);
1281
+ }
1282
+ else {
1283
+ this.store.record({
1284
+ kind: 'mapping-issue',
1285
+ instanceId,
1286
+ elementId: element.id,
1287
+ elementName: elementName(element),
1288
+ target: mapping.target,
1289
+ reason: evaluation.reason,
1290
+ });
1291
+ }
1292
+ }
1293
+ return result;
1294
+ }
1295
+ }
1296
+ DataSimulation.$inject = ['config.dataSimulation', 'eventBus', 'dataSimulationStore'];
1297
+ function withoutKeys(variables, keys) {
1298
+ return Object.fromEntries(Object.entries(variables).filter(([key]) => !keys.includes(key)));
1299
+ }
1300
+
1301
+ const OUTCOME_LABELS = {
1302
+ taken: { symbol: '✓', title: 'Taken' },
1303
+ 'not-taken': { symbol: '✗', title: 'Condition is false' },
1304
+ error: { symbol: '!', title: 'Condition could not be evaluated' },
1305
+ skipped: { symbol: '–', title: 'Not evaluated' },
1306
+ };
1307
+ const DEFAULT_FLOW_TITLES = {
1308
+ taken: 'Default flow taken, no condition is true',
1309
+ 'not-taken': 'Default flow not needed',
1310
+ };
1311
+ function createOutcomeBadge(outcome, detail, isDefault = false) {
1312
+ const { symbol } = OUTCOME_LABELS[outcome];
1313
+ const title = (isDefault && DEFAULT_FLOW_TITLES[outcome]) || OUTCOME_LABELS[outcome].title;
1314
+ const badge = document.createElement('span');
1315
+ badge.className = `bds-outcome bds-outcome--${outcome}`;
1316
+ badge.textContent = symbol;
1317
+ badge.title = detail ? `${title}: ${detail}` : title;
1318
+ return badge;
1319
+ }
1320
+ function createDecisionCard({ elementName, gatewayKind, chosenBy, decision, inputs }, onClose) {
1321
+ const closeButton = onClose
1322
+ ? h('button', { className: 'bds-icon-button bds-decision-close', type: 'button', 'aria-label': 'Close' }, '×')
1323
+ : null;
1324
+ closeButton?.addEventListener('click', onClose);
1325
+ return h('div', { className: `bds-decision${decision.stuckReason ? ' bds-decision--stuck' : ''}`, role: 'note' }, h('div', { className: 'bds-decision-title' }, h('span', {}, elementName), h('span', { className: 'bds-tag' }, chosenBy === 'click' ? `${gatewayKind} · by click` : gatewayKind), closeButton), decision.stuckReason
1326
+ ? h('p', { className: 'bds-error' }, `${decision.stuckReason}. Change the variables in Process Data, then press ▶ on the gateway.`)
1327
+ : null, h('ul', { className: 'bds-flows' }, ...decision.flows.map(({ flow, outcome, reason }) => h('li', { className: `bds-flow bds-flow--${outcome}` }, createOutcomeBadge(outcome, reason, flow.isDefault), h('span', { className: 'bds-flow-name' }, flow.name ?? flow.id), flow.isDefault
1328
+ ? h('span', { className: 'bds-tag' }, 'default')
1329
+ : flow.expression && h('code', {}, flow.expression)))), inputs.length ? createInputList(inputs) : null);
1330
+ }
1331
+ function createInputList(inputs) {
1332
+ return h('dl', { className: 'bds-decision-inputs' }, ...inputs.flatMap(({ name, value }) => [
1333
+ h('dt', {}, name),
1334
+ h('dd', {}, value === undefined ? h('span', { className: 'bds-hint' }, 'not set') : h('code', {}, formatValue(value))),
1335
+ ]));
1336
+ }
1337
+
1338
+ const GAP$1 = 12;
1339
+ const MARGIN = 8;
1340
+ function placePopover(anchor, popover, bounds) {
1341
+ const below = anchor.y + anchor.height + GAP$1;
1342
+ const above = anchor.y - GAP$1 - popover.height;
1343
+ const fitsBelow = below + popover.height <= bounds.height - MARGIN;
1344
+ const fitsAbove = above >= MARGIN;
1345
+ const height = Math.min(popover.height, bounds.height - 2 * MARGIN);
1346
+ return {
1347
+ left: clamp(anchor.x + anchor.width / 2 - popover.width / 2, MARGIN, bounds.width - popover.width - MARGIN),
1348
+ top: fitsBelow ? below : fitsAbove ? above : clamp(below, MARGIN, bounds.height - height - MARGIN),
1349
+ maxHeight: height < popover.height ? height : undefined,
1350
+ hidden: !isInView(anchor, bounds),
1351
+ };
1352
+ }
1353
+ function clamp(value, min, max) {
1354
+ return Math.max(min, Math.min(value, max));
1355
+ }
1356
+ function isInView(anchor, bounds) {
1357
+ return (anchor.x + anchor.width > 0 && anchor.x < bounds.width && anchor.y + anchor.height > 0 && anchor.y < bounds.height);
1358
+ }
1359
+
1360
+ var componentStyles = ":host {\n all: initial;\n display: contents;\n}\n\n.bds-panel {\n position: absolute;\n top: 30%;\n right: 20px;\n bottom: 50px;\n z-index: 10000;\n display: flex;\n flex-direction: column;\n width: 300px;\n overflow: hidden;\n font-family: var(--bds-font);\n font-size: 13px;\n color: var(--bds-ink);\n background: var(--token-simulation-control-background, #f1f2f4);\n border-radius: var(--surface-border-radius, 4px);\n}\n\n.bds-panel[hidden] {\n display: none;\n}\n\n.bds-panel-header {\n display: flex;\n flex: 0 0 auto;\n align-items: center;\n gap: var(--bds-space-2);\n box-sizing: border-box;\n height: 30px;\n padding: 6px 8px;\n font-size: 16px;\n color: var(--token-simulation-control-surface, #fff);\n background: var(--token-simulation-primary, #0067cc);\n}\n\n.bds-panel-heading {\n flex: 1;\n margin: 0;\n font: inherit;\n text-align: center;\n}\n\n.bds-panel-close {\n display: inline-flex;\n align-items: center;\n padding: 0;\n color: inherit;\n background: none;\n border: none;\n cursor: pointer;\n}\n\n.bds-variables-icon svg,\n.bds-panel-close svg {\n width: 1em;\n height: 1em;\n fill: none;\n stroke: currentColor;\n stroke-width: 1.6;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n\n.bds-variables-icon {\n display: inline-flex;\n align-items: center;\n}\n\n.bds-panel-body {\n display: flex;\n flex: 1;\n flex-direction: column;\n gap: var(--bds-space-2);\n margin: 7px 3px 7px 12px;\n padding: 5px 9px 5px 0;\n overflow-y: auto;\n}\n\n.bds-panel-engine {\n margin: 0;\n}\n\n.bds-panel .bds-section {\n padding: var(--bds-space-2);\n background: var(--token-simulation-control-surface, #fff);\n border-radius: var(--surface-border-radius, 4px);\n}\n\n.bds-panel-title {\n margin: 0;\n font-size: 14px;\n font-weight: 600;\n}\n\n.bds-engine {\n padding: 2px 8px;\n font-size: 11px;\n font-weight: 600;\n color: var(--bds-accent-ink);\n background: var(--bds-accent-soft);\n border-radius: var(--bds-radius-pill);\n}\n\n.bds-icon-button {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n margin-left: auto;\n width: 26px;\n height: 26px;\n padding: 0;\n color: var(--bds-muted);\n background: transparent;\n border: 1px solid transparent;\n border-radius: var(--bds-radius-sm);\n cursor: pointer;\n}\n\n.bds-icon-button svg {\n width: 16px;\n height: 16px;\n fill: none;\n stroke: currentColor;\n stroke-width: 1.5;\n stroke-linecap: round;\n stroke-linejoin: round;\n transition: transform var(--bds-motion-fast) var(--bds-ease);\n}\n\n.bds-icon-button:hover {\n color: var(--bds-accent-ink);\n background: var(--bds-accent-soft);\n}\n\n.bds-section {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-1);\n}\n\n.bds-section[hidden] {\n display: none;\n}\n\n.bds-section-title,\n.bds-label {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-1);\n margin: 0;\n font-size: 12px;\n font-weight: 600;\n letter-spacing: 0.01em;\n color: var(--bds-muted);\n}\n\n.bds-section-title {\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n}\n\n.bds-hint {\n margin: 0;\n font-size: 12px;\n color: var(--bds-muted);\n}\n\n.bds-hint[hidden],\n.bds-error[hidden] {\n display: none;\n}\n\n.bds-error {\n margin: 0;\n font-size: 12px;\n color: var(--bds-danger);\n}\n\n.bds-input {\n box-sizing: border-box;\n width: 100%;\n padding: 6px 10px;\n font-family: inherit;\n font-size: 13px;\n font-weight: 400;\n color: var(--bds-ink);\n background: var(--bds-surface);\n border: 1px solid var(--bds-line);\n border-radius: var(--bds-radius-sm);\n transition:\n border-color var(--bds-motion-fast) var(--bds-ease),\n box-shadow var(--bds-motion-fast) var(--bds-ease);\n}\n\n.bds-input:focus,\n.bds-input:focus-visible {\n outline: none;\n border-color: var(--bds-accent);\n box-shadow: 0 0 0 3px var(--bds-accent-soft);\n}\n\n.bds-input--invalid,\n.bds-input--invalid:focus {\n border-color: var(--bds-danger);\n box-shadow: 0 0 0 3px var(--bds-danger-soft);\n}\n\n.bds-json {\n min-height: 72px;\n font-family: var(--bds-font-mono);\n font-size: 12px;\n line-height: 1.5;\n resize: vertical;\n}\n\n.bds-instance-select[hidden] {\n display: none;\n}\n\n.bds-instance-select {\n padding: 4px 8px;\n font-size: 12px;\n}\n\n.bds-actions {\n display: flex;\n justify-content: flex-end;\n gap: var(--bds-space-2);\n margin-top: var(--bds-space-2);\n}\n\n.bds-button {\n padding: 5px 12px;\n font-family: inherit;\n font-size: 12px;\n font-weight: 600;\n color: var(--bds-ink);\n background: var(--bds-surface);\n border: 1px solid var(--bds-line);\n border-radius: var(--bds-radius-sm);\n box-shadow: var(--bds-shadow-1);\n cursor: pointer;\n transition:\n background var(--bds-motion-fast) var(--bds-ease),\n border-color var(--bds-motion-fast) var(--bds-ease),\n color var(--bds-motion-fast) var(--bds-ease);\n}\n\n.bds-button:hover {\n color: var(--bds-accent-ink);\n border-color: var(--bds-accent);\n background: var(--bds-accent-soft);\n}\n\n.bds-button--primary {\n color: var(--bds-on-accent);\n background: var(--bds-accent);\n border-color: var(--bds-accent);\n}\n\n.bds-button--primary:hover {\n color: var(--bds-on-accent);\n background: var(--bds-accent-ink);\n}\n\n.bds-button:focus-visible,\n.bds-icon-button:focus-visible {\n outline: none;\n box-shadow: 0 0 0 3px var(--bds-accent-soft);\n}\n\n.bds-status {\n margin: 0 0 var(--bds-space-1);\n font-size: 12px;\n font-weight: 600;\n}\n\n.bds-status--running {\n color: var(--bds-accent-ink);\n}\n\n.bds-status--completed {\n color: var(--bds-success);\n}\n\n.bds-status--waiting {\n color: var(--bds-danger);\n}\n\n.bds-variables {\n width: 100%;\n border-collapse: collapse;\n}\n\n.bds-variables th,\n.bds-variables td {\n padding: 4px 0;\n text-align: left;\n vertical-align: top;\n border-bottom: 1px solid var(--bds-line);\n}\n\n.bds-variables tr:last-child th,\n.bds-variables tr:last-child td {\n border-bottom: none;\n}\n\n.bds-variables th {\n width: 1%;\n padding-right: var(--bds-space-3);\n font-weight: 500;\n white-space: nowrap;\n}\n\n.bds-variables code,\n.bds-flow code {\n font-family: var(--bds-font-mono);\n font-size: 12px;\n overflow-wrap: anywhere;\n}\n\n.bds-log {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-2);\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.bds-log-entry {\n padding: var(--bds-space-2);\n background: var(--bds-surface);\n border: 1px solid var(--bds-line);\n border-radius: var(--bds-radius-sm);\n}\n\n.bds-log-entry--issue {\n border-color: var(--bds-danger-soft);\n background: linear-gradient(var(--bds-danger-soft), var(--bds-danger-soft)), var(--bds-surface);\n}\n\n.bds-log-title {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: var(--bds-space-2);\n margin-bottom: var(--bds-space-1);\n font-weight: 600;\n}\n\n.bds-tag {\n padding: 1px 6px;\n font-size: 11px;\n font-weight: 500;\n color: var(--bds-muted);\n background: var(--bds-code-bg);\n border-radius: var(--bds-radius-pill);\n}\n\n.bds-flows {\n display: flex;\n flex-direction: column;\n gap: 2px;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.bds-flow {\n display: grid;\n grid-template-columns: 18px 1fr;\n align-items: center;\n column-gap: var(--bds-space-2);\n row-gap: 2px;\n}\n\n.bds-flow code,\n.bds-flow .bds-tag {\n grid-column: 2;\n justify-self: start;\n}\n\n.bds-flow code {\n padding: 1px 4px;\n color: var(--bds-muted);\n background: var(--bds-code-bg);\n border-radius: 4px;\n}\n\n.bds-flow--skipped,\n.bds-flow--not-taken {\n color: var(--bds-muted);\n}\n\n.bds-outcome {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n box-sizing: border-box;\n width: 18px;\n height: 18px;\n font-family: var(--bds-font);\n font-size: 11px;\n font-weight: 700;\n line-height: 1;\n border-radius: var(--bds-radius-pill);\n border: 1px solid transparent;\n cursor: default;\n}\n\n.bds-outcome--taken {\n color: var(--bds-on-accent);\n background: var(--bds-success);\n}\n\n.bds-outcome--not-taken {\n color: var(--bds-muted);\n background: var(--bds-surface);\n border-color: var(--bds-line);\n}\n\n.bds-outcome--error {\n color: var(--bds-on-accent);\n background: var(--bds-danger);\n}\n\n.bds-outcome--skipped {\n color: var(--bds-muted);\n background: var(--bds-code-bg);\n}\n\n.bds-outcome--on-flow {\n display: flex;\n box-shadow: var(--bds-shadow-1);\n transform: translate(-50%, -50%);\n}\n\n.bds-popover {\n position: absolute;\n z-index: 100;\n overflow-y: auto;\n}\n\n.bds-popover[hidden] {\n display: none;\n}\n\n.bds-decision {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-2);\n box-sizing: border-box;\n width: 300px;\n padding: 12px;\n font-family: var(--bds-font);\n font-size: 12px;\n line-height: 1.4;\n color: var(--bds-ink);\n background: var(--bds-surface);\n border: 1px solid var(--bds-line);\n border-radius: var(--bds-radius-md);\n box-shadow: var(--bds-shadow-3);\n}\n\n.bds-decision--stuck {\n border-color: var(--bds-danger);\n}\n\n.bds-decision-title {\n display: flex;\n align-items: center;\n gap: var(--bds-space-2);\n font-size: 13px;\n font-weight: 600;\n}\n\n.bds-decision-title .bds-tag {\n margin-left: auto;\n}\n\n.bds-decision-close {\n margin-left: 0;\n width: 22px;\n height: 22px;\n font-size: 16px;\n line-height: 1;\n}\n\n.bds-decision-inputs {\n display: grid;\n grid-template-columns: auto 1fr;\n gap: 2px var(--bds-space-3);\n margin: 0;\n padding-top: var(--bds-space-2);\n border-top: 1px solid var(--bds-line);\n}\n\n.bds-decision-inputs dt {\n font-family: var(--bds-font-mono);\n color: var(--bds-muted);\n}\n\n.bds-decision-inputs dd {\n margin: 0;\n overflow-wrap: anywhere;\n}\n\n.bds-decision-inputs code {\n font-family: var(--bds-font-mono);\n}\n\n.bds-dialog-backdrop {\n position: fixed;\n inset: 0;\n z-index: 10010;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: var(--bds-space-3);\n background: rgba(29, 29, 29, 0.24);\n}\n\n.bds-dialog {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-3);\n box-sizing: border-box;\n width: 420px;\n max-width: 100%;\n max-height: 100%;\n margin: 0;\n padding: 20px;\n font-family: var(--bds-font);\n font-size: 13px;\n color: var(--bds-ink);\n background: var(--bds-surface);\n border: 1px solid var(--bds-line);\n border-radius: var(--bds-radius-lg);\n box-shadow: var(--bds-shadow-3);\n}\n\n.bds-dialog-content {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-3);\n min-height: 0;\n overflow-y: auto;\n}\n\n.bds-dialog-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: var(--bds-space-2);\n}\n\n.bds-dialog .bds-actions {\n margin-top: 0;\n}\n\n.bds-form {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.bds-field {\n display: flex;\n flex-direction: column;\n gap: var(--bds-space-1);\n}\n\n.bds-field-name {\n font-family: var(--bds-font-mono);\n font-size: 12px;\n font-weight: 600;\n}\n\n.bds-field-hint {\n font-size: 11px;\n color: var(--bds-muted);\n}\n\n.bds-checkbox {\n display: inline-flex;\n align-items: center;\n gap: var(--bds-space-2);\n cursor: pointer;\n}\n\n.bds-checkbox input {\n width: 16px;\n height: 16px;\n margin: 0;\n accent-color: var(--bds-accent);\n}\n\n@media (prefers-reduced-motion: reduce) {\n * {\n transition-duration: 0.001ms !important;\n }\n}\n\n.bds-form .bds-json {\n min-height: 0;\n}\n";
1361
+
1362
+ let sharedSheet;
1363
+ function inShadow(...children) {
1364
+ const host = h('div', { className: 'bds-host' });
1365
+ const root = host.attachShadow({ mode: 'open' });
1366
+ adoptComponentStyles(root);
1367
+ root.append(...children);
1368
+ return host;
1369
+ }
1370
+ function adoptComponentStyles(root) {
1371
+ if ('adoptedStyleSheets' in root && 'replaceSync' in CSSStyleSheet.prototype) {
1372
+ sharedSheet ?? (sharedSheet = createSheet());
1373
+ root.adoptedStyleSheets = [sharedSheet];
1374
+ }
1375
+ else {
1376
+ root.append(h('style', {}, componentStyles));
1377
+ }
1378
+ }
1379
+ function createSheet() {
1380
+ const sheet = new CSSStyleSheet();
1381
+ sheet.replaceSync(componentStyles);
1382
+ return sheet;
1383
+ }
1384
+
1385
+ const OUTCOME_OVERLAY = 'bds-flow-outcome';
1386
+ const DECIDED_MARKER = 'bds-gateway--decided';
1387
+ const STUCK_MARKER = 'bds-gateway--stuck';
1388
+ const BADGE_DISTANCE = 38;
1389
+ const BADGE_MIN_SCALE = 1;
1390
+ class DataSimulationOverlays {
1391
+ constructor(eventBus, overlays, elementRegistry, canvas, dataSimulation) {
1392
+ this.overlays = overlays;
1393
+ this.elementRegistry = elementRegistry;
1394
+ this.canvas = canvas;
1395
+ this.pinnedGatewayIds = new Set();
1396
+ this.markedGateways = [];
1397
+ this.popovers = [];
1398
+ this.popoverLayer = inShadow();
1399
+ this.renderedState = '';
1400
+ this.snapshot = dataSimulation.getSnapshot();
1401
+ const unsubscribe = dataSimulation.subscribe(snapshot => {
1402
+ this.snapshot = snapshot;
1403
+ this.render();
1404
+ });
1405
+ eventBus.on('element.hover', ({ element }) => {
1406
+ this.hoveredGatewayId = gatewayOf(element);
1407
+ this.render();
1408
+ });
1409
+ eventBus.on('element.click', ({ element }) => {
1410
+ if (!isGateway(element))
1411
+ return;
1412
+ if (!this.pinnedGatewayIds.delete(element.id))
1413
+ this.pinnedGatewayIds.add(element.id);
1414
+ this.render();
1415
+ });
1416
+ eventBus.on(['canvas.viewbox.changed', 'canvas.resized'], () => this.placePopovers());
1417
+ canvas.getContainer().append(this.popoverLayer);
1418
+ eventBus.on('diagram.destroy', () => {
1419
+ unsubscribe();
1420
+ this.popoverLayer.remove();
1421
+ });
1422
+ }
1423
+ render() {
1424
+ const decisions = latestDecisionPerGateway(this.snapshot);
1425
+ const shownPerGateway = new Map(decisions.map(entry => [entry.elementId, entry]));
1426
+ for (const entry of latestStuckDecisionPerGateway(this.snapshot))
1427
+ shownPerGateway.set(entry.elementId, entry);
1428
+ const shown = [...shownPerGateway.values()];
1429
+ const cards = shown.filter(({ elementId }) => elementId === this.hoveredGatewayId || this.pinnedGatewayIds.has(elementId));
1430
+ const state = JSON.stringify([
1431
+ decisions.map(entry => entry.id),
1432
+ shown.map(entry => entry.id),
1433
+ cards.map(entry => [entry.id, this.pinnedGatewayIds.has(entry.elementId)]),
1434
+ ]);
1435
+ if (state === this.renderedState)
1436
+ return;
1437
+ this.renderedState = state;
1438
+ this.overlays.remove({ type: OUTCOME_OVERLAY });
1439
+ this.unmarkGateways();
1440
+ for (const entry of decisions)
1441
+ this.showOutcomes(entry.decision);
1442
+ for (const entry of shown)
1443
+ this.markGateway(entry);
1444
+ this.showCards(cards);
1445
+ }
1446
+ markGateway({ elementId, decision }) {
1447
+ const gateway = this.elementRegistry.get(elementId);
1448
+ if (!gateway)
1449
+ return;
1450
+ this.canvas.addMarker(gateway, decision.stuckReason ? STUCK_MARKER : DECIDED_MARKER);
1451
+ this.markedGateways.push(gateway);
1452
+ }
1453
+ unmarkGateways() {
1454
+ for (const gateway of this.markedGateways) {
1455
+ this.canvas.removeMarker(gateway, DECIDED_MARKER);
1456
+ this.canvas.removeMarker(gateway, STUCK_MARKER);
1457
+ }
1458
+ this.markedGateways = [];
1459
+ }
1460
+ showOutcomes(decision) {
1461
+ for (const { flow, outcome, reason } of decision.flows) {
1462
+ const connection = this.elementRegistry.get(flow.id);
1463
+ if (!connection?.waypoints)
1464
+ continue;
1465
+ const badge = createOutcomeBadge(outcome, reason, flow.isDefault);
1466
+ badge.classList.add('bds-outcome--on-flow');
1467
+ this.overlays.add(connection, OUTCOME_OVERLAY, {
1468
+ position: badgePosition(connection.waypoints),
1469
+ scale: { min: BADGE_MIN_SCALE },
1470
+ html: inShadow(badge),
1471
+ });
1472
+ }
1473
+ }
1474
+ showCards(entries) {
1475
+ this.popovers = entries.flatMap(entry => {
1476
+ const gateway = this.elementRegistry.get(entry.elementId);
1477
+ if (!gateway)
1478
+ return [];
1479
+ const close = () => {
1480
+ this.pinnedGatewayIds.delete(entry.elementId);
1481
+ this.render();
1482
+ };
1483
+ const card = createDecisionCard(entry, this.pinnedGatewayIds.has(entry.elementId) ? close : undefined);
1484
+ card.classList.add('bds-popover');
1485
+ card.dataset.elementId = entry.elementId;
1486
+ return [{ gateway, card }];
1487
+ });
1488
+ this.popoverLayer.shadowRoot.replaceChildren(...this.popovers.map(({ card }) => card));
1489
+ this.placePopovers();
1490
+ }
1491
+ placePopovers() {
1492
+ const container = this.canvas.getContainer();
1493
+ const bounds = { width: container.clientWidth, height: container.clientHeight };
1494
+ for (const { gateway, card } of this.popovers) {
1495
+ card.style.maxHeight = '';
1496
+ const { left, top, maxHeight, hidden } = placePopover(this.canvas.getAbsoluteBBox(gateway), { width: card.offsetWidth, height: card.offsetHeight }, bounds);
1497
+ card.hidden = hidden;
1498
+ card.style.left = `${left}px`;
1499
+ card.style.top = `${top}px`;
1500
+ card.style.maxHeight = maxHeight === undefined ? '' : `${maxHeight}px`;
1501
+ }
1502
+ }
1503
+ }
1504
+ DataSimulationOverlays.$inject = ['eventBus', 'overlays', 'elementRegistry', 'canvas', 'dataSimulation'];
1505
+ function isGateway(element) {
1506
+ return element.type === 'bpmn:ExclusiveGateway' || element.type === 'bpmn:InclusiveGateway';
1507
+ }
1508
+ function gatewayOf(element) {
1509
+ if (isGateway(element))
1510
+ return element.id;
1511
+ if (element.type === 'bpmn:SequenceFlow' && element.source && isGateway(element.source))
1512
+ return element.source.id;
1513
+ return undefined;
1514
+ }
1515
+ function latestDecisionPerGateway({ log, selectedInstanceId }) {
1516
+ const latest = new Map();
1517
+ for (const entry of log) {
1518
+ if (entry.kind === 'decision' && entry.instanceId === selectedInstanceId)
1519
+ latest.set(entry.elementId, entry);
1520
+ }
1521
+ return [...latest.values()];
1522
+ }
1523
+ function latestStuckDecisionPerGateway({ instances, log }) {
1524
+ const latest = new Map();
1525
+ for (const instance of instances) {
1526
+ for (const { gatewayId } of instance.waiting) {
1527
+ const decision = [...log]
1528
+ .reverse()
1529
+ .find((entry) => entry.kind === 'decision' && entry.instanceId === instance.id && entry.elementId === gatewayId);
1530
+ if (decision && (latest.get(gatewayId)?.id ?? 0) < decision.id)
1531
+ latest.set(gatewayId, decision);
1532
+ }
1533
+ }
1534
+ return [...latest.values()];
1535
+ }
1536
+ function badgePosition(waypoints) {
1537
+ const [start, next] = waypoints;
1538
+ const length = Math.hypot(next.x - start.x, next.y - start.y) || 1;
1539
+ const distance = Math.min(BADGE_DISTANCE, length / 2);
1540
+ const x = start.x + ((next.x - start.x) / length) * distance;
1541
+ const y = start.y + ((next.y - start.y) / length) * distance;
1542
+ const minX = Math.min(...waypoints.map(point => point.x));
1543
+ const minY = Math.min(...waypoints.map(point => point.y));
1544
+ return { left: x - minX, top: y - minY };
1545
+ }
1546
+
1547
+ const VARIABLES_ICON = '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M5.5 2.5C4 2.5 4 3.5 4 5v1c0 1-.8 2-2 2 1.2 0 2 1 2 2v1c0 1.5 0 2.5 1.5 2.5M10.5 2.5c1.5 0 1.5 1 1.5 2.5v1c0 1 .8 2 2 2-1.2 0-2 1-2 2v1c0 1.5 0 2.5-1.5 2.5" /></svg>';
1548
+ const CLOSE_ICON = '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" /></svg>';
1549
+ class VariablesPanel {
1550
+ constructor(actions) {
1551
+ this.actions = actions;
1552
+ this.paletteEntry = h('button', {
1553
+ className: 'bts-entry bds-palette-entry',
1554
+ type: 'button',
1555
+ title: 'Toggle Process Data',
1556
+ 'aria-label': 'Toggle Process Data',
1557
+ });
1558
+ this.engineBadge = h('span', { className: 'bds-engine' });
1559
+ this.closeButton = h('button', { className: 'bds-panel-close', type: 'button', 'aria-label': 'Close' });
1560
+ this.instanceTitle = h('h3', { className: 'bds-section-title' }, 'Instance');
1561
+ this.instancePicker = h('select', {
1562
+ className: 'bds-input bds-instance-select',
1563
+ 'aria-label': 'Process instance',
1564
+ });
1565
+ this.instanceBody = h('div', { className: 'bds-instance-body' });
1566
+ this.issueList = h('ol', { className: 'bds-log' });
1567
+ this.issueSection = h('section', { className: 'bds-section bds-issues' }, h('h3', { className: 'bds-section-title' }, 'Issues'), this.issueList);
1568
+ this.shownInstances = '';
1569
+ this.paletteEntry.innerHTML = `<span class="bts-icon bds-variables-icon">${VARIABLES_ICON}</span>`;
1570
+ this.closeButton.innerHTML = CLOSE_ICON;
1571
+ const icon = h('span', { className: 'bds-variables-icon' });
1572
+ icon.innerHTML = VARIABLES_ICON;
1573
+ this.element = h('aside', { className: 'bds-panel', 'aria-label': 'Process Data' }, h('header', { className: 'bds-panel-header' }, icon, h('h2', { className: 'bds-panel-heading' }, 'Process Data'), this.closeButton), h('div', { className: 'bds-panel-body' }, h('p', { className: 'bds-panel-engine' }, this.engineBadge), h('section', { className: 'bds-section bds-instance' }, this.instanceTitle, this.instanceBody), this.issueSection));
1574
+ this.paletteEntry.addEventListener('click', () => this.toggle());
1575
+ this.closeButton.addEventListener('click', () => this.toggle(false));
1576
+ this.instancePicker.addEventListener('change', () => this.actions.selectInstance(this.instancePicker.value));
1577
+ this.toggle(false);
1578
+ }
1579
+ toggle(shown = this.element.hidden === true) {
1580
+ this.element.hidden = !shown;
1581
+ this.paletteEntry.classList.toggle('active', shown);
1582
+ }
1583
+ render(snapshot) {
1584
+ this.snapshot = snapshot;
1585
+ this.engineBadge.textContent = `${snapshot.engineLabel} · ${snapshot.expressionLanguage}`;
1586
+ this.renderInstance(snapshot);
1587
+ this.renderIssues(snapshot);
1588
+ }
1589
+ renderInstance({ instances, selectedInstanceId, scenarios }) {
1590
+ const editedInstance = instances.find(candidate => candidate.id === this.editingInstanceId);
1591
+ if (editedInstance && editedInstance.status !== 'completed' && editedInstance.id !== selectedInstanceId) {
1592
+ this.actions.selectInstance(editedInstance.id);
1593
+ return;
1594
+ }
1595
+ const instance = instances.find(candidate => candidate.id === selectedInstanceId);
1596
+ this.renderInstancePicker(instances, selectedInstanceId, scenarios);
1597
+ if (this.editingInstanceId && this.editingInstanceId === instance?.id && instance.status !== 'completed')
1598
+ return;
1599
+ this.editingInstanceId = undefined;
1600
+ this.instanceBody.replaceChildren(instance
1601
+ ? this.instanceView(instance)
1602
+ : h('p', { className: 'bds-hint' }, 'Press ▶ on a start event to start a process instance.'));
1603
+ }
1604
+ renderInstancePicker(instances, selectedInstanceId, scenarios) {
1605
+ const signature = JSON.stringify(instances.map(instance => [instance.id, instance.status]));
1606
+ if (signature !== this.shownInstances) {
1607
+ this.shownInstances = signature;
1608
+ this.instancePicker.replaceChildren(...instances.map(instance => {
1609
+ const scenarioName = scenarios.find(scenario => scenario.id === instance.scenarioId)?.name ?? 'no scenario';
1610
+ return h('option', { value: instance.id }, `#${instance.number} ${scenarioName} (${instance.status})`);
1611
+ }));
1612
+ }
1613
+ this.instancePicker.value = selectedInstanceId ?? '';
1614
+ this.instancePicker.hidden = instances.length < 2;
1615
+ if (!this.instancePicker.isConnected)
1616
+ this.instanceTitle.after(this.instancePicker);
1617
+ }
1618
+ instanceView(instance) {
1619
+ const scenarioName = this.snapshot?.scenarios.find(scenario => scenario.id === instance.scenarioId)?.name;
1620
+ const entries = Object.entries(instance.variables);
1621
+ const editButton = h('button', { className: 'bds-button', type: 'button' }, 'Edit');
1622
+ editButton.addEventListener('click', () => this.editInstance(instance));
1623
+ return h('div', {}, h('p', { className: `bds-status bds-status--${instance.status}` }, describeStatus(instance)), scenarioName ? h('p', { className: 'bds-hint' }, `Scenario: ${scenarioName}`) : null, entries.length
1624
+ ? h('table', { className: 'bds-variables' }, h('tbody', {}, ...entries.map(([name, value]) => h('tr', {}, h('th', { scope: 'row' }, name), h('td', {}, h('code', {}, formatValue(value)))))))
1625
+ : h('p', { className: 'bds-hint' }, 'No variables yet.'), h('p', { className: 'bds-hint' }, 'Hover a gateway to see why it took its flow, click it to keep the card open.'), instance.status !== 'completed' ? h('div', { className: 'bds-actions' }, editButton) : null);
1626
+ }
1627
+ editInstance(instance) {
1628
+ this.editingInstanceId = instance.id;
1629
+ const editor = h('textarea', {
1630
+ className: 'bds-input bds-json bds-instance-editor',
1631
+ spellcheck: 'false',
1632
+ rows: '8',
1633
+ 'aria-label': 'Instance variables (JSON)',
1634
+ });
1635
+ editor.value = JSON.stringify(instance.variables, null, 2);
1636
+ const error = h('p', { className: 'bds-error', role: 'alert' });
1637
+ showError(error, editor, '');
1638
+ const applyButton = h('button', { className: 'bds-button bds-button--primary', type: 'button' }, 'Apply');
1639
+ const cancelButton = h('button', { className: 'bds-button', type: 'button' }, 'Cancel');
1640
+ applyButton.addEventListener('click', () => {
1641
+ const parsed = parseVariables(editor.value);
1642
+ if (typeof parsed === 'string') {
1643
+ showError(error, editor, parsed);
1644
+ return;
1645
+ }
1646
+ this.editingInstanceId = undefined;
1647
+ this.actions.setInstanceVariables(instance.id, parsed);
1648
+ });
1649
+ cancelButton.addEventListener('click', () => {
1650
+ this.editingInstanceId = undefined;
1651
+ if (this.snapshot)
1652
+ this.renderInstance(this.snapshot);
1653
+ });
1654
+ this.instanceBody.replaceChildren(editor, error, h('div', { className: 'bds-actions' }, cancelButton, applyButton));
1655
+ editor.focus();
1656
+ }
1657
+ renderIssues({ log, selectedInstanceId }) {
1658
+ const issues = log.filter((entry) => entry.kind === 'mapping-issue' && entry.instanceId === selectedInstanceId);
1659
+ this.issueSection.hidden = !issues.length;
1660
+ this.issueList.replaceChildren(...issues.slice().reverse().map(renderMappingIssue));
1661
+ }
1662
+ }
1663
+ function describeStatus({ processName, status, waiting }) {
1664
+ if (status !== 'waiting')
1665
+ return `${processName} · ${status}`;
1666
+ return `${processName} · waiting at ${waiting.map(gateway => gateway.gatewayName).join(', ')}`;
1667
+ }
1668
+ function showError(error, input, message) {
1669
+ error.textContent = message;
1670
+ error.hidden = !message;
1671
+ input.classList.toggle('bds-input--invalid', Boolean(message));
1672
+ }
1673
+ function renderMappingIssue({ elementName, target, reason }) {
1674
+ return h('li', { className: 'bds-log-entry bds-log-entry--issue' }, h('div', { className: 'bds-log-title' }, elementName, h('span', { className: 'bds-tag' }, 'mapping')), h('p', { className: 'bds-error' }, `${target}: ${reason}`));
1675
+ }
1676
+ function parseVariables(text) {
1677
+ try {
1678
+ const value = JSON.parse(text || '{}');
1679
+ return isVariables(value) ? value : 'Variables must be a JSON object';
1680
+ }
1681
+ catch (error) {
1682
+ return `Invalid JSON: ${error.message}`;
1683
+ }
1684
+ }
1685
+
1686
+ const PALETTE_INDEX = 4;
1687
+ class DataSimulationPanel {
1688
+ constructor(eventBus, canvas, palette, dataSimulation) {
1689
+ const panel = new VariablesPanel({
1690
+ selectInstance: instanceId => dataSimulation.selectInstance(instanceId),
1691
+ setInstanceVariables: (instanceId, variables) => dataSimulation.setInstanceVariables(instanceId, variables),
1692
+ });
1693
+ panel.render(dataSimulation.getSnapshot());
1694
+ const host = inShadow(panel.element);
1695
+ canvas.getContainer().append(host);
1696
+ palette.addEntry(panel.paletteEntry, PALETTE_INDEX);
1697
+ const showPaletteEntry = () => {
1698
+ panel.paletteEntry.hidden = !dataSimulation.isEnabled();
1699
+ };
1700
+ showPaletteEntry();
1701
+ const unsubscribe = dataSimulation.subscribe(snapshot => panel.render(snapshot));
1702
+ eventBus.on(TOGGLE_MODE_EVENT, () => panel.toggle(false));
1703
+ eventBus.on(DATA_TOGGLE_EVENT, showPaletteEntry);
1704
+ eventBus.on('diagram.destroy', () => {
1705
+ unsubscribe();
1706
+ host.remove();
1707
+ panel.paletteEntry.remove();
1708
+ });
1709
+ }
1710
+ }
1711
+ DataSimulationPanel.$inject = ['eventBus', 'canvas', 'tokenSimulationPalette', 'dataSimulation'];
1712
+
1713
+ const LABEL = 'Data Simulation';
1714
+ const GAP = 8;
1715
+ const TOGGLE_ON = '<svg viewBox="0 0 26 14" aria-hidden="true"><rect x="1" y="1" width="24" height="12" rx="6" /><circle cx="18" cy="7" r="3.5" /></svg>';
1716
+ const TOGGLE_OFF = '<svg viewBox="0 0 26 14" aria-hidden="true"><rect x="1" y="1" width="24" height="12" rx="6" /><circle cx="8" cy="7" r="3.5" /></svg>';
1717
+ class DataSimulationToggle {
1718
+ constructor(eventBus, canvas, toggleMode, dataSimulation) {
1719
+ let simulating = false;
1720
+ const button = h('button', { className: 'bds-data-toggle', type: 'button' });
1721
+ const render = () => {
1722
+ const enabled = dataSimulation.isEnabled();
1723
+ button.innerHTML = `${LABEL} <span class="bds-data-toggle-icon">${enabled ? TOGGLE_ON : TOGGLE_OFF}</span>`;
1724
+ button.classList.toggle('active', enabled);
1725
+ button.setAttribute('aria-pressed', String(enabled));
1726
+ };
1727
+ let tokenToggleObserver;
1728
+ const placeNextToTokenSimulationToggle = () => {
1729
+ const container = canvas.getContainer();
1730
+ const tokenToggle = container.querySelector('.bts-toggle-mode');
1731
+ if (!tokenToggle)
1732
+ return;
1733
+ const containerBox = container.getBoundingClientRect();
1734
+ const toggleBox = tokenToggle.getBoundingClientRect();
1735
+ const scale = containerBox.width / container.offsetWidth || 1;
1736
+ button.style.fontSize = getComputedStyle(tokenToggle).fontSize;
1737
+ button.style.left = `${(toggleBox.right - containerBox.left) / scale + GAP}px`;
1738
+ button.style.top = `${(toggleBox.top + toggleBox.height / 2 - containerBox.top) / scale - button.offsetHeight / 2}px`;
1739
+ if (!tokenToggleObserver && typeof ResizeObserver === 'function') {
1740
+ tokenToggleObserver = new ResizeObserver(placeNextToTokenSimulationToggle);
1741
+ tokenToggleObserver.observe(tokenToggle);
1742
+ }
1743
+ };
1744
+ render();
1745
+ canvas.getContainer().append(button);
1746
+ button.addEventListener('click', () => dataSimulation.setEnabled(!dataSimulation.isEnabled()));
1747
+ eventBus.on(TOGGLE_MODE_EVENT, ({ active }) => {
1748
+ simulating = active;
1749
+ if (active)
1750
+ placeNextToTokenSimulationToggle();
1751
+ });
1752
+ eventBus.on(DATA_TOGGLE_EVENT, () => {
1753
+ render();
1754
+ if (!simulating)
1755
+ return;
1756
+ toggleMode.toggleMode(false);
1757
+ toggleMode.toggleMode(true);
1758
+ });
1759
+ eventBus.on('diagram.destroy', () => {
1760
+ tokenToggleObserver?.disconnect();
1761
+ button.remove();
1762
+ });
1763
+ }
1764
+ }
1765
+ DataSimulationToggle.$inject = ['eventBus', 'canvas', 'toggleMode', 'dataSimulation'];
1766
+
1767
+ const NO_SCENARIO = '';
1768
+ function openStartDialog(container, options) {
1769
+ const { scenarios, renderer } = options;
1770
+ let baseVariables = options.startVariables;
1771
+ const scenarioSelect = h('select', { className: 'bds-input bds-scenario-select', 'aria-label': 'Scenario' });
1772
+ scenarioSelect.append(h('option', { value: NO_SCENARIO }, 'No scenario'), ...scenarios.map(scenario => h('option', { value: scenario.id }, scenario.name)));
1773
+ scenarioSelect.value = options.selectedScenarioId ?? NO_SCENARIO;
1774
+ const scenarioDescription = h('p', { className: 'bds-hint' });
1775
+ const formContainer = h('div', { className: 'bds-dialog-form' });
1776
+ const noFieldsHint = h('p', { className: 'bds-hint' }, 'The process reads no start variables.');
1777
+ const error = h('p', { className: 'bds-error', role: 'alert' });
1778
+ error.hidden = true;
1779
+ const cancelButton = h('button', { className: 'bds-button', type: 'button' }, 'Cancel');
1780
+ const startButton = h('button', { className: 'bds-button bds-button--primary', type: 'submit' }, 'Start instance');
1781
+ const titleId = `bds-start-title-${Math.random().toString(36).slice(2)}`;
1782
+ const form = h('form', { className: 'bds-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId }, h('header', { className: 'bds-dialog-header' }, h('h2', { className: 'bds-panel-title', id: titleId }, `Start “${options.processName}”`), h('span', { className: 'bds-engine' }, options.engineLabel)), h('div', { className: 'bds-dialog-content' }, scenarios.length
1783
+ ? h('section', { className: 'bds-section' }, h('label', { className: 'bds-label' }, 'Scenario', scenarioSelect), scenarioDescription)
1784
+ : null, h('section', { className: 'bds-section' }, h('h3', { className: 'bds-section-title' }, 'Start variables'), formContainer, noFieldsHint), error), h('footer', { className: 'bds-actions' }, cancelButton, startButton));
1785
+ const backdrop = h('div', { className: 'bds-dialog-backdrop' }, form);
1786
+ const selectedScenarioId = () => scenarioSelect.value || null;
1787
+ let fields = [];
1788
+ const renderForm = () => {
1789
+ fields = options.fieldsFor(selectedScenarioId());
1790
+ noFieldsHint.hidden = fields.length > 0;
1791
+ return renderer.render(formContainer, fields, baseVariables);
1792
+ };
1793
+ let rendered = renderForm();
1794
+ const close = () => {
1795
+ rendered.destroy();
1796
+ backdrop.remove();
1797
+ };
1798
+ const showScenarioDescription = () => {
1799
+ const description = scenarios.find(scenario => scenario.id === scenarioSelect.value)?.description ?? '';
1800
+ scenarioDescription.textContent = description;
1801
+ scenarioDescription.hidden = !description;
1802
+ };
1803
+ scenarioSelect.addEventListener('change', () => {
1804
+ baseVariables = scenarios.find(scenario => scenario.id === scenarioSelect.value)?.variables ?? {};
1805
+ rendered.destroy();
1806
+ rendered = renderForm();
1807
+ showScenarioDescription();
1808
+ });
1809
+ cancelButton.addEventListener('click', close);
1810
+ backdrop.addEventListener('mousedown', event => {
1811
+ if (event.target === backdrop)
1812
+ close();
1813
+ });
1814
+ backdrop.addEventListener('keydown', event => {
1815
+ event.stopPropagation();
1816
+ if (event.key === 'Escape')
1817
+ close();
1818
+ });
1819
+ form.addEventListener('submit', event => {
1820
+ event.preventDefault();
1821
+ const values = rendered.readValues();
1822
+ if (!values.ok) {
1823
+ error.textContent = values.reason;
1824
+ error.hidden = false;
1825
+ return;
1826
+ }
1827
+ close();
1828
+ options.onStart(selectedScenarioId(), applyFieldValues(baseVariables, values.values));
1829
+ });
1830
+ showScenarioDescription();
1831
+ container.append(backdrop);
1832
+ if (fields.length)
1833
+ rendered.focus();
1834
+ else
1835
+ startButton.focus();
1836
+ return close;
1837
+ }
1838
+
1839
+ class DataStartForm {
1840
+ constructor(config, eventBus, dataSimulation, store) {
1841
+ this.dataSimulation = dataSimulation;
1842
+ this.store = store;
1843
+ this.renderer = config?.startFormRenderer ?? simpleStartFormRenderer;
1844
+ eventBus.on(TOGGLE_MODE_EVENT, () => this.closeDialog?.());
1845
+ eventBus.on('diagram.destroy', () => {
1846
+ this.closeDialog?.();
1847
+ this.dialogHost?.remove();
1848
+ });
1849
+ }
1850
+ isProcessStart(element) {
1851
+ return (is(element, 'bpmn:StartEvent') &&
1852
+ Boolean(element.parent) &&
1853
+ (is(element.parent, 'bpmn:Process') || is(element.parent, 'bpmn:Participant')));
1854
+ }
1855
+ fieldsFor(startEvent, scenarioId) {
1856
+ const snapshot = this.store.getSnapshot();
1857
+ const examples = [snapshot.startVariables, ...snapshot.scenarios.map(scenario => scenario.variables)];
1858
+ const taskResults = snapshot.scenarios.find(scenario => scenario.id === scenarioId)?.taskResults ?? {};
1859
+ const taskResultNames = Object.values(taskResults).flatMap(result => Object.keys(result));
1860
+ return deriveStartFields(this.collectUsages(startEvent.parent), { examples, taskResultNames });
1861
+ }
1862
+ open(startEvent, start) {
1863
+ this.closeDialog?.();
1864
+ const snapshot = this.store.getSnapshot();
1865
+ this.dialogHost ?? (this.dialogHost = document.body.appendChild(inShadow()));
1866
+ const close = openStartDialog(this.dialogHost.shadowRoot, {
1867
+ processName: elementName(startEvent.parent),
1868
+ engineLabel: `${snapshot.engineLabel} · ${snapshot.expressionLanguage}`,
1869
+ scenarios: snapshot.scenarios,
1870
+ selectedScenarioId: snapshot.selectedScenarioId,
1871
+ startVariables: snapshot.startVariables,
1872
+ fieldsFor: scenarioId => this.fieldsFor(startEvent, scenarioId),
1873
+ renderer: this.renderer,
1874
+ onStart: (scenarioId, variables) => {
1875
+ this.closeDialog = undefined;
1876
+ this.store.selectScenario(scenarioId);
1877
+ this.store.setStartVariables(variables);
1878
+ start();
1879
+ },
1880
+ });
1881
+ this.closeDialog = () => {
1882
+ close();
1883
+ this.closeDialog = undefined;
1884
+ };
1885
+ }
1886
+ collectUsages(container) {
1887
+ const engine = this.dataSimulation.getEngine();
1888
+ const usages = [];
1889
+ const visit = (element) => {
1890
+ if (element.type === 'label')
1891
+ return;
1892
+ const businessObject = element.businessObject;
1893
+ if (is(element, 'bpmn:SequenceFlow')) {
1894
+ const condition = engine.readCondition(businessObject);
1895
+ if (condition)
1896
+ usages.push(usage(element, { conditionReads: engine.readVariableNames(condition) }));
1897
+ }
1898
+ else if (is(element, 'bpmn:FlowNode')) {
1899
+ const inputs = engine.readInputMappings(businessObject);
1900
+ const outputs = engine.readOutputMappings(businessObject);
1901
+ usages.push(usage(element, {
1902
+ inputReads: inputs.flatMap(mapping => engine.readVariableNames(mapping.source)),
1903
+ inputTargets: inputs.map(mapping => mapping.target),
1904
+ outputReads: outputs.flatMap(mapping => engine.readVariableNames(mapping.source)),
1905
+ outputTargets: outputs.map(mapping => mapping.target),
1906
+ }));
1907
+ }
1908
+ element.children?.forEach(visit);
1909
+ };
1910
+ container.children?.forEach(visit);
1911
+ return usages;
1912
+ }
1913
+ }
1914
+ DataStartForm.$inject = ['config.dataSimulation', 'eventBus', 'dataSimulation', 'dataSimulationStore'];
1915
+ function usage(element, reads) {
1916
+ const target = is(element, 'bpmn:SequenceFlow') ? (element.source ?? element) : element;
1917
+ return {
1918
+ elementName: elementName(target),
1919
+ conditionReads: [],
1920
+ inputReads: [],
1921
+ inputTargets: [],
1922
+ outputReads: [],
1923
+ outputTargets: [],
1924
+ ...reads,
1925
+ };
1926
+ }
1927
+
1928
+ const DataSimulationModule = {
1929
+ __init__: [
1930
+ 'dataSimulation',
1931
+ 'dataSimulationOverlays',
1932
+ 'dataSimulationPanel',
1933
+ 'dataSimulationToggle',
1934
+ 'dataGatewayBehaviors',
1935
+ 'dataGatewaySettings',
1936
+ 'dataContextPads',
1937
+ ],
1938
+ dataSimulationStore: ['type', DataSimulationStore],
1939
+ dataSimulation: ['type', DataSimulation],
1940
+ dataSimulationOverlays: ['type', DataSimulationOverlays],
1941
+ dataSimulationPanel: ['type', DataSimulationPanel],
1942
+ dataSimulationToggle: ['type', DataSimulationToggle],
1943
+ dataGateways: ['type', DataGateways],
1944
+ dataStartForm: ['type', DataStartForm],
1945
+ dataGatewayBehaviors: ['type', DataGatewayBehaviors],
1946
+ dataGatewaySettings: ['type', DataGatewaySettings],
1947
+ dataContextPads: ['type', DataContextPads],
1948
+ };
1949
+
1950
+ export { DataSimulationStore, ScenarioError, camunda7Engine, DataSimulationModule as default, formatFieldValue, parseFieldValue, parseScenarios, resolveEngine, routeGateway, simpleStartFormRenderer, zeebeEngine };
1951
+ //# sourceMappingURL=index.js.map