@bpmnkit/core 1.15.0 → 1.17.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 (60) hide show
  1. package/builder-reference.md +2 -1
  2. package/dist/bpmn/auto-layout.d.ts +0 -8
  3. package/dist/bpmn/auto-layout.js +605 -98
  4. package/dist/bpmn/bpmn-builder.d.ts +120 -14
  5. package/dist/bpmn/bpmn-builder.js +411 -152
  6. package/dist/bpmn/bpmn-model.d.ts +15 -0
  7. package/dist/bpmn/bpmn-parser.js +32 -6
  8. package/dist/bpmn/bpmn-serializer.js +9 -2
  9. package/dist/bpmn/compact-stream.d.ts +7 -0
  10. package/dist/bpmn/compact-stream.js +7 -0
  11. package/dist/bpmn/compact.d.ts +124 -9
  12. package/dist/bpmn/compact.js +295 -27
  13. package/dist/bpmn/full-operations.d.ts +19 -0
  14. package/dist/bpmn/full-operations.js +191 -7
  15. package/dist/bpmn/make-room.js +114 -0
  16. package/dist/bpmn/place-new-shapes.js +4 -2
  17. package/dist/bpmn/preserving-writer.d.ts +1 -1
  18. package/dist/bpmn/preserving-writer.js +1 -1
  19. package/dist/bpmn/process-delta.d.ts +32 -1
  20. package/dist/bpmn/process-delta.js +62 -1
  21. package/dist/bpmn/process-text-writer.d.ts +18 -7
  22. package/dist/bpmn/process-text-writer.js +105 -22
  23. package/dist/bpmn/process-text.d.ts +27 -1
  24. package/dist/bpmn/process-text.js +350 -2
  25. package/dist/bpmn/swimlanes.d.ts +178 -0
  26. package/dist/bpmn/swimlanes.js +774 -0
  27. package/dist/index.d.ts +5 -4
  28. package/dist/index.js +3 -2
  29. package/dist/layout/collaboration/crossings.d.ts +13 -0
  30. package/dist/layout/collaboration/crossings.js +37 -0
  31. package/dist/layout/collaboration/docked-labels.d.ts +21 -0
  32. package/dist/layout/collaboration/docked-labels.js +65 -0
  33. package/dist/layout/collaboration/message-tracks.d.ts +20 -0
  34. package/dist/layout/collaboration/message-tracks.js +78 -0
  35. package/dist/layout/collaboration/stack-crossings.d.ts +38 -0
  36. package/dist/layout/collaboration/stack-crossings.js +155 -0
  37. package/dist/layout/grid/edge-labels.js +21 -10
  38. package/dist/layout/layered/coords.d.ts +13 -0
  39. package/dist/layout/layered/coords.js +211 -0
  40. package/dist/layout/layered/index.d.ts +21 -0
  41. package/dist/layout/layered/index.js +288 -0
  42. package/dist/layout/layered/layers.d.ts +60 -0
  43. package/dist/layout/layered/layers.js +374 -0
  44. package/dist/layout/layered/route.d.ts +66 -0
  45. package/dist/layout/layered/route.js +369 -0
  46. package/dist/layout/layout-engine.d.ts +6 -2
  47. package/dist/layout/layout-engine.js +4 -2
  48. package/dist/layout/semantic/bands.js +8 -2
  49. package/dist/layout/semantic/graph.d.ts +33 -1
  50. package/dist/layout/semantic/graph.js +200 -4
  51. package/dist/layout/semantic/index.d.ts +8 -2
  52. package/dist/layout/semantic/index.js +114 -14
  53. package/dist/layout/semantic/lanes.d.ts +40 -0
  54. package/dist/layout/semantic/lanes.js +198 -0
  55. package/dist/layout/semantic/place.d.ts +46 -2
  56. package/dist/layout/semantic/place.js +248 -30
  57. package/dist/layout/semantic/route.js +35 -2
  58. package/dist/layout/types.d.ts +0 -8
  59. package/dist/xml/xml-patch.d.ts +1 -1
  60. package/package.json +2 -2
@@ -0,0 +1,774 @@
1
+ /**
2
+ * Pure helpers for writing lanes and pools: every writer (builder, compact,
3
+ * process text, change scripts, editor) goes through these so they agree on
4
+ * one set of invariants. None of them mutates its input.
5
+ *
6
+ * Invariants a well-formed laned process meets (see {@link laneProblems}):
7
+ * every top-level flow node sits in exactly one leaf lane, a boundary event
8
+ * sits in its host's lane, sub-process children and data references sit in
9
+ * none. Ancestor lanes may or may not repeat their descendants' refs: Flowable
10
+ * and Camunda Modeler write the union, the editor writes leaves only, and both
11
+ * are accepted.
12
+ */
13
+ import { levenshtein } from "./optimize/variable-flow.js";
14
+ const DATA_ELEMENT_TYPES = new Set([
15
+ "dataObject",
16
+ "dataObjectReference",
17
+ "dataStoreReference",
18
+ ]);
19
+ /**
20
+ * Every lane of `laneSet`, depth first with each lane's ancestors.
21
+ * Throws when a lane object is reached twice, which is the only way a
22
+ * programmatically built lane tree can loop.
23
+ */
24
+ function laneEntries(laneSet) {
25
+ const entries = [];
26
+ const seen = new Set();
27
+ const visit = (set, ancestors) => {
28
+ for (const lane of set?.lanes ?? []) {
29
+ if (seen.has(lane))
30
+ throw new Error(revisitMessage(lane.id));
31
+ seen.add(lane);
32
+ entries.push({ lane, ancestors });
33
+ visit(lane.childLaneSet, [...ancestors, lane]);
34
+ }
35
+ };
36
+ visit(laneSet, []);
37
+ return entries;
38
+ }
39
+ /** The error a lane tree that loops back on itself is refused with. */
40
+ export function revisitMessage(laneId) {
41
+ return `Lane "${laneId}" appears twice in one lane tree; a lane tree must not loop back on itself`;
42
+ }
43
+ function isLeaf(lane) {
44
+ return (lane.childLaneSet?.lanes.length ?? 0) === 0;
45
+ }
46
+ /** Rebuilds `laneSet` with each lane's refs replaced by `refsFor(lane)`, keeping everything else. */
47
+ function mapLaneRefs(laneSet, refsFor) {
48
+ const seen = new Set();
49
+ const rebuild = (set) => ({
50
+ ...set,
51
+ lanes: set.lanes.map((lane) => {
52
+ if (seen.has(lane))
53
+ throw new Error(revisitMessage(lane.id));
54
+ seen.add(lane);
55
+ const next = { ...lane, flowNodeRefs: refsFor(lane) };
56
+ if (lane.childLaneSet !== undefined)
57
+ next.childLaneSet = rebuild(lane.childLaneSet);
58
+ return next;
59
+ }),
60
+ });
61
+ return rebuild(laneSet);
62
+ }
63
+ function isFlowNode(element) {
64
+ return !DATA_ELEMENT_TYPES.has(element.type);
65
+ }
66
+ /** Ids of the top-level boundary events attached to `hostId`. */
67
+ function boundaryEventIds(process, hostId) {
68
+ return process.flowElements
69
+ .filter((element) => element.type === "boundaryEvent" && element.attachedToRef === hostId)
70
+ .map((element) => element.id);
71
+ }
72
+ /** Ids of every element nested inside a container (sub-process, transaction, …), at any depth. */
73
+ function nestedElementIds(elements) {
74
+ const ids = new Set();
75
+ const seen = new Set();
76
+ const visit = (children) => {
77
+ for (const child of children) {
78
+ if (seen.has(child)) {
79
+ throw new Error(`Flow element "${child.id}" appears twice in one element tree`);
80
+ }
81
+ seen.add(child);
82
+ ids.add(child.id);
83
+ if ("flowElements" in child)
84
+ visit(child.flowElements);
85
+ }
86
+ };
87
+ for (const element of elements) {
88
+ if ("flowElements" in element)
89
+ visit(element.flowElements);
90
+ }
91
+ return ids;
92
+ }
93
+ function hasContent(process) {
94
+ return process.flowElements.length > 0 || process.laneSet !== undefined;
95
+ }
96
+ /**
97
+ * Every lane of `laneSet`, nested ones included, depth first (a parent before
98
+ * its children). Throws when the lane tree loops back on itself.
99
+ */
100
+ export function allLanes(laneSet) {
101
+ return laneEntries(laneSet).map((entry) => entry.lane);
102
+ }
103
+ /**
104
+ * The lanes of `laneSet` that have no child lanes, depth first: the lanes a
105
+ * flow node is assigned to. Throws when the lane tree loops back on itself.
106
+ */
107
+ export function leafLanes(laneSet) {
108
+ return allLanes(laneSet).filter(isLeaf);
109
+ }
110
+ /**
111
+ * The deepest lane of `process` whose refs list `nodeId`, so a union-convention
112
+ * ancestor never wins over the leaf. `undefined` when no lane lists it.
113
+ */
114
+ export function laneOf(process, nodeId) {
115
+ let deepest;
116
+ for (const entry of laneEntries(process.laneSet)) {
117
+ if (!entry.lane.flowNodeRefs.includes(nodeId))
118
+ continue;
119
+ if (deepest === undefined || entry.ancestors.length > deepest.ancestors.length)
120
+ deepest = entry;
121
+ }
122
+ return deepest?.lane;
123
+ }
124
+ /**
125
+ * True when one of `ancestors` already repeats a ref of its descendants, i.e.
126
+ * the file follows the union convention and expects it kept.
127
+ */
128
+ function followsUnion(ancestors) {
129
+ return ancestors.some((ancestor) => {
130
+ const own = new Set(ancestor.flowNodeRefs);
131
+ return allLanes(ancestor.childLaneSet).some((lane) => lane.flowNodeRefs.some((ref) => own.has(ref)));
132
+ });
133
+ }
134
+ /**
135
+ * Returns a copy of `process` in which `nodeId` and the boundary events
136
+ * attached to it sit in leaf lane `laneId` and in no other lane.
137
+ *
138
+ * Ancestors of the target receive the node too only when the file already
139
+ * follows the union convention there; otherwise only the leaf is written.
140
+ * Whether `nodeId` exists is not checked ({@link laneProblems} reports it).
141
+ *
142
+ * @throws Error when `laneId` is not a lane of `process`, or has child lanes,
143
+ * or when `nodeId` is a boundary event whose host sits in another leaf lane:
144
+ * a boundary event goes where its host goes.
145
+ */
146
+ export function assignLane(process, nodeId, laneId) {
147
+ const laneSet = process.laneSet;
148
+ const target = laneEntries(laneSet).find((entry) => entry.lane.id === laneId);
149
+ if (laneSet === undefined || target === undefined) {
150
+ throw new Error(`Lane "${laneId}" is not declared in process "${process.id}"`);
151
+ }
152
+ if (!isLeaf(target.lane)) {
153
+ throw new Error(`Lane "${laneId}" has child lanes; "${nodeId}" must go in one of its leaf lanes`);
154
+ }
155
+ const element = process.flowElements.find((candidate) => candidate.id === nodeId);
156
+ if (element?.type === "boundaryEvent") {
157
+ const host = leafLanes(laneSet).find((lane) => lane.flowNodeRefs.includes(element.attachedToRef));
158
+ if (host !== undefined && host !== target.lane) {
159
+ throw new Error(`Boundary event "${nodeId}" sits in the lane of its host "${element.attachedToRef}" ("${host.id}"); move the host instead`);
160
+ }
161
+ }
162
+ const moving = [nodeId, ...boundaryEventIds(process, nodeId)];
163
+ const movingIds = new Set(moving);
164
+ const receivers = new Set([
165
+ target.lane,
166
+ ...(followsUnion(target.ancestors) ? target.ancestors : []),
167
+ ]);
168
+ return {
169
+ ...process,
170
+ laneSet: mapLaneRefs(laneSet, (lane) => {
171
+ const kept = lane.flowNodeRefs.filter((ref) => !movingIds.has(ref));
172
+ return receivers.has(lane) ? [...kept, ...moving] : kept;
173
+ }),
174
+ };
175
+ }
176
+ /**
177
+ * Returns a copy of `process` whose lanes list only its top-level flow nodes:
178
+ * refs to missing ids, sub-process children and data references are dropped.
179
+ * A lane set without lanes is removed. A process without a lane set is
180
+ * returned as it is.
181
+ */
182
+ export function pruneLaneRefs(process) {
183
+ const { laneSet, ...rest } = process;
184
+ if (laneSet === undefined)
185
+ return process;
186
+ if (laneSet.lanes.length === 0)
187
+ return rest;
188
+ const flowNodeIds = new Set(process.flowElements.filter(isFlowNode).map((e) => e.id));
189
+ return {
190
+ ...rest,
191
+ laneSet: mapLaneRefs(laneSet, (lane) => lane.flowNodeRefs.filter((r) => flowNodeIds.has(r))),
192
+ };
193
+ }
194
+ /** Ids of all lanes in `specs`, and of the leaves among them. Throws on a looping spec tree or a repeated id. */
195
+ function specIds(specs) {
196
+ const all = new Set();
197
+ const leaves = new Set();
198
+ const seen = new Set();
199
+ const visit = (children) => {
200
+ for (const spec of children) {
201
+ if (seen.has(spec))
202
+ throw new Error(revisitMessage(spec.id));
203
+ seen.add(spec);
204
+ // Two leaves with one id would get the same refs and one DI shape between them.
205
+ if (all.has(spec.id))
206
+ throw new Error(`Lane "${spec.id}" is declared twice`);
207
+ all.add(spec.id);
208
+ if ((spec.lanes?.length ?? 0) === 0)
209
+ leaves.add(spec.id);
210
+ else
211
+ visit(spec.lanes ?? []);
212
+ }
213
+ };
214
+ visit(specs);
215
+ return { all, leaves };
216
+ }
217
+ /**
218
+ * Builds the lane set of `process` from `specs` and `leafOf` (flow node id to
219
+ * leaf lane id). Refs keep `leafOf`'s order and ids verbatim, so
220
+ * {@link laneProblems} can still report a ref to an unknown node. A boundary
221
+ * event always joins its host's lane when the host is mapped. Parent lanes list
222
+ * the union of their descendants' refs. Ids: `LaneSet_<processId>` for the set,
223
+ * `LaneSet_<laneId>` for a child set, with a numeric suffix when already in use.
224
+ *
225
+ * @throws Error listing every `leafOf` entry that names an undeclared lane or a
226
+ * lane with child lanes, or when `specs` loops back on itself or declares
227
+ * one id twice.
228
+ */
229
+ export function buildLaneSet(process, specs, leafOf) {
230
+ const ids = specIds(specs);
231
+ const problems = [];
232
+ for (const [nodeId, laneId] of leafOf) {
233
+ if (!ids.all.has(laneId))
234
+ problems.push(`Lane "${laneId}" is not declared`);
235
+ else if (!ids.leaves.has(laneId)) {
236
+ problems.push(`Lane "${laneId}" has child lanes; "${nodeId}" must go in one of its leaf lanes`);
237
+ }
238
+ }
239
+ if (problems.length > 0)
240
+ throw new Error(`Invalid lane membership:\n ${problems.join("\n ")}`);
241
+ const hostOf = new Map();
242
+ for (const element of process.flowElements) {
243
+ if (element.type === "boundaryEvent")
244
+ hostOf.set(element.id, element.attachedToRef);
245
+ }
246
+ const refsByLane = new Map();
247
+ const place = (laneId, nodeId) => {
248
+ refsByLane.set(laneId, [...(refsByLane.get(laneId) ?? []), nodeId]);
249
+ };
250
+ for (const [nodeId, laneId] of leafOf) {
251
+ const host = hostOf.get(nodeId);
252
+ if (host !== undefined && leafOf.has(host))
253
+ continue; // placed together with its host
254
+ place(laneId, nodeId);
255
+ for (const eventId of boundaryEventIds(process, nodeId))
256
+ place(laneId, eventId);
257
+ }
258
+ // A lane may be named `LaneSet_<id>` too; the set ids step around every id in use.
259
+ const taken = new Set([
260
+ process.id,
261
+ ...ids.all,
262
+ ...process.flowElements.map((element) => element.id),
263
+ ...process.sequenceFlows.map((flow) => flow.id),
264
+ ]);
265
+ const setId = (owner) => freshId(`LaneSet_${owner}`, (n) => `LaneSet_${owner}_${n}`, taken);
266
+ // specIds has rejected a looping spec tree, so this recursion terminates.
267
+ const toLane = (spec) => {
268
+ const children = (spec.lanes ?? []).map(toLane);
269
+ const lane = {
270
+ id: spec.id,
271
+ flowNodeRefs: children.length === 0
272
+ ? (refsByLane.get(spec.id) ?? [])
273
+ : [...new Set(children.flatMap((child) => child.flowNodeRefs))],
274
+ unknownAttributes: {},
275
+ };
276
+ if (spec.name !== undefined)
277
+ lane.name = spec.name;
278
+ if (children.length > 0) {
279
+ lane.childLaneSet = { id: setId(spec.id), lanes: children, unknownAttributes: {} };
280
+ }
281
+ return lane;
282
+ };
283
+ const rootId = setId(process.id);
284
+ return { id: rootId, lanes: specs.map(toLane), unknownAttributes: {} };
285
+ }
286
+ /**
287
+ * The leaf lane a node newly added to an already-laned `process` belongs in:
288
+ * its host's lane for a boundary event, else the lane of its first sequence-flow
289
+ * predecessor that has one, else of its first such successor, else the first
290
+ * leaf lane. `undefined` when the process has no lanes.
291
+ */
292
+ export function laneForNewNode(process, nodeId) {
293
+ const leaves = leafLanes(process.laneSet);
294
+ if (leaves.length === 0)
295
+ return undefined;
296
+ const element = process.flowElements.find((e) => e.id === nodeId);
297
+ const neighbours = [
298
+ ...(element?.type === "boundaryEvent" ? [element.attachedToRef] : []),
299
+ ...process.sequenceFlows.filter((f) => f.targetRef === nodeId).map((f) => f.sourceRef),
300
+ ...process.sequenceFlows.filter((f) => f.sourceRef === nodeId).map((f) => f.targetRef),
301
+ ];
302
+ for (const neighbour of neighbours) {
303
+ const leaf = leaves.find((lane) => lane.flowNodeRefs.includes(neighbour));
304
+ if (leaf !== undefined)
305
+ return leaf;
306
+ }
307
+ return leaves[0];
308
+ }
309
+ /**
310
+ * The process a single-process writer edits: the first process, in the
311
+ * participant order of `collaborations[0]`, that is explicitly executable; else
312
+ * the first explicitly executable process; else the first process with flow
313
+ * elements or lanes. When every process is empty, the candidates are the ones
314
+ * not marked `isExecutable="false"` (Flowable reads an absent attribute as
315
+ * executable), or all of them when every one is; among them the one whose pool
316
+ * is drawn largest, else the first. Modeler files do not always put the
317
+ * executable pool first.
318
+ *
319
+ * {@link BpmnDefinitions.primaryProcessId}, while it names a process of
320
+ * `defs`, comes right after the explicitly executable process: it breaks the
321
+ * tie the semantics cannot, as an emptied own pool next to a partner's pool
322
+ * with content and `isExecutable="false"` reads exactly like a partner's empty
323
+ * pool next to a file's only process. An explicit `isExecutable="true"`, which
324
+ * another tool may have set since, is no tie and still wins.
325
+ */
326
+ export function primaryProcess(defs) {
327
+ const byId = new Map(defs.processes.map((process) => [process.id, process]));
328
+ for (const participant of defs.collaborations[0]?.participants ?? []) {
329
+ const process = participant.processRef === undefined ? undefined : byId.get(participant.processRef);
330
+ if (process?.isExecutable === true)
331
+ return process;
332
+ }
333
+ const pinned = defs.primaryProcessId === undefined ? undefined : byId.get(defs.primaryProcessId);
334
+ return (defs.processes.find((process) => process.isExecutable === true) ??
335
+ pinned ??
336
+ // An empty process is a partner's; picking it would mark the real one
337
+ // non-executable in poolLanedProcesses, and Flowable would deploy nothing.
338
+ defs.processes.find(hasContent) ??
339
+ emptiedPrimary(defs));
340
+ }
341
+ /** The namespace of the `primaryProcess` attribute {@link pinnedPrimaryToWrite} puts on `<definitions>`. */
342
+ export const BPMNKIT_NAMESPACE = "https://bpmnkit.com/schema/bpmn";
343
+ /**
344
+ * `namespaces` with {@link BPMNKIT_NAMESPACE} declared, and its prefix: the one
345
+ * already declared, else `bpmnkit`, else the first free `bpmnkit<n>`.
346
+ */
347
+ export function withBpmnkitNamespace(namespaces) {
348
+ const declared = Object.keys(namespaces).find((prefix) => prefix !== "" && namespaces[prefix] === BPMNKIT_NAMESPACE);
349
+ if (declared !== undefined)
350
+ return { namespaces, prefix: declared };
351
+ let prefix = "bpmnkit";
352
+ for (let n = 2; prefix in namespaces; n++)
353
+ prefix = `bpmnkit${n}`;
354
+ return { namespaces: { ...namespaces, [prefix]: BPMNKIT_NAMESPACE }, prefix };
355
+ }
356
+ /**
357
+ * `defs` with {@link BpmnDefinitions.primaryProcessId} set to `processId`, or
358
+ * cleared when it is `undefined`. Setting it also declares the bpmnkit
359
+ * namespace, and clearing it leaves the declaration: a document parsed from a
360
+ * pinned file keeps it too, so both write the same bytes whatever happens to
361
+ * the pin later.
362
+ */
363
+ export function pinPrimaryProcess(defs, processId) {
364
+ const { primaryProcessId: _old, ...bare } = defs;
365
+ if (processId === undefined)
366
+ return bare;
367
+ return {
368
+ ...bare,
369
+ namespaces: withBpmnkitNamespace(defs.namespaces).namespaces,
370
+ primaryProcessId: processId,
371
+ };
372
+ }
373
+ /**
374
+ * The {@link BpmnDefinitions.primaryProcessId} a file must carry, or
375
+ * `undefined` when the file alone already leads {@link primaryProcess} there,
376
+ * so a document nobody emptied stays byte-identical.
377
+ */
378
+ export function pinnedPrimaryToWrite(defs) {
379
+ const pinned = defs.primaryProcessId;
380
+ if (pinned === undefined || !defs.processes.some((process) => process.id === pinned)) {
381
+ return undefined;
382
+ }
383
+ return primaryProcess({ ...defs, primaryProcessId: undefined })?.id === pinned
384
+ ? undefined
385
+ : pinned;
386
+ }
387
+ /**
388
+ * Once an edit empties the process the user works on, nothing in the semantics
389
+ * may tell it from an empty partner, and a switch would lock the user out of
390
+ * their own pool. The drawing still does: a partner is a thin band.
391
+ * A file without pool DI has no thin band to go by, so it falls back to
392
+ * document order.
393
+ */
394
+ function emptiedPrimary(defs) {
395
+ const runnable = defs.processes.filter((process) => process.isExecutable !== false);
396
+ const candidates = runnable.length > 0 ? runnable : defs.processes;
397
+ const area = new Map();
398
+ for (const diagram of defs.diagrams ?? []) {
399
+ for (const shape of diagram.plane.shapes) {
400
+ area.set(shape.bpmnElement, shape.bounds.width * shape.bounds.height);
401
+ }
402
+ }
403
+ const poolArea = (process) => {
404
+ let largest = 0;
405
+ for (const participant of defs.collaborations.flatMap((c) => c.participants)) {
406
+ if (participant.processRef !== process.id)
407
+ continue;
408
+ largest = Math.max(largest, area.get(participant.id) ?? 0);
409
+ }
410
+ return largest;
411
+ };
412
+ let best = candidates[0];
413
+ for (const candidate of candidates) {
414
+ if (best === undefined || poolArea(candidate) > poolArea(best))
415
+ best = candidate;
416
+ }
417
+ return best;
418
+ }
419
+ /**
420
+ * Every id the document uses, once per use, so an id listed twice is a clash:
421
+ * the definitions, root elements, processes with their flow elements, flows and
422
+ * artifacts at any depth, lane sets and lanes, and collaborations with what
423
+ * they hold. Duplicate checks and fresh ids both read this one list, so they
424
+ * cannot disagree about what is taken.
425
+ */
426
+ export function documentIdList(defs) {
427
+ const ids = [];
428
+ if (defs.id)
429
+ ids.push(defs.id);
430
+ for (const root of [
431
+ ...(defs.messages ?? []),
432
+ ...(defs.errors ?? []),
433
+ ...(defs.signals ?? []),
434
+ ...(defs.escalations ?? []),
435
+ ]) {
436
+ ids.push(root.id);
437
+ }
438
+ const visit = (scope) => {
439
+ for (const item of [
440
+ ...scope.flowElements,
441
+ ...scope.sequenceFlows,
442
+ ...(scope.textAnnotations ?? []),
443
+ ...(scope.associations ?? []),
444
+ ...(scope.groups ?? []),
445
+ ]) {
446
+ ids.push(item.id);
447
+ }
448
+ for (const element of scope.flowElements) {
449
+ if ("flowElements" in element && "sequenceFlows" in element)
450
+ visit(element);
451
+ }
452
+ };
453
+ for (const process of defs.processes ?? []) {
454
+ ids.push(process.id);
455
+ visit(process);
456
+ const lanes = allLanes(process.laneSet);
457
+ for (const set of [process.laneSet, ...lanes.map((lane) => lane.childLaneSet)]) {
458
+ if (set?.id)
459
+ ids.push(set.id);
460
+ }
461
+ for (const lane of lanes)
462
+ ids.push(lane.id);
463
+ }
464
+ for (const collaboration of defs.collaborations ?? []) {
465
+ ids.push(collaboration.id);
466
+ for (const item of [
467
+ ...collaboration.participants,
468
+ ...collaboration.messageFlows,
469
+ ...collaboration.textAnnotations,
470
+ ...collaboration.associations,
471
+ ...collaboration.groups,
472
+ ]) {
473
+ ids.push(item.id);
474
+ }
475
+ }
476
+ return ids;
477
+ }
478
+ /** Every repeated use in {@link documentIdList}: an id used three times is listed twice. */
479
+ export function duplicateIds(defs) {
480
+ const seen = new Set();
481
+ const repeats = [];
482
+ for (const id of documentIdList(defs)) {
483
+ if (seen.has(id))
484
+ repeats.push(id);
485
+ else
486
+ seen.add(id);
487
+ }
488
+ return repeats;
489
+ }
490
+ /**
491
+ * `first` when free, else the first free `nth(2)`, `nth(3)`, …; claims it in `taken`.
492
+ * Bounded: at most `taken.size` candidates can be taken, so one of the first
493
+ * `taken.size + 1` distinct candidates is free.
494
+ */
495
+ export function freshId(first, nth, taken) {
496
+ let id = first;
497
+ for (let n = 2; taken.has(id) && n <= taken.size + 2; n++)
498
+ id = nth(n);
499
+ taken.add(id);
500
+ return id;
501
+ }
502
+ /**
503
+ * "Lanes imply a pool": auto-layout draws lanes only inside a participant, and
504
+ * once a collaboration exists a process without one is drawn pool-less.
505
+ *
506
+ * When any process has a lane set or any collaboration exists, returns a copy
507
+ * in which `collaborations[0]` exists (id `Collaboration_1` unless taken) and
508
+ * every process with flow elements or a lane set is referenced by a
509
+ * participant (`Participant_<processId>`, named after the process, else its
510
+ * id). A process pooled here that is not the {@link primaryProcess} and has no
511
+ * `isExecutable` gets `isExecutable: false`, because Flowable reads an absent
512
+ * attribute as executable. Otherwise returns `defs` itself.
513
+ */
514
+ export function poolLanedProcesses(defs) {
515
+ const hasLanes = defs.processes.some((process) => process.laneSet !== undefined);
516
+ if (!hasLanes && defs.collaborations.length === 0)
517
+ return defs;
518
+ const pooled = new Set(defs.collaborations.flatMap((c) => c.participants.map((participant) => participant.processRef)));
519
+ const unpooled = defs.processes.filter((process) => hasContent(process) && !pooled.has(process.id));
520
+ if (unpooled.length === 0 && defs.collaborations.length > 0)
521
+ return defs;
522
+ const taken = new Set(documentIdList(defs));
523
+ const first = defs.collaborations[0] ?? {
524
+ id: freshId("Collaboration_1", (n) => `Collaboration_${n}`, taken),
525
+ participants: [],
526
+ messageFlows: [],
527
+ textAnnotations: [],
528
+ associations: [],
529
+ groups: [],
530
+ extensionElements: [],
531
+ unknownAttributes: {},
532
+ };
533
+ const added = unpooled.map((process) => ({
534
+ id: freshId(`Participant_${process.id}`, (n) => `Participant_${process.id}_${n}`, taken),
535
+ name: process.name ?? process.id,
536
+ processRef: process.id,
537
+ unknownAttributes: {},
538
+ }));
539
+ const primary = primaryProcess(defs);
540
+ const partners = new Set(unpooled.filter((process) => process !== primary));
541
+ return {
542
+ ...defs,
543
+ collaborations: [
544
+ { ...first, participants: [...first.participants, ...added] },
545
+ ...defs.collaborations.slice(1),
546
+ ],
547
+ processes: defs.processes.map((process) => partners.has(process) && process.isExecutable === undefined
548
+ ? { ...process, isExecutable: false }
549
+ : process),
550
+ };
551
+ }
552
+ /**
553
+ * Everything wrong with the lanes of `process`, one message per finding:
554
+ * duplicate lane ids, refs to missing ids, to sub-process children or to data
555
+ * references, a flow node in two leaf lanes, and — once lanes exist — a
556
+ * top-level flow node in no leaf lane (data references, and boundary events
557
+ * whose host is assigned, are exempt), and a boundary event in a leaf lane its
558
+ * host is not in. Whether parents repeat their children's refs is not checked.
559
+ * Empty for a process without lanes.
560
+ */
561
+ export function laneProblems(process) {
562
+ const entries = laneEntries(process.laneSet);
563
+ if (entries.length === 0)
564
+ return [];
565
+ const problems = [];
566
+ const laneIds = new Set();
567
+ for (const { lane } of entries) {
568
+ if (laneIds.has(lane.id))
569
+ problems.push(`Duplicate lane ID "${lane.id}"`);
570
+ laneIds.add(lane.id);
571
+ }
572
+ const topLevel = new Map(process.flowElements.map((element) => [element.id, element]));
573
+ const nested = nestedElementIds(process.flowElements);
574
+ // A union-convention parent repeats its children's refs; one finding per ref is enough.
575
+ const reported = new Set();
576
+ for (const { lane } of entries) {
577
+ for (const ref of lane.flowNodeRefs) {
578
+ const problem = refProblem(process, lane.id, ref, topLevel.get(ref), nested.has(ref));
579
+ if (problem === undefined || reported.has(ref))
580
+ continue;
581
+ reported.add(ref);
582
+ problems.push(problem);
583
+ }
584
+ }
585
+ const leavesOf = new Map();
586
+ for (const { lane } of entries.filter((entry) => isLeaf(entry.lane))) {
587
+ for (const ref of new Set(lane.flowNodeRefs)) {
588
+ leavesOf.set(ref, [...(leavesOf.get(ref) ?? []), lane.id]);
589
+ }
590
+ }
591
+ for (const element of process.flowElements.filter(isFlowNode)) {
592
+ const leaves = leavesOf.get(element.id) ?? [];
593
+ if (leaves.length > 1) {
594
+ problems.push(`Flow node "${element.id}" is in lanes ${leaves.map((id) => `"${id}"`).join(" and ")}; a node belongs to one leaf lane`);
595
+ }
596
+ if (leaves.length > 0) {
597
+ const host = element.type === "boundaryEvent" ? leavesOf.get(element.attachedToRef) : undefined;
598
+ if (element.type === "boundaryEvent" && host && !leaves.some((leaf) => host.includes(leaf))) {
599
+ problems.push(`Boundary event "${element.id}" is in lane "${leaves[0]}" but its host "${element.attachedToRef}" is in "${host[0]}"; a boundary event sits in its host's lane`);
600
+ }
601
+ continue;
602
+ }
603
+ if (element.type === "boundaryEvent" && leavesOf.has(element.attachedToRef))
604
+ continue;
605
+ problems.push(`Flow node "${element.id}" is in no lane of process "${process.id}"`);
606
+ }
607
+ return problems;
608
+ }
609
+ function refProblem(process, laneId, ref, element, isNested) {
610
+ if (element !== undefined) {
611
+ return isFlowNode(element)
612
+ ? undefined
613
+ : `Lane "${laneId}" lists "${ref}", a data object or data store reference; lanes hold flow nodes only`;
614
+ }
615
+ if (isNested) {
616
+ return `Lane "${laneId}" lists "${ref}", which sits inside a sub-process; only top-level flow nodes belong in a lane`;
617
+ }
618
+ return `Lane "${laneId}" lists "${ref}", which is not a flow node of process "${process.id}"`;
619
+ }
620
+ const MESSAGE_EVENTS = new Set([
621
+ "startEvent",
622
+ "endEvent",
623
+ "intermediateCatchEvent",
624
+ "intermediateThrowEvent",
625
+ "boundaryEvent",
626
+ ]);
627
+ const DATA_TYPES = new Set([
628
+ "dataObject",
629
+ "dataObjectReference",
630
+ "dataStoreReference",
631
+ ]);
632
+ /**
633
+ * Why an element of `type` cannot be the `side` end of a message flow, or
634
+ * undefined when it can. `trigger` is an event's first event definition
635
+ * (`"message"`, `"timer"`, …), undefined for a plain event or anything else.
636
+ * A pool can be either end. One rule for every writer, so a change script, the
637
+ * process text reader and the editor refuse the same messages.
638
+ */
639
+ export function messageEndProblem(type, trigger, side) {
640
+ if (type.endsWith("Gateway"))
641
+ return "a gateway cannot send or receive a message";
642
+ if (DATA_TYPES.has(type))
643
+ return "a data object or store cannot send or receive a message";
644
+ if (side === "source") {
645
+ if (type === "startEvent")
646
+ return "a start event cannot send a message";
647
+ if (type === "intermediateCatchEvent" || type === "boundaryEvent") {
648
+ return "a catch event cannot send a message";
649
+ }
650
+ }
651
+ else {
652
+ if (type === "endEvent")
653
+ return "an end event cannot receive a message";
654
+ if (type === "intermediateThrowEvent")
655
+ return "a throw event cannot receive a message";
656
+ }
657
+ // A timer or a signal waits for, or sends, something else; only a plain event can be made a message one.
658
+ if (MESSAGE_EVENTS.has(type) && trigger !== undefined && trigger !== "message") {
659
+ return `a ${trigger} event cannot ${side === "source" ? "send" : "receive"} a message`;
660
+ }
661
+ return undefined;
662
+ }
663
+ /**
664
+ * Everything about the collaborations of `defs` that a modeler would refuse
665
+ * or open broken, one message per finding: duplicate participant or message
666
+ * flow ids, a participant naming a missing process, two participants claiming
667
+ * one process, a message-flow end that is neither a participant nor a flow node
668
+ * in one, a message flow that stays inside one pool, a message flow naming an
669
+ * undeclared message, and — once a collaboration exists — a process with
670
+ * content that no participant references. Empty without collaborations.
671
+ */
672
+ export function collaborationProblems(defs) {
673
+ if (defs.collaborations.length === 0)
674
+ return [];
675
+ const participants = defs.collaborations.flatMap((collaboration) => collaboration.participants);
676
+ const messageFlows = defs.collaborations.flatMap((collaboration) => collaboration.messageFlows);
677
+ const problems = [];
678
+ // Every id in the document, not only pools and message flows: two processes
679
+ // may each declare the same lane, and a node may share a pool's id, which
680
+ // would also make the owning pool of a message-flow end ambiguous.
681
+ // Ids are global in a collaboration, so the same id in two pools gets both
682
+ // pools named and the fix.
683
+ const owners = new Map();
684
+ for (const process of defs.processes) {
685
+ const ids = [
686
+ ...process.flowElements.map((element) => element.id),
687
+ ...nestedElementIds(process.flowElements),
688
+ ...process.sequenceFlows.map((flow) => flow.id),
689
+ ];
690
+ for (const id of ids)
691
+ owners.set(id, (owners.get(id) ?? new Set()).add(process.id));
692
+ }
693
+ for (const id of duplicateIds(defs)) {
694
+ const [first, second] = owners.get(id) ?? [];
695
+ problems.push(first !== undefined && second !== undefined
696
+ ? `Duplicate element ID "${id}" in processes "${first}" and "${second}": ids are global in a collaboration; prefix them per pool (e.g. "${second}_${id}")`
697
+ : `Duplicate element ID "${id}"`);
698
+ }
699
+ const processIds = new Set(defs.processes.map((process) => process.id));
700
+ const claimed = new Map();
701
+ for (const participant of participants) {
702
+ const processId = participant.processRef;
703
+ if (processId === undefined)
704
+ continue;
705
+ if (!processIds.has(processId)) {
706
+ problems.push(`Participant "${participant.id}" references process "${processId}", which this diagram does not contain`);
707
+ continue;
708
+ }
709
+ const owner = claimed.get(processId);
710
+ if (owner !== undefined) {
711
+ problems.push(`Participants "${owner}" and "${participant.id}" both reference process "${processId}"; a process belongs to one pool`);
712
+ }
713
+ claimed.set(processId, participant.id);
714
+ }
715
+ const owningParticipant = participantIndex(participants, defs.processes);
716
+ const messageIds = new Set(defs.messages.map((message) => message.id));
717
+ for (const flow of messageFlows) {
718
+ for (const [role, ref] of [
719
+ ["source", flow.sourceRef],
720
+ ["target", flow.targetRef],
721
+ ]) {
722
+ if (!owningParticipant.has(ref)) {
723
+ problems.push(`Message flow "${flow.id}" names ${role} "${ref}", which is not a participant or a flow node in one${closeIds(ref, [...owningParticipant.keys()])}`);
724
+ }
725
+ }
726
+ const from = owningParticipant.get(flow.sourceRef);
727
+ const to = owningParticipant.get(flow.targetRef);
728
+ if (from !== undefined && from === to) {
729
+ problems.push(`Message flow "${flow.id}" starts and ends in participant "${from}"; a message flow crosses pools, a sequence flow stays inside one`);
730
+ }
731
+ if (flow.messageRef !== undefined && !messageIds.has(flow.messageRef)) {
732
+ problems.push(`Message flow "${flow.id}" references message "${flow.messageRef}", which this diagram does not declare`);
733
+ }
734
+ }
735
+ for (const process of defs.processes) {
736
+ if (hasContent(process) && !claimed.has(process.id)) {
737
+ problems.push(`Process "${process.id}" has content but no participant; once a diagram has a collaboration, every process with content needs a pool`);
738
+ }
739
+ }
740
+ return problems;
741
+ }
742
+ /** A "did you mean" suffix naming up to three existing ids close to `ref`. */
743
+ function closeIds(ref, existing) {
744
+ const lower = ref.toLowerCase();
745
+ const close = existing
746
+ .filter((id) => id.length >= 3)
747
+ .map((id) => ({ id, d: levenshtein(lower, id.toLowerCase()) }))
748
+ .filter(({ id, d }) => d <= Math.max(2, Math.floor(ref.length / 3)) || id.includes(ref) || ref.includes(id))
749
+ .sort((a, b) => a.d - b.d)
750
+ .slice(0, 3)
751
+ .map(({ id }) => `"${id}"`);
752
+ return close.length > 0 ? `; did you mean ${close.join(", ")}?` : "";
753
+ }
754
+ /** Maps every participant id and every flow node id (nested ones included) to its owning participant. */
755
+ function participantIndex(participants, processes) {
756
+ const index = new Map();
757
+ const byProcess = new Map();
758
+ for (const participant of participants) {
759
+ index.set(participant.id, participant.id);
760
+ if (participant.processRef !== undefined)
761
+ byProcess.set(participant.processRef, participant.id);
762
+ }
763
+ for (const process of processes) {
764
+ const owner = byProcess.get(process.id);
765
+ if (owner === undefined)
766
+ continue;
767
+ for (const element of process.flowElements)
768
+ index.set(element.id, owner);
769
+ for (const id of nestedElementIds(process.flowElements))
770
+ index.set(id, owner);
771
+ }
772
+ return index;
773
+ }
774
+ //# sourceMappingURL=swimlanes.js.map