@bpmnkit/core 0.2.0 → 0.3.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.
@@ -647,6 +647,76 @@ export function serializeBpmn(definitions) {
647
647
  children.push(serializeDiagram(d, ns));
648
648
  }
649
649
  const root = el(`${bp}:definitions`, attrs, children);
650
+ declareUsedNamespaces(root, attrs);
650
651
  return serializeXml(root);
651
652
  }
653
+ /**
654
+ * URIs for the extension prefixes a document can acquire after it was parsed.
655
+ *
656
+ * Scoped deliberately to extension namespaces — the ones that arrive on content
657
+ * the serializer keeps verbatim, where nothing else is in a position to declare
658
+ * them. A caller adds a `zeebe:taskDefinition` to an element and has no handle
659
+ * on the definitions to declare `zeebe` with.
660
+ *
661
+ * The structural prefixes (`bpmn`, `bpmndi`, `dc`, `di`) are deliberately
662
+ * absent. The serializer emits those itself, so a model carrying a diagram it
663
+ * never declared namespaces for is a different gap with a different owner —
664
+ * and repairing it here would change the model a round trip produces, which
665
+ * `semanticHash` and the `writeBpmn` boundary both hold constant on purpose.
666
+ * Recorded in doc/roadmap.md rather than fixed in passing.
667
+ */
668
+ const KNOWN_NAMESPACE_URIS = {
669
+ zeebe: "http://camunda.org/schema/zeebe/1.0",
670
+ camunda: "http://camunda.org/schema/1.0/bpmn",
671
+ modeler: "http://camunda.org/schema/modeler/1.0",
672
+ bioc: "http://bpmn.io/schema/bpmn/biocolor/1.0",
673
+ color: "http://www.omg.org/spec/BPMN/non-normative/color/1.0",
674
+ };
675
+ /** Prefixes an element tree uses, and prefixes it declares — at any depth. */
676
+ function collectPrefixes(node, used, declared) {
677
+ const nameParts = node.name.split(":");
678
+ if (nameParts.length > 1 && nameParts[0] !== undefined)
679
+ used.add(nameParts[0]);
680
+ for (const key of Object.keys(node.attributes)) {
681
+ if (key.startsWith("xmlns:")) {
682
+ declared.add(key.slice("xmlns:".length));
683
+ continue;
684
+ }
685
+ if (key === "xmlns")
686
+ continue;
687
+ const parts = key.split(":");
688
+ if (parts.length > 1 && parts[0] !== undefined)
689
+ used.add(parts[0]);
690
+ }
691
+ for (const child of node.children)
692
+ collectPrefixes(child, used, declared);
693
+ }
694
+ /**
695
+ * Declares any namespace the document uses but does not announce.
696
+ *
697
+ * A model parsed from a vendor-neutral file has no `zeebe` declaration; give
698
+ * one of its tasks a `zeebe:taskDefinition` — which is what applying a
699
+ * connector template does — and the export would otherwise carry a prefix
700
+ * bound to nothing. That is not merely untidy: the document is no longer
701
+ * namespace-well-formed, and a conforming reader is entitled to reject it.
702
+ *
703
+ * Only prefixes with a known URI are repaired, and only when the model has not
704
+ * already bound them; a document that declares its own mapping keeps it.
705
+ */
706
+ function declareUsedNamespaces(root, attrs) {
707
+ const used = new Set();
708
+ const declared = new Set();
709
+ collectPrefixes(root, used, declared);
710
+ for (const prefix of used) {
711
+ // Declared anywhere counts. A model can bind a prefix on a nested element
712
+ // — `xsi` on an `extensionElements` child is common — and the parser keeps
713
+ // only root-level bindings in `namespaces`, so looking at the root alone
714
+ // would hoist a duplicate declaration and change a document that was fine.
715
+ if (declared.has(prefix))
716
+ continue;
717
+ const uri = KNOWN_NAMESPACE_URIS[prefix];
718
+ if (uri !== undefined)
719
+ attrs[`xmlns:${prefix}`] = uri;
720
+ }
721
+ }
652
722
  //# sourceMappingURL=bpmn-serializer.js.map
@@ -0,0 +1,71 @@
1
+ import type { BpmnDefinitions } from "./bpmn-model.js";
2
+ /**
3
+ * How an element differs between two versions of a diagram.
4
+ *
5
+ * - `added` — present only in the later model.
6
+ * - `removed` — present only in the earlier model.
7
+ * - `changed` — the model changed (a property, an expression, an extension).
8
+ * - `moved` — the model is identical but the picture is not: position, size,
9
+ * waypoints, label placement, or a diagram flag such as collapsed/expanded.
10
+ *
11
+ * An element that is both changed and moved is reported as `changed` — a
12
+ * semantic change is what a reviewer needs to see first.
13
+ */
14
+ export type BpmnDiffCategory = "added" | "removed" | "changed" | "moved";
15
+ /**
16
+ * How many differences fall on one diagram plane.
17
+ *
18
+ * A plane is a drawing surface: the process itself, and one more for each
19
+ * collapsed sub-process. A viewer shows one at a time, so a change inside a
20
+ * collapsed sub-process is invisible until the reader drills into it — these
21
+ * counts are what tells them there is something down there to look at.
22
+ */
23
+ export interface BpmnDiffPlaneSummary {
24
+ /** The plane's `bpmnElement` — the process or sub-process it draws. */
25
+ readonly id: string;
26
+ readonly added: number;
27
+ readonly removed: number;
28
+ readonly changed: number;
29
+ readonly moved: number;
30
+ readonly total: number;
31
+ }
32
+ /**
33
+ * What changed between two diagrams, as element ids per category.
34
+ *
35
+ * Restricted to elements that carry diagram interchange on at least one side —
36
+ * those are exactly the elements a canvas can show. A change with nothing to
37
+ * draw (a `targetNamespace`, an exporter attribute) is not a visual diff and is
38
+ * left out, so the counts match what the reviewer actually sees.
39
+ */
40
+ export interface BpmnDiffResult {
41
+ readonly added: readonly string[];
42
+ readonly removed: readonly string[];
43
+ readonly changed: readonly string[];
44
+ readonly moved: readonly string[];
45
+ /** `added.length + removed.length + changed.length + moved.length`. */
46
+ readonly total: number;
47
+ /** Per-plane breakdown, planes with no differences omitted, ordered by id. */
48
+ readonly planes: readonly BpmnDiffPlaneSummary[];
49
+ }
50
+ /**
51
+ * Compares two BPMN diagrams and reports what a reviewer would see change.
52
+ *
53
+ * The semantic half is {@link diffSemantics}, which excludes diagram
54
+ * interchange by design — so a pure layout change reads as "no change" there.
55
+ * This adds the layout half back as its own category, which is the difference
56
+ * between a model diff and a *diagram* diff.
57
+ *
58
+ * @param before - The earlier model.
59
+ * @param after - The later model.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const result = diffDiagram(Bpmn.parse(oldXml), Bpmn.parse(newXml));
64
+ * console.log(`${result.changed.length} changed, ${result.moved.length} moved`);
65
+ * for (const plane of result.planes) {
66
+ * console.log(` ${plane.id}: ${plane.total}`);
67
+ * }
68
+ * ```
69
+ */
70
+ export declare function diffDiagram(before: BpmnDefinitions, after: BpmnDefinitions): BpmnDiffResult;
71
+ //# sourceMappingURL=diagram-diff.d.ts.map
@@ -0,0 +1,124 @@
1
+ import { diffSemantics } from "./semantic-hash.js";
2
+ /**
3
+ * Rounds to two decimals so re-serialising a file cannot register as a move.
4
+ * BPMN coordinates are usually integers, but a round trip through a modeler can
5
+ * leave `100` as `100.00000000000001`.
6
+ */
7
+ function round(value) {
8
+ return Math.round(value * 100) / 100;
9
+ }
10
+ function shapeKey(shape) {
11
+ const { x, y, width, height } = shape.bounds;
12
+ const label = shape.label?.bounds;
13
+ return [
14
+ round(x),
15
+ round(y),
16
+ round(width),
17
+ round(height),
18
+ shape.isExpanded ?? "",
19
+ shape.isMarkerVisible ?? "",
20
+ shape.isHorizontal ?? "",
21
+ label === undefined ? "" : `${round(label.x)},${round(label.y)}`,
22
+ ].join("|");
23
+ }
24
+ function edgeKey(edge) {
25
+ const label = edge.label?.bounds;
26
+ return [
27
+ edge.waypoints.map((p) => `${round(p.x)},${round(p.y)}`).join(" "),
28
+ label === undefined ? "" : `${round(label.x)},${round(label.y)}`,
29
+ ].join("|");
30
+ }
31
+ /** Indexes every element that carries diagram interchange, in any plane. */
32
+ function indexLayout(definitions) {
33
+ const index = new Map();
34
+ for (const diagram of definitions.diagrams) {
35
+ const plane = diagram.plane.bpmnElement;
36
+ for (const shape of diagram.plane.shapes) {
37
+ index.set(shape.bpmnElement, { plane, key: shapeKey(shape) });
38
+ }
39
+ for (const edge of diagram.plane.edges) {
40
+ index.set(edge.bpmnElement, { plane, key: edgeKey(edge) });
41
+ }
42
+ }
43
+ return index;
44
+ }
45
+ function summarisePlanes(assignments) {
46
+ const counts = new Map();
47
+ for (const [plane, category] of assignments) {
48
+ const entry = counts.get(plane) ?? { added: 0, removed: 0, changed: 0, moved: 0 };
49
+ entry[category] += 1;
50
+ counts.set(plane, entry);
51
+ }
52
+ return [...counts.entries()]
53
+ .map(([id, c]) => ({
54
+ id,
55
+ ...c,
56
+ total: c.added + c.removed + c.changed + c.moved,
57
+ }))
58
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
59
+ }
60
+ /**
61
+ * Compares two BPMN diagrams and reports what a reviewer would see change.
62
+ *
63
+ * The semantic half is {@link diffSemantics}, which excludes diagram
64
+ * interchange by design — so a pure layout change reads as "no change" there.
65
+ * This adds the layout half back as its own category, which is the difference
66
+ * between a model diff and a *diagram* diff.
67
+ *
68
+ * @param before - The earlier model.
69
+ * @param after - The later model.
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * const result = diffDiagram(Bpmn.parse(oldXml), Bpmn.parse(newXml));
74
+ * console.log(`${result.changed.length} changed, ${result.moved.length} moved`);
75
+ * for (const plane of result.planes) {
76
+ * console.log(` ${plane.id}: ${plane.total}`);
77
+ * }
78
+ * ```
79
+ */
80
+ export function diffDiagram(before, after) {
81
+ const beforeLayout = indexLayout(before);
82
+ const afterLayout = indexLayout(after);
83
+ /** Ids a canvas could draw on one side or the other. */
84
+ const drawable = new Set([...beforeLayout.keys(), ...afterLayout.keys()]);
85
+ const semantic = diffSemantics(before, after);
86
+ const added = semantic.added.filter((id) => drawable.has(id));
87
+ const removed = semantic.removed.filter((id) => drawable.has(id));
88
+ const changed = semantic.changed.map((entry) => entry.id).filter((id) => drawable.has(id));
89
+ const changedIds = new Set(changed);
90
+ const moved = [];
91
+ for (const [id, placement] of afterLayout) {
92
+ if (changedIds.has(id))
93
+ continue;
94
+ const previous = beforeLayout.get(id);
95
+ if (previous !== undefined && previous.key !== placement.key)
96
+ moved.push(id);
97
+ }
98
+ moved.sort();
99
+ // An element is attributed to the plane that still draws it; only a removal
100
+ // has no later plane to belong to.
101
+ const planeOf = (id) => (afterLayout.get(id) ?? beforeLayout.get(id))?.plane;
102
+ const assignments = [];
103
+ for (const [category, ids] of [
104
+ ["added", added],
105
+ ["removed", removed],
106
+ ["changed", changed],
107
+ ["moved", moved],
108
+ ]) {
109
+ for (const id of ids) {
110
+ const plane = planeOf(id);
111
+ if (plane !== undefined)
112
+ assignments.push([plane, category]);
113
+ }
114
+ }
115
+ return {
116
+ added,
117
+ removed,
118
+ changed,
119
+ moved,
120
+ total: added.length + removed.length + changed.length + moved.length,
121
+ planes: summarisePlanes(assignments),
122
+ };
123
+ }
124
+ //# sourceMappingURL=diagram-diff.js.map
@@ -0,0 +1,97 @@
1
+ import type { BpmnDefinitions } from "./bpmn-model.js";
2
+ import type { OptimizationCategory, OptimizationSeverity, OptimizeOptions } from "./optimize/types.js";
3
+ /**
4
+ * The engine a model says it targets, read from `modeler:executionPlatform`.
5
+ *
6
+ * `none` is a real answer, not a failure: a diagram authored in a
7
+ * vendor-neutral tool names no engine, and judging it against one produces
8
+ * findings its author cannot act on.
9
+ */
10
+ export type ExecutionPlatform = "camunda-cloud" | "camunda-platform" | "none";
11
+ export interface DetectedPlatform {
12
+ id: ExecutionPlatform;
13
+ /** The raw attribute value, when there was one. */
14
+ name?: string;
15
+ version?: string;
16
+ }
17
+ /** A finding as plain data — no functions, so a host can forward it anywhere. */
18
+ export interface LintDiagnostic {
19
+ id: string;
20
+ severity: OptimizationSeverity;
21
+ category: OptimizationCategory;
22
+ message: string;
23
+ suggestion: string;
24
+ processId: string;
25
+ elementIds: string[];
26
+ /**
27
+ * The diagram plane the elements are drawn on, when they are drawn at all.
28
+ * A viewer shows one plane at a time, so a host needs this to say where to
29
+ * look rather than only what is wrong.
30
+ */
31
+ plane?: string;
32
+ /** Whether the live report carries an automatic fix for this finding. */
33
+ fixable: boolean;
34
+ }
35
+ export interface LintReport {
36
+ diagnostics: LintDiagnostic[];
37
+ /** The engine the model claims, and therefore which rules were applied. */
38
+ platform: DetectedPlatform;
39
+ /** Categories that were run — engine rules are dropped on a neutral model. */
40
+ categories: OptimizationCategory[];
41
+ counts: Record<OptimizationSeverity, number>;
42
+ total: number;
43
+ }
44
+ export interface LintOptions extends OptimizeOptions {
45
+ /**
46
+ * Run engine rules even when the model names no platform. Off by default:
47
+ * an engine-neutral diagram should not be told it is undeployable.
48
+ */
49
+ forceEngineRules?: boolean;
50
+ }
51
+ /**
52
+ * Reads the execution platform a model declares.
53
+ *
54
+ * @param definitions - The model to inspect.
55
+ */
56
+ export declare function detectExecutionPlatform(definitions: BpmnDefinitions): DetectedPlatform;
57
+ /**
58
+ * Runs the static analysis and returns it as plain, forwardable data.
59
+ *
60
+ * Two things this adds over calling {@link optimize} directly, both of them
61
+ * about handing findings to something that is not this process:
62
+ *
63
+ * - **The result is serialisable.** An `OptimizationFinding` carries an
64
+ * `applyFix` function, so it cannot cross a `postMessage` or a JSON boundary;
65
+ * a `LintDiagnostic` says `fixable: true` instead and leaves the fix where it
66
+ * can still be called.
67
+ * - **The rules match the model.** A diagram that names no execution platform
68
+ * is not judged against Camunda 8 deployability, so an engine-neutral file
69
+ * does not open covered in errors about extensions it was never going to
70
+ * have.
71
+ *
72
+ * @param definitions - The model to lint.
73
+ * @param options - Optimizer options, plus `forceEngineRules`.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const report = lintDiagram(Bpmn.parse(xml));
78
+ * for (const d of report.diagnostics) {
79
+ * console.log(`${d.severity} ${d.elementIds.join(",")}: ${d.message}`);
80
+ * }
81
+ * ```
82
+ */
83
+ export declare function lintDiagram(definitions: BpmnDefinitions, options?: LintOptions): LintReport;
84
+ /**
85
+ * The categories that should run against a given model.
86
+ *
87
+ * Exported because more than one surface needs the same answer and they must
88
+ * not disagree: the canvas plugin lints through {@link lintDiagram}, while
89
+ * `casen lint` calls `optimize` directly so it can keep the `applyFix` closures
90
+ * that `LintDiagnostic` deliberately drops. Both ask here which rules apply.
91
+ *
92
+ * @param definitions - The model whose execution platform decides.
93
+ * @param options - `categories` to narrow to, and `forceEngineRules` to keep
94
+ * the engine layer on a model that names no platform.
95
+ */
96
+ export declare function lintCategories(definitions: BpmnDefinitions, options?: Pick<LintOptions, "categories" | "forceEngineRules">): OptimizationCategory[];
97
+ //# sourceMappingURL=lint.d.ts.map
@@ -0,0 +1,135 @@
1
+ import { optimize } from "./optimize/index.js";
2
+ /**
3
+ * Categories whose findings only mean something against a Camunda 8 engine.
4
+ *
5
+ * Measured rather than assumed: on a model with no execution platform and no
6
+ * Zeebe extensions, every other category either stays quiet or reports
7
+ * something structural that holds regardless, while `deploy` reports
8
+ * "serviceTask has no zeebe:taskDefinition type" as an **error** — a demand the
9
+ * author never signed up for. `connector` and `agentic` are the same kind of
10
+ * claim about the same engine.
11
+ */
12
+ const ENGINE_CATEGORIES = ["deploy", "connector", "agentic"];
13
+ /**
14
+ * Reads the execution platform a model declares.
15
+ *
16
+ * @param definitions - The model to inspect.
17
+ */
18
+ export function detectExecutionPlatform(definitions) {
19
+ const name = definitions.unknownAttributes["modeler:executionPlatform"];
20
+ const version = definitions.unknownAttributes["modeler:executionPlatformVersion"];
21
+ if (name === undefined || name === "")
22
+ return { id: "none" };
23
+ const normalised = name.toLowerCase();
24
+ const id = normalised.includes("cloud")
25
+ ? "camunda-cloud"
26
+ : normalised.includes("camunda")
27
+ ? "camunda-platform"
28
+ : "none";
29
+ return version === undefined ? { id, name } : { id, name, version };
30
+ }
31
+ /** Maps every element that carries diagram interchange to the plane drawing it. */
32
+ function planeIndex(definitions) {
33
+ const index = new Map();
34
+ for (const diagram of definitions.diagrams) {
35
+ const plane = diagram.plane.bpmnElement;
36
+ for (const shape of diagram.plane.shapes)
37
+ index.set(shape.bpmnElement, plane);
38
+ for (const edge of diagram.plane.edges)
39
+ index.set(edge.bpmnElement, plane);
40
+ }
41
+ return index;
42
+ }
43
+ /**
44
+ * Runs the static analysis and returns it as plain, forwardable data.
45
+ *
46
+ * Two things this adds over calling {@link optimize} directly, both of them
47
+ * about handing findings to something that is not this process:
48
+ *
49
+ * - **The result is serialisable.** An `OptimizationFinding` carries an
50
+ * `applyFix` function, so it cannot cross a `postMessage` or a JSON boundary;
51
+ * a `LintDiagnostic` says `fixable: true` instead and leaves the fix where it
52
+ * can still be called.
53
+ * - **The rules match the model.** A diagram that names no execution platform
54
+ * is not judged against Camunda 8 deployability, so an engine-neutral file
55
+ * does not open covered in errors about extensions it was never going to
56
+ * have.
57
+ *
58
+ * @param definitions - The model to lint.
59
+ * @param options - Optimizer options, plus `forceEngineRules`.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const report = lintDiagram(Bpmn.parse(xml));
64
+ * for (const d of report.diagnostics) {
65
+ * console.log(`${d.severity} ${d.elementIds.join(",")}: ${d.message}`);
66
+ * }
67
+ * ```
68
+ */
69
+ export function lintDiagram(definitions, options = {}) {
70
+ const platform = detectExecutionPlatform(definitions);
71
+ const engineRules = options.forceEngineRules === true || platform.id !== "none";
72
+ const { forceEngineRules: _ignored, ...optimizeOptions } = options;
73
+ const report = optimize(definitions, optimizeOptions);
74
+ const requested = optimizeOptions.categories;
75
+ const findings = engineRules
76
+ ? report.findings
77
+ : report.findings.filter((f) => !ENGINE_CATEGORIES.includes(f.category));
78
+ const planes = planeIndex(definitions);
79
+ const diagnostics = findings.map((finding) => {
80
+ const plane = finding.elementIds.map((id) => planes.get(id)).find((p) => p !== undefined);
81
+ const base = {
82
+ id: finding.id,
83
+ severity: finding.severity,
84
+ category: finding.category,
85
+ message: finding.message,
86
+ suggestion: finding.suggestion,
87
+ processId: finding.processId,
88
+ elementIds: finding.elementIds,
89
+ fixable: finding.applyFix !== undefined,
90
+ };
91
+ return plane === undefined ? base : { ...base, plane };
92
+ });
93
+ const counts = { error: 0, warning: 0, info: 0 };
94
+ for (const diagnostic of diagnostics)
95
+ counts[diagnostic.severity] += 1;
96
+ return {
97
+ diagnostics,
98
+ platform,
99
+ categories: lintCategories(definitions, options),
100
+ counts,
101
+ total: diagnostics.length,
102
+ };
103
+ }
104
+ /** Every category the optimizer knows, in the order it runs them. */
105
+ const ALL_CATEGORIES = [
106
+ "feel",
107
+ "feel-syntax",
108
+ "flow",
109
+ "naming",
110
+ "task-reuse",
111
+ "extract",
112
+ "pattern",
113
+ "data-flow",
114
+ "deploy",
115
+ "agentic",
116
+ "connector",
117
+ ];
118
+ /**
119
+ * The categories that should run against a given model.
120
+ *
121
+ * Exported because more than one surface needs the same answer and they must
122
+ * not disagree: the canvas plugin lints through {@link lintDiagram}, while
123
+ * `casen lint` calls `optimize` directly so it can keep the `applyFix` closures
124
+ * that `LintDiagnostic` deliberately drops. Both ask here which rules apply.
125
+ *
126
+ * @param definitions - The model whose execution platform decides.
127
+ * @param options - `categories` to narrow to, and `forceEngineRules` to keep
128
+ * the engine layer on a model that names no platform.
129
+ */
130
+ export function lintCategories(definitions, options = {}) {
131
+ const base = options.categories ?? ALL_CATEGORIES;
132
+ const engineRules = options.forceEngineRules === true || detectExecutionPlatform(definitions).id !== "none";
133
+ return engineRules ? [...base] : base.filter((c) => !ENGINE_CATEGORIES.includes(c));
134
+ }
135
+ //# sourceMappingURL=lint.js.map
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Writing a model back over the file it came from, changing as little as
3
+ * possible.
4
+ *
5
+ * {@link serializeBpmn} writes a model the way this toolkit writes models. That
6
+ * is the right output for a new document and the wrong one for an existing
7
+ * file: the first visual edit reformats every line, and the commit says "the
8
+ * whole diagram" when it means "a box moved". These write the file that was
9
+ * already there, and change only what the model changed.
10
+ *
11
+ * ## Why order needs deciding, and why it is checked
12
+ *
13
+ * The model cannot represent the order a file writes its children in — a
14
+ * process holds `flowElements` and `sequenceFlows` as separate lists, a plane
15
+ * holds `shapes` and `edges` — so every serialization emits its own order, and
16
+ * a file written by another tool comes back reshuffled even when nothing
17
+ * changed. Keeping the original order is therefore worth more than keeping the
18
+ * indentation. The same goes for an attribute set to its schema default:
19
+ * `isExecutable="false"` disappears from a file that said it out loud.
20
+ *
21
+ * Neither is safe to assume in general, so neither is assumed. Each strategy is
22
+ * tried, the result is **parsed back and compared against a plain write**, and
23
+ * the first that reads the same is the one used. The plain write is the floor,
24
+ * so calling this is never worse than not.
25
+ *
26
+ * @packageDocumentation
27
+ */
28
+ import { type VerifiedPreserve } from "../xml/xml-patch.js";
29
+ import type { BpmnDefinitions } from "./bpmn-model.js";
30
+ export type { VerifiedPreserve as PreservingWriteResult };
31
+ /**
32
+ * Rewrites a document to say what a freshly serialized one says, keeping the
33
+ * original's formatting wherever a BPMN reader cannot tell the difference.
34
+ *
35
+ * Takes both sides as text, for a caller holding a serialized document rather
36
+ * than a model — an editor's `exportXml()`, say.
37
+ *
38
+ * @param original - The file's current contents.
39
+ * @param updated - The document as the serializer would write it now.
40
+ */
41
+ export declare function preserveBpmnFormatting(original: string, updated: string): VerifiedPreserve;
42
+ /**
43
+ * Serializes a model over the document it came from, and reports what it
44
+ * managed to keep.
45
+ *
46
+ * @param original - The file's current contents.
47
+ * @param definitions - The model to write.
48
+ */
49
+ export declare function exportPreservingResult(original: string, definitions: BpmnDefinitions): VerifiedPreserve;
50
+ /**
51
+ * Serializes a model over the document it came from.
52
+ *
53
+ * @param original - The file's current contents.
54
+ * @param definitions - The model to write.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const onDisk = await readFile("order.bpmn", "utf8");
59
+ * await writeFile("order.bpmn", exportPreserving(onDisk, edited));
60
+ * // Renaming one task changes one line, not the whole file.
61
+ * ```
62
+ */
63
+ export declare function exportPreserving(original: string, definitions: BpmnDefinitions): string;
64
+ //# sourceMappingURL=preserving-writer.d.ts.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Writing a model back over the file it came from, changing as little as
3
+ * possible.
4
+ *
5
+ * {@link serializeBpmn} writes a model the way this toolkit writes models. That
6
+ * is the right output for a new document and the wrong one for an existing
7
+ * file: the first visual edit reformats every line, and the commit says "the
8
+ * whole diagram" when it means "a box moved". These write the file that was
9
+ * already there, and change only what the model changed.
10
+ *
11
+ * ## Why order needs deciding, and why it is checked
12
+ *
13
+ * The model cannot represent the order a file writes its children in — a
14
+ * process holds `flowElements` and `sequenceFlows` as separate lists, a plane
15
+ * holds `shapes` and `edges` — so every serialization emits its own order, and
16
+ * a file written by another tool comes back reshuffled even when nothing
17
+ * changed. Keeping the original order is therefore worth more than keeping the
18
+ * indentation. The same goes for an attribute set to its schema default:
19
+ * `isExecutable="false"` disappears from a file that said it out loud.
20
+ *
21
+ * Neither is safe to assume in general, so neither is assumed. Each strategy is
22
+ * tried, the result is **parsed back and compared against a plain write**, and
23
+ * the first that reads the same is the one used. The plain write is the floor,
24
+ * so calling this is never worse than not.
25
+ *
26
+ * @packageDocumentation
27
+ */
28
+ import { preserveFormattingVerified } from "../xml/xml-patch.js";
29
+ import { parseBpmn } from "./bpmn-parser.js";
30
+ import { serializeBpmn } from "./bpmn-serializer.js";
31
+ /**
32
+ * Rewrites a document to say what a freshly serialized one says, keeping the
33
+ * original's formatting wherever a BPMN reader cannot tell the difference.
34
+ *
35
+ * Takes both sides as text, for a caller holding a serialized document rather
36
+ * than a model — an editor's `exportXml()`, say.
37
+ *
38
+ * @param original - The file's current contents.
39
+ * @param updated - The document as the serializer would write it now.
40
+ */
41
+ export function preserveBpmnFormatting(original, updated) {
42
+ return preserveFormattingVerified(original, updated, parseBpmn);
43
+ }
44
+ /**
45
+ * Serializes a model over the document it came from, and reports what it
46
+ * managed to keep.
47
+ *
48
+ * @param original - The file's current contents.
49
+ * @param definitions - The model to write.
50
+ */
51
+ export function exportPreservingResult(original, definitions) {
52
+ return preserveBpmnFormatting(original, serializeBpmn(definitions));
53
+ }
54
+ /**
55
+ * Serializes a model over the document it came from.
56
+ *
57
+ * @param original - The file's current contents.
58
+ * @param definitions - The model to write.
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const onDisk = await readFile("order.bpmn", "utf8");
63
+ * await writeFile("order.bpmn", exportPreserving(onDisk, edited));
64
+ * // Renaming one task changes one line, not the whole file.
65
+ * ```
66
+ */
67
+ export function exportPreserving(original, definitions) {
68
+ return exportPreservingResult(original, definitions).xml;
69
+ }
70
+ //# sourceMappingURL=preserving-writer.js.map
@@ -68,9 +68,14 @@ function serializeRule(rule) {
68
68
  }
69
69
  function serializeDecisionTable(table) {
70
70
  const attrs = { id: table.id };
71
- if (table.hitPolicy && table.hitPolicy !== "UNIQUE") {
71
+ // Written whenever the model has one, including `UNIQUE`. Omitting the
72
+ // schema default looked tidy and broke the round trip: the parser reads
73
+ // `hitPolicy="UNIQUE"` into the model, so dropping it here meant
74
+ // `parse(export(m))` no longer equalled `m` — and a preserving write, which
75
+ // checks itself against exactly that, had to throw away everything else it
76
+ // was keeping about the file.
77
+ if (table.hitPolicy)
72
78
  attrs.hitPolicy = table.hitPolicy;
73
- }
74
79
  if (table.aggregation)
75
80
  attrs.aggregation = table.aggregation;
76
81
  const children = [