@bpmnkit/core 1.14.0 → 1.15.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.
@@ -13,6 +13,8 @@ export interface CompactElement {
13
13
  documentation?: string;
14
14
  /** Zeebe job type (serviceTask: zeebe:taskDefinition.type) */
15
15
  jobType?: string;
16
+ /** Job retries (`zeebe:taskDefinition` retries), a number or FEEL. */
17
+ retries?: string;
16
18
  /** dataObjectReference: id of the dataObject it points at. */
17
19
  dataObjectRef?: string;
18
20
  /** dataStoreReference: id of the data store it points at. */
@@ -471,7 +471,11 @@ export function makeExtensions(el) {
471
471
  const ext = [];
472
472
  const { inputs, headers } = zeebeConfig(el);
473
473
  if (el.jobType) {
474
- ext.push({ name: "zeebe:taskDefinition", attributes: { type: el.jobType }, children: [] });
474
+ ext.push({
475
+ name: "zeebe:taskDefinition",
476
+ attributes: { type: el.jobType, ...(el.retries ? { retries: el.retries } : {}) },
477
+ children: [],
478
+ });
475
479
  }
476
480
  if (Object.keys(headers).length > 0) {
477
481
  ext.push({
@@ -597,7 +601,10 @@ function buildSubContent(children, roots) {
597
601
  sourceRef: f.from,
598
602
  targetRef: f.to,
599
603
  conditionExpression: f.condition
600
- ? { text: toFeelCondition(f.condition), attributes: {} }
604
+ ? {
605
+ text: toFeelCondition(f.condition),
606
+ attributes: { "xsi:type": "bpmn:tFormalExpression" },
607
+ }
601
608
  : undefined,
602
609
  extensionElements: [],
603
610
  unknownAttributes: {},
@@ -920,7 +927,7 @@ function expandProcess(compact, roots) {
920
927
  sourceRef: f.from,
921
928
  targetRef: f.to,
922
929
  conditionExpression: f.condition
923
- ? { text: toFeelCondition(f.condition), attributes: {} }
930
+ ? { text: toFeelCondition(f.condition), attributes: { "xsi:type": "bpmn:tFormalExpression" } }
924
931
  : undefined,
925
932
  extensionElements: [],
926
933
  unknownAttributes: {},
@@ -0,0 +1,26 @@
1
+ import type { BpmnDefinitions } from "./bpmn-model.js";
2
+ /** What {@link makeRoom} moved. */
3
+ export interface MakeRoomResult {
4
+ /** A copy of the input with the shifted shapes; the input is not changed. */
5
+ definitions: BpmnDefinitions;
6
+ /** One entry per insertion point: the node new ones follow, and how far right the rest moved. */
7
+ shifted: Array<{
8
+ after: string;
9
+ dx: number;
10
+ }>;
11
+ }
12
+ /**
13
+ * Makes space for nodes inserted into a path of a laid-out diagram, the way a
14
+ * modeler's "make space" does: every shape right of the node a new path leaves
15
+ * from moves right by the width the new nodes need on their longest path, less
16
+ * the room already free on that row; pools, lanes and expanded
17
+ * sub-processes spanning that point grow by as much. Run it before
18
+ * {@link placeNewShapes}, which then finds room next to the anchor instead of
19
+ * drawing the new nodes over the old ones.
20
+ *
21
+ * Only new nodes on a path count (reached by sequence flows from a drawn node
22
+ * that is not a boundary event): an exception path hangs below its task and
23
+ * needs no horizontal room.
24
+ */
25
+ export declare function makeRoom(input: BpmnDefinitions): MakeRoomResult;
26
+ //# sourceMappingURL=make-room.d.ts.map
@@ -0,0 +1,151 @@
1
+ import { sizeOf } from "../layout/semantic/place.js";
2
+ import { isContainerType } from "./element-shape.js";
3
+ /** Horizontal space left per inserted node, on top of its width. */
4
+ const GAP = 50;
5
+ function* scopes(elements, flows) {
6
+ yield { elements, flows };
7
+ for (const el of elements) {
8
+ const inner = el;
9
+ if (inner.flowElements)
10
+ yield* scopes(inner.flowElements, inner.sequenceFlows ?? []);
11
+ }
12
+ }
13
+ /**
14
+ * Makes space for nodes inserted into a path of a laid-out diagram, the way a
15
+ * modeler's "make space" does: every shape right of the node a new path leaves
16
+ * from moves right by the width the new nodes need on their longest path, less
17
+ * the room already free on that row; pools, lanes and expanded
18
+ * sub-processes spanning that point grow by as much. Run it before
19
+ * {@link placeNewShapes}, which then finds room next to the anchor instead of
20
+ * drawing the new nodes over the old ones.
21
+ *
22
+ * Only new nodes on a path count (reached by sequence flows from a drawn node
23
+ * that is not a boundary event): an exception path hangs below its task and
24
+ * needs no horizontal room.
25
+ */
26
+ export function makeRoom(input) {
27
+ const defs = structuredClone(input);
28
+ const result = { definitions: defs, shifted: [] };
29
+ const shapes = defs.diagrams.flatMap((d) => d.plane.shapes);
30
+ const shapeOf = new Map(shapes.map((s) => [s.bpmnElement, s]));
31
+ if (shapes.length === 0)
32
+ return result;
33
+ // Shapes that may contain others: they grow across the insertion point instead of moving.
34
+ const containers = new Set();
35
+ for (const c of defs.collaborations)
36
+ for (const p of c.participants)
37
+ containers.add(p.id);
38
+ for (const process of defs.processes) {
39
+ const lanes = (set) => {
40
+ for (const lane of set?.lanes ?? []) {
41
+ containers.add(lane.id);
42
+ lanes(lane.childLaneSet);
43
+ }
44
+ };
45
+ lanes(process.laneSet);
46
+ for (const scope of scopes(process.flowElements, process.sequenceFlows))
47
+ for (const el of scope.elements)
48
+ if (isContainerType(el.type))
49
+ containers.add(el.id);
50
+ }
51
+ const anchors = [];
52
+ for (const process of defs.processes) {
53
+ for (const scope of scopes(process.flowElements, process.sequenceFlows)) {
54
+ const byId = new Map(scope.elements.map((e) => [e.id, e]));
55
+ const isNew = (id) => {
56
+ const el = byId.get(id);
57
+ return el !== undefined && !shapeOf.has(id) && el.type !== "boundaryEvent";
58
+ };
59
+ for (const el of scope.elements) {
60
+ const shape = shapeOf.get(el.id);
61
+ if (shape === undefined || el.type === "boundaryEvent")
62
+ continue;
63
+ // The new nodes reachable from this drawn node through new nodes only.
64
+ const chain = new Set();
65
+ const queue = scope.flows
66
+ .filter((f) => f.sourceRef === el.id && isNew(f.targetRef))
67
+ .map((f) => f.targetRef);
68
+ while (queue.length > 0) {
69
+ const id = queue.shift() ?? "";
70
+ if (chain.has(id))
71
+ continue;
72
+ chain.add(id);
73
+ for (const f of scope.flows)
74
+ if (f.sourceRef === id && isNew(f.targetRef))
75
+ queue.push(f.targetRef);
76
+ }
77
+ if (chain.size === 0)
78
+ continue;
79
+ // Branches of a new split stack vertically: only the longest path needs width.
80
+ const memo = new Map();
81
+ const longest = (id, seen) => {
82
+ const known = memo.get(id);
83
+ if (known !== undefined)
84
+ return known;
85
+ if (seen.has(id))
86
+ return 0;
87
+ seen.add(id);
88
+ const node = byId.get(id);
89
+ let next = 0;
90
+ for (const f of scope.flows)
91
+ if (f.sourceRef === id && chain.has(f.targetRef))
92
+ next = Math.max(next, longest(f.targetRef, seen));
93
+ seen.delete(id);
94
+ const width = (node ? sizeOf(node).width + GAP : 0) + next;
95
+ memo.set(id, width);
96
+ return width;
97
+ };
98
+ let need = 0;
99
+ for (const f of scope.flows)
100
+ if (f.sourceRef === el.id && chain.has(f.targetRef))
101
+ need = Math.max(need, longest(f.targetRef, new Set()));
102
+ // Room already free on the anchor's row counts: a shape only moves as far as it must.
103
+ const x0 = shape.bounds.x + shape.bounds.width;
104
+ const top = shape.bounds.y - 20;
105
+ const bottom = shape.bounds.y + shape.bounds.height + 20;
106
+ let nextX = Number.POSITIVE_INFINITY;
107
+ for (const s of shapes) {
108
+ const b = s.bounds;
109
+ if (s === shape || containers.has(s.bpmnElement) || b.x < x0)
110
+ continue;
111
+ if (b.y + b.height > top && b.y < bottom)
112
+ nextX = Math.min(nextX, b.x);
113
+ }
114
+ const dx = Math.max(0, need + GAP - (nextX - x0));
115
+ if (dx === 0)
116
+ continue;
117
+ anchors.push({ shape, after: el.id, dx });
118
+ }
119
+ }
120
+ }
121
+ // Rightmost first, so a later shift carries the earlier one along instead of splitting it.
122
+ anchors.sort((a, b) => b.shape.bounds.x - a.shape.bounds.x);
123
+ for (const { shape, after, dx } of anchors) {
124
+ const x0 = shape.bounds.x + shape.bounds.width;
125
+ for (const s of shapes) {
126
+ const b = s.bounds;
127
+ if (b.x >= x0) {
128
+ b.x += dx;
129
+ if (s.label?.bounds)
130
+ s.label.bounds.x += dx;
131
+ }
132
+ else if (b.x + b.width > x0 && containers.has(s.bpmnElement)) {
133
+ // A pool, lane or expanded sub-process spanning the insertion point.
134
+ b.width += dx;
135
+ }
136
+ else if (s.label?.bounds && s.label.bounds.x >= x0) {
137
+ s.label.bounds.x += dx;
138
+ }
139
+ }
140
+ for (const edge of defs.diagrams.flatMap((d) => d.plane.edges)) {
141
+ for (const p of edge.waypoints)
142
+ if (p.x >= x0)
143
+ p.x += dx;
144
+ if (edge.label?.bounds && edge.label.bounds.x >= x0)
145
+ edge.label.bounds.x += dx;
146
+ }
147
+ result.shifted.push({ after, dx });
148
+ }
149
+ return result;
150
+ }
151
+ //# sourceMappingURL=make-room.js.map
@@ -1,5 +1,11 @@
1
1
  import { generateId } from "../../types/id-generator.js";
2
2
  import { buildFlowIndex, findDiPlane, findProcess, insertElement, insertFlow, isEndEvent, isGateway, isStartEvent, reachableFrom, removeElement, removeFlow, } from "./utils.js";
3
+ /** Data elements sit beside the flow: no sequence flow in or out, by design. */
4
+ const OFF_FLOW_TYPES = new Set([
5
+ "dataObject",
6
+ "dataObjectReference",
7
+ "dataStoreReference",
8
+ ]);
3
9
  export function analyzeFlow(p, _opts) {
4
10
  const findings = [];
5
11
  const processId = p.id;
@@ -55,6 +61,8 @@ export function analyzeFlow(p, _opts) {
55
61
  }
56
62
  const reachable = reachableFrom(startIds, reachabilityEdges);
57
63
  for (const el of p.flowElements) {
64
+ if (OFF_FLOW_TYPES.has(el.type))
65
+ continue;
58
66
  // flow/unreachable
59
67
  if (!reachable.has(el.id)) {
60
68
  findings.push({
@@ -24,7 +24,12 @@ export interface PlaceNewShapesResult {
24
24
  resized: string[];
25
25
  /** Flow nodes added to a lane's `flowNodeRefs`. */
26
26
  laneAssigned: string[];
27
- /** What could not be placed, and why. */
27
+ /**
28
+ * What could not be placed, and why. A new shape that could only be put on
29
+ * top of another shape or label is drawn anyway (its edges need it) and
30
+ * listed here too, with a reason that says what it overlaps: existing shapes
31
+ * never move, so making room is the caller's call.
32
+ */
28
33
  unplaced: Array<{
29
34
  id: string;
30
35
  reason: string;
@@ -87,6 +87,8 @@ class Placer {
87
87
  laneOf = new Map();
88
88
  lanesOfProcess = new Map();
89
89
  mainPlane;
90
+ /** Shapes this run chose a spot for one by one, rather than as a laid-out block. */
91
+ spotted = [];
90
92
  constructor(defs, result, options) {
91
93
  this.defs = defs;
92
94
  this.result = result;
@@ -135,6 +137,7 @@ class Placer {
135
137
  this.placePools();
136
138
  this.placeFlowNodes();
137
139
  this.placeAnnotations();
140
+ this.reportOverlaps();
138
141
  this.reportLanes();
139
142
  this.routeEdges();
140
143
  }
@@ -327,7 +330,7 @@ class Placer {
327
330
  const label = this.labelSize(el);
328
331
  let chosen;
329
332
  if (direction === "below" && anchorId) {
330
- chosen = this.boundarySpot(el.id, anchorId, size, plane);
333
+ chosen = this.boundarySpot(el.id, anchorId, size, label, plane);
331
334
  }
332
335
  else {
333
336
  chosen = this.bestSpot(el.id, size, label, anchorId, direction, box, plane);
@@ -347,6 +350,7 @@ class Placer {
347
350
  if (label)
348
351
  shape.label = { bounds: this.labelRect(chosen, label) };
349
352
  this.result.placed.push(el.id);
353
+ this.spotted.push(el.id);
350
354
  if (content) {
351
355
  const dx = chosen.x + INNER_PADDING - content.minX;
352
356
  const dy = chosen.y + SUB_PROCESS_TOP - content.minY;
@@ -675,7 +679,7 @@ class Placer {
675
679
  return out;
676
680
  }
677
681
  /** A spot on the host's bottom border, the right-most free one; then the top border. */
678
- boundarySpot(id, hostId, size, plane) {
682
+ boundarySpot(id, hostId, size, label, plane) {
679
683
  const host = this.shapes.get(hostId)?.shape.bounds;
680
684
  if (!host)
681
685
  return undefined;
@@ -685,14 +689,28 @@ class Placer {
685
689
  return el?.type === "boundaryEvent" && el.attachedToRef === hostId;
686
690
  })
687
691
  .map((s) => s.bounds);
692
+ // The first free spot on the border, unless it or its label would sit on
693
+ // another shape and a later spot would not.
694
+ // The shape sits on the host's border by design; its label may not.
695
+ const obstacles = this.obstacles(plane, id);
696
+ const others = obstacles.filter((o) => o !== host);
697
+ let first;
688
698
  for (const y of [host.y + host.height - size.height / 2, host.y - size.height / 2]) {
689
699
  for (let x = host.x + host.width - size.width - 8; x >= host.x + 4; x -= 6) {
690
700
  const r = { x: Math.round(x), y: Math.round(y), ...size };
691
701
  if (siblings.some((s) => overlaps(r, s, 6)))
692
702
  continue;
703
+ first ??= r;
704
+ const l = label ? this.labelRect(r, label) : undefined;
705
+ if (others.some((o) => overlaps(r, o, 0)))
706
+ continue;
707
+ if (l !== undefined && obstacles.some((o) => overlaps(l, o, 0)))
708
+ continue;
693
709
  return r;
694
710
  }
695
711
  }
712
+ if (first)
713
+ return first;
696
714
  this.result.unplaced.push({ id, reason: `no room left on the border of ${hostId}` });
697
715
  return undefined;
698
716
  }
@@ -791,6 +809,39 @@ class Placer {
791
809
  this.growToFit(box, spot, undefined, plane);
792
810
  this.addShape(plane, annotation.id, spot, {});
793
811
  this.result.placed.push(annotation.id);
812
+ this.spotted.push(annotation.id);
813
+ }
814
+ }
815
+ /**
816
+ * Placement keeps new shapes clear of others when it can, but a crowded
817
+ * spot (a boundary event's border, a label) can leave no clean choice. Say
818
+ * so instead of reporting a clean result over a diagram that reads wrong.
819
+ */
820
+ reportOverlaps() {
821
+ for (const id of this.spotted) {
822
+ const own = this.shapes.get(id);
823
+ // A sub-process drawn around its content overlaps that content by design.
824
+ if (!own || this.isContainerShape(own.shape))
825
+ continue;
826
+ const host = this.elements.get(id)?.attachedToRef;
827
+ const mine = [own.shape.bounds, ...(own.shape.label?.bounds ? [own.shape.label.bounds] : [])];
828
+ const clash = own.plane.shapes.find((other) => {
829
+ if (other.bpmnElement === id || this.isContainerShape(other))
830
+ return false;
831
+ const theirHost = this.elements.get(other.bpmnElement)
832
+ ?.attachedToRef;
833
+ // A boundary event sits on its host's border by design.
834
+ if (other.bpmnElement === host || theirHost === id)
835
+ return false;
836
+ const theirs = [other.bounds, ...(other.label?.bounds ? [other.label.bounds] : [])];
837
+ return mine.some((m) => theirs.some((t) => overlaps(m, t, 0)));
838
+ });
839
+ if (!clash)
840
+ continue;
841
+ this.result.unplaced.push({
842
+ id,
843
+ reason: `placed, but it or its label overlaps "${clash.bpmnElement}"; existing shapes do not move, so move one by hand or redraw with applyAutoLayout`,
844
+ });
794
845
  }
795
846
  }
796
847
  reportLanes() {
@@ -162,6 +162,12 @@ export declare function conditionOrLabel(edge: Pick<CompactFlow, "name" | "condi
162
162
  edge: Pick<CompactFlow, "name" | "condition" | "isDefault">;
163
163
  problem?: string;
164
164
  };
165
+ /**
166
+ * An ISO 8601 duration from what models write: `PT5M` as it is, `5m`, `5 min`,
167
+ * `5 minutes`, `2 hours` or `1 day`, also inside a name ("Wait 5 minutes").
168
+ */
169
+ /** A readable decision id from a task name: `Assess risk` → `assess-risk`. */
170
+ export declare function decisionIdFrom(name: string): string | undefined;
165
171
  /**
166
172
  * A timer cycle from `every=`: an ISO 8601 repeating interval (`R/PT1H`, `R3/PT10M`)
167
173
  * as written, or a duration (`PT1H`, `1h`, `2 days`) repeated forever.
@@ -194,7 +200,7 @@ export declare function edgeLabel(label: string | undefined): Pick<CompactFlow,
194
200
  * gateway's question; flows out of anything else carry no condition or label;
195
201
  * - an unnamed event, task or decision is named from its id;
196
202
  * - a service or send task without `job=` uses its id as its job type, and a
197
- * rule task its id as its decision id.
203
+ * rule task its name, kebab-cased, as its decision id (`decision=` names another).
198
204
  *
199
205
  * @example
200
206
  * ```typescript
@@ -731,6 +731,8 @@ class Reader {
731
731
  element.jobType = value;
732
732
  else if (key === "called" && value && element.type === "callActivity")
733
733
  element.calledProcess = value;
734
+ else if (key === "decision" && value && element.type === "businessRuleTask")
735
+ element.decisionId = value;
734
736
  else if (key === "key" &&
735
737
  value &&
736
738
  (EVENTS.has(element.type) || element.type === "receiveTask"))
@@ -810,8 +812,39 @@ class Reader {
810
812
  else if (key === "result" && value && ACTIVITIES.has(element.type)) {
811
813
  element.resultVariable = value;
812
814
  }
813
- else
814
- this.problems.push({ line: n, message: `unknown attribute "${attr}" on "${id}"; ignored` });
815
+ else if (key === "retries" &&
816
+ value &&
817
+ (element.type === "serviceTask" || element.type === "sendTask")) {
818
+ element.retries = value;
819
+ }
820
+ else if (key?.startsWith("header.") &&
821
+ key.length > 7 &&
822
+ value &&
823
+ ACTIVITIES.has(element.type)) {
824
+ element.taskHeaders = { ...element.taskHeaders, [key.slice(7)]: value };
825
+ }
826
+ else if (key !== undefined && value && USER_ATTRS.has(key) && element.type === "userTask") {
827
+ const field = USER_ATTRS.get(key);
828
+ // `;` separates list items: `,` already separates attributes
829
+ if (field === "priority")
830
+ element.priority = /^\d+$/.test(value) ? Number(value) : value;
831
+ else
832
+ element[field] = value.replace(/;/g, ",");
833
+ }
834
+ else if (key !== undefined && value && (key === "retries" || USER_ATTRS.has(key))) {
835
+ this.problems.push({
836
+ line: n,
837
+ message: `${key}= takes a ${key === "retries" ? "service or send" : "user"} task; ignored on "${id}"`,
838
+ });
839
+ }
840
+ else {
841
+ const typo = /^([A-Za-z][\w.-]*)=+(.+)$/.exec(attr);
842
+ const hint = attr.includes("==") && typo ? `; did you mean ${typo[1]}=${typo[2]}` : "";
843
+ this.problems.push({
844
+ line: n,
845
+ message: `unknown attribute "${attr}" on "${id}"${hint}; ignored`,
846
+ });
847
+ }
815
848
  }
816
849
  if (feel !== undefined) {
817
850
  // `calc[task Count open issues | feel=…]`: a step that evaluates FEEL is a script task
@@ -874,6 +907,14 @@ class Reader {
874
907
  return id;
875
908
  }
876
909
  }
910
+ /** Text attribute → user task field (assignment, schedule, priority). */
911
+ const USER_ATTRS = new Map([
912
+ ["assignee", "assignee"],
913
+ ["groups", "candidateGroups"],
914
+ ["users", "candidateUsers"],
915
+ ["due", "dueDate"],
916
+ ["priority", "priority"],
917
+ ]);
877
918
  /** "Every day" is a schedule, not a list. */
878
919
  const TIME_WORDS = new Set([
879
920
  "second",
@@ -918,6 +959,17 @@ const UNITS = { s: "S", m: "M", h: "H", d: "D", w: "W" };
918
959
  * An ISO 8601 duration from what models write: `PT5M` as it is, `5m`, `5 min`,
919
960
  * `5 minutes`, `2 hours` or `1 day`, also inside a name ("Wait 5 minutes").
920
961
  */
962
+ /** A readable decision id from a task name: `Assess risk` → `assess-risk`. */
963
+ export function decisionIdFrom(name) {
964
+ const id = name
965
+ .trim()
966
+ .toLowerCase()
967
+ .replace(/[^a-z0-9]+/g, "-")
968
+ .replace(/^-+|-+$/g, "");
969
+ if (id === "")
970
+ return undefined;
971
+ return /^[a-z]/.test(id) ? id : `decision-${id}`;
972
+ }
921
973
  /** The trigger an attribute names (`msg=` a message): {@link parseProcessText} reads it as the event's. */
922
974
  const NAMED_TRIGGERS = new Map([
923
975
  ["msg", "message"],
@@ -1819,11 +1871,14 @@ function assemble(reader, final) {
1819
1871
  el.errorCode ??= el.id;
1820
1872
  if (el.eventType === "escalation" && throws)
1821
1873
  el.escalationCode ??= el.id;
1822
- // A DMN task needs a decision to deploy; the id stands in, as it does for a job type.
1874
+ // A DMN task needs a decision to deploy. Its name reads better as the DMN's id than an
1875
+ // element id does, and the DMN file is written to match it.
1823
1876
  if (node.element.type === "businessRuleTask" &&
1824
1877
  node.element.jobType === undefined &&
1825
1878
  node.element.decisionId === undefined) {
1826
- node.element.decisionId = node.element.id;
1879
+ const decision = decisionIdFrom(node.element.name ?? "") ?? node.element.id;
1880
+ node.element.decisionId = decision;
1881
+ fixes.push(`"${node.element.id}" calls decision "${decision}"; set decision= to call another`);
1827
1882
  }
1828
1883
  }
1829
1884
  const processBase = reader.title ? slugify(reader.title) : "Process_1";
@@ -1954,7 +2009,7 @@ function assemble(reader, final) {
1954
2009
  * gateway's question; flows out of anything else carry no condition or label;
1955
2010
  * - an unnamed event, task or decision is named from its id;
1956
2011
  * - a service or send task without `job=` uses its id as its job type, and a
1957
- * rule task its id as its decision id.
2012
+ * rule task its name, kebab-cased, as its decision id (`decision=` names another).
1958
2013
  *
1959
2014
  * @example
1960
2015
  * ```typescript
@@ -0,0 +1,45 @@
1
+ import type { BpmnDefinitions } from "../bpmn/bpmn-model.js";
2
+ import type { FormComponent, FormDefinition } from "./form-model.js";
3
+ /** Options for {@link attachUserTaskForms}. */
4
+ export interface UserTaskFormsOptions {
5
+ /**
6
+ * Form fields per user task id, as `key[:type]` items separated by commas:
7
+ * `amount:number,approved:checkbox,decision:select(approve|reject),note:textarea,due:date,name`.
8
+ * Types: `text` (default), `textarea`, `number`, `checkbox`, `date`, `select(a|b)`.
9
+ * A task without an entry gets a heading and a "Done" checkbox.
10
+ */
11
+ fields?: Record<string, string>;
12
+ /** Form ids that already exist (a `.form` file next to the model); no form is generated for them. */
13
+ existing?: ReadonlySet<string>;
14
+ /** Element ids left as they are: an edit gives forms to the user tasks it adds, not to those already there. */
15
+ skip?: ReadonlySet<string>;
16
+ }
17
+ /** What {@link attachUserTaskForms} did. */
18
+ export interface UserTaskFormsResult {
19
+ /** Ids of the user tasks that had no form and now link one. */
20
+ attached: string[];
21
+ /** One generated form per linked form id not in `existing`; write each as `<id>.form`. */
22
+ forms: FormDefinition[];
23
+ }
24
+ /**
25
+ * Parses a `key[:type]` field list. Unknown types fall back to a text field, so a
26
+ * typo still yields a deployable form.
27
+ */
28
+ export declare function parseFormFields(spec: string): FormComponent[];
29
+ /**
30
+ * Gives every user task a Camunda form in one step, so the model passes the
31
+ * Camunda lint (`camunda-compat/user-task-definition`) and deploys with its forms.
32
+ *
33
+ * A user task with no `zeebe:formDefinition` (or `zeebe:formKey`) gets
34
+ * `formId="<processId>-<taskId>"` and becomes a Camunda user task
35
+ * (`zeebe:userTask`). Every form id a user task or start event links, and that
36
+ * is not in `options.existing`, gets a generated form. Changes `defs` in place.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const { forms } = attachUserTaskForms(defs, { fields: { review: "amount:number,approved:checkbox" } })
41
+ * for (const form of forms) writeFileSync(`${form.id}.form`, Form.export(form))
42
+ * ```
43
+ */
44
+ export declare function attachUserTaskForms(defs: BpmnDefinitions, options?: UserTaskFormsOptions): UserTaskFormsResult;
45
+ //# sourceMappingURL=user-task-forms.d.ts.map
@@ -0,0 +1,129 @@
1
+ const FORM_LINK = new Set(["zeebe:formDefinition", "zeebe:formKey"]);
2
+ function* walk(elements) {
3
+ for (const el of elements) {
4
+ yield el;
5
+ if ("flowElements" in el && Array.isArray(el.flowElements))
6
+ yield* walk(el.flowElements);
7
+ }
8
+ }
9
+ function labelOf(key) {
10
+ const words = key
11
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
12
+ .replace(/[_-]+/g, " ")
13
+ .trim();
14
+ return words.charAt(0).toUpperCase() + words.slice(1).toLowerCase();
15
+ }
16
+ /** A FEEL-safe variable name: form keys become process variables. */
17
+ function variableOf(text) {
18
+ const camel = text.replace(/[^A-Za-z0-9]+(.)?/g, (_m, c) => c === undefined ? "" : c.toUpperCase());
19
+ return /^[A-Za-z_]/.test(camel) ? camel : `v${camel}`;
20
+ }
21
+ /**
22
+ * Parses a `key[:type]` field list. Unknown types fall back to a text field, so a
23
+ * typo still yields a deployable form.
24
+ */
25
+ export function parseFormFields(spec) {
26
+ const components = [];
27
+ for (const raw of spec.split(",")) {
28
+ const item = raw.trim();
29
+ if (item === "")
30
+ continue;
31
+ const match = /^([^:]+)(?::(\w+)(?:\(([^)]*)\))?)?$/.exec(item);
32
+ const key = variableOf((match?.[1] ?? item).trim());
33
+ const type = (match?.[2] ?? "text").toLowerCase();
34
+ const id = `Field_${key}`;
35
+ const label = labelOf(key);
36
+ switch (type) {
37
+ case "number":
38
+ case "textarea":
39
+ case "checkbox":
40
+ components.push({ id, type, label, key });
41
+ break;
42
+ case "date":
43
+ components.push({ id, type: "datetime", key, subtype: "date", dateLabel: label });
44
+ break;
45
+ case "select": {
46
+ const values = (match?.[3] ?? "")
47
+ .split("|")
48
+ .map((v) => v.trim())
49
+ .filter(Boolean)
50
+ .map((value) => ({ label: labelOf(value), value }));
51
+ components.push({ id, type: "select", label, key, values });
52
+ break;
53
+ }
54
+ default:
55
+ components.push({ id, type: "textfield", label, key });
56
+ }
57
+ }
58
+ return components;
59
+ }
60
+ function formFor(formId, title, spec, taskId) {
61
+ const fields = spec !== undefined
62
+ ? parseFormFields(spec)
63
+ : [
64
+ {
65
+ id: "Field_done",
66
+ type: "checkbox",
67
+ label: "Done",
68
+ key: `${variableOf(taskId)}Done`,
69
+ },
70
+ ];
71
+ const form = {
72
+ id: formId,
73
+ type: "default",
74
+ executionPlatform: "Camunda Cloud",
75
+ executionPlatformVersion: "8.10.0",
76
+ schemaVersion: 16,
77
+ components: [{ id: "Field_title", type: "text", text: `## ${title}` }, ...fields],
78
+ };
79
+ return form;
80
+ }
81
+ /**
82
+ * Gives every user task a Camunda form in one step, so the model passes the
83
+ * Camunda lint (`camunda-compat/user-task-definition`) and deploys with its forms.
84
+ *
85
+ * A user task with no `zeebe:formDefinition` (or `zeebe:formKey`) gets
86
+ * `formId="<processId>-<taskId>"` and becomes a Camunda user task
87
+ * (`zeebe:userTask`). Every form id a user task or start event links, and that
88
+ * is not in `options.existing`, gets a generated form. Changes `defs` in place.
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * const { forms } = attachUserTaskForms(defs, { fields: { review: "amount:number,approved:checkbox" } })
93
+ * for (const form of forms) writeFileSync(`${form.id}.form`, Form.export(form))
94
+ * ```
95
+ */
96
+ export function attachUserTaskForms(defs, options = {}) {
97
+ const attached = [];
98
+ const forms = new Map();
99
+ for (const process of defs.processes) {
100
+ for (const el of walk(process.flowElements)) {
101
+ if (el.type !== "userTask" && el.type !== "startEvent")
102
+ continue;
103
+ if (options.skip?.has(el.id))
104
+ continue;
105
+ const ext = el.extensionElements;
106
+ let link = ext.find((x) => FORM_LINK.has(x.name));
107
+ if (link === undefined && el.type === "userTask") {
108
+ link = {
109
+ name: "zeebe:formDefinition",
110
+ attributes: { formId: `${process.id}-${el.id}` },
111
+ children: [],
112
+ };
113
+ if (!ext.some((x) => x.name === "zeebe:userTask"))
114
+ ext.push({ name: "zeebe:userTask", attributes: {}, children: [] });
115
+ ext.push(link);
116
+ attached.push(el.id);
117
+ }
118
+ const formId = link?.attributes.formId;
119
+ // A FEEL form id is resolved at runtime; only a static one names a file to write.
120
+ if (formId === undefined || formId === "" || formId.startsWith("="))
121
+ continue;
122
+ if (options.existing?.has(formId) || forms.has(formId))
123
+ continue;
124
+ forms.set(formId, formFor(formId, el.name ?? el.id, options.fields?.[el.id], el.id));
125
+ }
126
+ }
127
+ return { attached, forms: [...forms.values()] };
128
+ }
129
+ //# sourceMappingURL=user-task-forms.js.map