@bpmnkit/core 0.3.0 → 0.5.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.
@@ -1,16 +1,43 @@
1
+ import { ValidationError } from "../errors.js";
1
2
  import { generateId } from "../types/id-generator.js";
2
3
  import { applyAutoLayout } from "./auto-layout.js";
4
+ import { createFlowElement } from "./element-shape.js";
3
5
  import { restConnectorRetries, restConnectorTaskType, restConnectorToIoMappingInputs, restConnectorToTaskHeaders, } from "./rest-connector.js";
6
+ import { assignStableFlowIds, rootDefinitionId } from "./stable-ids.js";
4
7
  import { ensureZeebeExtension, zeebeExtensionsToXmlElements, } from "./zeebe-extensions.js";
5
8
  // Keep in sync with packages/core/package.json version
6
9
  const EXPORTER_VERSION = "0.0.23";
7
10
  // ---------------------------------------------------------------------------
8
11
  // Internal helpers
9
12
  // ---------------------------------------------------------------------------
13
+ /**
14
+ * Decides whether an explicit root declaration can be recorded.
15
+ *
16
+ * Returns false when the identical declaration is already there, so declaring
17
+ * twice is harmless. Throws when it contradicts one the document already
18
+ * carries: events resolve these by name, so the ones built before this call
19
+ * hold the *other* id, and keeping two definitions of one message is how a
20
+ * `messageRef` ends up naming the wrong one.
21
+ */
22
+ function canDeclareRoot(kind, label, id, existing, all) {
23
+ if (existing !== undefined) {
24
+ if (existing.id === id)
25
+ return false;
26
+ throw new Error(`${kind} "${label}" is already declared as "${existing.id}". Declare it before the events that use it, or name that id instead.`);
27
+ }
28
+ if (all.some((definition) => definition.id === id)) {
29
+ throw new Error(`Duplicate ${kind} id "${id}".`);
30
+ }
31
+ return true;
32
+ }
10
33
  function resolveMessage(messageName, rootMessages) {
11
34
  let existing = rootMessages.find((m) => m.name === messageName);
12
35
  if (!existing) {
13
- existing = { id: generateId("Message"), name: messageName, unknownAttributes: {} };
36
+ existing = {
37
+ id: rootDefinitionId("Message", messageName, rootMessages),
38
+ name: messageName,
39
+ unknownAttributes: {},
40
+ };
14
41
  rootMessages.push(existing);
15
42
  }
16
43
  return existing.id;
@@ -37,7 +64,11 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
37
64
  if (codeOrRef !== undefined && rootErrors) {
38
65
  let existing = rootErrors.find((e) => e.errorCode === codeOrRef || e.name === codeOrRef);
39
66
  if (!existing) {
40
- existing = { id: generateId("Error"), name: codeOrRef, errorCode: codeOrRef };
67
+ existing = {
68
+ id: rootDefinitionId("Error", codeOrRef, rootErrors),
69
+ name: codeOrRef,
70
+ errorCode: codeOrRef,
71
+ };
41
72
  rootErrors.push(existing);
42
73
  }
43
74
  errorRef = existing.id;
@@ -58,7 +89,10 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
58
89
  if (rootSignals) {
59
90
  let existing = rootSignals.find((s) => s.name === opts.signalName);
60
91
  if (!existing) {
61
- existing = { id: generateId("Signal"), name: opts.signalName };
92
+ existing = {
93
+ id: rootDefinitionId("Signal", opts.signalName, rootSignals),
94
+ name: opts.signalName,
95
+ };
62
96
  rootSignals.push(existing);
63
97
  }
64
98
  signalRef = existing.id;
@@ -71,7 +105,7 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
71
105
  let existing = rootEscalations.find((e) => e.escalationCode === opts.escalationCode);
72
106
  if (!existing) {
73
107
  existing = {
74
- id: generateId("Escalation"),
108
+ id: rootDefinitionId("Escalation", opts.escalationCode, rootEscalations),
75
109
  name: opts.escalationCode,
76
110
  escalationCode: opts.escalationCode,
77
111
  };
@@ -86,89 +120,15 @@ function buildEventDefinitions(opts, rootErrors, rootMessages, rootSignals, root
86
120
  }
87
121
  return defs;
88
122
  }
123
+ /**
124
+ * Build an empty flow element.
125
+ *
126
+ * Delegates to `createFlowElement`, which holds the exhaustive type → shape
127
+ * switch; this wrapper exists so the builder's many call sites keep their
128
+ * shorter local name.
129
+ */
89
130
  function makeFlowElement(id, type, options) {
90
- const base = {
91
- id,
92
- name: options?.name,
93
- incoming: [],
94
- outgoing: [],
95
- documentation: options?.documentation,
96
- extensionElements: options?.extensionElements ?? [],
97
- unknownAttributes: {},
98
- };
99
- switch (type) {
100
- case "startEvent":
101
- case "endEvent":
102
- case "intermediateThrowEvent":
103
- case "intermediateCatchEvent":
104
- return { ...base, type, eventDefinitions: [] };
105
- case "boundaryEvent":
106
- return {
107
- ...base,
108
- type: "boundaryEvent",
109
- attachedToRef: "",
110
- eventDefinitions: [],
111
- };
112
- case "task":
113
- case "serviceTask":
114
- case "scriptTask":
115
- case "userTask":
116
- case "sendTask":
117
- case "receiveTask":
118
- case "businessRuleTask":
119
- case "manualTask":
120
- case "callActivity":
121
- return { ...base, type };
122
- case "exclusiveGateway":
123
- case "inclusiveGateway":
124
- case "complexGateway":
125
- return { ...base, type };
126
- case "parallelGateway":
127
- case "eventBasedGateway":
128
- return { ...base, type };
129
- case "subProcess":
130
- return {
131
- ...base,
132
- type: "subProcess",
133
- flowElements: [],
134
- sequenceFlows: [],
135
- textAnnotations: [],
136
- associations: [],
137
- groups: [],
138
- };
139
- case "adHocSubProcess":
140
- return {
141
- ...base,
142
- type: "adHocSubProcess",
143
- flowElements: [],
144
- sequenceFlows: [],
145
- textAnnotations: [],
146
- associations: [],
147
- groups: [],
148
- };
149
- case "eventSubProcess":
150
- return {
151
- ...base,
152
- type: "eventSubProcess",
153
- flowElements: [],
154
- sequenceFlows: [],
155
- textAnnotations: [],
156
- associations: [],
157
- groups: [],
158
- };
159
- case "transaction":
160
- return {
161
- ...base,
162
- type: "transaction",
163
- flowElements: [],
164
- sequenceFlows: [],
165
- textAnnotations: [],
166
- associations: [],
167
- groups: [],
168
- };
169
- default:
170
- return { ...base, type };
171
- }
131
+ return createFlowElement(id, type, options);
172
132
  }
173
133
  function buildMultiInstance(options) {
174
134
  const extChildren = [];
@@ -449,6 +409,14 @@ function makeInclusiveGatewayEl(id, options) {
449
409
  }
450
410
  return el;
451
411
  }
412
+ function makeComplexGatewayEl(id, options) {
413
+ const el = makeFlowElement(id, "complexGateway", options);
414
+ if (options?.defaultFlow && el.type === "complexGateway") {
415
+ ;
416
+ el.default = options.defaultFlow;
417
+ }
418
+ return el;
419
+ }
452
420
  /**
453
421
  * `subProcess`/`eventSubProcess`/`adHocSubProcess` all take a required content
454
422
  * callback as their 2nd argument and an optional options object as their 3rd.
@@ -474,6 +442,52 @@ function resolveSubProcessArgs(content, options) {
474
442
  }
475
443
  throw new TypeError("subProcess() requires a content callback function");
476
444
  }
445
+ /**
446
+ * `boundaryEvent` takes its host activity in `options.attachedTo`, but the
447
+ * positional shape `boundaryEvent(id, hostId, options)` reads just as naturally
448
+ * and is what callers reach for when they have only seen the parameter names.
449
+ * Accept both, for the same reason `resolveSubProcessArgs` accepts a reversed
450
+ * pair: the alternative was emitting a boundary event with no `attachedToRef`,
451
+ * which is invalid BPMN that this library's own parser then refuses to read.
452
+ *
453
+ * A missing host is a genuine error rather than a shape to guess at, so it
454
+ * throws here — at the call that caused it — instead of at export time.
455
+ */
456
+ function resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions) {
457
+ const options = typeof attachedToOrOptions === "string"
458
+ ? { ...maybeOptions, attachedTo: attachedToOrOptions }
459
+ : attachedToOrOptions;
460
+ if (typeof options?.attachedTo !== "string" || options.attachedTo === "") {
461
+ throw new ValidationError(`boundaryEvent("${id}") requires the id of the activity it attaches to. Pass it as options.attachedTo, as boundaryEvent("${id}", hostId, options), or use withBoundary() to attach to the preceding activity.`);
462
+ }
463
+ return options;
464
+ }
465
+ /**
466
+ * Build a transaction element from a content callback.
467
+ *
468
+ * A transaction is a sub-process with atomic semantics: the same container
469
+ * shape and the same content builder, under a distinct element name so a cancel
470
+ * boundary event has a scope to attach to. Shared by all three flow builders —
471
+ * unlike `subProcess`, whose cursor handling differs per class, nothing here
472
+ * varies between them.
473
+ */
474
+ function makeTransactionEl(id, content, options, rootMessages) {
475
+ const resolved = resolveSubProcessArgs(content, options);
476
+ const sub = new SubProcessContentBuilder(rootMessages);
477
+ resolved.content(sub);
478
+ finalizeScope(sub._elements, sub._flows);
479
+ const element = makeFlowElement(id, "transaction", resolved.options);
480
+ if (element.type === "transaction") {
481
+ element.flowElements = sub._elements;
482
+ element.sequenceFlows = sub._flows;
483
+ element.textAnnotations = sub._textAnnotations;
484
+ element.associations = sub._associations;
485
+ if (resolved.options?.multiInstance) {
486
+ element.loopCharacteristics = buildMultiInstance(resolved.options.multiInstance);
487
+ }
488
+ }
489
+ return element;
490
+ }
477
491
  // ---------------------------------------------------------------------------
478
492
  // Shared graph helpers — used by ProcessBuilder and SubProcessContentBuilder
479
493
  // ---------------------------------------------------------------------------
@@ -550,6 +564,17 @@ function insertJoinGateways(elements, flows) {
550
564
  }
551
565
  }
552
566
  }
567
+ /**
568
+ * Settles a finished scope: infer the joins its branches imply, name its
569
+ * sequence flows after what they connect, then rebuild the `incoming`/
570
+ * `outgoing` lists the ids feed. Order matters — a flow's endpoints are not
571
+ * final until join inference has run, and its id is not final until this pass.
572
+ */
573
+ function finalizeScope(elements, flows) {
574
+ insertJoinGateways(elements, flows);
575
+ assignStableFlowIds(elements, flows);
576
+ recomputeIncomingOutgoing(elements, flows);
577
+ }
553
578
  function traceBackToSplit(nodeId, splitGateways, flows) {
554
579
  const visited = new Set();
555
580
  let current = nodeId;
@@ -751,6 +776,13 @@ export class BranchBuilder {
751
776
  callActivity(id, options) {
752
777
  return this.addElement(makeCallActivityEl(id, options));
753
778
  }
779
+ /** Add a manual task — work performed outside the engine, with no job worker. */
780
+ manualTask(id, options) {
781
+ const el = makeFlowElement(id, "manualTask", options);
782
+ if (options?.isForCompensation)
783
+ el.isForCompensation = true;
784
+ return this.addElement(el);
785
+ }
754
786
  /** Add an abstract task with no Zeebe extensions. */
755
787
  task(id, options) {
756
788
  const el = makeFlowElement(id, "task", options);
@@ -805,6 +837,10 @@ export class BranchBuilder {
805
837
  this.currentGatewayId = id;
806
838
  return this.addElement(makeFlowElement(id, "eventBasedGateway", options));
807
839
  }
840
+ complexGateway(id, options) {
841
+ this.currentGatewayId = id;
842
+ return this.addElement(makeComplexGatewayEl(id, options));
843
+ }
808
844
  /**
809
845
  * Add a boundary event attached to an existing activity in this branch.
810
846
  *
@@ -813,7 +849,8 @@ export class BranchBuilder {
813
849
  * subsequent elements chain from it. Use `withBoundary()` if you want the
814
850
  * cursor to return to the task afterward.
815
851
  */
816
- boundaryEvent(id, options) {
852
+ boundaryEvent(id, attachedToOrOptions, maybeOptions) {
853
+ const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
817
854
  const element = makeFlowElement(id, "boundaryEvent", {
818
855
  ...options,
819
856
  extensionElements: buildMessageSubscriptionExt(options.correlationKey),
@@ -869,8 +906,7 @@ export class BranchBuilder {
869
906
  const resolved = resolveSubProcessArgs(content, options);
870
907
  const sub = new SubProcessContentBuilder(this.rootMessages);
871
908
  resolved.content(sub);
872
- insertJoinGateways(sub._elements, sub._flows);
873
- recomputeIncomingOutgoing(sub._elements, sub._flows);
909
+ finalizeScope(sub._elements, sub._flows);
874
910
  const element = makeFlowElement(id, "subProcess", resolved.options);
875
911
  if (element.type === "subProcess") {
876
912
  element.flowElements = sub._elements;
@@ -883,13 +919,24 @@ export class BranchBuilder {
883
919
  }
884
920
  return this.addElement(element);
885
921
  }
886
- /** Add an ad-hoc sub-process (mirrors `ProcessBuilder.adHocSubProcess`). */
922
+ /** Add a transaction sub-process (mirrors `ProcessBuilder.transaction`). */
923
+ transaction(id, content, options) {
924
+ return this.addElement(makeTransactionEl(id, content, options, this.rootMessages));
925
+ }
926
+ /**
927
+ * Add an ad-hoc sub-process (mirrors `ProcessBuilder.adHocSubProcess`).
928
+ *
929
+ * Its children are **not** auto-chained: BPMN defines them as an unordered set
930
+ * of independently-invocable activities, and Camunda 8 reads a child with an
931
+ * incoming flow as part of an internal sub-flow rather than an LLM-invocable
932
+ * tool. Use `connectTo()` inside the callback to state ordering you do want.
933
+ */
887
934
  adHocSubProcess(id, content, options) {
888
935
  const resolved = resolveSubProcessArgs(content, options);
889
- const sub = new SubProcessContentBuilder(this.rootMessages);
936
+ // Ad-hoc sub-process children are unordered — see SubProcessContentBuilder.autoConnect.
937
+ const sub = new SubProcessContentBuilder(this.rootMessages, false);
890
938
  resolved.content(sub);
891
- insertJoinGateways(sub._elements, sub._flows);
892
- recomputeIncomingOutgoing(sub._elements, sub._flows);
939
+ finalizeScope(sub._elements, sub._flows);
893
940
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
894
941
  const element = makeFlowElement(id, "adHocSubProcess", {
895
942
  name: resolved.options?.name,
@@ -904,8 +951,7 @@ export class BranchBuilder {
904
951
  const resolved = resolveSubProcessArgs(content, options);
905
952
  const sub = new SubProcessContentBuilder(this.rootMessages);
906
953
  resolved.content(sub);
907
- insertJoinGateways(sub._elements, sub._flows);
908
- recomputeIncomingOutgoing(sub._elements, sub._flows);
954
+ finalizeScope(sub._elements, sub._flows);
909
955
  const element = makeFlowElement(id, "subProcess", resolved.options);
910
956
  if (element.type === "subProcess") {
911
957
  element.triggeredByEvent = true;
@@ -991,9 +1037,22 @@ export class SubProcessContentBuilder {
991
1037
  currentGatewayId;
992
1038
  openBranchEnds = [];
993
1039
  rootMessages;
1040
+ /**
1041
+ * Whether sequential calls chain themselves with sequence flows.
1042
+ *
1043
+ * False inside an ad-hoc sub-process, whose children BPMN defines as an
1044
+ * unordered set of independently-invocable activities. Chaining them there is
1045
+ * not merely redundant: Camunda 8 reads a child *with* an incoming flow as
1046
+ * part of an internal sub-flow rather than an LLM-invocable tool, so the
1047
+ * fabricated flows silently turned a three-tool agent into one tool and a
1048
+ * two-step sub-flow. Ordering inside such a container is stated explicitly
1049
+ * with `connectTo()`.
1050
+ */
1051
+ autoConnect;
994
1052
  /** @internal */
995
- constructor(rootMessages = []) {
1053
+ constructor(rootMessages = [], autoConnect = true) {
996
1054
  this.rootMessages = rootMessages;
1055
+ this.autoConnect = autoConnect;
997
1056
  }
998
1057
  addElement(element) {
999
1058
  if (this._ids.has(element.id)) {
@@ -1001,25 +1060,29 @@ export class SubProcessContentBuilder {
1001
1060
  }
1002
1061
  this._elements.push(element);
1003
1062
  this._ids.add(element.id);
1004
- if (this.lastNodeId) {
1005
- this._flows.push({
1006
- id: generateId("Flow"),
1007
- sourceRef: this.lastNodeId,
1008
- targetRef: element.id,
1009
- extensionElements: [],
1010
- unknownAttributes: {},
1011
- });
1012
- }
1013
- for (const branchEnd of this.openBranchEnds) {
1014
- this._flows.push({
1015
- id: generateId("Flow"),
1016
- sourceRef: branchEnd,
1017
- targetRef: element.id,
1018
- extensionElements: [],
1019
- unknownAttributes: {},
1020
- });
1063
+ if (this.autoConnect) {
1064
+ if (this.lastNodeId) {
1065
+ this._flows.push({
1066
+ id: generateId("Flow"),
1067
+ sourceRef: this.lastNodeId,
1068
+ targetRef: element.id,
1069
+ extensionElements: [],
1070
+ unknownAttributes: {},
1071
+ });
1072
+ }
1073
+ for (const branchEnd of this.openBranchEnds) {
1074
+ this._flows.push({
1075
+ id: generateId("Flow"),
1076
+ sourceRef: branchEnd,
1077
+ targetRef: element.id,
1078
+ extensionElements: [],
1079
+ unknownAttributes: {},
1080
+ });
1081
+ }
1082
+ this.openBranchEnds = [];
1021
1083
  }
1022
- this.openBranchEnds = [];
1084
+ // The cursor still moves even when nothing is wired, so `connectTo()` after
1085
+ // an activity keeps naming that activity as the flow's source.
1023
1086
  this.lastNodeId = element.id;
1024
1087
  return this;
1025
1088
  }
@@ -1102,6 +1165,13 @@ export class SubProcessContentBuilder {
1102
1165
  el.messageRef = resolveMessage(options.messageName, this.rootMessages);
1103
1166
  return this.addElement(el);
1104
1167
  }
1168
+ /** Add a manual task — work performed outside the engine, with no job worker. */
1169
+ manualTask(id, options) {
1170
+ const el = makeFlowElement(id, "manualTask", options);
1171
+ if (options?.isForCompensation)
1172
+ el.isForCompensation = true;
1173
+ return this.addElement(el);
1174
+ }
1105
1175
  /** Add an abstract task with no Zeebe extensions. */
1106
1176
  task(id, options) {
1107
1177
  const el = makeFlowElement(id, "task", options);
@@ -1126,6 +1196,10 @@ export class SubProcessContentBuilder {
1126
1196
  this.currentGatewayId = id;
1127
1197
  return this.addElement(makeFlowElement(id, "eventBasedGateway", options));
1128
1198
  }
1199
+ complexGateway(id, options) {
1200
+ this.currentGatewayId = id;
1201
+ return this.addElement(makeComplexGatewayEl(id, options));
1202
+ }
1129
1203
  // ---- Annotations ----
1130
1204
  /** Attach a text annotation to the element at the current cursor position. */
1131
1205
  textAnnotation(text) {
@@ -1220,7 +1294,8 @@ export class SubProcessContentBuilder {
1220
1294
  * subsequent elements chain from it. Use `withBoundary()` if you want the
1221
1295
  * cursor to return to the task afterward.
1222
1296
  */
1223
- boundaryEvent(id, options) {
1297
+ boundaryEvent(id, attachedToOrOptions, maybeOptions) {
1298
+ const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
1224
1299
  const element = makeFlowElement(id, "boundaryEvent", {
1225
1300
  ...options,
1226
1301
  extensionElements: buildMessageSubscriptionExt(options.correlationKey),
@@ -1273,8 +1348,7 @@ export class SubProcessContentBuilder {
1273
1348
  const resolved = resolveSubProcessArgs(content, options);
1274
1349
  const sub = new SubProcessContentBuilder(this.rootMessages);
1275
1350
  resolved.content(sub);
1276
- insertJoinGateways(sub._elements, sub._flows);
1277
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1351
+ finalizeScope(sub._elements, sub._flows);
1278
1352
  const element = makeFlowElement(id, "subProcess", resolved.options);
1279
1353
  if (element.type === "subProcess") {
1280
1354
  element.flowElements = sub._elements;
@@ -1287,13 +1361,24 @@ export class SubProcessContentBuilder {
1287
1361
  }
1288
1362
  return this.addElement(element);
1289
1363
  }
1290
- /** Add an ad-hoc sub-process nested inside this sub-process's content. */
1364
+ /** Add a transaction sub-process nested inside this sub-process's content. */
1365
+ transaction(id, content, options) {
1366
+ return this.addElement(makeTransactionEl(id, content, options, this.rootMessages));
1367
+ }
1368
+ /**
1369
+ * Add an ad-hoc sub-process nested inside this sub-process's content.
1370
+ *
1371
+ * Its children are **not** auto-chained: BPMN defines them as an unordered set
1372
+ * of independently-invocable activities, and Camunda 8 reads a child with an
1373
+ * incoming flow as part of an internal sub-flow rather than an LLM-invocable
1374
+ * tool. Use `connectTo()` inside the callback to state ordering you do want.
1375
+ */
1291
1376
  adHocSubProcess(id, content, options) {
1292
1377
  const resolved = resolveSubProcessArgs(content, options);
1293
- const sub = new SubProcessContentBuilder(this.rootMessages);
1378
+ // Ad-hoc sub-process children are unordered — see SubProcessContentBuilder.autoConnect.
1379
+ const sub = new SubProcessContentBuilder(this.rootMessages, false);
1294
1380
  resolved.content(sub);
1295
- insertJoinGateways(sub._elements, sub._flows);
1296
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1381
+ finalizeScope(sub._elements, sub._flows);
1297
1382
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1298
1383
  const element = makeFlowElement(id, "adHocSubProcess", {
1299
1384
  name: resolved.options?.name,
@@ -1308,8 +1393,7 @@ export class SubProcessContentBuilder {
1308
1393
  const resolved = resolveSubProcessArgs(content, options);
1309
1394
  const sub = new SubProcessContentBuilder(this.rootMessages);
1310
1395
  resolved.content(sub);
1311
- insertJoinGateways(sub._elements, sub._flows);
1312
- recomputeIncomingOutgoing(sub._elements, sub._flows);
1396
+ finalizeScope(sub._elements, sub._flows);
1313
1397
  const element = makeFlowElement(id, "subProcess", resolved.options);
1314
1398
  if (element.type === "subProcess") {
1315
1399
  element.triggeredByEvent = true;
@@ -1523,6 +1607,80 @@ export class ProcessBuilder {
1523
1607
  this._versionTag = tag;
1524
1608
  return this;
1525
1609
  }
1610
+ // ---- Root definitions ----
1611
+ /**
1612
+ * Declares the root `bpmn:message` for a message name, with the id you choose.
1613
+ *
1614
+ * Events name messages by name — `{ messageName: "Order Received" }` — and the
1615
+ * builder declares one on first use, deriving its id from that name. Call this
1616
+ * first when the id itself matters, typically because something outside this
1617
+ * process already refers to it.
1618
+ *
1619
+ * @param id - The message's element id, used verbatim.
1620
+ * @throws If a message with this name is already declared under another id,
1621
+ * which the events built before this call already point at.
1622
+ * @example
1623
+ * ```typescript
1624
+ * Bpmn.createProcess("orders")
1625
+ * .message("Msg_OrderReceived", { name: "Order Received" })
1626
+ * .startEvent("start", { messageName: "Order Received" })
1627
+ * ```
1628
+ */
1629
+ message(id, options) {
1630
+ const existing = this.rootMessages.find((message) => message.name === options.name);
1631
+ if (canDeclareRoot("Message", options.name, id, existing, this.rootMessages)) {
1632
+ this.rootMessages.push({ id, name: options.name, unknownAttributes: {} });
1633
+ }
1634
+ return this;
1635
+ }
1636
+ /**
1637
+ * Declares the root `bpmn:error` for an error code, with the id you choose.
1638
+ *
1639
+ * @param id - The error's element id, used verbatim.
1640
+ * @param options - The `code` events match on, and the display `name`, which
1641
+ * defaults to the code.
1642
+ * @throws If this code is already declared under another id.
1643
+ */
1644
+ error(id, options) {
1645
+ const existing = this.rootErrors.find((error) => error.errorCode === options.code || error.name === options.code);
1646
+ if (canDeclareRoot("Error", options.code, id, existing, this.rootErrors)) {
1647
+ this.rootErrors.push({ id, name: options.name ?? options.code, errorCode: options.code });
1648
+ }
1649
+ return this;
1650
+ }
1651
+ /**
1652
+ * Declares the root `bpmn:signal` for a signal name, with the id you choose.
1653
+ *
1654
+ * @param id - The signal's element id, used verbatim.
1655
+ * @throws If this name is already declared under another id.
1656
+ */
1657
+ signal(id, options) {
1658
+ const existing = this.rootSignals.find((signal) => signal.name === options.name);
1659
+ if (canDeclareRoot("Signal", options.name, id, existing, this.rootSignals)) {
1660
+ this.rootSignals.push({ id, name: options.name });
1661
+ }
1662
+ return this;
1663
+ }
1664
+ /**
1665
+ * Declares the root `bpmn:escalation` for an escalation code, with the id you
1666
+ * choose.
1667
+ *
1668
+ * @param id - The escalation's element id, used verbatim.
1669
+ * @param options - The `code` events match on, and the display `name`, which
1670
+ * defaults to the code.
1671
+ * @throws If this code is already declared under another id.
1672
+ */
1673
+ escalation(id, options) {
1674
+ const existing = this.rootEscalations.find((escalation) => escalation.escalationCode === options.code);
1675
+ if (canDeclareRoot("Escalation", options.code, id, existing, this.rootEscalations)) {
1676
+ this.rootEscalations.push({
1677
+ id,
1678
+ name: options.name ?? options.code,
1679
+ escalationCode: options.code,
1680
+ });
1681
+ }
1682
+ return this;
1683
+ }
1526
1684
  // ---- Events ----
1527
1685
  /** Add a start event. Start events never auto-connect from the previous element. */
1528
1686
  startEvent(id, options) {
@@ -1535,6 +1693,7 @@ export class ProcessBuilder {
1535
1693
  }
1536
1694
  const element = makeFlowElement(nodeId, "startEvent", {
1537
1695
  name: options?.name,
1696
+ documentation: options?.documentation,
1538
1697
  extensionElements: extElements,
1539
1698
  });
1540
1699
  if (element.type === "startEvent" && options) {
@@ -1613,7 +1772,8 @@ export class ProcessBuilder {
1613
1772
  * Boundary events do not auto-connect from the previous element.
1614
1773
  * They start a new outgoing chain from the boundary event itself.
1615
1774
  */
1616
- boundaryEvent(id, options) {
1775
+ boundaryEvent(id, attachedToOrOptions, maybeOptions) {
1776
+ const options = resolveBoundaryEventArgs(id, attachedToOrOptions, maybeOptions);
1617
1777
  const element = makeFlowElement(id, "boundaryEvent", {
1618
1778
  ...options,
1619
1779
  extensionElements: buildMessageSubscriptionExt(options.correlationKey),
@@ -1740,6 +1900,14 @@ export class ProcessBuilder {
1740
1900
  this.addFlowElement(makeCallActivityEl(id, options));
1741
1901
  return this;
1742
1902
  }
1903
+ /** Add a manual task — work performed outside the engine, with no job worker. */
1904
+ manualTask(id, options) {
1905
+ const el = makeFlowElement(id, "manualTask", options);
1906
+ if (options?.isForCompensation)
1907
+ el.isForCompensation = true;
1908
+ this.addFlowElement(el);
1909
+ return this;
1910
+ }
1743
1911
  /** Add an abstract task with no Zeebe extensions. */
1744
1912
  task(id, options) {
1745
1913
  const el = makeFlowElement(id, "task", options);
@@ -1773,6 +1941,12 @@ export class ProcessBuilder {
1773
1941
  this.currentGatewayId = id;
1774
1942
  return this;
1775
1943
  }
1944
+ /** Add a complex gateway. Aspirational — Zeebe does not execute these. */
1945
+ complexGateway(id, options) {
1946
+ this.addFlowElement(makeComplexGatewayEl(id, options));
1947
+ this.currentGatewayId = id;
1948
+ return this;
1949
+ }
1776
1950
  // ---- Branching & flow control ----
1777
1951
  /**
1778
1952
  * Create a named branch from the current gateway.
@@ -1866,13 +2040,20 @@ export class ProcessBuilder {
1866
2040
  return this;
1867
2041
  }
1868
2042
  // ---- Sub-processes ----
1869
- /** Add an ad-hoc sub-process with optional AI agent or multi-instance configuration. */
2043
+ /**
2044
+ * Add an ad-hoc sub-process with optional AI agent or multi-instance configuration.
2045
+ *
2046
+ * Its children are **not** auto-chained: BPMN defines them as an unordered set
2047
+ * of independently-invocable activities, and Camunda 8 reads a child with an
2048
+ * incoming flow as part of an internal sub-flow rather than an LLM-invocable
2049
+ * tool. Use `connectTo()` inside the callback to state ordering you do want.
2050
+ */
1870
2051
  adHocSubProcess(id, content, options) {
1871
2052
  const resolved = resolveSubProcessArgs(content, options);
1872
- const sub = new SubProcessContentBuilder(this.rootMessages);
2053
+ // Ad-hoc sub-process children are unordered — see SubProcessContentBuilder.autoConnect.
2054
+ const sub = new SubProcessContentBuilder(this.rootMessages, false);
1873
2055
  resolved.content(sub);
1874
- insertJoinGateways(sub._elements, sub._flows);
1875
- recomputeIncomingOutgoing(sub._elements, sub._flows);
2056
+ finalizeScope(sub._elements, sub._flows);
1876
2057
  const { extensionElements, completionCondition } = buildAdHocSubProcessExtensions(resolved.options);
1877
2058
  const element = makeFlowElement(id, "adHocSubProcess", {
1878
2059
  name: resolved.options?.name,
@@ -1888,8 +2069,7 @@ export class ProcessBuilder {
1888
2069
  const resolved = resolveSubProcessArgs(content, options);
1889
2070
  const sub = new SubProcessContentBuilder(this.rootMessages);
1890
2071
  resolved.content(sub);
1891
- insertJoinGateways(sub._elements, sub._flows);
1892
- recomputeIncomingOutgoing(sub._elements, sub._flows);
2072
+ finalizeScope(sub._elements, sub._flows);
1893
2073
  const element = makeFlowElement(id, "subProcess", resolved.options);
1894
2074
  if (element.type === "subProcess") {
1895
2075
  element.flowElements = sub._elements;
@@ -1903,13 +2083,17 @@ export class ProcessBuilder {
1903
2083
  this.addFlowElement(element);
1904
2084
  return this;
1905
2085
  }
2086
+ /** Add a transaction sub-process — a sub-process with atomic semantics. */
2087
+ transaction(id, content, options) {
2088
+ this.addFlowElement(makeTransactionEl(id, content, options, this.rootMessages));
2089
+ return this;
2090
+ }
1906
2091
  /** Add an event sub-process. Triggered by its start event — no incoming or outgoing sequence flows. */
1907
2092
  eventSubProcess(id, content, options) {
1908
2093
  const resolved = resolveSubProcessArgs(content, options);
1909
2094
  const sub = new SubProcessContentBuilder(this.rootMessages);
1910
2095
  resolved.content(sub);
1911
- insertJoinGateways(sub._elements, sub._flows);
1912
- recomputeIncomingOutgoing(sub._elements, sub._flows);
2096
+ finalizeScope(sub._elements, sub._flows);
1913
2097
  const element = makeFlowElement(id, "subProcess", resolved.options);
1914
2098
  if (element.type === "subProcess") {
1915
2099
  element.triggeredByEvent = true;
@@ -2000,6 +2184,9 @@ export class ProcessBuilder {
2000
2184
  }
2001
2185
  this.validate();
2002
2186
  this.assertSourceTopologyIntact();
2187
+ // Flows the document already had keep their ids: continuing a model must
2188
+ // not renumber the part the caller did not touch.
2189
+ assignStableFlowIds(this.flowElements, this.sequenceFlows, this._source === undefined ? undefined : new Set(this._sourceFlowTargets.keys()));
2003
2190
  recomputeIncomingOutgoing(this.flowElements, this.sequenceFlows);
2004
2191
  if (this._source !== undefined)
2005
2192
  return this.buildOntoSource(this._source);
@@ -2204,6 +2391,16 @@ export class ProcessBuilder {
2204
2391
  // ---------------------------------------------------------------------------
2205
2392
  // Diagram builder — multi-process support
2206
2393
  // ---------------------------------------------------------------------------
2394
+ /** Appends the root definitions the document does not already declare, matched by id. */
2395
+ function mergeRootDefinitions(into, incoming) {
2396
+ const present = new Set(into.map((definition) => definition.id));
2397
+ for (const definition of incoming) {
2398
+ if (present.has(definition.id))
2399
+ continue;
2400
+ present.add(definition.id);
2401
+ into.push(definition);
2402
+ }
2403
+ }
2207
2404
  /**
2208
2405
  * Builder for a complete BPMN definitions document containing one or more processes.
2209
2406
  * Use `Bpmn.createDiagram(id?)` to obtain an instance.
@@ -2230,8 +2427,11 @@ export class DiagramBuilder {
2230
2427
  callback(builder);
2231
2428
  const defs = builder.build();
2232
2429
  this._processes.push(...defs.processes);
2233
- this._errors.push(...defs.errors);
2234
- this._messages.push(...defs.messages);
2430
+ // Root definitions are named after the message or error code they carry, so
2431
+ // two pools declaring the same one produce the same definition twice. The
2432
+ // document needs it once.
2433
+ mergeRootDefinitions(this._errors, defs.errors);
2434
+ mergeRootDefinitions(this._messages, defs.messages);
2235
2435
  return this;
2236
2436
  }
2237
2437
  /** Renames the collaboration element. Defaults to `"Collaboration_1"`. */