@bpmnkit/core 1.14.0 → 1.16.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 (44) hide show
  1. package/AGENTS.md +5 -4
  2. package/agent-cards/bpmn.md +86 -80
  3. package/builder-reference.md +27 -8
  4. package/dist/bpmn/auto-layout.js +235 -42
  5. package/dist/bpmn/bpmn-builder.d.ts +171 -17
  6. package/dist/bpmn/bpmn-builder.js +792 -135
  7. package/dist/bpmn/bpmn-model.d.ts +15 -0
  8. package/dist/bpmn/bpmn-parser.js +32 -6
  9. package/dist/bpmn/bpmn-serializer.js +9 -2
  10. package/dist/bpmn/compact-stream.d.ts +7 -0
  11. package/dist/bpmn/compact-stream.js +7 -0
  12. package/dist/bpmn/compact.d.ts +126 -9
  13. package/dist/bpmn/compact.js +305 -30
  14. package/dist/bpmn/full-operations.d.ts +19 -0
  15. package/dist/bpmn/full-operations.js +191 -7
  16. package/dist/bpmn/make-room.d.ts +26 -0
  17. package/dist/bpmn/make-room.js +151 -0
  18. package/dist/bpmn/optimize/flow.js +8 -0
  19. package/dist/bpmn/place-new-shapes.d.ts +6 -1
  20. package/dist/bpmn/place-new-shapes.js +53 -2
  21. package/dist/bpmn/preserving-writer.d.ts +1 -1
  22. package/dist/bpmn/preserving-writer.js +1 -1
  23. package/dist/bpmn/process-delta.d.ts +32 -1
  24. package/dist/bpmn/process-delta.js +62 -1
  25. package/dist/bpmn/process-text-writer.d.ts +18 -7
  26. package/dist/bpmn/process-text-writer.js +105 -22
  27. package/dist/bpmn/process-text.d.ts +34 -2
  28. package/dist/bpmn/process-text.js +410 -7
  29. package/dist/bpmn/swimlanes.d.ts +178 -0
  30. package/dist/bpmn/swimlanes.js +774 -0
  31. package/dist/form/user-task-forms.d.ts +45 -0
  32. package/dist/form/user-task-forms.js +129 -0
  33. package/dist/index.d.ts +9 -4
  34. package/dist/index.js +5 -2
  35. package/dist/layout/collaboration/message-labels.d.ts +25 -0
  36. package/dist/layout/collaboration/message-labels.js +108 -0
  37. package/dist/layout/collaboration/ordering.d.ts +5 -1
  38. package/dist/layout/collaboration/ordering.js +24 -9
  39. package/dist/layout/semantic/graph.js +3 -0
  40. package/dist/layout/semantic/place.d.ts +2 -0
  41. package/dist/layout/semantic/place.js +77 -9
  42. package/dist/xml/xml-patch.d.ts +1 -1
  43. package/llms.txt +1 -1
  44. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import { assertBpmnDefinitions, assertCompactDiagram } from "./argument-guards.js";
2
- import { buildFlowElement, compactify, defaultFlows, makeEventDef, } from "./compact.js";
2
+ import { buildFlowElement, compactify, compactifyLanes, compactifyMessageFlow, compactifyParticipant, defaultFlows, executability, expandCollaborations, fillLanes, isPooled, makeEventDef, withLanes, } from "./compact.js";
3
3
  import { assignEventDefinitionIds } from "./stable-ids.js";
4
+ import { allLanes, collaborationProblems, documentIdList, poolLanedProcesses, pruneLaneRefs, } from "./swimlanes.js";
4
5
  import { assertZeebePlacement, bpmnElementName, ensureZeebeExtension, isZeebePlacementAllowed, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
5
6
  /** Thrown by {@link applyBpmnOperations} in strict mode. */
6
7
  export class OperationError extends Error {
@@ -617,16 +618,23 @@ export function applyBpmnOperations(definitions, operations, options = {}) {
617
618
  const draft = structuredClone(definitions);
618
619
  const problems = [];
619
620
  let applied = 0;
621
+ const inserted = [];
620
622
  operations.forEach((operation, index) => {
621
623
  const reason = applyOne(draft, operation);
622
- if (reason === undefined)
623
- applied++;
624
- else
624
+ if (reason !== undefined)
625
625
  problems.push({ index, operation, reason });
626
+ else {
627
+ applied++;
628
+ if (operation.op === "insert")
629
+ inserted.push(operation.element.id);
630
+ }
626
631
  });
627
632
  if ((options.strict ?? true) && problems.length > 0) {
628
633
  throw new OperationError(problems);
629
634
  }
635
+ // After every operation rather than at the insert, so the flows a batch adds
636
+ // next to a new node decide its lane.
637
+ draft.processes = draft.processes.map((process) => fillLanes(process, inserted));
630
638
  return { definitions: draft, applied, problems };
631
639
  }
632
640
  function applyOne(definitions, operation) {
@@ -652,6 +660,11 @@ function applyOne(definitions, operation) {
652
660
  // A flow to or from a removed element would dangle.
653
661
  found.container.sequenceFlows = found.container.sequenceFlows.filter((flow) => flow.sourceRef !== operation.id && flow.targetRef !== operation.id);
654
662
  recomputeRefs(found.container);
663
+ // A lane ref or a message flow naming the removed node would dangle too.
664
+ definitions.processes = definitions.processes.map((process) => process === found.container ? pruneLaneRefs(process) : process);
665
+ for (const collaboration of definitions.collaborations) {
666
+ collaboration.messageFlows = collaboration.messageFlows.filter((flow) => flow.sourceRef !== operation.id && flow.targetRef !== operation.id);
667
+ }
655
668
  return undefined;
656
669
  }
657
670
  case "insert": {
@@ -762,20 +775,44 @@ function recomputeRefs(container) {
762
775
  * a multi-process document means "this is how that process should look", not
763
776
  * "delete the others".
764
777
  *
778
+ * Lanes, pools and executability follow the same rule: a key the compact leaves
779
+ * out leaves that part of the model alone. A process's `lanes` rebuilds its
780
+ * membership (an empty list removes the lane set), keeping the attributes and
781
+ * extensions of every lane whose id survives; members that are not top-level
782
+ * flow nodes are dropped and unlisted nodes are placed as {@link expand} places
783
+ * them. `participants` and `messageFlows` replace those of the first
784
+ * collaboration, keeping what the compact form does not carry (`messageRef`,
785
+ * extensions, foreign attributes) on every id that survives. A lane, pool or
786
+ * message flow listed without a `name` has none, as {@link compactify} writes
787
+ * it, so a compact edit can remove a name. A laned process
788
+ * without a pool then gets one. A process the compact adds gets the
789
+ * `isExecutable` {@link expand} would give it, so a keyless partner pool is
790
+ * not executable. Without the keys, a deleted node still leaves
791
+ * its lanes and message flows, and an inserted one joins its predecessor's lane.
792
+ *
765
793
  * @param definitions - The model to update. Never mutated.
766
794
  * @param compact - The intended topology.
767
795
  * @param options - `strict` (default `true`) throws instead of returning problems.
768
796
  * @returns The updated model, plus what applied and what did not.
797
+ * @throws Error, in either mode, when the result would carry an id used twice
798
+ * or a collaboration problem (a dangling message end or process reference, a
799
+ * message inside one pool) that `definitions` did not already have: the
800
+ * input is invalid, as {@link expand} would find it.
769
801
  */
770
802
  export function reconcileCompact(definitions, compact, options = {}) {
771
803
  assertBpmnDefinitions(definitions, "reconcileCompact");
772
804
  assertCompactDiagram(compact, "reconcileCompact");
773
805
  const draft = structuredClone(definitions);
774
- for (const compactProcess of compact.processes) {
806
+ // A new process gets the executability expand would give it: Flowable deploys
807
+ // a process with no isExecutable, so a keyless partner pool must say false.
808
+ // poolLanedProcesses cannot, as it only marks the pools it creates itself.
809
+ const executable = executability(compact, isPooled(compact));
810
+ compact.processes.forEach((compactProcess, index) => {
775
811
  if (!draft.processes.some((process) => process.id === compactProcess.id)) {
776
812
  draft.processes.push({
777
813
  id: compactProcess.id,
778
814
  name: compactProcess.name,
815
+ ...(executable[index] === false ? { isExecutable: false } : {}),
779
816
  extensionElements: [],
780
817
  flowElements: [],
781
818
  sequenceFlows: [],
@@ -785,10 +822,157 @@ export function reconcileCompact(definitions, compact, options = {}) {
785
822
  unknownAttributes: {},
786
823
  });
787
824
  }
788
- }
825
+ });
789
826
  const result = applyBpmnOperations(draft, operationsForCompact(draft, compact), options);
790
827
  reconcileDefaultFlows(result.definitions, compact);
791
- return result;
828
+ const reconciled = reconcilePools(result.definitions, compact);
829
+ const broken = newStructureProblems(definitions, reconciled);
830
+ if (broken.length > 0) {
831
+ throw new Error(`reconcileCompact: invalid CompactDiagram — ${broken.join("; ")}`);
832
+ }
833
+ return { ...result, definitions: reconciled };
834
+ }
835
+ /**
836
+ * What `after` gets wrong that `before` did not: {@link collaborationProblems}
837
+ * and ids used twice across the document. The pool and lane keys are merged in
838
+ * after the operations, so nothing else checks that their ids and references
839
+ * hold. A problem the input already had is the caller's document, not this edit.
840
+ */
841
+ function newStructureProblems(before, after) {
842
+ const had = new Set(collaborationProblems(before));
843
+ const found = collaborationProblems(after).filter((problem) => !had.has(problem));
844
+ // Counted rather than compared as messages, so a new clash on an id the
845
+ // input already used twice is still caught.
846
+ const wasUsed = idCounts(before);
847
+ for (const [id, count] of idCounts(after)) {
848
+ if (count > 1 && count > (wasUsed.get(id) ?? 0))
849
+ found.push(`Duplicate element ID "${id}"`);
850
+ }
851
+ return [...new Set(found)];
852
+ }
853
+ /** How many times each id is used in the document ({@link documentIdList}). */
854
+ function idCounts(definitions) {
855
+ const counts = new Map();
856
+ for (const id of documentIdList(definitions))
857
+ counts.set(id, (counts.get(id) ?? 0) + 1);
858
+ return counts;
859
+ }
860
+ /**
861
+ * Applies the `executable`, `lanes`, `participants` and `messageFlows` keys
862
+ * `compact` carries. A key that says what the model already says changes
863
+ * nothing, so reconciling `compactify(defs)` onto `defs` stays a no-op.
864
+ */
865
+ function reconcilePools(definitions, compact) {
866
+ const wanted = new Map(compact.processes.map((process) => [process.id, process]));
867
+ let changed = false;
868
+ const processes = definitions.processes.map((process) => {
869
+ const compactProcess = wanted.get(process.id);
870
+ let next = process;
871
+ const executable = compactProcess?.executable;
872
+ // An absent attribute already means executable (Flowable), so `true` leaves it absent.
873
+ if (executable !== undefined && executable !== (next.isExecutable !== false)) {
874
+ next = { ...next, isExecutable: executable };
875
+ }
876
+ const lanes = compactProcess?.lanes;
877
+ if (lanes !== undefined && !sameJson(compactifyLanes(next), lanes)) {
878
+ next = relane(next, lanes);
879
+ changed = true;
880
+ }
881
+ return next;
882
+ });
883
+ const first = definitions.collaborations[0];
884
+ const poolsChanged = (compact.participants !== undefined &&
885
+ !sameJson(first?.participants.map(compactifyParticipant) ?? [], compact.participants)) ||
886
+ (compact.messageFlows !== undefined &&
887
+ !sameJson(first?.messageFlows.map(compactifyMessageFlow) ?? [], compact.messageFlows));
888
+ if (!changed && !poolsChanged)
889
+ return { ...definitions, processes };
890
+ return poolLanedProcesses({
891
+ ...definitions,
892
+ processes,
893
+ collaborations: poolsChanged
894
+ ? reconcileCollaborations({ ...definitions, processes }, compact)
895
+ : definitions.collaborations,
896
+ });
897
+ }
898
+ /** Equal as JSON: key order counts, so a reordered but equal input reads as a change, which is safe. */
899
+ function sameJson(a, b) {
900
+ return JSON.stringify(a) === JSON.stringify(b);
901
+ }
902
+ /** `process` with the membership `lanes` describes, keeping what each surviving lane carries. */
903
+ function relane(process, lanes) {
904
+ const { laneSet: previous, ...bare } = process;
905
+ if (lanes.length === 0)
906
+ return bare;
907
+ const rebuilt = pruneLaneRefs(withLanes(bare, lanes)).laneSet;
908
+ if (rebuilt === undefined)
909
+ return bare;
910
+ const before = new Map(allLanes(previous).map((lane) => [lane.id, lane]));
911
+ // `rebuilt` comes from buildLaneSet, which refuses a looping tree, so this terminates.
912
+ const mergeSet = (built, old) => ({
913
+ ...built,
914
+ ...old,
915
+ lanes: built.lanes.map(mergeLane),
916
+ });
917
+ const mergeLane = (built) => {
918
+ const old = before.get(built.id);
919
+ // The compact lane states its name the way compactify writes it: none when it has none.
920
+ const { childLaneSet: _oldChildren, name: _oldName, ...kept } = old ?? { unknownAttributes: {} };
921
+ const lane = { ...kept, id: built.id, flowNodeRefs: built.flowNodeRefs };
922
+ if (built.name)
923
+ lane.name = built.name;
924
+ if (built.childLaneSet !== undefined) {
925
+ lane.childLaneSet = mergeSet(built.childLaneSet, old?.childLaneSet);
926
+ }
927
+ return lane;
928
+ };
929
+ return { ...bare, laneSet: mergeSet(rebuilt, previous) };
930
+ }
931
+ /** The collaborations once the compact's `participants` and `messageFlows` keys are applied. */
932
+ function reconcileCollaborations(definitions, compact) {
933
+ if (compact.participants === undefined && compact.messageFlows === undefined) {
934
+ return definitions.collaborations;
935
+ }
936
+ const [first, ...rest] = definitions.collaborations;
937
+ if (first === undefined)
938
+ return expandCollaborations(compact, documentIds(definitions, compact));
939
+ return [
940
+ {
941
+ ...first,
942
+ participants: compact.participants?.map((participant) => mergeParticipant(first.participants.find((p) => p.id === participant.id), participant)) ?? first.participants,
943
+ messageFlows: compact.messageFlows?.map((flow) => mergeMessageFlow(first.messageFlows.find((f) => f.id === flow.id), flow)) ?? first.messageFlows,
944
+ },
945
+ ...rest,
946
+ ];
947
+ }
948
+ function mergeParticipant(old, wanted) {
949
+ const { processRef: _oldRef, name: _oldName, ...kept } = old ?? { unknownAttributes: {} };
950
+ const participant = { ...kept, id: wanted.id };
951
+ if (wanted.name)
952
+ participant.name = wanted.name;
953
+ if (wanted.processId !== undefined)
954
+ participant.processRef = wanted.processId;
955
+ return participant;
956
+ }
957
+ function mergeMessageFlow(old, wanted) {
958
+ const { name: _oldName, ...kept } = old ?? { unknownAttributes: {} };
959
+ const flow = {
960
+ ...kept,
961
+ id: wanted.id,
962
+ sourceRef: wanted.source,
963
+ targetRef: wanted.target,
964
+ };
965
+ if (wanted.name)
966
+ flow.name = wanted.name;
967
+ return flow;
968
+ }
969
+ /** Ids a new collaboration must not take: every process, element, flow and lane, and the compact's pool ids. */
970
+ function documentIds(definitions, compact) {
971
+ const ids = new Set(documentIdList(definitions));
972
+ for (const item of [...(compact.participants ?? []), ...(compact.messageFlows ?? [])]) {
973
+ ids.add(item.id);
974
+ }
975
+ return ids;
792
976
  }
793
977
  /**
794
978
  * Brings each gateway's `bpmn:default` in line with the flow the compact input
@@ -0,0 +1,26 @@
1
+ import type { BpmnDefinitions } from "./bpmn-model.js";
2
+ /** What {@link makeRoom} moved. */
3
+ export interface MakeRoomResult {
4
+ /** A copy of the input with the shifted shapes; the input is not changed. */
5
+ definitions: BpmnDefinitions;
6
+ /** One entry per insertion point: the node new ones follow, and how far right the rest moved. */
7
+ shifted: Array<{
8
+ after: string;
9
+ dx: number;
10
+ }>;
11
+ }
12
+ /**
13
+ * Makes space for nodes inserted into a path of a laid-out diagram, the way a
14
+ * modeler's "make space" does: every shape right of the node a new path leaves
15
+ * from moves right by the width the new nodes need on their longest path, less
16
+ * the room already free on that row; pools, lanes and expanded
17
+ * sub-processes spanning that point grow by as much. Run it before
18
+ * {@link placeNewShapes}, which then finds room next to the anchor instead of
19
+ * drawing the new nodes over the old ones.
20
+ *
21
+ * Only new nodes on a path count (reached by sequence flows from a drawn node
22
+ * that is not a boundary event): an exception path hangs below its task and
23
+ * needs no horizontal room.
24
+ */
25
+ export declare function makeRoom(input: BpmnDefinitions): MakeRoomResult;
26
+ //# sourceMappingURL=make-room.d.ts.map
@@ -0,0 +1,151 @@
1
+ import { sizeOf } from "../layout/semantic/place.js";
2
+ import { isContainerType } from "./element-shape.js";
3
+ /** Horizontal space left per inserted node, on top of its width. */
4
+ const GAP = 50;
5
+ function* scopes(elements, flows) {
6
+ yield { elements, flows };
7
+ for (const el of elements) {
8
+ const inner = el;
9
+ if (inner.flowElements)
10
+ yield* scopes(inner.flowElements, inner.sequenceFlows ?? []);
11
+ }
12
+ }
13
+ /**
14
+ * Makes space for nodes inserted into a path of a laid-out diagram, the way a
15
+ * modeler's "make space" does: every shape right of the node a new path leaves
16
+ * from moves right by the width the new nodes need on their longest path, less
17
+ * the room already free on that row; pools, lanes and expanded
18
+ * sub-processes spanning that point grow by as much. Run it before
19
+ * {@link placeNewShapes}, which then finds room next to the anchor instead of
20
+ * drawing the new nodes over the old ones.
21
+ *
22
+ * Only new nodes on a path count (reached by sequence flows from a drawn node
23
+ * that is not a boundary event): an exception path hangs below its task and
24
+ * needs no horizontal room.
25
+ */
26
+ export function makeRoom(input) {
27
+ const defs = structuredClone(input);
28
+ const result = { definitions: defs, shifted: [] };
29
+ const shapes = defs.diagrams.flatMap((d) => d.plane.shapes);
30
+ const shapeOf = new Map(shapes.map((s) => [s.bpmnElement, s]));
31
+ if (shapes.length === 0)
32
+ return result;
33
+ // Shapes that may contain others: they grow across the insertion point instead of moving.
34
+ const containers = new Set();
35
+ for (const c of defs.collaborations)
36
+ for (const p of c.participants)
37
+ containers.add(p.id);
38
+ for (const process of defs.processes) {
39
+ const lanes = (set) => {
40
+ for (const lane of set?.lanes ?? []) {
41
+ containers.add(lane.id);
42
+ lanes(lane.childLaneSet);
43
+ }
44
+ };
45
+ lanes(process.laneSet);
46
+ for (const scope of scopes(process.flowElements, process.sequenceFlows))
47
+ for (const el of scope.elements)
48
+ if (isContainerType(el.type))
49
+ containers.add(el.id);
50
+ }
51
+ const anchors = [];
52
+ for (const process of defs.processes) {
53
+ for (const scope of scopes(process.flowElements, process.sequenceFlows)) {
54
+ const byId = new Map(scope.elements.map((e) => [e.id, e]));
55
+ const isNew = (id) => {
56
+ const el = byId.get(id);
57
+ return el !== undefined && !shapeOf.has(id) && el.type !== "boundaryEvent";
58
+ };
59
+ for (const el of scope.elements) {
60
+ const shape = shapeOf.get(el.id);
61
+ if (shape === undefined || el.type === "boundaryEvent")
62
+ continue;
63
+ // The new nodes reachable from this drawn node through new nodes only.
64
+ const chain = new Set();
65
+ const queue = scope.flows
66
+ .filter((f) => f.sourceRef === el.id && isNew(f.targetRef))
67
+ .map((f) => f.targetRef);
68
+ while (queue.length > 0) {
69
+ const id = queue.shift() ?? "";
70
+ if (chain.has(id))
71
+ continue;
72
+ chain.add(id);
73
+ for (const f of scope.flows)
74
+ if (f.sourceRef === id && isNew(f.targetRef))
75
+ queue.push(f.targetRef);
76
+ }
77
+ if (chain.size === 0)
78
+ continue;
79
+ // Branches of a new split stack vertically: only the longest path needs width.
80
+ const memo = new Map();
81
+ const longest = (id, seen) => {
82
+ const known = memo.get(id);
83
+ if (known !== undefined)
84
+ return known;
85
+ if (seen.has(id))
86
+ return 0;
87
+ seen.add(id);
88
+ const node = byId.get(id);
89
+ let next = 0;
90
+ for (const f of scope.flows)
91
+ if (f.sourceRef === id && chain.has(f.targetRef))
92
+ next = Math.max(next, longest(f.targetRef, seen));
93
+ seen.delete(id);
94
+ const width = (node ? sizeOf(node).width + GAP : 0) + next;
95
+ memo.set(id, width);
96
+ return width;
97
+ };
98
+ let need = 0;
99
+ for (const f of scope.flows)
100
+ if (f.sourceRef === el.id && chain.has(f.targetRef))
101
+ need = Math.max(need, longest(f.targetRef, new Set()));
102
+ // Room already free on the anchor's row counts: a shape only moves as far as it must.
103
+ const x0 = shape.bounds.x + shape.bounds.width;
104
+ const top = shape.bounds.y - 20;
105
+ const bottom = shape.bounds.y + shape.bounds.height + 20;
106
+ let nextX = Number.POSITIVE_INFINITY;
107
+ for (const s of shapes) {
108
+ const b = s.bounds;
109
+ if (s === shape || containers.has(s.bpmnElement) || b.x < x0)
110
+ continue;
111
+ if (b.y + b.height > top && b.y < bottom)
112
+ nextX = Math.min(nextX, b.x);
113
+ }
114
+ const dx = Math.max(0, need + GAP - (nextX - x0));
115
+ if (dx === 0)
116
+ continue;
117
+ anchors.push({ shape, after: el.id, dx });
118
+ }
119
+ }
120
+ }
121
+ // Rightmost first, so a later shift carries the earlier one along instead of splitting it.
122
+ anchors.sort((a, b) => b.shape.bounds.x - a.shape.bounds.x);
123
+ for (const { shape, after, dx } of anchors) {
124
+ const x0 = shape.bounds.x + shape.bounds.width;
125
+ for (const s of shapes) {
126
+ const b = s.bounds;
127
+ if (b.x >= x0) {
128
+ b.x += dx;
129
+ if (s.label?.bounds)
130
+ s.label.bounds.x += dx;
131
+ }
132
+ else if (b.x + b.width > x0 && containers.has(s.bpmnElement)) {
133
+ // A pool, lane or expanded sub-process spanning the insertion point.
134
+ b.width += dx;
135
+ }
136
+ else if (s.label?.bounds && s.label.bounds.x >= x0) {
137
+ s.label.bounds.x += dx;
138
+ }
139
+ }
140
+ for (const edge of defs.diagrams.flatMap((d) => d.plane.edges)) {
141
+ for (const p of edge.waypoints)
142
+ if (p.x >= x0)
143
+ p.x += dx;
144
+ if (edge.label?.bounds && edge.label.bounds.x >= x0)
145
+ edge.label.bounds.x += dx;
146
+ }
147
+ result.shifted.push({ after, dx });
148
+ }
149
+ return result;
150
+ }
151
+ //# sourceMappingURL=make-room.js.map
@@ -1,5 +1,11 @@
1
1
  import { generateId } from "../../types/id-generator.js";
2
2
  import { buildFlowIndex, findDiPlane, findProcess, insertElement, insertFlow, isEndEvent, isGateway, isStartEvent, reachableFrom, removeElement, removeFlow, } from "./utils.js";
3
+ /** Data elements sit beside the flow: no sequence flow in or out, by design. */
4
+ const OFF_FLOW_TYPES = new Set([
5
+ "dataObject",
6
+ "dataObjectReference",
7
+ "dataStoreReference",
8
+ ]);
3
9
  export function analyzeFlow(p, _opts) {
4
10
  const findings = [];
5
11
  const processId = p.id;
@@ -55,6 +61,8 @@ export function analyzeFlow(p, _opts) {
55
61
  }
56
62
  const reachable = reachableFrom(startIds, reachabilityEdges);
57
63
  for (const el of p.flowElements) {
64
+ if (OFF_FLOW_TYPES.has(el.type))
65
+ continue;
58
66
  // flow/unreachable
59
67
  if (!reachable.has(el.id)) {
60
68
  findings.push({
@@ -24,7 +24,12 @@ export interface PlaceNewShapesResult {
24
24
  resized: string[];
25
25
  /** Flow nodes added to a lane's `flowNodeRefs`. */
26
26
  laneAssigned: string[];
27
- /** What could not be placed, and why. */
27
+ /**
28
+ * What could not be placed, and why. A new shape that could only be put on
29
+ * top of another shape or label is drawn anyway (its edges need it) and
30
+ * listed here too, with a reason that says what it overlaps: existing shapes
31
+ * never move, so making room is the caller's call.
32
+ */
28
33
  unplaced: Array<{
29
34
  id: string;
30
35
  reason: string;
@@ -87,6 +87,8 @@ class Placer {
87
87
  laneOf = new Map();
88
88
  lanesOfProcess = new Map();
89
89
  mainPlane;
90
+ /** Shapes this run chose a spot for one by one, rather than as a laid-out block. */
91
+ spotted = [];
90
92
  constructor(defs, result, options) {
91
93
  this.defs = defs;
92
94
  this.result = result;
@@ -135,6 +137,7 @@ class Placer {
135
137
  this.placePools();
136
138
  this.placeFlowNodes();
137
139
  this.placeAnnotations();
140
+ this.reportOverlaps();
138
141
  this.reportLanes();
139
142
  this.routeEdges();
140
143
  }
@@ -327,7 +330,7 @@ class Placer {
327
330
  const label = this.labelSize(el);
328
331
  let chosen;
329
332
  if (direction === "below" && anchorId) {
330
- chosen = this.boundarySpot(el.id, anchorId, size, plane);
333
+ chosen = this.boundarySpot(el.id, anchorId, size, label, plane);
331
334
  }
332
335
  else {
333
336
  chosen = this.bestSpot(el.id, size, label, anchorId, direction, box, plane);
@@ -347,6 +350,7 @@ class Placer {
347
350
  if (label)
348
351
  shape.label = { bounds: this.labelRect(chosen, label) };
349
352
  this.result.placed.push(el.id);
353
+ this.spotted.push(el.id);
350
354
  if (content) {
351
355
  const dx = chosen.x + INNER_PADDING - content.minX;
352
356
  const dy = chosen.y + SUB_PROCESS_TOP - content.minY;
@@ -675,7 +679,7 @@ class Placer {
675
679
  return out;
676
680
  }
677
681
  /** A spot on the host's bottom border, the right-most free one; then the top border. */
678
- boundarySpot(id, hostId, size, plane) {
682
+ boundarySpot(id, hostId, size, label, plane) {
679
683
  const host = this.shapes.get(hostId)?.shape.bounds;
680
684
  if (!host)
681
685
  return undefined;
@@ -685,14 +689,28 @@ class Placer {
685
689
  return el?.type === "boundaryEvent" && el.attachedToRef === hostId;
686
690
  })
687
691
  .map((s) => s.bounds);
692
+ // The first free spot on the border, unless it or its label would sit on
693
+ // another shape and a later spot would not.
694
+ // The shape sits on the host's border by design; its label may not.
695
+ const obstacles = this.obstacles(plane, id);
696
+ const others = obstacles.filter((o) => o !== host);
697
+ let first;
688
698
  for (const y of [host.y + host.height - size.height / 2, host.y - size.height / 2]) {
689
699
  for (let x = host.x + host.width - size.width - 8; x >= host.x + 4; x -= 6) {
690
700
  const r = { x: Math.round(x), y: Math.round(y), ...size };
691
701
  if (siblings.some((s) => overlaps(r, s, 6)))
692
702
  continue;
703
+ first ??= r;
704
+ const l = label ? this.labelRect(r, label) : undefined;
705
+ if (others.some((o) => overlaps(r, o, 0)))
706
+ continue;
707
+ if (l !== undefined && obstacles.some((o) => overlaps(l, o, 0)))
708
+ continue;
693
709
  return r;
694
710
  }
695
711
  }
712
+ if (first)
713
+ return first;
696
714
  this.result.unplaced.push({ id, reason: `no room left on the border of ${hostId}` });
697
715
  return undefined;
698
716
  }
@@ -791,6 +809,39 @@ class Placer {
791
809
  this.growToFit(box, spot, undefined, plane);
792
810
  this.addShape(plane, annotation.id, spot, {});
793
811
  this.result.placed.push(annotation.id);
812
+ this.spotted.push(annotation.id);
813
+ }
814
+ }
815
+ /**
816
+ * Placement keeps new shapes clear of others when it can, but a crowded
817
+ * spot (a boundary event's border, a label) can leave no clean choice. Say
818
+ * so instead of reporting a clean result over a diagram that reads wrong.
819
+ */
820
+ reportOverlaps() {
821
+ for (const id of this.spotted) {
822
+ const own = this.shapes.get(id);
823
+ // A sub-process drawn around its content overlaps that content by design.
824
+ if (!own || this.isContainerShape(own.shape))
825
+ continue;
826
+ const host = this.elements.get(id)?.attachedToRef;
827
+ const mine = [own.shape.bounds, ...(own.shape.label?.bounds ? [own.shape.label.bounds] : [])];
828
+ const clash = own.plane.shapes.find((other) => {
829
+ if (other.bpmnElement === id || this.isContainerShape(other))
830
+ return false;
831
+ const theirHost = this.elements.get(other.bpmnElement)
832
+ ?.attachedToRef;
833
+ // A boundary event sits on its host's border by design.
834
+ if (other.bpmnElement === host || theirHost === id)
835
+ return false;
836
+ const theirs = [other.bounds, ...(other.label?.bounds ? [other.label.bounds] : [])];
837
+ return mine.some((m) => theirs.some((t) => overlaps(m, t, 0)));
838
+ });
839
+ if (!clash)
840
+ continue;
841
+ this.result.unplaced.push({
842
+ id,
843
+ reason: `placed, but it or its label overlaps "${clash.bpmnElement}"; existing shapes do not move, so move one by hand or redraw with applyAutoLayout`,
844
+ });
794
845
  }
795
846
  }
796
847
  reportLanes() {
@@ -16,7 +16,7 @@
16
16
  * a file written by another tool comes back reshuffled even when nothing
17
17
  * changed. Keeping the original order is therefore worth more than keeping the
18
18
  * indentation. The same goes for an attribute set to its schema default:
19
- * `isExecutable="false"` disappears from a file that said it out loud.
19
+ * `isSequential="false"` disappears from a file that said it out loud.
20
20
  *
21
21
  * Neither is safe to assume in general, so neither is assumed. Each strategy is
22
22
  * tried, the result is **parsed back and compared against a plain write**, and
@@ -16,7 +16,7 @@
16
16
  * a file written by another tool comes back reshuffled even when nothing
17
17
  * changed. Keeping the original order is therefore worth more than keeping the
18
18
  * indentation. The same goes for an attribute set to its schema default:
19
- * `isExecutable="false"` disappears from a file that said it out loud.
19
+ * `isSequential="false"` disappears from a file that said it out loud.
20
20
  *
21
21
  * Neither is safe to assume in general, so neither is assumed. Each strategy is
22
22
  * tried, the result is **parsed back and compared against a plain write**, and
@@ -29,7 +29,7 @@ export declare const FIXED_KINDS: Readonly<Record<string, BpmnElementType>>;
29
29
  * after {@link PROCESS_TEXT_GUIDE}. A test parses its example and expects no
30
30
  * problems.
31
31
  */
32
- export declare const PROCESS_DELTA_GUIDE = "Change script \u2014 write only what changes, one line each:\na > new[kind Name] > b add nodes and flows; an existing node is written by its id only\na >(Label: condition) b add a flow; restating an existing flow with a new label changes it\nx[kind Name] an existing id declared again changes its kind or name\nx[user Name | form=f in.a=b] form and in./out. mappings (FEEL; write a = 1 with spaces) go after the bar\n- a > b remove the flow from a to b\n- x remove node x and its flows\n@2 x y feedback item 2 is answered by the changes to x and y\nRules:\n- Use the ids of the diagram you were given. Never repeat a line that changes nothing.\n- A new node written between two connected nodes (a > new > b) replaces the flow a > b.\n- Removing a node with one way in and one way out joins the two.\n- End with one @ line for each feedback item you answered.\n\nExample:\ncheck > second[user Second approval] > pay\nreview[user Review application]\n- notify\n@1 second\n@2 review";
32
+ export declare const PROCESS_DELTA_GUIDE = "Change script \u2014 write only what changes, one line each:\na > new[kind Name] > b add nodes and flows; an existing node is written by its id only\na >(Label: condition) b add a flow; restating an existing flow with a new label changes it\nx[kind Name] an existing id declared again changes its kind or name\nx[user Name | form=f in.a=b] form and in./out. mappings (FEEL; write a = 1 with spaces) go after the bar\n- a > b remove the flow from a to b\n- x remove node x and its flows\nlane sales: a, b move a and b into lane sales; lane ops[Operations]: c adds or renames a lane\npool bank[Bank] add or rename a partner pool; msg pay >(Payment) bank sends it a message\n- msg pay > bank remove that message\n@2 x y feedback item 2 is answered by the changes to x and y\nRules:\n- Use the ids of the diagram you were given. Never repeat a line that changes nothing.\n- A new node written between two connected nodes (a > new > b) replaces the flow a > b.\n- Removing a node with one way in and one way out joins the two.\n- End with one @ line for each feedback item you answered.\n\nExample:\ncheck > second[user Second approval] > pay\nreview[user Review application]\n- notify\n@1 second\n@2 review";
33
33
  /** A node the script declares: a new one, or a change to an existing one. */
34
34
  export interface DeltaNode {
35
35
  /** The id as written. */
@@ -119,6 +119,37 @@ export interface ProcessDelta {
119
119
  text: string;
120
120
  line: number;
121
121
  }[];
122
+ /**
123
+ * `lane` lines, in the order written; a lane written twice appears twice. An
124
+ * absent `name` keeps an existing lane's name, and a new lane is named from its
125
+ * id. `nodes` move into the lane and may be empty: the line then only renames
126
+ * or adds the lane.
127
+ */
128
+ lanes: {
129
+ id: string;
130
+ name?: string;
131
+ nodes: string[];
132
+ line: number;
133
+ }[];
134
+ /** `pool` lines: a partner pool added, or an existing one renamed. */
135
+ pools: {
136
+ id: string;
137
+ name?: string;
138
+ line: number;
139
+ }[];
140
+ /** `msg` lines: message flows between a node and a pool, label as written. */
141
+ messageFlows: {
142
+ from: string;
143
+ to: string;
144
+ name?: string;
145
+ line: number;
146
+ }[];
147
+ /** `- msg a > b` lines. */
148
+ removedMessageFlows: {
149
+ from: string;
150
+ to: string;
151
+ line: number;
152
+ }[];
122
153
  /** Lines, or parts of lines, that were left out. */
123
154
  problems: ProcessTextProblem[];
124
155
  }