@bpmnkit/core 1.10.1 → 1.12.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.
@@ -8,7 +8,7 @@ Write a Camunda 8 BPMN process with `@bpmnkit/core` in one script: create, expor
8
8
 
9
9
  ```ts
10
10
  import { readFileSync, writeFileSync } from "node:fs"
11
- import { Bpmn, exportPreserving, lintDiagram } from "@bpmnkit/core"
11
+ import { Bpmn, exportPreserving, lintDiagram, placeNewShapes } from "@bpmnkit/core"
12
12
 
13
13
  // 1. Create. The process id is the deploy key: same id = new version of that process.
14
14
  const definitions = Bpmn.createProcess("order")
@@ -32,12 +32,18 @@ const definitions = Bpmn.createProcess("order")
32
32
  // 2. Export.
33
33
  writeFileSync("order.bpmn", Bpmn.export(definitions))
34
34
 
35
- // 3. Edit an existing file: parse, change, write with exportPreserving to keep layout and formatting.
35
+ // 3. Edit an existing file: change the model, draw only the new elements, write with
36
+ // exportPreserving. Existing shapes keep their positions and the file its formatting.
36
37
  const original = readFileSync("order.bpmn", "utf8")
37
- const edited = Bpmn.parse(original)
38
+ const edited = Bpmn.continueProcess(Bpmn.parse(original), "order")
39
+ .insertAfter("ship")
40
+ .serviceTask("notify", { name: "Notify customer", taskType: "notify-customer" })
41
+ .build()
38
42
  const ship = edited.processes[0]?.flowElements.find((e) => e.id === "ship")
39
43
  if (ship) ship.name = "Ship parcel"
40
- writeFileSync("order.bpmn", exportPreserving(original, edited))
44
+ const { definitions: drawn, unplaced } = placeNewShapes(edited)
45
+ if (unplaced.length > 0) console.log("not drawn:", unplaced)
46
+ writeFileSync("order.bpmn", exportPreserving(original, drawn))
41
47
 
42
48
  // 4. Validate: Camunda 8 deployability and modelling rules.
43
49
  const report = lintDiagram(Bpmn.parse(readFileSync("order.bpmn", "utf8")))
@@ -46,7 +52,7 @@ for (const d of report.diagnostics.filter((d) => d.severity !== "info"))
46
52
  if (report.counts.error > 0) process.exit(1)
47
53
  ```
48
54
 
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.
55
+ `npm i @bpmnkit/core`. The script writes `order.bpmn`, re-opens it, adds a task and renames one without moving a shape, and exits 1 on a lint error.
50
56
 
51
57
  ## Top builder options
52
58
 
@@ -67,7 +73,7 @@ if (report.counts.error > 0) process.exit(1)
67
73
  - **User tasks default to job-worker tasks**, which 8.10 deprecates. Pass `zeebeUserTask: true` for a Camunda user task.
68
74
  - **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
75
  - **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.
76
+ - **Edit with the preserving writer.** For an existing file, `Bpmn.parse` it (or `Bpmn.continueProcess(parsed, processId)`), change the model, run `placeNewShapes(edited)` so the new elements get shapes next to what they connect to, and write `exportPreserving(original, drawn)`. Existing shapes stay put; a pool, lane or sub-process only grows when the new shapes do not fit. Rebuilding with `withAutoLayout()`, `applyAutoLayout`, or `Bpmn.export` alone moves every shape and reformats the diff. `placeNewShapes` does not draw new lanes; it lists them in `unplaced`.
71
77
  - FEEL in the builder starts with `=` (`"=amount > 1000"`); a value without `=` is a literal string.
72
78
  - Unknown option names are silently dropped: `timer: { duration }` does nothing; use `timerDuration`.
73
79
 
@@ -1137,8 +1137,9 @@ export declare class ProcessBuilder {
1137
1137
  * continuing rather than regenerating.
1138
1138
  *
1139
1139
  * Diagram interchange is *not* regenerated: existing shapes keep their
1140
- * positions, and elements added here have none until `withAutoLayout()` or a
1141
- * later `applyAutoLayout()` gives them one.
1140
+ * positions, and elements added here have none until `placeNewShapes()` draws
1141
+ * just those (existing shapes never move), or `withAutoLayout()` /
1142
+ * `applyAutoLayout()` redraws everything.
1142
1143
  */
1143
1144
  private buildOntoSource;
1144
1145
  /**
@@ -2882,8 +2882,9 @@ export class ProcessBuilder {
2882
2882
  * continuing rather than regenerating.
2883
2883
  *
2884
2884
  * Diagram interchange is *not* regenerated: existing shapes keep their
2885
- * positions, and elements added here have none until `withAutoLayout()` or a
2886
- * later `applyAutoLayout()` gives them one.
2885
+ * positions, and elements added here have none until `placeNewShapes()` draws
2886
+ * just those (existing shapes never move), or `withAutoLayout()` /
2887
+ * `applyAutoLayout()` redraws everything.
2887
2888
  */
2888
2889
  buildOntoSource(source, elements, flows) {
2889
2890
  const definitions = structuredClone(source.definitions);
@@ -0,0 +1,78 @@
1
+ import type { BpmnDefinitions } from "./bpmn-model.js";
2
+ import { type BpmnDiffPlaneSummary } from "./diagram-diff.js";
3
+ import { type JsonValue } from "./semantic-hash.js";
4
+ /** How an element differs; same vocabulary as {@link BpmnDiffCategory}. */
5
+ export type BpmnChangeKind = "added" | "removed" | "changed" | "moved";
6
+ /**
7
+ * One property that differs inside a changed element.
8
+ *
9
+ * `path` is a JSON-pointer-like route into the element's projection, with `/`
10
+ * and `~` escaped as `~1` / `~0`. Extension elements read as
11
+ * `extensionElements/zeebe:taskDefinition/@type`; list entries are keyed by `id`
12
+ * or `name` when they carry one, and by position otherwise. A side that does
13
+ * not have the property is omitted.
14
+ */
15
+ export interface BpmnFieldChange {
16
+ readonly path: string;
17
+ readonly before?: JsonValue;
18
+ readonly after?: JsonValue;
19
+ }
20
+ /** Where an element is drawn, rounded to two decimals. A shape has a box, an edge a route. */
21
+ export interface BpmnGeometry {
22
+ readonly x?: number;
23
+ readonly y?: number;
24
+ readonly width?: number;
25
+ readonly height?: number;
26
+ readonly waypoints?: ReadonlyArray<{
27
+ readonly x: number;
28
+ readonly y: number;
29
+ }>;
30
+ }
31
+ export interface BpmnElementChange {
32
+ readonly id: string;
33
+ readonly kind: BpmnChangeKind;
34
+ /** `type` of the element, or the singular of the list it sits in (`participant`, `sequenceFlow`, …). */
35
+ readonly elementType?: string;
36
+ readonly nameBefore?: string;
37
+ readonly nameAfter?: string;
38
+ /** Only for `changed`; empty otherwise. */
39
+ readonly fields: readonly BpmnFieldChange[];
40
+ readonly geometryBefore?: BpmnGeometry;
41
+ readonly geometryAfter?: BpmnGeometry;
42
+ }
43
+ export interface BpmnDiffSummary {
44
+ readonly added: number;
45
+ readonly removed: number;
46
+ readonly changed: number;
47
+ readonly moved: number;
48
+ readonly total: number;
49
+ }
50
+ /**
51
+ * A full diff of two models: every semantic change with its field-level detail,
52
+ * layout-only moves, and the per-plane counts of what a canvas can show.
53
+ *
54
+ * `changes` lists every semantic difference, including elements with nothing to
55
+ * draw (a process attribute, a message definition); `planes` counts only the
56
+ * drawable ones, exactly as {@link diffDiagram} does. `beforeHash === afterHash`
57
+ * means the models are semantically identical.
58
+ */
59
+ export interface BpmnDiff {
60
+ readonly changes: readonly BpmnElementChange[];
61
+ readonly planes: readonly BpmnDiffPlaneSummary[];
62
+ readonly summary: BpmnDiffSummary;
63
+ readonly beforeHash: string;
64
+ readonly afterHash: string;
65
+ }
66
+ /**
67
+ * Diffs two models: what changed, field by field, what only moved, and a hash
68
+ * of each side.
69
+ *
70
+ * Composes {@link diffSemantics} (the model half) and {@link diffDiagram} (the
71
+ * layout half). The Rust crate `bpmnkit-diff` produces the same result; both
72
+ * are held to `conformance/diff/`.
73
+ *
74
+ * @param before - The earlier model.
75
+ * @param after - The later model.
76
+ */
77
+ export declare function diffBpmn(before: BpmnDefinitions, after: BpmnDefinitions): BpmnDiff;
78
+ //# sourceMappingURL=bpmn-diff.d.ts.map
@@ -0,0 +1,202 @@
1
+ import { diffDiagram } from "./diagram-diff.js";
2
+ import { diffSemantics, projectSemantics, semanticHash } from "./semantic-hash.js";
3
+ const KIND_ORDER = { added: 0, removed: 1, changed: 2, moved: 3 };
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ // UTF-16 code-unit order, which the Rust twin reproduces, so both sort alike.
8
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
9
+ const escapeSegment = (s) => s.replaceAll("~", "~0").replaceAll("/", "~1");
10
+ function singular(key) {
11
+ if (key.endsWith("ies"))
12
+ return `${key.slice(0, -3)}y`;
13
+ if (key.endsWith("ses"))
14
+ return key.slice(0, -2);
15
+ return key.endsWith("s") ? key.slice(0, -1) : key;
16
+ }
17
+ /** Same walk as the semantic index, so every indexed id gets a type. */
18
+ function collectTypes(value, key, into) {
19
+ if (Array.isArray(value)) {
20
+ for (const entry of value)
21
+ collectTypes(entry, key, into);
22
+ return;
23
+ }
24
+ if (!isRecord(value))
25
+ return;
26
+ if (typeof value.id === "string") {
27
+ into.set(value.id, typeof value.type === "string" ? value.type : singular(key));
28
+ }
29
+ for (const [k, entry] of Object.entries(value))
30
+ collectTypes(entry, k, into);
31
+ }
32
+ function itemKey(item) {
33
+ if (typeof item === "string")
34
+ return item;
35
+ if (isRecord(item)) {
36
+ if (typeof item.id === "string")
37
+ return item.id;
38
+ if (typeof item.name === "string")
39
+ return item.name;
40
+ }
41
+ return undefined;
42
+ }
43
+ /** Keys for matching two lists entry by entry, or `undefined` when they are not unique. */
44
+ function listKeys(left, right) {
45
+ const keysOf = (list) => {
46
+ const keys = list.map(itemKey);
47
+ if (keys.some((k) => k === undefined))
48
+ return undefined;
49
+ return new Set(keys).size === keys.length ? keys : undefined;
50
+ };
51
+ const l = keysOf(left);
52
+ const r = keysOf(right);
53
+ return l !== undefined && r !== undefined ? [l, r] : undefined;
54
+ }
55
+ // Empty `attributes` / `children` are dropped by the projection, so either one marks an XML node.
56
+ const isXmlElement = (v) => isRecord(v) && typeof v.name === "string" && (isRecord(v.attributes) || Array.isArray(v.children));
57
+ function jsonChanges(before, after, path, out) {
58
+ if (before === undefined || after === undefined) {
59
+ if (before !== after)
60
+ out.push(change(path, before, after));
61
+ return;
62
+ }
63
+ if (isRecord(before) && isRecord(after)) {
64
+ const xml = isXmlElement(before) || isXmlElement(after);
65
+ const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(compare);
66
+ for (const key of keys) {
67
+ const l = before[key];
68
+ const r = after[key];
69
+ if (xml && key === "attributes") {
70
+ // An attribute reads as `@name`, the way XPath writes it.
71
+ const lo = (l ?? {});
72
+ const ro = (r ?? {});
73
+ for (const n of [...new Set([...Object.keys(lo), ...Object.keys(ro)])].sort(compare)) {
74
+ jsonChanges(lo[n], ro[n], join(path, `@${n}`), out);
75
+ }
76
+ }
77
+ else {
78
+ // `children` is the XML tree's own nesting, not a name worth a path segment.
79
+ jsonChanges(l, r, xml && key === "children" ? path : join(path, key), out);
80
+ }
81
+ }
82
+ return;
83
+ }
84
+ if (Array.isArray(before) && Array.isArray(after)) {
85
+ const keyed = listKeys(before, after);
86
+ if (keyed !== undefined) {
87
+ const [lk, rk] = keyed;
88
+ const l = new Map(lk.map((k, i) => [k, before[i]]));
89
+ const r = new Map(rk.map((k, i) => [k, after[i]]));
90
+ for (const k of [...new Set([...lk, ...rk])].sort(compare)) {
91
+ jsonChanges(l.get(k), r.get(k), join(path, k), out);
92
+ }
93
+ return;
94
+ }
95
+ const n = Math.max(before.length, after.length);
96
+ for (let i = 0; i < n; i++)
97
+ jsonChanges(before[i], after[i], join(path, `[${i}]`), out);
98
+ return;
99
+ }
100
+ if (JSON.stringify(before) !== JSON.stringify(after))
101
+ out.push(change(path, before, after));
102
+ }
103
+ function change(path, before, after) {
104
+ return {
105
+ path,
106
+ ...(before !== undefined ? { before } : {}),
107
+ ...(after !== undefined ? { after } : {}),
108
+ };
109
+ }
110
+ function join(path, segment) {
111
+ const s = escapeSegment(segment);
112
+ return path === "" ? s : `${path}/${s}`;
113
+ }
114
+ const round = (v) => Math.round(v * 100) / 100;
115
+ function geometryOf(definitions) {
116
+ const index = new Map();
117
+ for (const diagram of definitions.diagrams) {
118
+ for (const shape of diagram.plane.shapes) {
119
+ const { x, y, width, height } = shape.bounds;
120
+ index.set(shape.bpmnElement, {
121
+ x: round(x),
122
+ y: round(y),
123
+ width: round(width),
124
+ height: round(height),
125
+ });
126
+ }
127
+ for (const edge of diagram.plane.edges) {
128
+ index.set(edge.bpmnElement, {
129
+ waypoints: edge.waypoints.map((p) => ({ x: round(p.x), y: round(p.y) })),
130
+ });
131
+ }
132
+ }
133
+ return index;
134
+ }
135
+ /**
136
+ * Diffs two models: what changed, field by field, what only moved, and a hash
137
+ * of each side.
138
+ *
139
+ * Composes {@link diffSemantics} (the model half) and {@link diffDiagram} (the
140
+ * layout half). The Rust crate `bpmnkit-diff` produces the same result; both
141
+ * are held to `conformance/diff/`.
142
+ *
143
+ * @param before - The earlier model.
144
+ * @param after - The later model.
145
+ */
146
+ export function diffBpmn(before, after) {
147
+ const left = projectSemantics(before);
148
+ const right = projectSemantics(after);
149
+ const semantic = diffSemantics(before, after);
150
+ const diagram = diffDiagram(before, after);
151
+ const types = new Map();
152
+ collectTypes(left.value, "definitions", types);
153
+ collectTypes(right.value, "definitions", types);
154
+ const nameOf = (v) => isRecord(v) && typeof v.name === "string" ? v.name : undefined;
155
+ const geoBefore = geometryOf(before);
156
+ const geoAfter = geometryOf(after);
157
+ const make = (id, kind, b, a) => {
158
+ const fields = [];
159
+ if (kind === "changed")
160
+ jsonChanges(b, a, "", fields);
161
+ const elementType = types.get(id);
162
+ const nameBefore = nameOf(b);
163
+ const nameAfter = nameOf(a);
164
+ const gb = geoBefore.get(id);
165
+ const ga = geoAfter.get(id);
166
+ return {
167
+ id,
168
+ kind,
169
+ ...(elementType !== undefined ? { elementType } : {}),
170
+ ...(nameBefore !== undefined ? { nameBefore } : {}),
171
+ ...(nameAfter !== undefined ? { nameAfter } : {}),
172
+ fields,
173
+ ...(gb !== undefined ? { geometryBefore: gb } : {}),
174
+ ...(ga !== undefined ? { geometryAfter: ga } : {}),
175
+ };
176
+ };
177
+ const changes = [
178
+ ...semantic.added.map((id) => make(id, "added", undefined, right.elements.get(id))),
179
+ ...semantic.removed.map((id) => make(id, "removed", left.elements.get(id), undefined)),
180
+ // A parent whose child list was merely reordered by the canonical sort differs in
181
+ // `diffSemantics` but in no field; there is nothing to show for it.
182
+ ...semantic.changed
183
+ .map((c) => make(c.id, "changed", c.before, c.after))
184
+ .filter((c) => c.fields.length > 0),
185
+ ...diagram.moved.map((id) => make(id, "moved", left.elements.get(id), right.elements.get(id))),
186
+ ].sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || compare(a.id, b.id));
187
+ const count = (kind) => changes.filter((c) => c.kind === kind).length;
188
+ return {
189
+ changes,
190
+ planes: diagram.planes,
191
+ summary: {
192
+ added: count("added"),
193
+ removed: count("removed"),
194
+ changed: count("changed"),
195
+ moved: count("moved"),
196
+ total: changes.length,
197
+ },
198
+ beforeHash: semanticHash(before),
199
+ afterHash: semanticHash(after),
200
+ };
201
+ }
202
+ //# sourceMappingURL=bpmn-diff.js.map
@@ -0,0 +1,36 @@
1
+ import type { BpmnDiff } from "./bpmn-diff.js";
2
+ import type { BpmnDefinitions } from "./bpmn-model.js";
3
+ import { type SvgExportOptions } from "./svg.js";
4
+ export interface DiffHtmlOptions {
5
+ /** Page title and heading. Default: "BPMN diff". */
6
+ title?: string;
7
+ /** Name of the earlier model in the toolbar and pane caption. Default: "before". */
8
+ beforeLabel?: string;
9
+ /** Name of the later model. Default: "after". */
10
+ afterLabel?: string;
11
+ /** Diagram theme; the page chrome follows `prefers-color-scheme`. Default: "light". */
12
+ theme?: SvgExportOptions["theme"];
13
+ /** Padding around each diagram. Default: 20. */
14
+ padding?: number;
15
+ /** Lay out a model that has no diagram interchange. Default: false. */
16
+ autoLayout?: boolean;
17
+ }
18
+ /**
19
+ * A single self-contained HTML page comparing two models: both diagrams with the changes
20
+ * highlighted, side by side or overlaid, and the change list with field-level detail. It loads
21
+ * nothing (a CSP forbids it) and reads without JavaScript; with it, a click on a change zooms
22
+ * both diagrams to it. The same inputs give the same bytes as Rust `bpmnkit_diff::diff_to_html`.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const diff = diffBpmn(before, after)
27
+ * writeFileSync("diff.html", renderDiffHtml(before, after, diff, { title: "order.bpmn" }))
28
+ * ```
29
+ */
30
+ export declare function renderDiffHtml(before: BpmnDefinitions, after: BpmnDefinitions, diff: BpmnDiff, options?: DiffHtmlOptions): string;
31
+ /**
32
+ * The later model's SVG with the diff drawn over it (added, changed and moved elements, moves
33
+ * with a ghost of the old place): one image for chat surfaces that cannot show HTML.
34
+ */
35
+ export declare function diffToSvg(after: BpmnDefinitions, diff: BpmnDiff, options?: SvgExportOptions): string;
36
+ //# sourceMappingURL=diff-html.d.ts.map
@@ -0,0 +1,182 @@
1
+ import { DIFF_VIEWER_TEMPLATE } from "../generated/diff-viewer.js";
2
+ import { esc, exportSvg, exportSvgDetailed, } from "./svg.js";
3
+ const KINDS = ["added", "removed", "changed", "moved"];
4
+ const SYMBOL = {
5
+ added: "+",
6
+ removed: "−",
7
+ changed: "~",
8
+ moved: "↔",
9
+ };
10
+ /** Semantic colours, exempt from brand tokens; inline so a PNG of `diffToSvg` keeps them. */
11
+ const COLOR = {
12
+ added: "#16a34a",
13
+ removed: "#dc2626",
14
+ changed: "#d97706",
15
+ moved: "#2563eb",
16
+ };
17
+ function sortKeys(v) {
18
+ if (Array.isArray(v))
19
+ return v.map(sortKeys);
20
+ if (v !== null && typeof v === "object") {
21
+ return Object.fromEntries(Object.keys(v)
22
+ .sort()
23
+ .map((k) => [k, sortKeys(v[k])]));
24
+ }
25
+ return v;
26
+ }
27
+ const stringify = (v) => JSON.stringify(sortKeys(v));
28
+ /** One highlight mark: a wide translucent route for an edge, an outset box for a shape. */
29
+ function mark(g, color, ghost) {
30
+ const line = ghost
31
+ ? `stroke="${color}" stroke-width="2" stroke-dasharray="6 4"`
32
+ : `stroke="${color}" stroke-width="4"`;
33
+ if (g.waypoints !== undefined && g.waypoints.length > 0) {
34
+ const points = g.waypoints.map((p) => `${p.x},${p.y}`).join(" ");
35
+ const wide = ghost ? line : `stroke="${color}" stroke-width="10" stroke-opacity="0.35"`;
36
+ return `<polyline points="${points}" fill="none" ${wide} stroke-linecap="round" stroke-linejoin="round"/>`;
37
+ }
38
+ if (g.x === undefined || g.y === undefined || g.width === undefined || g.height === undefined) {
39
+ return "";
40
+ }
41
+ return `<rect x="${g.x - 4}" y="${g.y - 4}" width="${g.width + 8}" height="${g.height + 8}" rx="6" fill="none" ${line}/>`;
42
+ }
43
+ function changeLabel(c) {
44
+ const name = c.nameAfter ?? c.nameBefore;
45
+ return name === undefined || name === "" ? c.id : `${name} (${c.id})`;
46
+ }
47
+ /**
48
+ * The overlay marks for one side. Removed elements show on the earlier diagram, added ones on
49
+ * the later; changed and moved show on both, a move with a dashed ghost of where it was.
50
+ */
51
+ function highlights(diff, side, links) {
52
+ let out = "";
53
+ diff.changes.forEach((c, i) => {
54
+ if (side === "before" ? c.kind === "added" : c.kind === "removed")
55
+ return;
56
+ const geometry = side === "before" ? c.geometryBefore : c.geometryAfter;
57
+ const color = COLOR[c.kind];
58
+ let marks = geometry === undefined ? "" : mark(geometry, color, false);
59
+ if (side === "after" && c.kind === "moved" && c.geometryBefore !== undefined) {
60
+ marks = mark(c.geometryBefore, color, true) + marks;
61
+ }
62
+ if (marks === "")
63
+ return;
64
+ const g = `<g class="bk-hl bk-k-${c.kind}" data-i="${i}"><title>${c.kind}: ${esc(changeLabel(c))}</title>${marks}</g>`;
65
+ out += links ? `<a href="#bk-c${i}">${g}</a>` : g;
66
+ });
67
+ return out;
68
+ }
69
+ /** Element ids made unique per pane: two inlined SVGs would otherwise share `#arr`. */
70
+ const prefixIds = (svg, prefix) => svg.replaceAll(' id="', ` id="${prefix}`).replaceAll("url(#", `url(#${prefix}`);
71
+ function pane(r, union, prefix, label, hl) {
72
+ const u = `${union.x} ${union.y} ${union.w} ${union.h}`;
73
+ return `<svg class="bk-svg" xmlns="http://www.w3.org/2000/svg" viewBox="${u}" role="img" aria-label="${esc(label)}"><g transform="translate(${r.viewBox.x} ${r.viewBox.y})">${prefixIds(r.svg, prefix)}</g><g class="bk-diff">${hl}</g></svg>`;
74
+ }
75
+ function summary(diff) {
76
+ let chips = "";
77
+ for (const kind of KINDS) {
78
+ const n = diff.summary[kind];
79
+ chips += `<span class="bk-chip bk-k-${kind}${n === 0 ? " bk-zero" : ""}">${SYMBOL[kind]}${n} ${kind}</span>`;
80
+ }
81
+ if (diff.beforeHash === diff.afterHash) {
82
+ chips += `<span class="bk-chip bk-same" title="semantic hash ${diff.afterHash}">semantically identical</span>`;
83
+ }
84
+ return `<p class="bk-sum">${chips}</p>`;
85
+ }
86
+ function value(v, tag) {
87
+ return `<${tag}>${v === undefined ? "(none)" : esc(stringify(v))}</${tag}>`;
88
+ }
89
+ function changeList(diff) {
90
+ if (diff.changes.length === 0)
91
+ return `<p class="bk-empty">No differences.</p>`;
92
+ let out = "";
93
+ for (const kind of KINDS) {
94
+ let rows = "";
95
+ let n = 0;
96
+ diff.changes.forEach((c, i) => {
97
+ if (c.kind !== kind)
98
+ return;
99
+ n++;
100
+ const name = c.nameAfter ?? c.nameBefore;
101
+ let row = `<li class="bk-row bk-k-${kind}" id="bk-c${i}" data-i="${i}" tabindex="0">`;
102
+ if (name !== undefined && name !== "")
103
+ row += `<span class="bk-name">${esc(name)}</span> `;
104
+ if (c.elementType !== undefined)
105
+ row += `<span class="bk-type">${esc(c.elementType)}</span> `;
106
+ row += `<code class="bk-id">${esc(c.id)}</code>`;
107
+ if (c.fields.length > 0) {
108
+ row += `<ul class="bk-fields">`;
109
+ for (const f of c.fields) {
110
+ row += `<li><code>${esc(f.path)}</code> ${value(f.before, "del")} → ${value(f.after, "ins")}</li>`;
111
+ }
112
+ row += "</ul>";
113
+ }
114
+ rows += `${row}</li>`;
115
+ });
116
+ if (n === 0)
117
+ continue;
118
+ out += `<section class="bk-group bk-k-${kind}"><h2>${SYMBOL[kind]} ${kind} <span class="bk-n">${n}</span></h2><ol>${rows}</ol></section>`;
119
+ }
120
+ return out;
121
+ }
122
+ function render(defs, options) {
123
+ if (options.autoLayout !== true && defs.diagrams.length === 0) {
124
+ throw new Error("model has no diagram to draw (pass autoLayout: true)");
125
+ }
126
+ return exportSvgDetailed(defs, {
127
+ theme: options.theme,
128
+ padding: options.padding,
129
+ autoLayout: options.autoLayout,
130
+ });
131
+ }
132
+ /** `{{NAME}}` → `vars.NAME` in one pass, so substituted text is never scanned again. */
133
+ function fill(template, vars) {
134
+ return template.replace(/\{\{([A-Z_]+)\}\}/g, (m, key) => vars[key] ?? m);
135
+ }
136
+ /**
137
+ * A single self-contained HTML page comparing two models: both diagrams with the changes
138
+ * highlighted, side by side or overlaid, and the change list with field-level detail. It loads
139
+ * nothing (a CSP forbids it) and reads without JavaScript; with it, a click on a change zooms
140
+ * both diagrams to it. The same inputs give the same bytes as Rust `bpmnkit_diff::diff_to_html`.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * const diff = diffBpmn(before, after)
145
+ * writeFileSync("diff.html", renderDiffHtml(before, after, diff, { title: "order.bpmn" }))
146
+ * ```
147
+ */
148
+ export function renderDiffHtml(before, after, diff, options = {}) {
149
+ const b = render(before, options);
150
+ const a = render(after, options);
151
+ const x = Math.min(b.viewBox.x, a.viewBox.x);
152
+ const y = Math.min(b.viewBox.y, a.viewBox.y);
153
+ const union = {
154
+ x,
155
+ y,
156
+ w: Math.max(b.viewBox.x + b.viewBox.w, a.viewBox.x + a.viewBox.w) - x,
157
+ h: Math.max(b.viewBox.y + b.viewBox.h, a.viewBox.y + a.viewBox.h) - y,
158
+ };
159
+ const beforeLabel = options.beforeLabel ?? "before";
160
+ const afterLabel = options.afterLabel ?? "after";
161
+ return fill(DIFF_VIEWER_TEMPLATE, {
162
+ TITLE: esc(options.title ?? "BPMN diff"),
163
+ SUMMARY: summary(diff),
164
+ BEFORE_LABEL: esc(beforeLabel),
165
+ AFTER_LABEL: esc(afterLabel),
166
+ BEFORE_SVG: pane(b, union, "bk-b-", beforeLabel, highlights(diff, "before", true)),
167
+ AFTER_SVG: pane(a, union, "bk-a-", afterLabel, highlights(diff, "after", true)),
168
+ CHANGES: changeList(diff),
169
+ // `<` escaped so no value can close the <script> it sits in.
170
+ DIFF_JSON: stringify(diff).replaceAll("<", "\\u003c"),
171
+ });
172
+ }
173
+ /**
174
+ * The later model's SVG with the diff drawn over it (added, changed and moved elements, moves
175
+ * with a ghost of the old place): one image for chat surfaces that cannot show HTML.
176
+ */
177
+ export function diffToSvg(after, diff, options) {
178
+ const svg = exportSvg(after, options);
179
+ const end = svg.lastIndexOf("</svg>");
180
+ return `${svg.slice(0, end)}<g class="bk-diff">${highlights(diff, "after", false)}</g></svg>`;
181
+ }
182
+ //# sourceMappingURL=diff-html.js.map
@@ -62,6 +62,8 @@ export declare const Bpmn: {
62
62
  * `build()` returns that document with the named process's contents replaced,
63
63
  * so other processes, the collaboration, lanes, diagram interchange, root
64
64
  * elements and unmodelled content all survive. The input is not mutated.
65
+ * Added elements have no shapes; call `placeNewShapes()` on the result to
66
+ * draw only those without moving existing ones.
65
67
  *
66
68
  * @param definitions - The parsed model to continue.
67
69
  * @param processId - Which process to continue, named explicitly.
@@ -73,6 +73,8 @@ export const Bpmn = {
73
73
  * `build()` returns that document with the named process's contents replaced,
74
74
  * so other processes, the collaboration, lanes, diagram interchange, root
75
75
  * elements and unmodelled content all survive. The input is not mutated.
76
+ * Added elements have no shapes; call `placeNewShapes()` on the result to
77
+ * draw only those without moving existing ones.
76
78
  *
77
79
  * @param definitions - The parsed model to continue.
78
80
  * @param processId - Which process to continue, named explicitly.
@@ -382,7 +382,7 @@ const RULES = {
382
382
  const missing = (id, processId) => {
383
383
  if (drawn.has(id))
384
384
  return;
385
- report("pattern/missing-di", `Element "${id}" has no diagram information (BPMNDI).`, "Open and save the file in a modeler, or run `casen bpmn layout`, to draw it.", processId, [id]);
385
+ report("pattern/missing-di", `Element "${id}" has no diagram information (BPMNDI).`, "In a script, call `placeNewShapes(definitions)` before `exportPreserving` to draw only the new elements; redraw everything only for a new file.", processId, [id]);
386
386
  };
387
387
  const lanes = (list, processId) => {
388
388
  for (const lane of list) {
@@ -0,0 +1,51 @@
1
+ import type { BpmnDefinitions } from "./bpmn-model.js";
2
+ export interface PlaceNewShapesOptions {
3
+ /**
4
+ * Re-route existing edges whose ends no longer touch their shapes, such as a
5
+ * flow the edit re-pointed at a new element. Default `true`.
6
+ */
7
+ rerouteStale?: boolean;
8
+ /**
9
+ * Add a new flow node to the lane it is drawn in when no lane lists it, as a
10
+ * modeller does when a shape is dropped into a lane. Default `true`.
11
+ */
12
+ assignLanes?: boolean;
13
+ }
14
+ export interface PlaceNewShapesResult {
15
+ /** A copy of the input with the new shapes and edges; the input is not changed. */
16
+ definitions: BpmnDefinitions;
17
+ /** Elements that got a shape: flow nodes, pools, annotations. */
18
+ placed: string[];
19
+ /** Connections that got an edge: sequence flows, message flows, associations. */
20
+ routed: string[];
21
+ /** Existing edges that got a new route because their ends no longer met their shapes. */
22
+ rerouted: string[];
23
+ /** Pools, lanes and sub-processes made larger so the new shapes fit. */
24
+ resized: string[];
25
+ /** Flow nodes added to a lane's `flowNodeRefs`. */
26
+ laneAssigned: string[];
27
+ /** What could not be placed, and why. */
28
+ unplaced: Array<{
29
+ id: string;
30
+ reason: string;
31
+ }>;
32
+ }
33
+ /**
34
+ * Gives every element that has no shape a place next to what it connects to,
35
+ * and every connection that has no edge a route, without moving existing shapes.
36
+ *
37
+ * Use it after editing a parsed file and before {@link exportPreserving}:
38
+ *
39
+ * ```ts
40
+ * const original = readFileSync("order.bpmn", "utf8")
41
+ * const defs = Bpmn.parse(original)
42
+ * // … add elements and flows to defs …
43
+ * const { definitions, unplaced } = placeNewShapes(defs)
44
+ * writeFileSync("order.bpmn", exportPreserving(original, definitions))
45
+ * ```
46
+ *
47
+ * New lanes are not placed: they need room inside a pool, which means moving
48
+ * the lanes below. They are reported in `unplaced`.
49
+ */
50
+ export declare function placeNewShapes(input: BpmnDefinitions, options?: PlaceNewShapesOptions): PlaceNewShapesResult;
51
+ //# sourceMappingURL=place-new-shapes.d.ts.map