@bpmnkit/core 1.6.1 → 1.8.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 (78) hide show
  1. package/AGENTS.md +19 -0
  2. package/README.md +2 -0
  3. package/agent-cards/bpmn.md +86 -0
  4. package/agent-cards/dmn.md +105 -0
  5. package/agent-cards/form.md +72 -0
  6. package/builder-reference.md +211 -0
  7. package/dist/bpmn/auto-layout.js +34 -5
  8. package/dist/bpmn/bpmn-builder.d.ts +127 -5
  9. package/dist/bpmn/bpmn-builder.js +270 -40
  10. package/dist/bpmn/bpmn-model.d.ts +2 -0
  11. package/dist/bpmn/bpmn-parser.js +8 -0
  12. package/dist/bpmn/bpmn-serializer.js +1 -1
  13. package/dist/bpmn/builder-coverage.js +4 -12
  14. package/dist/bpmn/camunda7/export.d.ts +25 -0
  15. package/dist/bpmn/camunda7/export.js +218 -0
  16. package/dist/bpmn/camunda7/migrate.d.ts +4 -1
  17. package/dist/bpmn/camunda7/migrate.js +4 -4
  18. package/dist/bpmn/compact.d.ts +21 -0
  19. package/dist/bpmn/compact.js +86 -1
  20. package/dist/bpmn/full-operations.js +338 -3
  21. package/dist/bpmn/index.d.ts +2 -0
  22. package/dist/bpmn/index.js +2 -0
  23. package/dist/bpmn/operations.d.ts +42 -1
  24. package/dist/bpmn/operations.js +12 -2
  25. package/dist/bpmn/optimize/deploy.js +14 -0
  26. package/dist/bpmn/optimize/index.d.ts +2 -0
  27. package/dist/bpmn/optimize/index.js +5 -0
  28. package/dist/bpmn/optimize/types.d.ts +7 -0
  29. package/dist/bpmn/stable-ids.d.ts +15 -0
  30. package/dist/bpmn/stable-ids.js +26 -0
  31. package/dist/bpmn/strip-camunda8.d.ts +22 -0
  32. package/dist/bpmn/strip-camunda8.js +55 -0
  33. package/dist/bpmn/svg.js +5 -6
  34. package/dist/bpmn/utils.js +151 -1
  35. package/dist/bpmn/zeebe-extensions.d.ts +59 -2
  36. package/dist/bpmn/zeebe-extensions.js +89 -1
  37. package/dist/check-finding.d.ts +19 -0
  38. package/dist/check-finding.js +5 -0
  39. package/dist/connectors/apply-element.d.ts +7 -3
  40. package/dist/connectors/apply-element.js +115 -4
  41. package/dist/connectors/apply-many.d.ts +5 -1
  42. package/dist/connectors/apply-many.js +5 -2
  43. package/dist/connectors/apply.d.ts +24 -3
  44. package/dist/connectors/apply.js +103 -3
  45. package/dist/connectors/catalog.js +5 -0
  46. package/dist/connectors/index.d.ts +1 -1
  47. package/dist/connectors/template-types.d.ts +30 -0
  48. package/dist/connectors/validate.js +33 -0
  49. package/dist/dmn/compact.js +14 -5
  50. package/dist/dmn/dmn-builder.js +3 -3
  51. package/dist/dmn/drd-builder.d.ts +53 -0
  52. package/dist/dmn/drd-builder.js +100 -0
  53. package/dist/dmn/index.d.ts +35 -0
  54. package/dist/dmn/index.js +36 -0
  55. package/dist/dmn/lint.d.ts +19 -0
  56. package/dist/dmn/lint.js +414 -0
  57. package/dist/form/form-builder.d.ts +9 -1
  58. package/dist/form/form-builder.js +34 -1
  59. package/dist/form/form-model.d.ts +7 -0
  60. package/dist/form/form-parser.js +22 -0
  61. package/dist/form/form-serializer.js +10 -0
  62. package/dist/form/index.d.ts +11 -2
  63. package/dist/form/index.js +10 -1
  64. package/dist/form/lint.d.ts +19 -0
  65. package/dist/form/lint.js +356 -0
  66. package/dist/index.d.ts +19 -5
  67. package/dist/index.js +12 -2
  68. package/dist/layout/annotations.d.ts +3 -1
  69. package/dist/layout/annotations.js +72 -14
  70. package/dist/layout/grid/edge-labels.d.ts +7 -1
  71. package/dist/layout/grid/edge-labels.js +62 -1
  72. package/dist/layout/semantic/index.js +78 -8
  73. package/dist/layout/semantic/place.d.ts +19 -4
  74. package/dist/layout/semantic/place.js +245 -29
  75. package/dist/layout/semantic/route.js +60 -12
  76. package/dist/layout/types.d.ts +2 -1
  77. package/llms.txt +9 -0
  78. package/package.json +6 -1
package/AGENTS.md ADDED
@@ -0,0 +1,19 @@
1
+ # @bpmnkit/core for agents
2
+
3
+ Do not read README.md (20 KB) or the .d.ts files first. Read the one card for your task (~1k tokens each). Each has a runnable script, the top options and the known traps.
4
+
5
+ | You write | Read |
6
+ | --- | --- |
7
+ | BPMN process | `node_modules/@bpmnkit/core/agent-cards/bpmn.md` |
8
+ | DMN decision table or DRD | `node_modules/@bpmnkit/core/agent-cards/dmn.md` |
9
+ | Camunda form | `node_modules/@bpmnkit/core/agent-cards/form.md` |
10
+
11
+ Rules that hold for all three:
12
+
13
+ - Build with the builders (`Bpmn`, `Dmn`, `Form`). Never write XML or form JSON by hand.
14
+ - Edit an existing file with `Bpmn.parse` and the `export*Preserving` writers, so layout and formatting stay.
15
+ - `formId` and `decisionId` must equal the deployed form id and decision id exactly.
16
+ - Validate before you finish: `npx @bpmnkit/cli check order.bpmn risk.dmn review.form --deploy` (`casen check` if the CLI is installed). Fix every error.
17
+ - Builder errors and check findings end with `agent-cards/<type>.md#traps`. Read that section.
18
+
19
+ The full API reference is `builder-reference.md` in this folder. Open it only when a card does not cover an option.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ > **Agents:** read `node_modules/@bpmnkit/core/AGENTS.md`, then `node_modules/@bpmnkit/core/agent-cards/<bpmn|dmn|form>.md` (~1k tokens) instead of this README.
2
+
1
3
  <div align="center">
2
4
  <a href="https://bpmnkit.com"><img src="https://bpmnkit.com/favicon.svg" width="72" height="72" alt="BPMN Kit logo"></a>
3
5
  <h1>@bpmnkit/core</h1>
@@ -0,0 +1,86 @@
1
+ # BPMN agent card
2
+
3
+ Write a Camunda 8 BPMN process with `@bpmnkit/core` in one script: create, export, edit, validate. Run it with `node --experimental-strip-types build.ts` (Node 22.6+) or `npx tsx build.ts`. Never write BPMN XML by hand.
4
+
5
+ <!-- docspack: tags=agent-card,cheat-sheet,build-script,bpmn,process,create,write,script,builder -->
6
+
7
+ ## Minimal BPMN build script: create, export, edit, validate
8
+
9
+ ```ts
10
+ import { readFileSync, writeFileSync } from "node:fs"
11
+ import { Bpmn, exportPreserving, lintDiagram } from "@bpmnkit/core"
12
+
13
+ // 1. Create. The process id is the deploy key: same id = new version of that process.
14
+ const definitions = Bpmn.createProcess("order")
15
+ .name("Order")
16
+ .withAutoLayout()
17
+ .startEvent("received", { name: "Order received" })
18
+ .businessRuleTask("score", { name: "Score risk", decisionId: "risk", resultVariable: "risk" })
19
+ .exclusiveGateway("check", { name: "Risky?" })
20
+ .branch("yes", (b) =>
21
+ b
22
+ .condition('=risk = "high"')
23
+ .label("Yes")
24
+ .userTask("review", { name: "Review order", formId: "review-order", zeebeUserTask: true })
25
+ .connectTo("ship"),
26
+ )
27
+ .branch("no", (b) => b.defaultFlow().label("No").connectTo("ship"))
28
+ .serviceTask("ship", { name: "Ship order", taskType: "ship-order", retries: "3" })
29
+ .endEvent("done", { name: "Order shipped" })
30
+ .build()
31
+
32
+ // 2. Export.
33
+ writeFileSync("order.bpmn", Bpmn.export(definitions))
34
+
35
+ // 3. Edit an existing file: parse, change, write with exportPreserving to keep layout and formatting.
36
+ const original = readFileSync("order.bpmn", "utf8")
37
+ const edited = Bpmn.parse(original)
38
+ const ship = edited.processes[0]?.flowElements.find((e) => e.id === "ship")
39
+ if (ship) ship.name = "Ship parcel"
40
+ writeFileSync("order.bpmn", exportPreserving(original, edited))
41
+
42
+ // 4. Validate: Camunda 8 deployability and modelling rules.
43
+ const report = lintDiagram(Bpmn.parse(readFileSync("order.bpmn", "utf8")))
44
+ for (const d of report.diagnostics.filter((d) => d.severity !== "info"))
45
+ console.log(`${d.severity} ${d.elementIds.join(",")}: ${d.message}`)
46
+ if (report.counts.error > 0) process.exit(1)
47
+ ```
48
+
49
+ `npm i @bpmnkit/core`. The script writes `order.bpmn`, re-opens it, renames a task without moving a shape, and exits 1 on a lint error.
50
+
51
+ ## Top builder options
52
+
53
+ - `Bpmn.createProcess(id)` … `.build()`; `.withAutoLayout()` before `.build()`, or the file has no shapes.
54
+ - Every element takes `(id, options)`; ids are unique and each element connects to the previous one.
55
+ - `serviceTask(id, { name, taskType, retries, ioMapping: { inputs, outputs }, taskHeaders })`: `taskType` is the job type a worker subscribes to.
56
+ - `userTask(id, { name, zeebeUserTask: true, formId, assignee, candidateGroups, dueDate })`.
57
+ - `businessRuleTask(id, { decisionId, resultVariable })`: both are required to deploy.
58
+ - `scriptTask(id, { expression: "=a + b", resultVariable })`; `callActivity(id, { processId })`.
59
+ - Gateways: `.exclusiveGateway(id)` then `.branch(name, (b) => b.condition("=x > 1")...)`, one branch `b.defaultFlow()`; `.label(text)` sets the flow label. Merge with `.connectTo(id)` and declare that id after the last branch.
60
+ - Events take named options: `timerDuration: "PT1H"`, `messageName` + `correlationKey`, `errorCode`, `signalName`. `.withBoundary(id, { errorCode }, (b) => ...)` hangs a boundary on the previous task.
61
+ - `multiInstance: { collection: "=items", elementVariable: "item" }` on any task.
62
+ - Full method list: `packages/core/builder-reference.md` in `@bpmnkit/core`, or `npx bpmnkit-docs ask "<option>"`.
63
+
64
+ ## Traps
65
+
66
+ - **Camunda 8.10 is the default target.** To target an older cluster, call `.executionPlatformVersion("8.8.0")` so lint checks that version.
67
+ - **User tasks default to job-worker tasks**, which 8.10 deprecates. Pass `zeebeUserTask: true` for a Camunda user task.
68
+ - **Deploy ids.** The engine keys a process by its process id (`createProcess("order")`), a decision by its `<decision id>`, a form by its JSON `id`. File names and display names do not count. `formId` and `decisionId` must equal those ids exactly; by default they bind to the latest deployed version, so deploy the `.dmn` and `.form` before an instance reaches the task. Redeploying the same id makes a new version.
69
+ - **Reference a DMN decision by its decision id**, not the DMN `definitions` id, the file name or the decision name.
70
+ - **Edit with the preserving writer.** For an existing file, `Bpmn.parse` it, change the model, and write `exportPreserving(original, edited)`. Rebuilding it with `withAutoLayout()`, or `Bpmn.export` alone, moves every shape and reformats the diff.
71
+ - FEEL in the builder starts with `=` (`"=amount > 1000"`); a value without `=` is a literal string.
72
+ - Unknown option names are silently dropped: `timer: { duration }` does nothing; use `timerDuration`.
73
+
74
+ ## Lint before you deploy or test
75
+
76
+ ```sh
77
+ casen check order.bpmn risk.dmn review-order.form --deploy # one gate: BPMN + DMN + forms, and the ids that link them
78
+ casen lint lint order.bpmn --profile deploy # BPMN only, errors only
79
+ casen deploy deploy order.bpmn # local Reebe; --target camunda8 for a cluster
80
+ ```
81
+
82
+ In code, `lintDiagram(definitions)` returns `{ diagnostics, counts }`; fail on `counts.error > 0`. Warnings (no timer boundary, no output mapping) are advice.
83
+
84
+ ## Writing a process as text instead
85
+
86
+ A model writing the diagram itself can use the line format: `parseProcessText(text)` then `expand(result.diagram)` from `@bpmnkit/core`. `casen agent-card bpmn --text` prints its guide. Related cards: `casen agent-card dmn`, `casen agent-card form`.
@@ -0,0 +1,105 @@
1
+ # DMN agent card
2
+
3
+ Write a Camunda 8 DMN decision table with `@bpmnkit/core` in one script: create, export, edit, validate. Run it with `node --experimental-strip-types build.ts` (Node 22.6+) or `npx tsx build.ts`. Never write DMN XML by hand.
4
+
5
+ <!-- docspack: tags=agent-card,cheat-sheet,build-script,dmn,decision,decision-table,rules,create,write,script -->
6
+
7
+ ## Minimal DMN build script: create, export, edit, validate
8
+
9
+ ```ts
10
+ import { readFileSync, writeFileSync } from "node:fs"
11
+ import { Dmn, exportDmnPreserving } from "@bpmnkit/core"
12
+
13
+ // 1. Create. "risk" is the decision id a BPMN businessRuleTask references as decisionId.
14
+ const definitions = Dmn.createDecisionTable("risk")
15
+ .name("Order risk")
16
+ .hitPolicy("FIRST")
17
+ .input({ label: "Amount", expression: "amount", typeRef: "number" })
18
+ .input({ label: "Country", expression: "country", typeRef: "string" })
19
+ .output({ label: "Risk", name: "risk", typeRef: "string" })
20
+ .rule({ inputs: ["> 1000", "-"], outputs: ['"high"'], description: "Large order" })
21
+ .rule({ inputs: ["-", 'not("DE", "AT")'], outputs: ['"medium"'] })
22
+ .rule({ inputs: ["-", "-"], outputs: ['"low"'] })
23
+ .build()
24
+
25
+ // 2. Export.
26
+ writeFileSync("risk.dmn", Dmn.export(definitions))
27
+
28
+ // 3. Edit an existing file: parse, change, write with exportDmnPreserving to keep the diagram.
29
+ const original = readFileSync("risk.dmn", "utf8")
30
+ const edited = Dmn.parse(original)
31
+ const decision = edited.decisions.find((d) => d.id === "risk")
32
+ if (decision) decision.name = "Order risk level"
33
+ writeFileSync("risk.dmn", exportDmnPreserving(original, edited))
34
+
35
+ // 4. Validate: it parses back and the decision id the process calls is there.
36
+ const check = Dmn.parse(readFileSync("risk.dmn", "utf8"))
37
+ if (!check.decisions.some((d) => d.id === "risk")) {
38
+ console.error("decision 'risk' missing")
39
+ process.exit(1)
40
+ }
41
+ ```
42
+
43
+ `npm i @bpmnkit/core`. The script writes `risk.dmn` with its diagram, re-opens it, renames the decision without touching the layout, and checks the decision id.
44
+
45
+ ## Several decisions in one file: `Dmn.drd()`
46
+
47
+ ```ts
48
+ import { writeFileSync } from "node:fs"
49
+ import { Dmn } from "@bpmnkit/core"
50
+
51
+ // Two decisions in one file: "approval" reads the result of "riskScore".
52
+ const drd = Dmn.drd("Order approval")
53
+ const riskScore = drd.decision("riskScore", (t) =>
54
+ t
55
+ .name("Risk score")
56
+ .hitPolicy("FIRST")
57
+ .input({ label: "Amount", expression: "amount", typeRef: "number" })
58
+ .output({ label: "Risk", name: "risk", typeRef: "string" })
59
+ .rule({ inputs: ["> 1000"], outputs: ['"high"'] })
60
+ .rule({ inputs: ["-"], outputs: ['"low"'] }),
61
+ )
62
+ drd.decision(
63
+ "approval",
64
+ (t) =>
65
+ t
66
+ .name("Approval")
67
+ .input({ label: "Risk", expression: "risk", typeRef: "string" })
68
+ .output({ label: "Approved", name: "approved", typeRef: "boolean" })
69
+ .rule({ inputs: ['"low"'], outputs: ["true"] })
70
+ .rule({ inputs: ["-"], outputs: ["false"] }),
71
+ { requires: [riskScore] }, // pass the handle; a name or label is a type error
72
+ )
73
+ writeFileSync("approval.dmn", drd.toXml())
74
+ ```
75
+
76
+ `drd.decision(id, table, { requires })` returns a handle; `requires` takes handles (or `drd.inputData(id, name)` handles), never names. A `requires` that points at an unknown id throws at `build()`/`toXml()`.
77
+
78
+ ## Top builder options
79
+
80
+ - `Dmn.createDecisionTable(decisionId)` … `.build()` returns `DmnDefinitions`; `Dmn.export(defs)` gives the XML with DMNDI shapes.
81
+ - `.name(text)` is the display name; `.hitPolicy("UNIQUE" | "FIRST" | "ANY" | "COLLECT" | "RULE ORDER" | "OUTPUT ORDER" | "PRIORITY")`.
82
+ - `.input({ label, expression, typeRef })`: `expression` is a FEEL expression over process variables (`amount`, `order.total`).
83
+ - `.output({ label, name, typeRef })`: `name` is the key in the result.
84
+ - `.rule({ inputs, outputs, description })`: one entry per column, in column order, or `build` throws.
85
+ - `typeRef`: `"string" | "number" | "boolean" | "date"`.
86
+ - Read or change an existing file: `Dmn.parse(xml)` → `defs.decisions[i].decisionTable`.
87
+
88
+ ## Traps
89
+
90
+ - **The process calls the decision id.** A BPMN `businessRuleTask(id, { decisionId: "risk", resultVariable: "risk" })` must use the argument of `createDecisionTable("risk")`, not the DMN `definitions` id, the file name or `.name()`. Ids are unique across the cluster: a second file with decision `risk` deploys as a new version of the same decision.
91
+ - **Deploy the `.dmn` before an instance reaches the task.** The call binds to the latest deployed version: `casen deploy deploy risk.dmn` first.
92
+ - **Hit policy `UNIQUE` is the default.** Two matching rules is a runtime incident. Use `FIRST` for a catch-all last row, or `COLLECT` for a list.
93
+ - **Input entries are FEEL unary tests, outputs are FEEL expressions,** and neither starts with `=`. `-` matches anything; `> 1000`, `[1..10]`, `"DE"`, `not("DE", "AT")`. A string output needs quotes: `'"high"'`, not `"high"`.
94
+ - **Result shape.** With one output column the result variable holds the value; with several it holds an object keyed by output `name`; `COLLECT` gives a list.
95
+ - **Edit with the preserving writer.** Write `exportDmnPreserving(original, edited)`; `Dmn.export` alone reformats the file and its diagram.
96
+
97
+ ## Validate
98
+
99
+ ```sh
100
+ casen check risk.dmn order.bpmn --deploy # DMN lint + every decisionId in the BPMN resolves
101
+ ```
102
+
103
+ `casen check <files...>` takes `.bpmn`, `.dmn` and `.form` together and exits 1 on errors; add `--json` for an agent loop. The script above also re-parses the file and checks the decision id.
104
+
105
+ Related cards: `casen agent-card bpmn`, `casen agent-card form`. More: `npx bpmnkit-docs ask "decision table hit policy"`.
@@ -0,0 +1,72 @@
1
+ # Form agent card
2
+
3
+ Write a Camunda 8 form (`.form` JSON) with `@bpmnkit/core` in one script: create, export, edit, validate. Run it with `node --experimental-strip-types build.ts` (Node 22.6+) or `npx tsx build.ts`. Never write form JSON by hand.
4
+
5
+ <!-- docspack: tags=agent-card,cheat-sheet,build-script,form,camunda-form,user-task-form,start-form,create,write,script -->
6
+
7
+ ## Minimal form build script: create, export, edit, validate
8
+
9
+ ```ts
10
+ import { readFileSync, writeFileSync } from "node:fs"
11
+ import { Form, exportFormPreserving } from "@bpmnkit/core"
12
+
13
+ // 1. Create. "review-order" is the form id a userTask or startEvent references as formId.
14
+ const form = Form.create("review-order")
15
+ .text("## Review order")
16
+ .textfield("Customer", "customer", { validate: { required: true } })
17
+ .select("Decision", "decision", {
18
+ values: [
19
+ { label: "Approve", value: "approve" },
20
+ { label: "Reject", value: "reject" },
21
+ ],
22
+ validate: { required: true },
23
+ })
24
+ .textarea("Comment", "comment")
25
+ .checkbox("Notify customer", "notify")
26
+ .build()
27
+
28
+ // 2. Export.
29
+ writeFileSync("review-order.form", Form.export(form))
30
+
31
+ // 3. Edit an existing file: parse, change, write with exportFormPreserving to keep key order and ids.
32
+ const original = readFileSync("review-order.form", "utf8")
33
+ const edited = Form.parse(original)
34
+ edited.components.push({
35
+ id: "Field_note",
36
+ type: "text",
37
+ text: "Reviewed orders ship the same day.",
38
+ })
39
+ writeFileSync("review-order.form", exportFormPreserving(original, edited))
40
+
41
+ // 4. Validate: it parses back with the id the process references.
42
+ const check = Form.parse(readFileSync("review-order.form", "utf8"))
43
+ if (check.id !== "review-order") {
44
+ console.error(`form id is ${check.id}, expected review-order`)
45
+ process.exit(1)
46
+ }
47
+ ```
48
+
49
+ `npm i @bpmnkit/core`. The script writes `review-order.form`, re-opens it, adds a component without reordering the rest, and checks the form id.
50
+
51
+ ## Top builder options
52
+
53
+ - `Form.create(id)` … `.build()` returns a `FormDefinition`; `Form.export(form)` gives the JSON.
54
+ - Fields take `(label, key, options)`: `textfield`, `textarea`, `select` (`values` or `valuesKey`), `checkbox`; `radio(label, key, values)`.
55
+ - `text(markdown)` is static text; `group(label, (g) => g.textfield(...))` nests fields.
56
+ - `options.validate`: `{ required, minLength, maxLength }`; `defaultValue`; `id` for a fixed component id.
57
+ - The builder stamps `8.10.0`; override with `.executionPlatformVersion("8.8.0")`.
58
+ - Read or change an existing file: `Form.parse(json)` → `form.components`.
59
+
60
+ ## Traps
61
+
62
+ - **The process calls the form id.** `userTask(id, { zeebeUserTask: true, formId: "review-order" })` and `startEvent(id, { formId })` must equal `Form.create("review-order")`, the JSON `id`, not the file name.
63
+ - **Deploy the `.form` before an instance reaches the task.** `formId` binds to the latest deployed form with that id: `casen deploy deploy review-order.form` first. With `formBindingType: "deployment"` it must be in the same deployment as the process.
64
+ - **`key` is the process variable** the field reads and writes. Keep keys equal to the variable names the process and its gateways use; a typo silently creates a new variable.
65
+ - **Use a Camunda user task** (`zeebeUserTask: true`) for a linked form; Camunda 8.10 deprecates job-worker user tasks.
66
+ - **Edit with the preserving writer.** Write `exportFormPreserving(original, edited)`; it keeps key order and component ids, so the diff shows only your change.
67
+
68
+ ## Validate
69
+
70
+ The script re-parses the file and checks the form id. Before deploying, run `casen check review-order.form order.bpmn --deploy`: it lints the form and checks that every `formId` in the `.bpmn` names a form. Check by hand that each `key` is a variable the process expects.
71
+
72
+ Related cards: `casen agent-card bpmn`, `casen agent-card dmn`. More: `npx bpmnkit-docs ask "form on a start event"`.
@@ -0,0 +1,211 @@
1
+ # @bpmnkit/core builder reference
2
+
3
+ Generated from `bpmn-builder.ts`; do not edit.
4
+
5
+ ## Rules
6
+
7
+ - Start with `Bpmn.createProcess(id)`, end with `.build()`, then `Bpmn.export(definitions)` for the XML. Call `.withAutoLayout()` before `.build()`, or the diagram has no shapes.
8
+ - Element ids are unique. Each element connects to the previous one automatically; there are no manual flows.
9
+ - `subProcess`, `transaction`, `eventSubProcess` and `adHocSubProcess` take the callback as the SECOND argument and options THIRD: `.subProcess(id, (sub) => sub.startEvent()..., { name })`. Swapped order is tolerated.
10
+ - Gateways fork with `.branch(name, (b) => b...)`. Inside, `b.condition(feelExpr)` sets the flow condition and `b.defaultFlow()` marks the default flow. To merge, end a branch with `.connectTo(targetId)` and declare that target after the last branch.
11
+ - Event definitions are named options, not nested objects: `timerDuration`, `timerDate`, `timerCycle`, `messageName` + `correlationKey`, `signalName`, `errorCode`, `escalationCode`, `linkName`. Unknown options are silently dropped: `timer: { duration }` does nothing.
12
+ - `withBoundary(id, options, (b) => ...)` attaches a boundary event to the PRECEDING activity; the callback builds the path leaving it, and the main chain continues from the activity.
13
+ - FEEL expressions start with `=`. Options without `?` are required.
14
+
15
+ ## Methods
16
+
17
+ `ProcessBuilder` methods (all return `this`; callback builders have the element methods too). `?` = optional.
18
+
19
+ Events:
20
+ - startEvent(id?: string, options?: StartEventOptions)
21
+ - endEvent(id?: string, options?: EndEventOptions)
22
+ - intermediateThrowEvent(id?: string, options?: IntermediateThrowEventOptions)
23
+ - intermediateCatchEvent(id?: string, options?: IntermediateCatchEventOptions)
24
+ - boundaryEvent(id: string, attachedToOrOptions: string | BoundaryEventOptions, maybeOptions?: Omit<BoundaryEventOptions, "attachedTo">)
25
+ - withBoundary(id: string, options: Omit<BoundaryEventOptions, "attachedTo">, handler: (b: ProcessBuilder) => void)
26
+ Tasks and connectors:
27
+ - serviceTask(id: string, options: ServiceTaskOptions)
28
+ - restConnector(id: string, config: RestConnectorConfig)
29
+ - scriptTask(id: string, options: ScriptTaskOptions)
30
+ - userTask(id: string, options?: UserTaskOptions)
31
+ - sendTask(id: string, options?: MessageTaskOptions)
32
+ - receiveTask(id: string, options?: MessageTaskOptions)
33
+ - businessRuleTask(id: string, options?: BusinessRuleTaskOptions)
34
+ - callActivity(id: string, options: CallActivityOptions)
35
+ - manualTask(id: string, options?: ElementOptions)
36
+ - task(id: string, options?: ElementOptions)
37
+ Gateways:
38
+ - exclusiveGateway(id: string, options?: GatewayOptions)
39
+ - parallelGateway(id: string, options?: ElementOptions)
40
+ - inclusiveGateway(id: string, options?: GatewayOptions)
41
+ - eventBasedGateway(id: string, options?: ElementOptions)
42
+ - complexGateway(id: string, options?: GatewayOptions)
43
+ Containers (sub-processes):
44
+ - adHocSubProcess(id: string, content: (b: SubProcessContentBuilder) => void, options?: AdHocSubProcessOptions)
45
+ - subProcess(id: string, content: (b: SubProcessContentBuilder) => void, options?: SubProcessOptions)
46
+ - transaction(id: string, content: (b: SubProcessContentBuilder) => void, options?: SubProcessOptions)
47
+ - eventSubProcess(id: string, content: (b: SubProcessContentBuilder) => void, options?: ElementOptions)
48
+ Flow control:
49
+ - at(nodeId: string)
50
+ - insertAfter(nodeId: string)
51
+ - branch(name: string, callback: (b: BranchBuilder) => void)
52
+ - connectTo(targetId: string)
53
+ - element(elementId: string)
54
+ Process settings and misc:
55
+ - withAutoLayout()
56
+ - executionPlatformVersion(version: string)
57
+ - defaults(options: {serviceTask?: {retries?: string}})
58
+ - name(name: string)
59
+ - executable(value: boolean)
60
+ - versionTag(tag: string)
61
+ - message(id: string, options: {name: string})
62
+ - error(id: string, options: {code: string; name?: string})
63
+ - signal(id: string, options: {name: string})
64
+ - escalation(id: string, options: {code: string; name?: string})
65
+ - textAnnotation(text: string)
66
+ - annotate(elementId: string, text: string, options?: AnnotateOptions)
67
+ - build(options?: BuildOptions)
68
+ Other:
69
+ - dataObject(id: string, options?: DataElementOptions)
70
+ - dataObjectReference(id: string, dataObjectRef: string, options?: DataElementOptions)
71
+ - dataStoreReference(id: string, dataStoreRef: string, options?: Pick<DataElementOptions, "name">)
72
+ - dataAssociation(activityId: string, dataRefId: string, direction: "input" | "output")
73
+
74
+ Only inside `.branch()` callbacks (BranchBuilder), applied to the flow leaving the gateway:
75
+ - condition(expression: string)
76
+ - label(text: string)
77
+ - flowId(id: string)
78
+ - defaultFlow()
79
+
80
+ Not available inside callbacks (top-level only): at, insertAfter, withAutoLayout, executionPlatformVersion, defaults, name, executable, versionTag, message, error, signal, escalation, restConnector, build.
81
+
82
+ ## Options
83
+
84
+ `+El` = also accepts the ElementOptions fields.
85
+
86
+ - ElementOptions: name?: string; documentation?: string (Free-text documentation…)
87
+ - StartEventOptions +El: condition?: string (FEEL condition); timerDuration?: string (Timer duration (ISO 8601)); timerDate?: string (Timer date (ISO 8601)); timerCycle?: string (Timer cycle (ISO 8601)); messageName?: string (Message name); formId?: string (Form to show when the process is…); isInterrupting?: boolean (Non-interrupting flag)
88
+ - EndEventOptions +El: errorCode?: string (Error code); messageName?: string; signalName?: string (Signal name); escalationCode?: string (Escalation code)
89
+ - IntermediateThrowEventOptions +El: messageName?: string; signalName?: string; escalationCode?: string; compensation?: boolean (Emit a compensateEventDefinition); linkName?: string (Link name)
90
+ - IntermediateCatchEventOptions +El: timerDuration?: string; timerDate?: string; timerCycle?: string; messageName?: string; correlationKey?: string (FEEL expression correlating this…); signalName?: string; linkName?: string; condition?: string
91
+ - BoundaryEventOptions +El: attachedTo: string (ID of the activity this boundary…); cancelActivity?: boolean (Whether the host activity is…); errorCode?: string; timerDuration?: string; timerDate?: string; timerCycle?: string; messageName?: string; correlationKey?: string; signalName?: string; compensation?: boolean; condition?: string
92
+ - ServiceTaskOptions: multiInstance?: MultiInstanceOptions (Runs the activity once per item…); name: string; taskType: string (Zeebe job type for this task); retries?: string (Number of retries…); ioMapping?: ioMapping shape (Input/output variable mappings); taskHeaders?: Record<string, string> (Task header key-value pairs); linkedResources?: ZeebeLinkedResource[] (Resources the task runs, e.g. an…); documentation?: string
93
+ - MultiInstanceOptions: isSequential?: boolean; collection?: string; elementVariable?: string; outputCollection?: string (Variable that collects each…); outputElement?: string (FEEL expression evaluated per…); completionCondition?: string
94
+ - RestConnectorConfig: name?: string; method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" (HTTP method…); url: string (Target URL); authentication?: {type: "noAuth"} | {type: "bearer"; token: string} (Authentication configuration); headers?: Record<string, string> | string (HTTP headers as key-value pairs…); body?: string (Request body); retries?: string; resultVariable?: string (Variable name to store the full…); resultExpression?: string (FEEL expression to extract values…)
95
+ - ScriptTaskOptions: multiInstance?: MultiInstanceOptions; name?: string; expression: string (FEEL expression for the script); resultVariable: string; documentation?: string
96
+ - UserTaskOptions: multiInstance?: MultiInstanceOptions; name?: string; formId?: string; externalReference?: string (External form URL…); embeddedForm?: {id: string; schema: string} (Embeds a Camunda Form: writes a…); ioMapping?: ioMapping shape; taskHeaders?: Record<string, string>; documentation?: string; assignee?: string (Static assignee…); candidateGroups?: string (Candidate groups, comma-separated…); candidateUsers?: string (Candidate users, comma-separated…); dueDate?: string (Due date); followUpDate?: string (Follow-up date); priority?: number (Task priority 0-100, default 50…)
97
+ - MessageTaskOptions +El: multiInstance?: MultiInstanceOptions; messageName?: string; correlationKey?: string
98
+ - BusinessRuleTaskOptions: multiInstance?: MultiInstanceOptions; name?: string; taskType?: string; decisionId?: string (DMN decision ID to evaluate); resultVariable?: string; documentation?: string
99
+ - CallActivityOptions: multiInstance?: MultiInstanceOptions; name?: string; processId: string (Process ID to call); propagateAllChildVariables?: boolean (Whether to propagate all child…); propagateAllParentVariables?: boolean (Whether the child process…); bindingType?: "latest" | "deployment" | "versionTag" (How the called process version is…); versionTag?: string (Version tag of the called…); ioMapping?: ioMapping shape; documentation?: string
100
+ - GatewayOptions +El: defaultFlow?: string (ID of the default sequence flow…)
101
+ - AdHocSubProcessOptions +El: activeElementsCollection?: string (FEEL expression for determining…); outputCollection?: string; outputElement?: string; taskDefinition?: {type: string; retries?: string} (Zeebe task definition…); ioMapping?: ioMapping shape; taskHeaders?: Record<string, string>; multiInstance?: MultiInstanceOptions; completionCondition?: string
102
+ - SubProcessOptions +El: multiInstance?: MultiInstanceOptions
103
+ - DataElementOptions: name?: string; isCollection?: boolean (Draws the collection…)
104
+ - AnnotateOptions: side?: "above" | "below" | "left" | "right" (Which side of the element…)
105
+ - BuildOptions: explicitJoins?: boolean (Refuse to infer join gateways, so…)
106
+ - ioMapping shape = {inputs?: Array<{source: string; target: string}>; outputs?: Array<{source: string; target: string}>}
107
+
108
+ ## Examples
109
+
110
+ ```typescript
111
+ import { Bpmn } from "@bpmnkit/core"
112
+
113
+ const definitions = Bpmn.createProcess("order")
114
+ .withAutoLayout()
115
+ .startEvent("start")
116
+ .serviceTask("charge", { name: "Charge card", taskType: "payments", retries: "3" })
117
+ .userTask("review", { name: "Review", assignee: "=reviewer" })
118
+ .scriptTask("total", { expression: "=price * qty", resultVariable: "total" })
119
+ .endEvent("end")
120
+ .build()
121
+ const xml = Bpmn.export(definitions)
122
+ ```
123
+
124
+ ```typescript
125
+ import { Bpmn } from "@bpmnkit/core"
126
+
127
+ const definitions = Bpmn.createProcess("approval")
128
+ .withAutoLayout()
129
+ .startEvent("start")
130
+ .exclusiveGateway("ok", { name: "Approved?" })
131
+ .branch("yes", (b) =>
132
+ b.condition("=approved").serviceTask("ship", { name: "Ship", taskType: "shipping" }).connectTo("end"),
133
+ )
134
+ .branch("no", (b) => b.defaultFlow().label("Rejected").endEvent("rejected"))
135
+ .endEvent("end")
136
+ .build()
137
+ const xml = Bpmn.export(definitions)
138
+ ```
139
+
140
+ ```typescript
141
+ import { Bpmn } from "@bpmnkit/core"
142
+
143
+ const definitions = Bpmn.createProcess("batch")
144
+ .withAutoLayout()
145
+ .startEvent("start")
146
+ .subProcess(
147
+ "each",
148
+ (sub) =>
149
+ sub
150
+ .startEvent("subStart")
151
+ .serviceTask("handle", { name: "Handle item", taskType: "handler" })
152
+ .endEvent("subEnd"),
153
+ { name: "Per item", multiInstance: { collection: "=items", elementVariable: "item" } },
154
+ )
155
+ .endEvent("end")
156
+ .build()
157
+ const xml = Bpmn.export(definitions)
158
+ ```
159
+
160
+ ```typescript
161
+ import { Bpmn } from "@bpmnkit/core"
162
+
163
+ const definitions = Bpmn.createProcess("sla")
164
+ .withAutoLayout()
165
+ .startEvent("start")
166
+ .serviceTask("work", { name: "Work", taskType: "worker" })
167
+ .withBoundary("late", { timerDuration: "PT1H", cancelActivity: false }, (b) =>
168
+ b.serviceTask("remind", { name: "Remind", taskType: "mailer" }).endEvent("reminded"),
169
+ )
170
+ .withBoundary("failed", { errorCode: "WORK_FAILED" }, (b) => b.endEvent("aborted"))
171
+ .endEvent("end")
172
+ .build()
173
+ const xml = Bpmn.export(definitions)
174
+ ```
175
+
176
+ ```typescript
177
+ import { Bpmn } from "@bpmnkit/core"
178
+
179
+ const definitions = Bpmn.createProcess("payment")
180
+ .withAutoLayout()
181
+ .startEvent("start", { messageName: "order-placed" })
182
+ .eventBasedGateway("wait")
183
+ .branch("paid", (b) =>
184
+ b
185
+ .intermediateCatchEvent("gotPayment", { messageName: "payment", correlationKey: "=orderId" })
186
+ .endEvent("done"),
187
+ )
188
+ .branch("late", (b) =>
189
+ b.intermediateCatchEvent("expired", { timerDuration: "P3D" }).endEvent("cancelled"),
190
+ )
191
+ .build()
192
+ const xml = Bpmn.export(definitions)
193
+ ```
194
+
195
+ ```typescript
196
+ import { Bpmn } from "@bpmnkit/core"
197
+
198
+ const definitions = Bpmn.createProcess("onboarding")
199
+ .withAutoLayout()
200
+ .startEvent("start")
201
+ .restConnector("lookup", {
202
+ name: "Look up customer",
203
+ method: "GET",
204
+ url: '="https://api.example.com/customers/" + customerId',
205
+ resultVariable: "customer",
206
+ })
207
+ .callActivity("kyc", { name: "KYC check", processId: "kyc-check", propagateAllChildVariables: true })
208
+ .endEvent("end")
209
+ .build()
210
+ const xml = Bpmn.export(definitions)
211
+ ```
@@ -148,6 +148,33 @@ function buildLaneShapes(lanes, nodes, dx, dy, poolY, poolHeaderWidth, laneConte
148
148
  return shape;
149
149
  });
150
150
  }
151
+ /**
152
+ * A view of `process` whose annotations and associations include those declared
153
+ * inside (nested) sub-processes. The builder stores them on the sub-process
154
+ * element, so packing only the process-level lists left them without a shape
155
+ * or edge. Layout nodes are already flat in diagram space, so one pass suffices.
156
+ */
157
+ function withNestedAnnotations(process) {
158
+ const textAnnotations = [...process.textAnnotations];
159
+ const associations = [...process.associations];
160
+ const walk = (elements) => {
161
+ for (const el of elements) {
162
+ const scope = el;
163
+ if (scope.textAnnotations)
164
+ textAnnotations.push(...scope.textAnnotations);
165
+ if (scope.associations)
166
+ associations.push(...scope.associations);
167
+ if (scope.flowElements)
168
+ walk(scope.flowElements);
169
+ }
170
+ };
171
+ walk(process.flowElements);
172
+ if (textAnnotations.length === process.textAnnotations.length &&
173
+ associations.length === process.associations.length) {
174
+ return process;
175
+ }
176
+ return { ...process, textAnnotations, associations };
177
+ }
151
178
  /** Also used by `expand`, which lays out one process without the pool handling above. */
152
179
  export function addAnnotationShapes(process, layoutNodes, annLocalBounds, allShapes, allEdges, dx, dy) {
153
180
  if (process.textAnnotations.length === 0 && process.associations.length === 0)
@@ -699,8 +726,9 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
699
726
  // they replace the proportional tiling below.
700
727
  const engineLanes = result.lanes;
701
728
  // Pre-compute annotation positions in layout space so they're included in the bbox
702
- const annBounds = process
703
- ? packAnnotations(process, result.nodes, result.edges, hints?.annotationSides)
729
+ const annProcess = process ? withNestedAnnotations(process) : undefined;
730
+ const annBounds = annProcess
731
+ ? packAnnotations(annProcess, result.nodes, result.edges, hints?.annotationSides)
704
732
  : new Map();
705
733
  const { minX, minY, maxX, maxY } = contentBbox(result.nodes, annBounds.values());
706
734
  const contentW = maxX - minX;
@@ -724,7 +752,8 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
724
752
  }
725
753
  else {
726
754
  dx = PADDING - minX;
727
- dy = PADDING - minY;
755
+ // Below any pools already stacked; poolY is 0 without a collaboration.
756
+ dy = (process?.id === primaryProcessId ? poolY : 0) + PADDING - minY;
728
757
  }
729
758
  // Only the primary process shares the root plane; any other root process
730
759
  // owns one, instead of being stacked on top of the first at the origin.
@@ -735,7 +764,7 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
735
764
  shapes.push(nodeToShape(node, dx, dy));
736
765
  for (const edge of result.edges)
737
766
  edges.push(edgeToShape(edge, dx, dy));
738
- addAnnotationShapes(process, result.nodes, annBounds, shapes, edges, dx, dy);
767
+ addAnnotationShapes(annProcess ?? process, result.nodes, annBounds, shapes, edges, dx, dy);
739
768
  rootPlanes.push({ elementId: process.id, shapes, edges });
740
769
  continue;
741
770
  }
@@ -744,7 +773,7 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
744
773
  for (const edge of result.edges)
745
774
  allEdges.push(edgeToShape(edge, dx, dy));
746
775
  if (process) {
747
- addAnnotationShapes(process, result.nodes, annBounds, allShapes, allEdges, dx, dy);
776
+ addAnnotationShapes(annProcess ?? process, result.nodes, annBounds, allShapes, allEdges, dx, dy);
748
777
  }
749
778
  if (participantId) {
750
779
  const innerW = (hasLanes ? LANE_HEADER : 0) + contentW + 2 * PADDING + alignDx;