@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
@@ -7,6 +7,7 @@ import { createFlowElement, isLoopCapableType } from "./element-shape.js";
7
7
  import { toFeelCondition } from "./feel-condition.js";
8
8
  import { REST_CONNECTOR_TEMPLATE_VERSION, restConnectorRetries, restConnectorTaskType, restConnectorToIoMappingInputs, restConnectorToTaskHeaders, } from "./rest-connector.js";
9
9
  import { assertExplicitFlowIdsUnique, assignEventDefinitionIds, assignStableFlowIds, copyFlowTags, markExplicitFlowId, rootDefinitionId, setFlowDiscriminatorSource, } from "./stable-ids.js";
10
+ import { allLanes, assignLane, buildLaneSet, collaborationProblems, freshId, laneForNewNode, laneProblems, poolLanedProcesses, } from "./swimlanes.js";
10
11
  import { assertRetriesOption, assertXsdValues } from "./xsd-guards.js";
11
12
  import { assertZeebePlacement, bpmnElementName, ensureZeebeExtension, makeConditionalDefinition, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
12
13
  import { assertDeployable, targetsCamunda8 } from "./zeebe-validate/gate.js";
@@ -22,6 +23,21 @@ function addDataElement(elements, ids, element) {
22
23
  elements.push(element);
23
24
  ids.add(element.id);
24
25
  }
26
+ /** Data objects a `dataObjectReference()` declared on its own; a later explicit `dataObject()` adopts them. */
27
+ const implicitDataObjects = new WeakSet();
28
+ function addDataObject(elements, ids, id, options) {
29
+ const implicit = elements.find((e) => e.id === id && implicitDataObjects.has(e));
30
+ if (implicit?.type === "dataObject") {
31
+ implicitDataObjects.delete(implicit);
32
+ const explicit = makeDataElement(id, "dataObject", undefined, options);
33
+ if (explicit.name !== undefined)
34
+ implicit.name = explicit.name;
35
+ if (options?.isCollection)
36
+ implicit.isCollection = true;
37
+ return;
38
+ }
39
+ addDataElement(elements, ids, makeDataElement(id, "dataObject", undefined, options));
40
+ }
25
41
  function makeDataElement(id, type, ref, options) {
26
42
  const el = createFlowElement(id, type, { name: options?.name });
27
43
  if (el.type === "dataObjectReference")
@@ -38,6 +54,13 @@ function makeDataElement(id, type, ref, options) {
38
54
  * this scope) rather than on itself.
39
55
  */
40
56
  function addDataObjectReference(elements, ids, id, dataObjectRef, options) {
57
+ // An unresolved dataObjectRef is a raw XSD IDREF error at build; agents
58
+ // expect the reference to bring its object, so declare it here.
59
+ if (!elements.some((e) => e.id === dataObjectRef && e.type === "dataObject")) {
60
+ const object = makeDataElement(dataObjectRef, "dataObject", undefined, undefined);
61
+ addDataElement(elements, ids, object);
62
+ implicitDataObjects.add(object);
63
+ }
41
64
  addDataElement(elements, ids, makeDataElement(id, "dataObjectReference", dataObjectRef, options));
42
65
  if (!options?.isCollection)
43
66
  return;
@@ -68,14 +91,17 @@ function addDataAssociation(elements, activityId, dataRefId, direction) {
68
91
  const activity = elements.find((e) => e.id === activityId);
69
92
  if (!activity)
70
93
  throw new Error(`dataAssociation(): no element "${activityId}" in this scope`);
94
+ const key = direction === "input" ? "dataInputAssociations" : "dataOutputAssociations";
95
+ // Ids let auto layout draw the association; without one it has no DI edge.
96
+ const id = `${direction === "input" ? "DataInputAssociation" : "DataOutputAssociation"}_${activityId}_${dataRefId}_${(activity[key]?.length ?? 0) + 1}`;
71
97
  const association = direction === "input"
72
98
  ? {
99
+ id,
73
100
  sourceRefs: [dataRefId],
74
101
  targetRef: targetRefPlaceholder(activity),
75
102
  unknownAttributes: {},
76
103
  }
77
- : { sourceRefs: [], targetRef: dataRefId, unknownAttributes: {} };
78
- const key = direction === "input" ? "dataInputAssociations" : "dataOutputAssociations";
104
+ : { id, sourceRefs: [], targetRef: dataRefId, unknownAttributes: {} };
79
105
  activity[key] = [...(activity[key] ?? []), association];
80
106
  }
81
107
  // ---------------------------------------------------------------------------
@@ -124,6 +150,44 @@ function resolveMessage(messageName, rootMessages) {
124
150
  * cannot hold both, so those stay on their elements, where lint reports them,
125
151
  * rather than one silently winning.
126
152
  */
153
+ function finishDocument(defs) {
154
+ return declareDataStores(hoistMessageSubscriptions(defs));
155
+ }
156
+ /**
157
+ * A `dataStoreReference` points at a root `bpmn:dataStore`; the builder only
158
+ * knows the reference, so the store is declared once per id here, after the
159
+ * model is complete (a store shared by two pools stays one element).
160
+ */
161
+ function declareDataStores(defs) {
162
+ const declared = new Set((defs.unknownChildren ?? [])
163
+ .filter((c) => c.name === "bpmn:dataStore")
164
+ .map((c) => c.attributes.id));
165
+ const stores = [];
166
+ const visit = (elements) => {
167
+ for (const el of elements) {
168
+ if (el.type === "dataStoreReference" && el.dataStoreRef !== undefined) {
169
+ if (!declared.has(el.dataStoreRef)) {
170
+ declared.add(el.dataStoreRef);
171
+ stores.push({
172
+ name: "bpmn:dataStore",
173
+ attributes: {
174
+ id: el.dataStoreRef,
175
+ ...(el.name !== undefined ? { name: el.name } : {}),
176
+ },
177
+ children: [],
178
+ });
179
+ }
180
+ }
181
+ if ("flowElements" in el && Array.isArray(el.flowElements))
182
+ visit(el.flowElements);
183
+ }
184
+ };
185
+ for (const process of defs.processes)
186
+ visit(process.flowElements);
187
+ if (stores.length > 0)
188
+ defs.unknownChildren = [...(defs.unknownChildren ?? []), ...stores];
189
+ return defs;
190
+ }
127
191
  function hoistMessageSubscriptions(defs) {
128
192
  const isSubscription = (el) => el.name === "zeebe:subscription";
129
193
  const owners = new Map();
@@ -295,9 +359,93 @@ const MESSAGE_JOB_TYPES = new Set([
295
359
  "intermediateThrowEvent",
296
360
  "endEvent",
297
361
  ]);
362
+ /** Per-node `lane` option, read when the owning builder adds the element. */
363
+ const laneOverride = new WeakMap();
364
+ /**
365
+ * Lane bookkeeping shared by a process builder and its gateway branches (never by
366
+ * sub-process contents: nodes inside a sub-process are not lane members).
367
+ */
368
+ class LaneState {
369
+ /** Lane id -> name, in first-use order (top to bottom). */
370
+ names = new Map();
371
+ membership = new Map();
372
+ current;
373
+ declare(id, name) {
374
+ if (id === "")
375
+ throw new Error("inLane() needs a non-empty lane id");
376
+ if (!this.names.has(id) || (name !== undefined && this.names.get(id) === undefined)) {
377
+ this.names.set(id, name);
378
+ }
379
+ }
380
+ enter(id, name) {
381
+ this.declare(id, name);
382
+ this.current = id;
383
+ }
384
+ record(el) {
385
+ // A boundary event rides on its host's lane (as bpmn-js lists it); resolved at build.
386
+ if (el.type === "boundaryEvent")
387
+ return;
388
+ const lane = laneOverride.get(el) ?? this.current;
389
+ if (lane === undefined)
390
+ return;
391
+ this.declare(lane);
392
+ this.membership.set(el.id, lane);
393
+ }
394
+ /** Runs `fn`, then puts back the lane that was current before it. */
395
+ scoped(fn) {
396
+ const saved = this.current;
397
+ try {
398
+ fn();
399
+ }
400
+ finally {
401
+ this.current = saved;
402
+ }
403
+ }
404
+ /** The process's lane set, or undefined when no lane was used. */
405
+ toLaneSet(processId, elements, inferredFrom) {
406
+ if (this.names.size === 0)
407
+ return undefined;
408
+ const laneOf = new Map(this.membership);
409
+ // Joins inferred at build() sit on the lane of the split they close.
410
+ for (const el of elements.slice(inferredFrom)) {
411
+ const lane = laneOf.get(el.id.replace(/_(join|merge)(_\d+)?$/, ""));
412
+ if (lane !== undefined)
413
+ laneOf.set(el.id, lane);
414
+ }
415
+ for (const el of elements) {
416
+ if (el.type !== "boundaryEvent" || !el.attachedToRef)
417
+ continue;
418
+ const lane = laneOf.get(el.attachedToRef);
419
+ if (lane !== undefined)
420
+ laneOf.set(el.id, lane);
421
+ }
422
+ // Data objects and stores are flow elements, not flow nodes: no lane holds them.
423
+ const isData = (el) => el.type === "dataObject" ||
424
+ el.type === "dataObjectReference" ||
425
+ el.type === "dataStoreReference";
426
+ const missing = elements.filter((el) => !isData(el) && !laneOf.has(el.id)).map((el) => el.id);
427
+ if (missing.length > 0) {
428
+ throw new Error(`Process "${processId}" uses lanes, so every flow node needs one; no lane for: ${missing.join(", ")}. Call inLane(id) before them or pass { lane } on the node. See agent-cards/bpmn.md#traps.`);
429
+ }
430
+ const lanes = [...this.names].map(([id, name]) => ({
431
+ id,
432
+ name: name ?? id,
433
+ flowNodeRefs: elements.filter((el) => laneOf.get(el.id) === id).map((el) => el.id),
434
+ unknownAttributes: {},
435
+ }));
436
+ return { id: `${processId}_laneSet`, lanes };
437
+ }
438
+ }
298
439
  function makeFlowElement(id, type, options) {
299
440
  const el = createFlowElement(id, type, options);
441
+ if (options?.lane !== undefined)
442
+ laneOverride.set(el, options.lane);
300
443
  el.extensionElements = [...el.extensionElements];
444
+ if (options?.messageName &&
445
+ options.correlationKey &&
446
+ (type === "endEvent" || type === "intermediateThrowEvent")) {
447
+ el.extensionElements.push(...zeebeExtensionsToXmlElements({ subscription: { correlationKey: options.correlationKey } }));
448
+ }
301
449
  if (options?.taskType !== undefined && MESSAGE_JOB_TYPES.has(type)) {
302
450
  el.extensionElements.push(...zeebeExtensionsToXmlElements({ taskDefinition: { type: options.taskType } }));
303
451
  }
@@ -601,6 +749,7 @@ function makeServiceTaskEl(id, options) {
601
749
  unknownAttributes["zeebe:modelerTemplateIcon"] = options.modelerTemplateIcon;
602
750
  const el = makeFlowElement(id, "serviceTask", {
603
751
  name: options.name,
752
+ lane: options.lane,
604
753
  documentation: options.documentation,
605
754
  extensionElements: buildServiceTaskExtensions(options),
606
755
  executionListeners: options.executionListeners,
@@ -615,6 +764,7 @@ function makeServiceTaskEl(id, options) {
615
764
  function makeScriptTaskEl(id, options) {
616
765
  const el = makeFlowElement(id, "scriptTask", {
617
766
  name: options.name,
767
+ lane: options.lane,
618
768
  documentation: options.documentation,
619
769
  executionListeners: options.executionListeners,
620
770
  extensionElements: zeebeExtensionsToXmlElements({
@@ -641,10 +791,15 @@ function applyModelerTemplate(el, options) {
641
791
  el.unknownAttributes["zeebe:modelerTemplateIcon"] = options.modelerTemplateIcon;
642
792
  }
643
793
  }
794
+ /** Only decision gateways give their branches a flow label; a parallel or event-based split's flows are unconditioned. */
795
+ function branchesAreNamed(gateway) {
796
+ return gateway?.type !== "parallelGateway" && gateway?.type !== "eventBasedGateway";
797
+ }
644
798
  /** Start-event shell shared by all three builders; the caller adds event definitions. */
645
799
  function makeStartEventEl(id, options) {
646
800
  const el = makeFlowElement(id, "startEvent", {
647
801
  name: options?.name,
802
+ lane: options?.lane,
648
803
  documentation: options?.documentation,
649
804
  executionListeners: options?.executionListeners,
650
805
  extensionElements: zeebeExtensionsToXmlElements({
@@ -707,6 +862,7 @@ function makeUserTaskEl(id, options) {
707
862
  });
708
863
  const el = makeFlowElement(id, "userTask", {
709
864
  name: options?.name,
865
+ lane: options?.lane,
710
866
  documentation: options?.documentation,
711
867
  executionListeners: options?.executionListeners,
712
868
  taskListeners: options?.taskListeners,
@@ -761,6 +917,7 @@ function makeBusinessRuleTaskEl(id, options) {
761
917
  }
762
918
  const el = makeFlowElement(id, "businessRuleTask", {
763
919
  name: options?.name,
920
+ lane: options?.lane,
764
921
  documentation: options?.documentation,
765
922
  executionListeners: options?.executionListeners,
766
923
  extensionElements: ext,
@@ -788,6 +945,7 @@ function makeCallActivityEl(id, options) {
788
945
  };
789
946
  const el = makeFlowElement(id, "callActivity", {
790
947
  name: options.name,
948
+ lane: options.lane,
791
949
  documentation: options.documentation,
792
950
  executionListeners: options.executionListeners,
793
951
  extensionElements: zeebeExtensionsToXmlElements(extensions),
@@ -868,6 +1026,124 @@ function resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions) {
868
1026
  function emptyLayoutHints() {
869
1027
  return { grids: new Map(), annotationSides: new Map() };
870
1028
  }
1029
+ /** Copies every hint of `from` into `into`; ids are document-wide, so nothing clashes. */
1030
+ function mergeLayoutHints(into, from) {
1031
+ for (const [id, grid] of from.grids)
1032
+ into.grids.set(id, grid);
1033
+ for (const [id, side] of from.annotationSides)
1034
+ into.annotationSides.set(id, side);
1035
+ }
1036
+ /**
1037
+ * Every id `process` already uses at any depth: the process, its flow elements
1038
+ * (sub-process children included), sequence flows, annotations and associations.
1039
+ * A new lane or pool id must not take one of them.
1040
+ *
1041
+ * @throws Error when one element object is reached twice, the only way an
1042
+ * element tree assembled by hand can loop.
1043
+ */
1044
+ function processIds(process) {
1045
+ const ids = new Set([process.id]);
1046
+ const seen = new Set();
1047
+ const visit = (scope) => {
1048
+ for (const item of [
1049
+ ...scope.sequenceFlows,
1050
+ ...(scope.textAnnotations ?? []),
1051
+ ...(scope.associations ?? []),
1052
+ ]) {
1053
+ ids.add(item.id);
1054
+ }
1055
+ for (const element of scope.flowElements) {
1056
+ if (seen.has(element)) {
1057
+ throw new Error(`Flow element "${element.id}" appears twice in one element tree`);
1058
+ }
1059
+ seen.add(element);
1060
+ ids.add(element.id);
1061
+ if ("flowElements" in element)
1062
+ visit(element);
1063
+ }
1064
+ };
1065
+ visit(process);
1066
+ return ids;
1067
+ }
1068
+ /**
1069
+ * The lane set a fresh build writes for `declarations`, and every reason the
1070
+ * build must refuse it: a lane id already in `usedIds` or declared twice (the
1071
+ * second declaration is dropped), an undeclared or looping `parent`, flow nodes
1072
+ * on a lane that has child lanes, and a node listed in two lanes. Lanes cut off
1073
+ * from the tree by a bad `parent` are left out. What the lane set itself gets
1074
+ * wrong (unknown refs, unassigned nodes) is for {@link laneProblems}.
1075
+ */
1076
+ function declaredLaneSet(process, declarations, usedIds) {
1077
+ const problems = [];
1078
+ const byId = new Map();
1079
+ for (const lane of declarations) {
1080
+ if (byId.has(lane.id) || usedIds.has(lane.id)) {
1081
+ problems.push(`Lane id "${lane.id}" is already used in process "${process.id}"`);
1082
+ continue;
1083
+ }
1084
+ byId.set(lane.id, lane);
1085
+ }
1086
+ const roots = [];
1087
+ const childrenOf = new Map();
1088
+ for (const lane of byId.values()) {
1089
+ if (lane.parent === undefined)
1090
+ roots.push(lane);
1091
+ else if (!byId.has(lane.parent)) {
1092
+ problems.push(`Lane "${lane.id}" names parent "${lane.parent}", which is not declared`);
1093
+ }
1094
+ else
1095
+ childrenOf.set(lane.parent, [...(childrenOf.get(lane.parent) ?? []), lane]);
1096
+ }
1097
+ for (const lane of byId.values()) {
1098
+ // A chain longer than the number of lanes has revisited one.
1099
+ let current = lane;
1100
+ for (let steps = 0; current?.parent !== undefined; steps++) {
1101
+ if (steps > byId.size) {
1102
+ problems.push(`Lane "${lane.id}" has a parent chain that loops back on itself`);
1103
+ break;
1104
+ }
1105
+ current = byId.get(current.parent);
1106
+ }
1107
+ }
1108
+ // Every lane reached from a root has a parent chain ending at that root, so
1109
+ // none of them sits on a loop and this recursion terminates.
1110
+ const inTree = new Set();
1111
+ const toSpec = (lane) => {
1112
+ inTree.add(lane.id);
1113
+ const spec = { id: lane.id };
1114
+ if (lane.name !== undefined)
1115
+ spec.name = lane.name;
1116
+ const children = childrenOf.get(lane.id) ?? [];
1117
+ if (children.length > 0)
1118
+ spec.lanes = children.map(toSpec);
1119
+ return spec;
1120
+ };
1121
+ const specs = roots.map(toSpec);
1122
+ const leafOf = new Map();
1123
+ for (const lane of byId.values()) {
1124
+ const nodes = lane.flowNodes ?? [];
1125
+ if (!inTree.has(lane.id) || nodes.length === 0)
1126
+ continue;
1127
+ if (childrenOf.has(lane.id)) {
1128
+ problems.push(`Lane "${lane.id}" has child lanes; its flow nodes (${nodes.map((id) => `"${id}"`).join(", ")}) must go in one of its leaf lanes`);
1129
+ continue;
1130
+ }
1131
+ for (const nodeId of nodes) {
1132
+ const owner = leafOf.get(nodeId);
1133
+ if (owner === undefined)
1134
+ leafOf.set(nodeId, lane.id);
1135
+ else if (owner !== lane.id) {
1136
+ problems.push(`Flow node "${nodeId}" is listed in lanes "${owner}" and "${lane.id}"; a node belongs to one leaf lane`);
1137
+ }
1138
+ }
1139
+ }
1140
+ return { laneSet: buildLaneSet(process, specs, leafOf), problems };
1141
+ }
1142
+ /**
1143
+ * Assigned in `ProcessBuilder`'s static block, the one place allowed to read its
1144
+ * private fields, so `DiagramBuilder` can see them without making them public API.
1145
+ */
1146
+ let processBuilderInternals;
871
1147
  /** Remembers an ad-hoc sub-process's `toolGrid` for the layout. */
872
1148
  function recordToolGrid(hints, id, options) {
873
1149
  const grid = options?.toolGrid;
@@ -980,6 +1256,81 @@ function insertJoinGateways(elements, flows) {
980
1256
  }
981
1257
  }
982
1258
  }
1259
+ /**
1260
+ * Puts an exclusive merge gateway (`<target>_merge`) in front of every
1261
+ * non-gateway node that still has several incoming flows once join inference
1262
+ * has run — typically a `connectTo()` looping back to a task, or a boundary
1263
+ * path rejoining the main flow. Several flows into a task already mean "each
1264
+ * arriving token starts it", which is exactly what an exclusive merge does, so
1265
+ * this changes how the diagram reads (and lints), not how it runs.
1266
+ *
1267
+ * `sourceFlows` holds the flows of a document being continued: they must keep
1268
+ * their id and target, so at most one of them may enter the node, and that one
1269
+ * becomes `merge → node` (only its source moves, as with `insertAfter`) while a
1270
+ * new flow takes its old source into the merge. Nodes with two or more of them
1271
+ * were already like that in the document and are left alone. The ids of flows
1272
+ * whose source moved are returned so the rewiring guard can allow it.
1273
+ */
1274
+ function insertMergeGateways(elements, flows, sourceFlows) {
1275
+ const moved = new Set();
1276
+ const taken = new Set(elements.map((el) => el.id));
1277
+ const incoming = new Map();
1278
+ for (const flow of flows) {
1279
+ const arr = incoming.get(flow.targetRef);
1280
+ if (arr)
1281
+ arr.push(flow);
1282
+ else
1283
+ incoming.set(flow.targetRef, [flow]);
1284
+ }
1285
+ for (const el of [...elements]) {
1286
+ if (isGatewayType(el.type) || el.type === "startEvent")
1287
+ continue;
1288
+ const inFlows = incoming.get(el.id) ?? [];
1289
+ if (inFlows.length < 2)
1290
+ continue;
1291
+ const kept = inFlows.filter((flow) => sourceFlows?.has(flow.id));
1292
+ if (kept.length > 1)
1293
+ continue;
1294
+ // A kept flow carrying a gateway's condition (or being its default) cannot
1295
+ // have its source moved without moving the decision; leave that node as is.
1296
+ const fixed = kept[0];
1297
+ if (fixed !== undefined &&
1298
+ (fixed.conditionExpression !== undefined ||
1299
+ elements.some((e) => "default" in e && e.default === fixed.id))) {
1300
+ continue;
1301
+ }
1302
+ let mergeId = `${el.id}_merge`;
1303
+ for (let n = 2; taken.has(mergeId); n++)
1304
+ mergeId = `${el.id}_merge_${n}`;
1305
+ taken.add(mergeId);
1306
+ elements.push(makeFlowElement(mergeId, "exclusiveGateway", {}));
1307
+ const anchor = kept[0];
1308
+ for (const flow of inFlows) {
1309
+ if (flow !== anchor)
1310
+ flow.targetRef = mergeId;
1311
+ }
1312
+ if (anchor === undefined) {
1313
+ flows.push({
1314
+ id: generateId("Flow"),
1315
+ sourceRef: mergeId,
1316
+ targetRef: el.id,
1317
+ extensionElements: [],
1318
+ unknownAttributes: {},
1319
+ });
1320
+ continue;
1321
+ }
1322
+ flows.push({
1323
+ id: generateId("Flow"),
1324
+ sourceRef: anchor.sourceRef,
1325
+ targetRef: mergeId,
1326
+ extensionElements: [],
1327
+ unknownAttributes: {},
1328
+ });
1329
+ anchor.sourceRef = mergeId;
1330
+ moved.add(anchor.id);
1331
+ }
1332
+ return moved;
1333
+ }
983
1334
  /**
984
1335
  * Settles a finished scope: infer the joins its branches imply, name its
985
1336
  * sequence flows after what they connect, then rebuild the `incoming`/
@@ -992,6 +1343,7 @@ function finalizeScope(elements, flows) {
992
1343
  assignEventDefinitionIds(el.id, el.eventDefinitions);
993
1344
  }
994
1345
  insertJoinGateways(elements, flows);
1346
+ insertMergeGateways(elements, flows);
995
1347
  assignStableFlowIds(elements, flows);
996
1348
  recomputeIncomingOutgoing(elements, flows);
997
1349
  }
@@ -1023,6 +1375,15 @@ function traceBackToSplit(nodeId, splitGateways, flows) {
1023
1375
  * Use `.condition(expr)` to set a FEEL condition on the outgoing sequence
1024
1376
  * flow from the gateway, or `.defaultFlow()` to mark it as the default path.
1025
1377
  */
1378
+ /**
1379
+ * A branch that adds nothing and connects nowhere leaves an unconditioned flow from
1380
+ * the gateway to whatever comes next, which is never what the author meant.
1381
+ */
1382
+ function assertBranchAddedSomething(b, name, gatewayId) {
1383
+ if (b._elements.length > 0 || b._connected)
1384
+ return;
1385
+ throw new Error(`branch("${name}") on gateway "${gatewayId}" added no elements: add a node, end it with .endEvent(id), or route it with .connectTo(id)`);
1386
+ }
1026
1387
  export class BranchBuilder {
1027
1388
  /** @internal */
1028
1389
  _elements = [];
@@ -1035,6 +1396,8 @@ export class BranchBuilder {
1035
1396
  lastNodeId;
1036
1397
  gatewayId;
1037
1398
  branchName;
1399
+ /** False after a parallel or event-based gateway, whose outgoing flows Camunda lints as `superfluous-label` when named. */
1400
+ nameFlow;
1038
1401
  isFirstElement = true;
1039
1402
  pendingCondition;
1040
1403
  pendingLabel;
@@ -1056,10 +1419,14 @@ export class BranchBuilder {
1056
1419
  rootSignals;
1057
1420
  rootEscalations;
1058
1421
  rootLayoutHints;
1422
+ /** Absent inside a sub-process, whose nodes are not lane members. */
1423
+ lanes;
1059
1424
  /** @internal */
1060
- constructor(gatewayId, branchName, rootErrors = [], rootMessages = [], rootSignals = [], rootEscalations = [], rootLayoutHints = emptyLayoutHints()) {
1425
+ constructor(gatewayId, branchName, rootErrors = [], rootMessages = [], rootSignals = [], rootEscalations = [], rootLayoutHints = emptyLayoutHints(), lanes, nameFlow = true) {
1426
+ this.lanes = lanes;
1061
1427
  this.gatewayId = gatewayId;
1062
1428
  this.branchName = branchName;
1429
+ this.nameFlow = nameFlow;
1063
1430
  this.lastNodeId = gatewayId;
1064
1431
  this.rootErrors = rootErrors;
1065
1432
  this.rootMessages = rootMessages;
@@ -1105,9 +1472,17 @@ export class BranchBuilder {
1105
1472
  if (this.pendingFlowId !== undefined)
1106
1473
  markExplicitFlowId(flow);
1107
1474
  }
1475
+ /** Moves the rest of this branch (and branches nested in it) to a lane; undone when the branch ends. */
1476
+ inLane(id, options) {
1477
+ if (!this.lanes)
1478
+ throw new Error("inLane() is not available inside a sub-process.");
1479
+ this.lanes.enter(id, options?.name);
1480
+ return this;
1481
+ }
1108
1482
  addElement(element) {
1109
1483
  this._elements.push(element);
1110
1484
  this._ids.add(element.id);
1485
+ this.lanes?.record(element);
1111
1486
  if (isLinkEvent(element, "intermediateCatchEvent")) {
1112
1487
  this.isFirstElement = false;
1113
1488
  this.lastNodeId = element.id;
@@ -1122,7 +1497,9 @@ export class BranchBuilder {
1122
1497
  id: flowId,
1123
1498
  sourceRef: this.lastNodeId,
1124
1499
  targetRef: element.id,
1125
- name: this.isFirstElement ? (this.pendingLabel ?? this.branchName) : undefined,
1500
+ name: this.isFirstElement
1501
+ ? (this.pendingLabel ?? (this.nameFlow ? this.branchName : undefined))
1502
+ : undefined,
1126
1503
  conditionExpression: this.isFirstElement && this.pendingCondition
1127
1504
  ? makeConditionExpression(this.pendingCondition)
1128
1505
  : undefined,
@@ -1179,7 +1556,9 @@ export class BranchBuilder {
1179
1556
  id: flowId,
1180
1557
  sourceRef: this.lastNodeId,
1181
1558
  targetRef: targetId,
1182
- name: this.isFirstElement ? (this.pendingLabel ?? this.branchName) : undefined,
1559
+ name: this.isFirstElement
1560
+ ? (this.pendingLabel ?? (this.nameFlow ? this.branchName : undefined))
1561
+ : undefined,
1183
1562
  conditionExpression: this.isFirstElement && this.pendingCondition
1184
1563
  ? makeConditionExpression(this.pendingCondition)
1185
1564
  : undefined,
@@ -1208,7 +1587,7 @@ export class BranchBuilder {
1208
1587
  // ---- Data elements (beside the chain; no sequence flows) ----
1209
1588
  /** Declares a data object. Link it to an activity via a `dataObjectReference()`. */
1210
1589
  dataObject(id, options) {
1211
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObject", undefined, options));
1590
+ addDataObject(this._elements, this._ids, id, options);
1212
1591
  return this;
1213
1592
  }
1214
1593
  /** Draws a reference to the data object `dataObjectRef`. */
@@ -1452,6 +1831,7 @@ export class BranchBuilder {
1452
1831
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1453
1832
  const element = makeFlowElement(id, "adHocSubProcess", {
1454
1833
  name: resolved.options?.name,
1834
+ lane: resolved.options?.lane,
1455
1835
  documentation: resolved.options?.documentation,
1456
1836
  executionListeners: resolved.options?.executionListeners,
1457
1837
  extensionElements,
@@ -1494,8 +1874,13 @@ export class BranchBuilder {
1494
1874
  if (!this.currentGatewayId) {
1495
1875
  throw new Error("branch() must be called after a gateway element");
1496
1876
  }
1497
- const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints);
1498
- callback(b);
1877
+ const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints, this.lanes, branchesAreNamed(this._elements.find((n) => n.id === this.currentGatewayId)));
1878
+ // Inside a sub-process there is no lane state, but the callback must still run.
1879
+ if (this.lanes)
1880
+ this.lanes.scoped(() => callback(b));
1881
+ else
1882
+ callback(b);
1883
+ assertBranchAddedSomething(b, name, this.currentGatewayId);
1499
1884
  for (const el of b._elements) {
1500
1885
  if (this._ids.has(el.id)) {
1501
1886
  throw new Error(`Duplicate element ID "${el.id}"`);
@@ -1744,7 +2129,7 @@ export class SubProcessContentBuilder {
1744
2129
  // ---- Data elements (beside the chain; no sequence flows) ----
1745
2130
  /** Declares a data object. Link it to an activity via a `dataObjectReference()`. */
1746
2131
  dataObject(id, options) {
1747
- addDataElement(this._elements, this._ids, makeDataElement(id, "dataObject", undefined, options));
2132
+ addDataObject(this._elements, this._ids, id, options);
1748
2133
  return this;
1749
2134
  }
1750
2135
  /** Draws a reference to the data object `dataObjectRef`. */
@@ -1792,8 +2177,9 @@ export class SubProcessContentBuilder {
1792
2177
  if (!this.currentGatewayId) {
1793
2178
  throw new Error("branch() must be called after a gateway element");
1794
2179
  }
1795
- const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints);
2180
+ const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints, undefined, branchesAreNamed(this._elements.find((n) => n.id === this.currentGatewayId)));
1796
2181
  callback(b);
2182
+ assertBranchAddedSomething(b, name, this.currentGatewayId);
1797
2183
  for (const el of b._elements) {
1798
2184
  if (this._ids.has(el.id)) {
1799
2185
  throw new Error(`Duplicate element ID "${el.id}"`);
@@ -1947,6 +2333,7 @@ export class SubProcessContentBuilder {
1947
2333
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1948
2334
  const element = makeFlowElement(id, "adHocSubProcess", {
1949
2335
  name: resolved.options?.name,
2336
+ lane: resolved.options?.lane,
1950
2337
  documentation: resolved.options?.documentation,
1951
2338
  executionListeners: resolved.options?.executionListeners,
1952
2339
  extensionElements,
@@ -2017,6 +2404,17 @@ export class ProcessBuilder {
2017
2404
  _pendingSpliceFlowId;
2018
2405
  /** Flows the caller deliberately spliced, exempt from the rewiring guard. */
2019
2406
  _splicedFlowIds = new Set();
2407
+ /** `lane()` calls, in call order. */
2408
+ _lanes = [];
2409
+ /** Set by `participant()`: the pool this process is drawn in. */
2410
+ _participant;
2411
+ static {
2412
+ processBuilderInternals = (builder) => ({
2413
+ executableSet: builder._executableSet,
2414
+ layoutHints: builder.rootLayoutHints,
2415
+ });
2416
+ }
2417
+ lanes = new LaneState();
2020
2418
  constructor(processId) {
2021
2419
  this.processId = processId;
2022
2420
  }
@@ -2177,7 +2575,11 @@ export class ProcessBuilder {
2177
2575
  this.processName = name;
2178
2576
  return this;
2179
2577
  }
2180
- /** Set whether this process is executable. */
2578
+ /**
2579
+ * Set whether this process is executable. Pass `false` for a partner pool the
2580
+ * engine must not deploy: Flowable reads an absent `isExecutable` as
2581
+ * executable, so a partner process has to say so explicitly.
2582
+ */
2181
2583
  executable(value) {
2182
2584
  this._isExecutable = value;
2183
2585
  this._executableSet = true;
@@ -2540,8 +2942,9 @@ export class ProcessBuilder {
2540
2942
  if (!this.currentGatewayId) {
2541
2943
  throw new Error("branch() must be called after a gateway element");
2542
2944
  }
2543
- const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints);
2544
- callback(b);
2945
+ const b = new BranchBuilder(this.currentGatewayId, name, this.rootErrors, this.rootMessages, this.rootSignals, this.rootEscalations, this.rootLayoutHints, this.lanes, branchesAreNamed(this.flowElements.find((n) => n.id === this.currentGatewayId)));
2946
+ this.lanes.scoped(() => callback(b));
2947
+ assertBranchAddedSomething(b, name, this.currentGatewayId);
2545
2948
  for (const el of b._elements) {
2546
2949
  if (this.elementIds.has(el.id)) {
2547
2950
  throw new Error(`Duplicate element ID "${el.id}"`);
@@ -2631,6 +3034,7 @@ export class ProcessBuilder {
2631
3034
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
2632
3035
  const element = makeFlowElement(id, "adHocSubProcess", {
2633
3036
  name: resolved.options?.name,
3037
+ lane: resolved.options?.lane,
2634
3038
  documentation: resolved.options?.documentation,
2635
3039
  executionListeners: resolved.options?.executionListeners,
2636
3040
  extensionElements,
@@ -2693,7 +3097,7 @@ export class ProcessBuilder {
2693
3097
  // ---- Data elements (beside the chain; no sequence flows) ----
2694
3098
  /** Declares a data object. Link it to an activity via a `dataObjectReference()`. */
2695
3099
  dataObject(id, options) {
2696
- addDataElement(this.flowElements, this.elementIds, makeDataElement(id, "dataObject", undefined, options));
3100
+ addDataObject(this.flowElements, this.elementIds, id, options);
2697
3101
  return this;
2698
3102
  }
2699
3103
  /** Draws a reference to the data object `dataObjectRef`. */
@@ -2736,6 +3140,192 @@ export class ProcessBuilder {
2736
3140
  });
2737
3141
  return this;
2738
3142
  }
3143
+ // ---- Lanes and pool ----
3144
+ /**
3145
+ * Declares a swimlane, or a child lane of `options.parent`.
3146
+ *
3147
+ * Once any lane is declared, a fresh build puts every top-level flow node in
3148
+ * exactly one leaf lane and refuses otherwise, listing every problem at once
3149
+ * (`Invalid lanes:` …): an unknown or sub-process ref, a node listed twice,
3150
+ * flow nodes on a lane with child lanes, an undeclared or looping parent, a
3151
+ * lane id already in use, an unassigned node. Boundary events follow their
3152
+ * host, and an inferred join gateway the lane of its first predecessor.
3153
+ * Parent lanes list the union of their descendants' refs. Lanes imply a
3154
+ * pool: without {@link participant} the build adds `Participant_<processId>`,
3155
+ * named after the process.
3156
+ *
3157
+ * Continuing a document ({@link ProcessBuilder.from}) instead names one of its
3158
+ * existing leaf lanes: the listed nodes move there, `name` renames it, and a
3159
+ * new lane or a `parent` is refused. Nodes added in continue mode join the lane
3160
+ * of their predecessor (see `laneForNewNode`) without any `lane()` call.
3161
+ *
3162
+ * @param id - The lane's element id, used verbatim.
3163
+ * @example
3164
+ * ```typescript
3165
+ * Bpmn.createProcess("order")
3166
+ * .startEvent("start").userTask("review").serviceTask("ship", { taskType: "ship" }).endEvent("end")
3167
+ * .lane("Lane_sales", { name: "Sales", flowNodes: ["start", "review"] })
3168
+ * .lane("Lane_ops", { name: "Operations", flowNodes: ["ship", "end"] })
3169
+ * ```
3170
+ */
3171
+ lane(id, options = {}) {
3172
+ this._lanes.push({ ...options, id });
3173
+ return this;
3174
+ }
3175
+ /**
3176
+ * Names the pool this process is drawn in: the build writes a collaboration
3177
+ * with one participant `id` referencing this process, named `options.name`,
3178
+ * else the process name, else the process id. Without this call a process
3179
+ * gets a pool only when it has lanes.
3180
+ *
3181
+ * Continuing a document, `id` must be the process's existing pool, which
3182
+ * `name` renames; adding or replacing a pool there is refused.
3183
+ *
3184
+ * @param id - The participant's element id, used verbatim.
3185
+ */
3186
+ participant(id, options = {}) {
3187
+ this._participant = { id, ...options };
3188
+ return this;
3189
+ }
3190
+ /**
3191
+ * Lanes and pool of a fresh build: `process` with its lane set, and the
3192
+ * collaboration `participant()` asked for. Both are returned untouched when
3193
+ * neither `lane()` nor `participant()` was called.
3194
+ *
3195
+ * @throws Error listing every lane and pool problem at once.
3196
+ */
3197
+ freshSwimlanes(process, inferredIds) {
3198
+ const pool = this._participant;
3199
+ if (this._lanes.length === 0 && pool === undefined)
3200
+ return { process, collaborations: [] };
3201
+ const used = processIds(process);
3202
+ const problems = [];
3203
+ if (pool !== undefined) {
3204
+ if (used.has(pool.id)) {
3205
+ problems.push(`Participant id "${pool.id}" is already used in process "${process.id}"`);
3206
+ }
3207
+ used.add(pool.id);
3208
+ }
3209
+ let laned = process;
3210
+ if (this._lanes.length > 0) {
3211
+ const plan = declaredLaneSet(process, this._lanes, used);
3212
+ problems.push(...plan.problems);
3213
+ laned = { ...process, laneSet: plan.laneSet };
3214
+ // The caller never saw an inferred join gateway, so could not list it.
3215
+ for (const id of inferredIds) {
3216
+ const lane = laneForNewNode(laned, id);
3217
+ if (lane !== undefined)
3218
+ laned = assignLane(laned, id, lane.id);
3219
+ }
3220
+ problems.push(...laneProblems(laned));
3221
+ }
3222
+ if (problems.length > 0) {
3223
+ const what = this._lanes.length > 0 ? "lanes" : "pool";
3224
+ throw new Error(`Invalid ${what}:\n ${problems.join("\n ")}`);
3225
+ }
3226
+ if (pool === undefined)
3227
+ return { process: laned, collaborations: [] };
3228
+ const participant = {
3229
+ id: pool.id,
3230
+ // A pool without a label is a lint finding; the process name is what a reader expects there.
3231
+ name: pool.name ?? process.name ?? process.id,
3232
+ processRef: process.id,
3233
+ unknownAttributes: {},
3234
+ };
3235
+ // The caller's ids are theirs: the collaboration steps around every one, lane sets included.
3236
+ const taken = new Set(used);
3237
+ for (const set of [laned.laneSet, ...allLanes(laned.laneSet).map((l) => l.childLaneSet)]) {
3238
+ if (set?.id !== undefined)
3239
+ taken.add(set.id);
3240
+ }
3241
+ for (const lane of allLanes(laned.laneSet))
3242
+ taken.add(lane.id);
3243
+ const collaboration = {
3244
+ id: freshId("Collaboration_1", (n) => `Collaboration_${n}`, taken),
3245
+ participants: [participant],
3246
+ messageFlows: [],
3247
+ textAnnotations: [],
3248
+ associations: [],
3249
+ groups: [],
3250
+ extensionElements: [],
3251
+ unknownAttributes: {},
3252
+ };
3253
+ return { process: laned, collaborations: [collaboration] };
3254
+ }
3255
+ /**
3256
+ * Continue mode: new nodes join the lane `laneForNewNode` picks, then each
3257
+ * `lane()` call moves its nodes into, and renames, an existing leaf lane.
3258
+ * Existing refs are kept as they are, even ones a fresh build would refuse:
3259
+ * the document is the caller's.
3260
+ *
3261
+ * @throws Error listing every `lane()` call that cannot be applied.
3262
+ */
3263
+ continueLanes(process, sourceIds) {
3264
+ let next = process;
3265
+ for (const element of this.flowElements) {
3266
+ if (sourceIds.has(element.id))
3267
+ continue;
3268
+ const lane = laneForNewNode(next, element.id);
3269
+ if (lane !== undefined)
3270
+ next = assignLane(next, element.id, lane.id);
3271
+ }
3272
+ const problems = [];
3273
+ for (const declaration of this._lanes) {
3274
+ if (!allLanes(next.laneSet).some((lane) => lane.id === declaration.id)) {
3275
+ problems.push(`Lane "${declaration.id}" is not declared in process "${process.id}"; continuing a document moves nodes between its lanes but does not add lanes`);
3276
+ continue;
3277
+ }
3278
+ if (declaration.parent !== undefined) {
3279
+ problems.push(`Lane "${declaration.id}": its parent cannot be changed when continuing a document`);
3280
+ }
3281
+ for (const nodeId of declaration.flowNodes ?? []) {
3282
+ if (!this.elementIds.has(nodeId)) {
3283
+ problems.push(`Lane "${declaration.id}" lists "${nodeId}", which is not a flow node of process "${process.id}"`);
3284
+ continue;
3285
+ }
3286
+ try {
3287
+ next = assignLane(next, nodeId, declaration.id);
3288
+ }
3289
+ catch (error) {
3290
+ // Collected so one build reports every bad lane() call; the rest of this
3291
+ // call's nodes would fail for the same reason.
3292
+ problems.push(error.message);
3293
+ break;
3294
+ }
3295
+ }
3296
+ }
3297
+ if (problems.length > 0)
3298
+ throw new Error(`Invalid lanes:\n ${problems.join("\n ")}`);
3299
+ if (next.laneSet !== undefined)
3300
+ process.laneSet = next.laneSet;
3301
+ for (const declaration of this._lanes) {
3302
+ const lane = allLanes(process.laneSet).find((candidate) => candidate.id === declaration.id);
3303
+ if (lane !== undefined && declaration.name !== undefined)
3304
+ lane.name = declaration.name;
3305
+ }
3306
+ }
3307
+ /**
3308
+ * Continue mode: `participant()` renames the pool that already references this
3309
+ * process.
3310
+ *
3311
+ * @throws Error when the process has no pool, or one with another id.
3312
+ */
3313
+ continuePool(definitions) {
3314
+ const pool = this._participant;
3315
+ if (pool === undefined)
3316
+ return;
3317
+ const existing = definitions.collaborations
3318
+ .flatMap((collaboration) => collaboration.participants)
3319
+ .find((participant) => participant.processRef === this.processId);
3320
+ if (existing === undefined) {
3321
+ throw new Error(`Process "${this.processId}" has no pool; continuing a document can rename a pool but not add one`);
3322
+ }
3323
+ if (existing.id !== pool.id) {
3324
+ throw new Error(`Process "${this.processId}" is drawn in pool "${existing.id}"; continuing a document can rename it with participant("${existing.id}", { name }) but not replace it`);
3325
+ }
3326
+ if (pool.name !== undefined)
3327
+ existing.name = pool.name;
3328
+ }
2739
3329
  // ---- Build ----
2740
3330
  /**
2741
3331
  * Build the complete BPMN definitions model.
@@ -2795,23 +3385,35 @@ export class ProcessBuilder {
2795
3385
  .join(", ");
2796
3386
  throw new Error(`Inferred join gateways: ${inserted}. Declare them with .connectTo(joinId), or drop { explicitJoins: true } to keep the inference.`);
2797
3387
  }
3388
+ const sourceFlowIds = this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys());
3389
+ const movedFlowIds = insertMergeGateways(elements, flows, sourceFlowIds);
2798
3390
  assertElementIdsUnique(elements, this.processId);
2799
3391
  this.validate(elements, flows);
2800
- this.assertSourceTopologyIntact(flows);
3392
+ this.assertSourceTopologyIntact(flows, movedFlowIds);
2801
3393
  // Flows the document already had keep their ids: continuing a model must
2802
3394
  // not renumber the part the caller did not touch.
2803
- assignStableFlowIds(elements, flows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
3395
+ assignStableFlowIds(elements, flows, sourceFlowIds);
2804
3396
  assertExplicitFlowIdsUnique(elements, flows);
2805
- // A continued document keeps its untouched part byte-for-byte, ids included.
2806
- if (this._source === undefined) {
2807
- for (const el of elements) {
2808
- if ("eventDefinitions" in el)
2809
- assignEventDefinitionIds(el.id, el.eventDefinitions);
2810
- }
3397
+ // A continued document keeps its untouched part byte-for-byte, ids included,
3398
+ // so only the elements this builder added get event definition ids there.
3399
+ const sourceElementIds = new Set(this._source?.process.flowElements.map((el) => el.id));
3400
+ for (const el of elements) {
3401
+ if (sourceElementIds.has(el.id))
3402
+ continue;
3403
+ if ("eventDefinitions" in el)
3404
+ assignEventDefinitionIds(el.id, el.eventDefinitions);
2811
3405
  }
2812
3406
  recomputeIncomingOutgoing(elements, flows);
2813
- if (this._source !== undefined)
3407
+ if (this._source !== undefined) {
3408
+ if (this.lanes.names.size > 0) {
3409
+ throw new Error("inLane() and { lane } build new lanes; they cannot be combined with ProcessBuilder.from(), which keeps the document's own lanes.");
3410
+ }
2814
3411
  return this.buildOntoSource(this._source, elements, flows);
3412
+ }
3413
+ const laneSet = this.lanes.toLaneSet(this.processId, elements, beforeCount);
3414
+ if (laneSet && this._lanes.length > 0) {
3415
+ throw new Error("inLane() and { lane } cannot be combined with lane(): use one way of declaring this process's lanes.");
3416
+ }
2815
3417
  const extensionElements = embeddedFormElements(elements);
2816
3418
  if (this._versionTag) {
2817
3419
  extensionElements.push({
@@ -2820,7 +3422,8 @@ export class ProcessBuilder {
2820
3422
  children: [],
2821
3423
  });
2822
3424
  }
2823
- const process = {
3425
+ const { process, collaborations } = this.freshSwimlanes({
3426
+ ...(laneSet ? { laneSet } : {}),
2824
3427
  id: this.processId,
2825
3428
  name: this.processName,
2826
3429
  isExecutable: this._isExecutable,
@@ -2831,7 +3434,11 @@ export class ProcessBuilder {
2831
3434
  associations: structuredClone(this._associations),
2832
3435
  groups: [],
2833
3436
  unknownAttributes: {},
2834
- };
3437
+ },
3438
+ // What the join inference added: the caller never saw those ids.
3439
+ elements
3440
+ .slice(beforeCount)
3441
+ .map((element) => element.id));
2835
3442
  const defs = {
2836
3443
  id: "Definitions_1",
2837
3444
  targetNamespace: "http://bpmn.io/schema/bpmn",
@@ -2854,32 +3461,35 @@ export class ProcessBuilder {
2854
3461
  escalations: structuredClone(this.rootEscalations),
2855
3462
  messages: structuredClone(this.rootMessages),
2856
3463
  signals: structuredClone(this.rootSignals),
2857
- collaborations: [],
3464
+ collaborations,
2858
3465
  processes: [process],
2859
- // Seed diagram stub so applyAutoLayout preserves process-specific IDs.
2860
- diagrams: this._autoLayout
2861
- ? [
2862
- {
2863
- id: `${this.processId}_di`,
2864
- plane: {
2865
- id: `${this.processId}_di_plane`,
2866
- bpmnElement: this.processId,
2867
- shapes: [],
2868
- edges: [],
2869
- },
2870
- },
2871
- ]
2872
- : [],
3466
+ diagrams: [],
3467
+ };
3468
+ const pooled = poolLanedProcesses(defs);
3469
+ if (!this._autoLayout)
3470
+ return finishDocument(pooled);
3471
+ // Seed diagram stub so applyAutoLayout preserves process-specific IDs. A
3472
+ // pooled diagram's plane draws the collaboration, not the process.
3473
+ const stub = {
3474
+ id: `${this.processId}_di`,
3475
+ plane: {
3476
+ id: `${this.processId}_di_plane`,
3477
+ bpmnElement: pooled.collaborations[0]?.id ?? this.processId,
3478
+ shapes: [],
3479
+ edges: [],
3480
+ },
2873
3481
  };
2874
- return hoistMessageSubscriptions(this._autoLayout ? applyAutoLayout(defs, "semantic", this.rootLayoutHints) : defs);
3482
+ return finishDocument(applyAutoLayout({ ...pooled, diagrams: [stub] }, "semantic", this.rootLayoutHints));
2875
3483
  }
2876
3484
  /**
2877
3485
  * Writes this process's contents back into the document it came from.
2878
3486
  *
2879
3487
  * Everything not listed here is kept by identity — other processes, the
2880
- * collaboration, diagram interchange, root elements, the process's own lanes,
2881
- * documentation, extensions and unmodelled content. That is the whole point of
2882
- * continuing rather than regenerating.
3488
+ * collaboration, diagram interchange, root elements, the process's existing
3489
+ * lane refs, documentation, extensions and unmodelled content. That is the
3490
+ * whole point of continuing rather than regenerating. The lanes change only
3491
+ * where nodes were added (each joins its predecessor's lane) or moved with
3492
+ * `lane()`; the pool only where `participant()` renames it.
2883
3493
  *
2884
3494
  * Diagram interchange is *not* regenerated: existing shapes keep their
2885
3495
  * positions, and elements added here have none until `placeNewShapes()` draws
@@ -2889,15 +3499,16 @@ export class ProcessBuilder {
2889
3499
  buildOntoSource(source, elements, flows) {
2890
3500
  const definitions = structuredClone(source.definitions);
2891
3501
  const process = definitions.processes[source.definitions.processes.indexOf(source.process)];
3502
+ const sourceIds = new Set(process.flowElements.map((element) => element.id));
2892
3503
  process.flowElements = elements;
2893
3504
  process.sequenceFlows = flows;
2894
3505
  process.textAnnotations = structuredClone(this._textAnnotations);
2895
3506
  process.associations = structuredClone(this._associations);
2896
3507
  if (this.processName !== undefined)
2897
3508
  process.name = this.processName;
2898
- // Only when asked. BPMN reads an absent `isExecutable` as false, so writing
2899
- // the builder's `true` default onto a process that never carried it makes a
2900
- // non-executable process executable — a change nobody requested.
3509
+ // Only when asked. Engines disagree on an absent `isExecutable` (Camunda:
3510
+ // not executable, Flowable: executable), so writing the builder's `true`
3511
+ // default onto a process that never carried it is a change nobody requested.
2901
3512
  if (this._executableSet)
2902
3513
  process.isExecutable = this._isExecutable;
2903
3514
  if (this._versionTag !== undefined) {
@@ -2912,6 +3523,8 @@ export class ProcessBuilder {
2912
3523
  else
2913
3524
  process.extensionElements.push(form);
2914
3525
  }
3526
+ this.continueLanes(process, sourceIds);
3527
+ this.continuePool(definitions);
2915
3528
  definitions.errors = structuredClone(this.rootErrors);
2916
3529
  definitions.messages = structuredClone(this.rootMessages);
2917
3530
  definitions.signals = structuredClone(this.rootSignals);
@@ -2928,7 +3541,7 @@ export class ProcessBuilder {
2928
3541
  * document would come back with edges the caller never touched pointing
2929
3542
  * somewhere else. Continuing a model has to leave the model alone.
2930
3543
  */
2931
- assertSourceTopologyIntact(flows) {
3544
+ assertSourceTopologyIntact(flows, mergedFlowIds) {
2932
3545
  if (this._source === undefined)
2933
3546
  return;
2934
3547
  const rewired = [];
@@ -2941,7 +3554,7 @@ export class ProcessBuilder {
2941
3554
  }
2942
3555
  // A spliced flow was moved on purpose, but only its source may move:
2943
3556
  // `insertAfter` inserts into a path, it does not redirect one.
2944
- if (this._splicedFlowIds.has(id)) {
3557
+ if (this._splicedFlowIds.has(id) || mergedFlowIds.has(id)) {
2945
3558
  if (flow.targetRef !== target) {
2946
3559
  rewired.push(`${id} (spliced flow now targets ${flow.targetRef}, not ${target})`);
2947
3560
  }
@@ -2976,10 +3589,27 @@ export class ProcessBuilder {
2976
3589
  }
2977
3590
  }
2978
3591
  }
3592
+ /**
3593
+ * Puts the nodes that follow in lane `id`, declaring it on first use (top to
3594
+ * bottom in first-use order); a later call may name it. Inside a `branch()`
3595
+ * callback it changes the lane for that branch only. Once any lane is used,
3596
+ * every top-level flow node needs one, or `build()` throws.
3597
+ *
3598
+ * @example
3599
+ * ```ts
3600
+ * Bpmn.createProcess("p").inLane("sales", { name: "Sales" }).startEvent("s")
3601
+ * .inLane("ops").serviceTask("t", { taskType: "x" }).endEvent("e").build()
3602
+ * ```
3603
+ */
3604
+ inLane(id, options) {
3605
+ this.lanes.enter(id, options?.name);
3606
+ return this;
3607
+ }
2979
3608
  addFlowElement(element) {
2980
3609
  if (this.elementIds.has(element.id)) {
2981
3610
  throw new Error(`Duplicate element ID "${element.id}" in process "${this.processId}"`);
2982
3611
  }
3612
+ this.lanes.record(element);
2983
3613
  this.flowElements.push(element);
2984
3614
  this.elementIds.add(element.id);
2985
3615
  // Compensation handlers are outside the normal token flow: link via association
@@ -3048,6 +3678,22 @@ function mergeRootDefinitions(into, incoming) {
3048
3678
  into.push(definition);
3049
3679
  }
3050
3680
  }
3681
+ function remapMessageRefs(elements, to) {
3682
+ for (const el of elements) {
3683
+ if ("messageRef" in el && typeof el.messageRef === "string") {
3684
+ el.messageRef = to.get(el.messageRef) ?? el.messageRef;
3685
+ }
3686
+ if ("eventDefinitions" in el) {
3687
+ for (const d of el.eventDefinitions) {
3688
+ if (d.type === "message" && d.messageRef !== undefined) {
3689
+ d.messageRef = to.get(d.messageRef) ?? d.messageRef;
3690
+ }
3691
+ }
3692
+ }
3693
+ if ("flowElements" in el && Array.isArray(el.flowElements))
3694
+ remapMessageRefs(el.flowElements, to);
3695
+ }
3696
+ }
3051
3697
  /**
3052
3698
  * A message two pools share keeps the correlation key a later pool hoisted onto
3053
3699
  * its copy when the first copy has none; dropping it would leave that pool's
@@ -3076,6 +3722,10 @@ export class DiagramBuilder {
3076
3722
  _messages = [];
3077
3723
  _participants = [];
3078
3724
  _messageFlows = [];
3725
+ /** Pools the processes brought along: `participant()` on the process, or the one lanes imply. */
3726
+ _processPools = [];
3727
+ _layoutHints = emptyLayoutHints();
3728
+ _autoLayout = false;
3079
3729
  _collaborationId = "Collaboration_1";
3080
3730
  _executionPlatformVersion = "8.10.0";
3081
3731
  constructor(id) {
@@ -3086,16 +3736,55 @@ export class DiagramBuilder {
3086
3736
  this._executionPlatformVersion = version;
3087
3737
  return this;
3088
3738
  }
3739
+ /**
3740
+ * Adds a process built by `callback`.
3741
+ *
3742
+ * The process keeps its lanes, and its pool: the one `participant()` named on
3743
+ * the process builder, or the one its lanes imply. A `participant()` on this
3744
+ * diagram that references the same process replaces that pool.
3745
+ *
3746
+ * A process with no flow elements and no lanes, whose builder never called
3747
+ * `executable()`, is written `isExecutable: false`: it can only be the
3748
+ * process of a black-box partner pool, and Flowable would otherwise deploy
3749
+ * it, since it reads an absent attribute as executable. Every other process
3750
+ * keeps the builder's default, `true`; call `.executable(false)` on a partner
3751
+ * that has content.
3752
+ */
3089
3753
  process(id, callback) {
3090
3754
  const builder = new ProcessBuilder(id);
3091
3755
  callback(builder);
3092
3756
  // The document is gated as a whole in build(): a pool may only deploy next to the others.
3093
3757
  const defs = builder.build({ validate: false });
3758
+ const internals = processBuilderInternals(builder);
3759
+ for (const process of defs.processes) {
3760
+ const empty = process.flowElements.length === 0 && process.laneSet === undefined;
3761
+ if (empty && !internals.executableSet)
3762
+ process.isExecutable = false;
3763
+ }
3094
3764
  this._processes.push(...defs.processes);
3765
+ this._processPools.push(...(defs.collaborations[0]?.participants ?? []));
3766
+ mergeLayoutHints(this._layoutHints, internals.layoutHints);
3095
3767
  // Root definitions are named after the message or error code they carry, so
3096
3768
  // two pools declaring the same one produce the same definition twice. The
3097
3769
  // document needs it once.
3098
3770
  mergeRootDefinitions(this._errors, defs.errors);
3771
+ const remap = new Map();
3772
+ for (const incoming of defs.messages) {
3773
+ const declared = this._messages.find((m) => m.id !== incoming.id && m.name !== undefined && m.name === incoming.name);
3774
+ if (!declared)
3775
+ continue;
3776
+ remap.set(incoming.id, declared.id);
3777
+ // message() ran first under another id: point this pool at that message.
3778
+ const sub = incoming.extensionElements?.find((x) => x.name === "zeebe:subscription");
3779
+ if (sub && !declared.extensionElements?.some((x) => x.name === "zeebe:subscription")) {
3780
+ declared.extensionElements = [...(declared.extensionElements ?? []), sub];
3781
+ }
3782
+ }
3783
+ if (remap.size > 0) {
3784
+ for (const process of defs.processes)
3785
+ remapMessageRefs(process.flowElements, remap);
3786
+ defs.messages = defs.messages.filter((m) => !remap.has(m.id));
3787
+ }
3099
3788
  mergeRootDefinitions(this._messages, defs.messages);
3100
3789
  adoptMessageSubscriptions(this._messages, defs.messages);
3101
3790
  return this;
@@ -3134,12 +3823,36 @@ export class DiagramBuilder {
3134
3823
  * @param id - The message's element id, used verbatim.
3135
3824
  */
3136
3825
  message(id, options = {}) {
3137
- const message = { id, unknownAttributes: {} };
3138
- if (options.name !== undefined)
3139
- message.name = options.name;
3826
+ const keepOthers = (x) => x.name !== "zeebe:subscription";
3140
3827
  const extensions = zeebeExtensionsToXmlElements(options.correlationKey === undefined
3141
3828
  ? {}
3142
3829
  : { subscription: { correlationKey: options.correlationKey } });
3830
+ // A process that already named the message created it as Message_<name>; a
3831
+ // second definition with that id or name would be a duplicate in the XML.
3832
+ const existing = this._messages.find((m) => m.id === id) ??
3833
+ (options.name === undefined ? undefined : this._messages.find((m) => m.name === options.name));
3834
+ if (existing) {
3835
+ if (existing.id !== id) {
3836
+ // The declared id wins, as it does when message() runs first: message
3837
+ // flows name it, so the pools built so far are re-pointed at it.
3838
+ const renamed = new Map([[existing.id, id]]);
3839
+ for (const process of this._processes)
3840
+ remapMessageRefs(process.flowElements, renamed);
3841
+ existing.id = id;
3842
+ }
3843
+ if (options.name !== undefined)
3844
+ existing.name = options.name;
3845
+ if (extensions.length > 0) {
3846
+ existing.extensionElements = [
3847
+ ...(existing.extensionElements ?? []).filter(keepOthers),
3848
+ ...extensions,
3849
+ ];
3850
+ }
3851
+ return this;
3852
+ }
3853
+ const message = { id, unknownAttributes: {} };
3854
+ if (options.name !== undefined)
3855
+ message.name = options.name;
3143
3856
  if (extensions.length > 0)
3144
3857
  message.extensionElements = extensions;
3145
3858
  this._messages.push(message);
@@ -3170,81 +3883,13 @@ export class DiagramBuilder {
3170
3883
  return this;
3171
3884
  }
3172
3885
  /**
3173
- * Reports every way the declared collaboration would not survive contact with
3174
- * a modeler, so `build()` can refuse rather than emit a file that opens broken.
3886
+ * Enable auto-layout: `build()` lays out the whole diagram (pools, lanes,
3887
+ * message flows and every process) and writes its diagram interchange, using
3888
+ * the layout hints each process builder recorded.
3175
3889
  */
3176
- collaborationProblems() {
3177
- const problems = [];
3178
- const seen = new Set();
3179
- for (const id of [
3180
- ...this._participants.map((p) => p.id),
3181
- ...this._messageFlows.map((f) => f.id),
3182
- ]) {
3183
- if (seen.has(id))
3184
- problems.push(`Duplicate element ID "${id}"`);
3185
- seen.add(id);
3186
- }
3187
- const processIds = new Set(this._processes.map((process) => process.id));
3188
- const claimed = new Map();
3189
- for (const participant of this._participants) {
3190
- const processId = participant.processRef;
3191
- if (processId === undefined)
3192
- continue;
3193
- if (!processIds.has(processId)) {
3194
- problems.push(`Participant "${participant.id}" references process "${processId}", which this diagram does not contain`);
3195
- continue;
3196
- }
3197
- const owner = claimed.get(processId);
3198
- if (owner !== undefined) {
3199
- problems.push(`Participants "${owner}" and "${participant.id}" both reference process "${processId}"; a process belongs to one pool`);
3200
- }
3201
- claimed.set(processId, participant.id);
3202
- }
3203
- const owningParticipant = this.participantIndex();
3204
- const messageIds = new Set(this._messages.map((message) => message.id));
3205
- for (const flow of this._messageFlows) {
3206
- for (const [role, ref] of [
3207
- ["source", flow.sourceRef],
3208
- ["target", flow.targetRef],
3209
- ]) {
3210
- if (!owningParticipant.has(ref)) {
3211
- problems.push(`Message flow "${flow.id}" names ${role} "${ref}", which is not a participant or a flow node in one`);
3212
- }
3213
- }
3214
- const from = owningParticipant.get(flow.sourceRef);
3215
- const to = owningParticipant.get(flow.targetRef);
3216
- if (from !== undefined && from === to) {
3217
- problems.push(`Message flow "${flow.id}" starts and ends in participant "${from}"; a message flow crosses pools, a sequence flow stays inside one`);
3218
- }
3219
- if (flow.messageRef !== undefined && !messageIds.has(flow.messageRef)) {
3220
- problems.push(`Message flow "${flow.id}" references message "${flow.messageRef}", which this diagram does not declare`);
3221
- }
3222
- }
3223
- return problems;
3224
- }
3225
- /** Maps every participant id and every flow node id to its owning participant. */
3226
- participantIndex() {
3227
- const index = new Map();
3228
- const byProcess = new Map();
3229
- for (const participant of this._participants) {
3230
- index.set(participant.id, participant.id);
3231
- if (participant.processRef !== undefined)
3232
- byProcess.set(participant.processRef, participant.id);
3233
- }
3234
- const walk = (elements, owner) => {
3235
- for (const element of elements) {
3236
- index.set(element.id, owner);
3237
- if ("flowElements" in element && Array.isArray(element.flowElements)) {
3238
- walk(element.flowElements, owner);
3239
- }
3240
- }
3241
- };
3242
- for (const process of this._processes) {
3243
- const owner = byProcess.get(process.id);
3244
- if (owner !== undefined)
3245
- walk(process.flowElements, owner);
3246
- }
3247
- return index;
3890
+ withAutoLayout() {
3891
+ this._autoLayout = true;
3892
+ return this;
3248
3893
  }
3249
3894
  /**
3250
3895
  * Build the document. Gated like {@link ProcessBuilder.build}: see
@@ -3256,7 +3901,7 @@ export class DiagramBuilder {
3256
3901
  return gateBuild(this.buildModel(), options);
3257
3902
  }
3258
3903
  buildModel() {
3259
- return hoistMessageSubscriptions({
3904
+ const defs = {
3260
3905
  id: this._id,
3261
3906
  targetNamespace: "http://bpmn.io/schema/bpmn",
3262
3907
  exporter: "@bpmnkit/core",
@@ -3281,7 +3926,8 @@ export class DiagramBuilder {
3281
3926
  collaborations: this.buildCollaborations(),
3282
3927
  processes: this._processes,
3283
3928
  diagrams: [],
3284
- });
3929
+ };
3930
+ return finishDocument(this._autoLayout ? applyAutoLayout(defs, "semantic", this._layoutHints) : defs);
3285
3931
  }
3286
3932
  /**
3287
3933
  * A document with no participants has no collaboration — an empty
@@ -3289,16 +3935,17 @@ export class DiagramBuilder {
3289
3935
  * pool-less participant in a modeler.
3290
3936
  */
3291
3937
  buildCollaborations() {
3292
- if (this._participants.length === 0 && this._messageFlows.length === 0)
3938
+ const declared = new Set(this._participants.map((participant) => participant.processRef));
3939
+ const participants = [
3940
+ ...this._processPools.filter((pool) => !declared.has(pool.processRef)),
3941
+ ...this._participants,
3942
+ ];
3943
+ if (participants.length === 0 && this._messageFlows.length === 0)
3293
3944
  return [];
3294
- const problems = this.collaborationProblems();
3295
- if (problems.length > 0) {
3296
- throw new Error(`Invalid collaboration:\n ${problems.join("\n ")}`);
3297
- }
3298
- return [
3945
+ const collaborations = [
3299
3946
  {
3300
3947
  id: this._collaborationId,
3301
- participants: this._participants,
3948
+ participants,
3302
3949
  messageFlows: this._messageFlows,
3303
3950
  textAnnotations: [],
3304
3951
  associations: [],
@@ -3307,6 +3954,16 @@ export class DiagramBuilder {
3307
3954
  unknownAttributes: {},
3308
3955
  },
3309
3956
  ];
3957
+ // Refuse rather than emit a file that opens broken in a modeler.
3958
+ const problems = collaborationProblems({
3959
+ collaborations,
3960
+ processes: this._processes,
3961
+ messages: this._messages,
3962
+ });
3963
+ if (problems.length > 0) {
3964
+ throw new Error(`Invalid collaboration:\n ${problems.join("\n ")}`);
3965
+ }
3966
+ return collaborations;
3310
3967
  }
3311
3968
  }
3312
3969
  //# sourceMappingURL=bpmn-builder.js.map