@bpmnkit/core 0.2.0 → 0.4.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 (42) hide show
  1. package/dist/bpmn/bpmn-builder.d.ts +71 -0
  2. package/dist/bpmn/bpmn-builder.js +240 -106
  3. package/dist/bpmn/bpmn-serializer.js +70 -0
  4. package/dist/bpmn/builder-coverage.d.ts +59 -0
  5. package/dist/bpmn/builder-coverage.js +62 -0
  6. package/dist/bpmn/compact.d.ts +6 -0
  7. package/dist/bpmn/compact.js +37 -2
  8. package/dist/bpmn/diagram-diff.d.ts +71 -0
  9. package/dist/bpmn/diagram-diff.js +124 -0
  10. package/dist/bpmn/element-catalog.d.ts +31 -0
  11. package/dist/bpmn/element-catalog.js +50 -0
  12. package/dist/bpmn/element-shape.d.ts +49 -0
  13. package/dist/bpmn/element-shape.js +182 -0
  14. package/dist/bpmn/lint.d.ts +97 -0
  15. package/dist/bpmn/lint.js +135 -0
  16. package/dist/bpmn/preserving-writer.d.ts +64 -0
  17. package/dist/bpmn/preserving-writer.js +70 -0
  18. package/dist/bpmn/stable-ids.d.ts +30 -0
  19. package/dist/bpmn/stable-ids.js +134 -0
  20. package/dist/dmn/dmn-serializer.js +7 -2
  21. package/dist/dmn/preserving-writer.d.ts +31 -0
  22. package/dist/dmn/preserving-writer.js +36 -0
  23. package/dist/form/preserving-writer.d.ts +47 -0
  24. package/dist/form/preserving-writer.js +50 -0
  25. package/dist/index.d.ts +15 -1
  26. package/dist/index.js +9 -1
  27. package/dist/json/index.d.ts +5 -0
  28. package/dist/json/index.js +3 -0
  29. package/dist/json/json-patch.d.ts +65 -0
  30. package/dist/json/json-patch.js +416 -0
  31. package/dist/json/json-spans.d.ts +48 -0
  32. package/dist/json/json-spans.js +153 -0
  33. package/dist/layout/types.js +4 -0
  34. package/dist/xml/index.d.ts +5 -1
  35. package/dist/xml/index.js +2 -0
  36. package/dist/xml/xml-parser.d.ts +39 -0
  37. package/dist/xml/xml-parser.js +43 -2
  38. package/dist/xml/xml-patch.d.ts +109 -0
  39. package/dist/xml/xml-patch.js +459 -0
  40. package/dist/xml/xml-spans.d.ts +45 -0
  41. package/dist/xml/xml-spans.js +74 -0
  42. package/package.json +2 -1
@@ -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
@@ -0,0 +1,30 @@
1
+ import type { BpmnFlowElement, BpmnSequenceFlow } from "./bpmn-model.js";
2
+ /**
3
+ * Replaces generated sequence-flow ids in one scope (a process or a
4
+ * sub-process) with ids derived from the flows themselves, and rewrites the
5
+ * `default` attributes that name them.
6
+ *
7
+ * Run it after the topology is final — after join inference and any pending
8
+ * splice — and before `incoming`/`outgoing` are recomputed.
9
+ *
10
+ * @param elements - The scope's flow elements. Their ids are reserved, and
11
+ * gateway `default` references are rewritten.
12
+ * @param flows - The scope's sequence flows, mutated in place.
13
+ * @param preserve - Ids to leave alone, for flows the builder did not create:
14
+ * continuing a parsed document must not renumber what it was handed.
15
+ */
16
+ export declare function assignStableFlowIds(elements: BpmnFlowElement[], flows: BpmnSequenceFlow[], preserve?: ReadonlySet<string>): void;
17
+ /**
18
+ * Derives a root definition's id from what callers look it up by — a message or
19
+ * signal name, an error or escalation code — so the same declaration keeps the
20
+ * same id across rebuilds.
21
+ *
22
+ * @param prefix - Element kind, e.g. `"Message"`.
23
+ * @param source - The name or code the definition is resolved by.
24
+ * @param existing - Definitions of the same kind already declared, whose ids
25
+ * the result is deduped against.
26
+ */
27
+ export declare function rootDefinitionId(prefix: string, source: string, existing: ReadonlyArray<{
28
+ id: string;
29
+ }>): string;
30
+ //# sourceMappingURL=stable-ids.d.ts.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Stable, content-derived ids for the parts of a model the caller does not name:
3
+ * sequence flows, and the root messages, errors, signals and escalations that
4
+ * event options declare.
5
+ *
6
+ * The fluent builder used to mint these with `generateId()`, so rebuilding an
7
+ * unchanged model produced different BPMN every time — noisy diffs, and a
8
+ * review that cannot tell a renamed edge from a new one. These ids come from
9
+ * the model instead: for a flow, the endpoints it connects plus a discriminator
10
+ * when one pair carries several flows; for a root definition, the name or code
11
+ * it is looked up by.
12
+ *
13
+ * Flow ids are assigned in a pass over a finished scope rather than at creation
14
+ * time, because a flow's endpoints are not final when it is created —
15
+ * `insertAfter()` re-points a flow's source, and `insertJoinGateways()`
16
+ * re-points its target.
17
+ */
18
+ import { slugify, uniqueId } from "../plan/slug.js";
19
+ /** Longest id this produces; anything longer is truncated and hashed. */
20
+ const MAX_ID_LENGTH = 200;
21
+ /**
22
+ * FNV-1a, base36. Not a checksum anyone verifies — just a short, stable
23
+ * discriminator for two flows the model distinguishes only by a long string.
24
+ */
25
+ function shortHash(text) {
26
+ let hash = 0x811c9dc5;
27
+ for (let i = 0; i < text.length; i++) {
28
+ hash ^= text.charCodeAt(i);
29
+ hash = Math.imul(hash, 0x01000193) >>> 0;
30
+ }
31
+ return hash.toString(36);
32
+ }
33
+ /** Keeps an id an XML NCName: letters, digits, `_` and `-`, never leading with a digit. */
34
+ function ncName(text) {
35
+ const cleaned = text.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^[^A-Za-z_]+/, "");
36
+ return cleaned.length > 0 ? cleaned : "x";
37
+ }
38
+ /** Truncates over-long ids, keeping them distinct by appending a hash of what was dropped. */
39
+ function capLength(id) {
40
+ if (id.length <= MAX_ID_LENGTH)
41
+ return id;
42
+ const suffix = `_${shortHash(id)}`;
43
+ return id.slice(0, MAX_ID_LENGTH - suffix.length) + suffix;
44
+ }
45
+ /** The id a flow gets when it is the only one between its two endpoints. */
46
+ function baseId(flow) {
47
+ return capLength(`Flow_${ncName(flow.sourceRef)}_${ncName(flow.targetRef)}`);
48
+ }
49
+ /**
50
+ * What tells two flows between the same endpoints apart, in order of how
51
+ * readable it is: the branch name, then the condition, then nothing — leaving
52
+ * `uniqueId` to number genuinely identical edges.
53
+ */
54
+ function discriminator(flow) {
55
+ if (flow.name !== undefined && flow.name.trim().length > 0)
56
+ return ncName(slugify(flow.name));
57
+ const condition = flow.conditionExpression?.text;
58
+ if (condition !== undefined && condition.trim().length > 0)
59
+ return `c${shortHash(condition)}`;
60
+ return undefined;
61
+ }
62
+ /**
63
+ * Replaces generated sequence-flow ids in one scope (a process or a
64
+ * sub-process) with ids derived from the flows themselves, and rewrites the
65
+ * `default` attributes that name them.
66
+ *
67
+ * Run it after the topology is final — after join inference and any pending
68
+ * splice — and before `incoming`/`outgoing` are recomputed.
69
+ *
70
+ * @param elements - The scope's flow elements. Their ids are reserved, and
71
+ * gateway `default` references are rewritten.
72
+ * @param flows - The scope's sequence flows, mutated in place.
73
+ * @param preserve - Ids to leave alone, for flows the builder did not create:
74
+ * continuing a parsed document must not renumber what it was handed.
75
+ */
76
+ export function assignStableFlowIds(elements, flows, preserve) {
77
+ const renamable = preserve === undefined ? flows : flows.filter((flow) => !preserve.has(flow.id));
78
+ if (renamable.length === 0)
79
+ return;
80
+ // Reserved up front so a derived id can never land on an element id or on a
81
+ // flow id this pass is not allowed to touch.
82
+ const taken = new Set(elements.map((element) => element.id));
83
+ if (preserve !== undefined) {
84
+ for (const flow of flows)
85
+ if (preserve.has(flow.id))
86
+ taken.add(flow.id);
87
+ }
88
+ // Flows sharing a base id all get a discriminator, so which one was built
89
+ // first — and so the order branches were declared in — does not decide who
90
+ // keeps the short id.
91
+ const byBase = new Map();
92
+ for (const flow of renamable) {
93
+ const base = baseId(flow);
94
+ const group = byBase.get(base);
95
+ if (group)
96
+ group.push(flow);
97
+ else
98
+ byBase.set(base, [flow]);
99
+ }
100
+ const renamed = new Map();
101
+ for (const [base, group] of byBase) {
102
+ for (const flow of group) {
103
+ const qualifier = group.length > 1 ? discriminator(flow) : undefined;
104
+ const id = uniqueId(qualifier === undefined ? base : capLength(`${base}_${qualifier}`), taken);
105
+ if (id !== flow.id)
106
+ renamed.set(flow.id, id);
107
+ flow.id = id;
108
+ }
109
+ }
110
+ if (renamed.size === 0)
111
+ return;
112
+ for (const element of elements) {
113
+ if (!("default" in element) || element.default === undefined)
114
+ continue;
115
+ const replacement = renamed.get(element.default);
116
+ if (replacement !== undefined)
117
+ element.default = replacement;
118
+ }
119
+ }
120
+ /**
121
+ * Derives a root definition's id from what callers look it up by — a message or
122
+ * signal name, an error or escalation code — so the same declaration keeps the
123
+ * same id across rebuilds.
124
+ *
125
+ * @param prefix - Element kind, e.g. `"Message"`.
126
+ * @param source - The name or code the definition is resolved by.
127
+ * @param existing - Definitions of the same kind already declared, whose ids
128
+ * the result is deduped against.
129
+ */
130
+ export function rootDefinitionId(prefix, source, existing) {
131
+ const taken = new Set(existing.map((definition) => definition.id));
132
+ return uniqueId(capLength(`${prefix}_${ncName(slugify(source))}`), taken);
133
+ }
134
+ //# sourceMappingURL=stable-ids.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 = [
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The BPMN preserving writer's counterpart for decision documents.
3
+ *
4
+ * Same problem, same shape, one difference worth naming: **DMN rule order is
5
+ * meaning**, not layout. A table with hit policy `FIRST` returns the first rule
6
+ * that matches, so moving a rule up changes what the decision decides. The
7
+ * strategy that keeps the file's own sibling order would quietly undo exactly
8
+ * that edit — which is why every strategy is checked against a plain write
9
+ * before it is used, and why this is a wrapper over the same verified ladder
10
+ * rather than a second implementation of it.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ import { type VerifiedPreserve } from "../xml/xml-patch.js";
15
+ import type { DmnDefinitions } from "./dmn-model.js";
16
+ /**
17
+ * Rewrites a decision document to say what a freshly serialized one says,
18
+ * keeping the original's formatting wherever a DMN reader cannot tell.
19
+ *
20
+ * @param original - The file's current contents.
21
+ * @param updated - The document as the serializer would write it now.
22
+ */
23
+ export declare function preserveDmnFormatting(original: string, updated: string): VerifiedPreserve;
24
+ /**
25
+ * Serializes a decision model over the document it came from.
26
+ *
27
+ * @param original - The file's current contents.
28
+ * @param definitions - The model to write.
29
+ */
30
+ export declare function exportDmnPreserving(original: string, definitions: DmnDefinitions): string;
31
+ //# sourceMappingURL=preserving-writer.d.ts.map
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The BPMN preserving writer's counterpart for decision documents.
3
+ *
4
+ * Same problem, same shape, one difference worth naming: **DMN rule order is
5
+ * meaning**, not layout. A table with hit policy `FIRST` returns the first rule
6
+ * that matches, so moving a rule up changes what the decision decides. The
7
+ * strategy that keeps the file's own sibling order would quietly undo exactly
8
+ * that edit — which is why every strategy is checked against a plain write
9
+ * before it is used, and why this is a wrapper over the same verified ladder
10
+ * rather than a second implementation of it.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ import { preserveFormattingVerified } from "../xml/xml-patch.js";
15
+ import { parseDmn } from "./dmn-parser.js";
16
+ import { serializeDmn } from "./dmn-serializer.js";
17
+ /**
18
+ * Rewrites a decision document to say what a freshly serialized one says,
19
+ * keeping the original's formatting wherever a DMN reader cannot tell.
20
+ *
21
+ * @param original - The file's current contents.
22
+ * @param updated - The document as the serializer would write it now.
23
+ */
24
+ export function preserveDmnFormatting(original, updated) {
25
+ return preserveFormattingVerified(original, updated, parseDmn);
26
+ }
27
+ /**
28
+ * Serializes a decision model over the document it came from.
29
+ *
30
+ * @param original - The file's current contents.
31
+ * @param definitions - The model to write.
32
+ */
33
+ export function exportDmnPreserving(original, definitions) {
34
+ return preserveDmnFormatting(original, serializeDmn(definitions)).xml;
35
+ }
36
+ //# sourceMappingURL=preserving-writer.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Writing a form back over the file it came from, changing as little as
3
+ * possible.
4
+ *
5
+ * The BPMN and DMN writers' counterpart, and the simpler of the two because a
6
+ * form is JSON. There is no schema question to get wrong: object key order is
7
+ * not information and array order always is, both by RFC 8259, so
8
+ * {@link preserveJsonFormatting} checks itself and this needs to supply
9
+ * nothing.
10
+ *
11
+ * What it buys is larger than it sounds. `exportForm` writes
12
+ * `JSON.stringify(…, null, 2)` in its own key order, so a form indented with
13
+ * tabs — or with four spaces, or minified — came back with **every line
14
+ * rewritten** the first time anyone touched it. Now it comes back with the line
15
+ * they touched.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { type PreservedJson } from "../json/json-patch.js";
20
+ import type { FormDefinition } from "./form-model.js";
21
+ export type { PreservedJson };
22
+ /**
23
+ * Rewrites a form document to say what a freshly serialized one says, keeping
24
+ * the original's formatting wherever JSON cannot tell the difference.
25
+ *
26
+ * Takes both sides as text, for a caller holding a serialized document rather
27
+ * than a model — an editor's schema, say.
28
+ *
29
+ * @param original - The file's current contents.
30
+ * @param updated - The form as the serializer would write it now.
31
+ */
32
+ export declare function preserveFormFormatting(original: string, updated: string): PreservedJson;
33
+ /**
34
+ * Serializes a form over the document it came from.
35
+ *
36
+ * @param original - The file's current contents.
37
+ * @param form - The form to write.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const onDisk = await readFile("approval.form", "utf8");
42
+ * await writeFile("approval.form", exportFormPreserving(onDisk, edited));
43
+ * // Renaming one label changes one line, whatever indentation the file uses.
44
+ * ```
45
+ */
46
+ export declare function exportFormPreserving(original: string, form: FormDefinition): string;
47
+ //# sourceMappingURL=preserving-writer.d.ts.map