@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.
- package/dist/bpmn/bpmn-serializer.js +70 -0
- package/dist/bpmn/diagram-diff.d.ts +71 -0
- package/dist/bpmn/diagram-diff.js +124 -0
- package/dist/bpmn/lint.d.ts +97 -0
- package/dist/bpmn/lint.js +135 -0
- package/dist/bpmn/preserving-writer.d.ts +64 -0
- package/dist/bpmn/preserving-writer.js +70 -0
- package/dist/dmn/dmn-serializer.js +7 -2
- package/dist/dmn/preserving-writer.d.ts +31 -0
- package/dist/dmn/preserving-writer.js +36 -0
- package/dist/form/preserving-writer.d.ts +47 -0
- package/dist/form/preserving-writer.js +50 -0
- package/dist/index.d.ts +12 -1
- package/dist/index.js +7 -1
- package/dist/json/index.d.ts +5 -0
- package/dist/json/index.js +3 -0
- package/dist/json/json-patch.d.ts +65 -0
- package/dist/json/json-patch.js +416 -0
- package/dist/json/json-spans.d.ts +48 -0
- package/dist/json/json-spans.js +153 -0
- package/dist/xml/index.d.ts +5 -1
- package/dist/xml/index.js +2 -0
- package/dist/xml/xml-parser.d.ts +39 -0
- package/dist/xml/xml-parser.js +43 -2
- package/dist/xml/xml-patch.d.ts +109 -0
- package/dist/xml/xml-patch.js +459 -0
- package/dist/xml/xml-spans.d.ts +45 -0
- package/dist/xml/xml-spans.js +74 -0
- package/package.json +1 -1
package/dist/xml/xml-parser.js
CHANGED
|
@@ -79,11 +79,26 @@ class XmlScanner {
|
|
|
79
79
|
colon = -1;
|
|
80
80
|
/** Position of the next "&" at or after the last place we looked, or -1 for none. */
|
|
81
81
|
nextAmp = 0;
|
|
82
|
+
// ── Source positions, recorded only for a sink that asked (XmlCursor) ────
|
|
83
|
+
wantSpans = false;
|
|
84
|
+
tagStart = 0;
|
|
85
|
+
tagEnd = 0;
|
|
86
|
+
endTagStart = 0;
|
|
87
|
+
endTagEnd = 0;
|
|
88
|
+
/** Attribute name → value span, rebuilt for each start tag. */
|
|
89
|
+
attrSpans = new Map();
|
|
90
|
+
attributeSpan(name) {
|
|
91
|
+
return this.attrSpans.get(name);
|
|
92
|
+
}
|
|
82
93
|
constructor(source) {
|
|
83
94
|
this.s = source;
|
|
84
95
|
this.n = source.length;
|
|
85
96
|
}
|
|
86
97
|
scan(sink) {
|
|
98
|
+
if (sink.cursor !== undefined) {
|
|
99
|
+
this.wantSpans = true;
|
|
100
|
+
sink.cursor(this);
|
|
101
|
+
}
|
|
87
102
|
while (this.i < this.n) {
|
|
88
103
|
this.skipWhitespace();
|
|
89
104
|
if (this.i >= this.n)
|
|
@@ -131,6 +146,7 @@ class XmlScanner {
|
|
|
131
146
|
}
|
|
132
147
|
const next = s.charCodeAt(this.i + 1);
|
|
133
148
|
if (next === SLASH) {
|
|
149
|
+
const endTagStart = this.i;
|
|
134
150
|
this.i += 2;
|
|
135
151
|
const closing = this.readName();
|
|
136
152
|
const name = open[open.length - 1];
|
|
@@ -141,6 +157,10 @@ class XmlScanner {
|
|
|
141
157
|
this.expectChar(GT, ">");
|
|
142
158
|
open.pop();
|
|
143
159
|
wantText.pop();
|
|
160
|
+
if (this.wantSpans) {
|
|
161
|
+
this.endTagStart = endTagStart;
|
|
162
|
+
this.endTagEnd = this.i;
|
|
163
|
+
}
|
|
144
164
|
sink.end(name);
|
|
145
165
|
}
|
|
146
166
|
else if (next === BANG) {
|
|
@@ -173,19 +193,34 @@ class XmlScanner {
|
|
|
173
193
|
*/
|
|
174
194
|
openTag(sink, open, wantText) {
|
|
175
195
|
const s = this.s;
|
|
196
|
+
const tagStart = this.i;
|
|
176
197
|
this.i++; // <
|
|
177
198
|
const name = this.readName();
|
|
178
199
|
const local = this.colon >= 0 ? s.substring(this.colon + 1, this.i) : name;
|
|
179
200
|
const attributes = {};
|
|
201
|
+
if (this.wantSpans)
|
|
202
|
+
this.attrSpans.clear();
|
|
180
203
|
this.readAttributes(attributes);
|
|
181
204
|
this.skipWhitespace();
|
|
182
205
|
if (s.charCodeAt(this.i) === SLASH && s.charCodeAt(this.i + 1) === GT) {
|
|
183
206
|
this.i += 2;
|
|
207
|
+
if (this.wantSpans) {
|
|
208
|
+
this.tagStart = tagStart;
|
|
209
|
+
// A self-closing tag is its own end tag; both spans name the same text
|
|
210
|
+
// so a sink does not have to special-case it.
|
|
211
|
+
this.tagEnd = this.i;
|
|
212
|
+
this.endTagStart = this.i;
|
|
213
|
+
this.endTagEnd = this.i;
|
|
214
|
+
}
|
|
184
215
|
if (sink.start(name, local, attributes, true) !== Visit.Skip)
|
|
185
216
|
sink.end(name);
|
|
186
217
|
return open.length;
|
|
187
218
|
}
|
|
188
219
|
this.expectChar(GT, ">");
|
|
220
|
+
if (this.wantSpans) {
|
|
221
|
+
this.tagStart = tagStart;
|
|
222
|
+
this.tagEnd = this.i;
|
|
223
|
+
}
|
|
189
224
|
const visit = sink.start(name, local, attributes, false);
|
|
190
225
|
if (visit === Visit.Skip) {
|
|
191
226
|
this.skipContent(name);
|
|
@@ -281,7 +316,11 @@ class XmlScanner {
|
|
|
281
316
|
this.skipWhitespace();
|
|
282
317
|
this.expectChar(EQ, "=");
|
|
283
318
|
this.skipWhitespace();
|
|
319
|
+
const valueStart = this.i + 1;
|
|
284
320
|
attrs[key] = this.readAttrValue();
|
|
321
|
+
// `readAttrValue` leaves `i` just past the closing quote.
|
|
322
|
+
if (this.wantSpans)
|
|
323
|
+
this.attrSpans.set(key, { start: valueStart, end: this.i - 1 });
|
|
285
324
|
}
|
|
286
325
|
}
|
|
287
326
|
/** Like readAttributes, but validates only; nothing is built. */
|
|
@@ -514,12 +553,14 @@ const ESCAPES = {
|
|
|
514
553
|
function escapeChar(ch) {
|
|
515
554
|
return ESCAPES[ch] ?? ch;
|
|
516
555
|
}
|
|
517
|
-
|
|
556
|
+
/** Escapes a value for use between attribute quotes. */
|
|
557
|
+
export function escapeAttr(value) {
|
|
518
558
|
if (!ATTR_ESCAPE_RE.test(value))
|
|
519
559
|
return value;
|
|
520
560
|
return value.replace(ATTR_ESCAPE_ALL_RE, escapeChar);
|
|
521
561
|
}
|
|
522
|
-
|
|
562
|
+
/** Escapes a value for use as character data. */
|
|
563
|
+
export function escapeText(value) {
|
|
523
564
|
if (!TEXT_ESCAPE_RE.test(value))
|
|
524
565
|
return value;
|
|
525
566
|
return value.replace(TEXT_ESCAPE_ALL_RE, escapeChar);
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewriting a document in place, so an edit reads as an edit.
|
|
3
|
+
*
|
|
4
|
+
* A serializer given a model produces its own formatting: its indentation, its
|
|
5
|
+
* attribute order, its choice of ` ` over `
`. That is correct output
|
|
6
|
+
* and a terrible diff. Move one element in a visual editor and every line of
|
|
7
|
+
* the file changes, so the commit says "the whole diagram" when it means "a box
|
|
8
|
+
* moved forty pixels" — and a reviewer has no way to tell those apart.
|
|
9
|
+
*
|
|
10
|
+
* {@link preserveFormatting} closes that gap without either side having to know
|
|
11
|
+
* about the other. It takes the document as it was and the document as the
|
|
12
|
+
* serializer would write it, and returns a third: the *content* of the second
|
|
13
|
+
* carried by the *bytes* of the first, everywhere the two agree. No model is
|
|
14
|
+
* involved, which is why it serves BPMN, DMN, forms and anything else this
|
|
15
|
+
* toolkit learns to write.
|
|
16
|
+
*
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
/** How to treat children that appear in both documents in a different order. */
|
|
20
|
+
export type SiblingOrder =
|
|
21
|
+
/**
|
|
22
|
+
* Reorder to match `updated`. Correct for any document, and the default:
|
|
23
|
+
* sibling order carries meaning in plenty of XML, and nothing here can tell
|
|
24
|
+
* which document that is.
|
|
25
|
+
*/
|
|
26
|
+
"follow"
|
|
27
|
+
/**
|
|
28
|
+
* Leave matched children where the original had them, patching each in
|
|
29
|
+
* place. Only correct where sibling order says nothing — which is a fact
|
|
30
|
+
* about a *schema*, so a caller choosing this should check the result rather
|
|
31
|
+
* than assume it. `exportPreserving` in the BPMN module is the worked
|
|
32
|
+
* example: it tries this, verifies the parsed model is unchanged, and falls
|
|
33
|
+
* back when it is not.
|
|
34
|
+
*/
|
|
35
|
+
| "keep";
|
|
36
|
+
export interface PreserveOptions {
|
|
37
|
+
/** Default `"follow"`. */
|
|
38
|
+
readonly siblingOrder?: SiblingOrder;
|
|
39
|
+
/**
|
|
40
|
+
* What to do about an attribute the original has and the update does not.
|
|
41
|
+
*
|
|
42
|
+
* - `"remove"` (default) — take it out, because the update says so.
|
|
43
|
+
* - `"keep"` — leave it. A serializer omits an attribute set to its schema
|
|
44
|
+
* default, so `isExecutable="false"` disappears from a file that said it
|
|
45
|
+
* out loud. Keeping it is only safe when re-reading the result gives the
|
|
46
|
+
* same model, which is a check the caller has to make; see
|
|
47
|
+
* `exportPreserving` in the BPMN module.
|
|
48
|
+
*/
|
|
49
|
+
readonly droppedAttributes?: "remove" | "keep";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Rewrites `original` to say what `updated` says, changing as little as it can.
|
|
53
|
+
*
|
|
54
|
+
* The result is `updated`'s document — the same elements, attributes and text —
|
|
55
|
+
* written with `original`'s formatting wherever the two agree. An element
|
|
56
|
+
* nobody touched comes back byte for byte, comments and all; a moved shape
|
|
57
|
+
* comes back as two changed numbers.
|
|
58
|
+
*
|
|
59
|
+
* Falls back to returning `updated` unchanged whenever it cannot do better:
|
|
60
|
+
* either document failing to parse, a different root element, or an alignment
|
|
61
|
+
* that would produce overlapping edits. The result is then exactly what the
|
|
62
|
+
* caller would have written anyway, so calling this is never worse than not.
|
|
63
|
+
*
|
|
64
|
+
* @param original - The document as it stands.
|
|
65
|
+
* @param updated - The same document as the serializer would write it now.
|
|
66
|
+
* @param options - `siblingOrder` decides what happens to children that appear
|
|
67
|
+
* in both documents in a different order. See {@link SiblingOrder}.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```typescript
|
|
71
|
+
* const onDisk = await readFile("order.bpmn", "utf8");
|
|
72
|
+
* const next = preserveFormatting(onDisk, Bpmn.export(edited));
|
|
73
|
+
* // `next` differs from `onDisk` only where `edited` differs from what it held.
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export declare function preserveFormatting(original: string, updated: string, options?: PreserveOptions): string;
|
|
77
|
+
/** How a verified preserve turned out, for a caller that wants to know. */
|
|
78
|
+
export interface VerifiedPreserve {
|
|
79
|
+
/** The document to write. */
|
|
80
|
+
readonly xml: string;
|
|
81
|
+
/**
|
|
82
|
+
* Which rung produced it.
|
|
83
|
+
*
|
|
84
|
+
* - `preserved` — the file's own order and formatting were kept.
|
|
85
|
+
* - `reordered` — formatting kept, children reordered as the update wants.
|
|
86
|
+
* Reached when the document really does depend on sibling order.
|
|
87
|
+
* - `rewritten` — the update itself, because neither of the above survived
|
|
88
|
+
* the check. Nothing is lost; the file is simply reformatted.
|
|
89
|
+
*/
|
|
90
|
+
readonly outcome: "preserved" | "reordered" | "rewritten";
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Preserves as much of `original` as a reader of the document will allow.
|
|
94
|
+
*
|
|
95
|
+
* The choices {@link preserveFormatting} cannot make safely on its own —
|
|
96
|
+
* whether sibling order carries meaning, whether an attribute the update
|
|
97
|
+
* dropped was a schema default — are made here by *trying and checking*. Each
|
|
98
|
+
* candidate is parsed with the caller's own reader and compared against the
|
|
99
|
+
* update; the first that reads the same is used, and the update itself is the
|
|
100
|
+
* floor. So the aggressive strategies are never assumed to be safe for a
|
|
101
|
+
* particular schema, only observed to be safe for a particular document.
|
|
102
|
+
*
|
|
103
|
+
* @param original - The document as it stands.
|
|
104
|
+
* @param updated - The same document as the serializer would write it now.
|
|
105
|
+
* @param read - Parses a document into something comparable with
|
|
106
|
+
* `JSON.stringify`. Anything it cannot parse counts as a failed check.
|
|
107
|
+
*/
|
|
108
|
+
export declare function preserveFormattingVerified(original: string, updated: string, read: (xml: string) => unknown): VerifiedPreserve;
|
|
109
|
+
//# sourceMappingURL=xml-patch.d.ts.map
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewriting a document in place, so an edit reads as an edit.
|
|
3
|
+
*
|
|
4
|
+
* A serializer given a model produces its own formatting: its indentation, its
|
|
5
|
+
* attribute order, its choice of ` ` over `
`. That is correct output
|
|
6
|
+
* and a terrible diff. Move one element in a visual editor and every line of
|
|
7
|
+
* the file changes, so the commit says "the whole diagram" when it means "a box
|
|
8
|
+
* moved forty pixels" — and a reviewer has no way to tell those apart.
|
|
9
|
+
*
|
|
10
|
+
* {@link preserveFormatting} closes that gap without either side having to know
|
|
11
|
+
* about the other. It takes the document as it was and the document as the
|
|
12
|
+
* serializer would write it, and returns a third: the *content* of the second
|
|
13
|
+
* carried by the *bytes* of the first, everywhere the two agree. No model is
|
|
14
|
+
* involved, which is why it serves BPMN, DMN, forms and anything else this
|
|
15
|
+
* toolkit learns to write.
|
|
16
|
+
*
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
import { escapeAttr, escapeText } from "./xml-parser.js";
|
|
20
|
+
import { parseXmlSpans } from "./xml-spans.js";
|
|
21
|
+
const WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
|
|
22
|
+
function isBlank(text) {
|
|
23
|
+
return text.trim() === "";
|
|
24
|
+
}
|
|
25
|
+
/** Offset of the first whitespace character in the run before `offset`. */
|
|
26
|
+
function whitespaceStart(source, offset) {
|
|
27
|
+
let start = offset;
|
|
28
|
+
while (start > 0 && WHITESPACE.has(source[start - 1]))
|
|
29
|
+
start -= 1;
|
|
30
|
+
return start;
|
|
31
|
+
}
|
|
32
|
+
/** The indentation of the line `offset` sits on, when it starts that line. */
|
|
33
|
+
function indentAt(source, offset) {
|
|
34
|
+
const start = whitespaceStart(source, offset);
|
|
35
|
+
const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
|
|
36
|
+
return start <= lineStart ? source.slice(lineStart, offset) : "";
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Where a whole attribute begins, walking back from its value.
|
|
40
|
+
*
|
|
41
|
+
* The scanner reports where a *value* sits; removing an attribute needs the
|
|
42
|
+
* name and the `=` and the space in front of them as well, or the document is
|
|
43
|
+
* left holding a stray `foo=` and stops parsing.
|
|
44
|
+
*/
|
|
45
|
+
function attributeStart(source, valueStart) {
|
|
46
|
+
// The opening quote, then whitespace, then "=", then whitespace, then the
|
|
47
|
+
// name, then the whitespace separating it from whatever came before.
|
|
48
|
+
let i = valueStart - 1;
|
|
49
|
+
while (i > 0 && WHITESPACE.has(source[i - 1]))
|
|
50
|
+
i -= 1;
|
|
51
|
+
if (source[i - 1] === "=")
|
|
52
|
+
i -= 1;
|
|
53
|
+
while (i > 0 && WHITESPACE.has(source[i - 1]))
|
|
54
|
+
i -= 1;
|
|
55
|
+
while (i > 0 && !WHITESPACE.has(source[i - 1]) && source[i - 1] !== '"')
|
|
56
|
+
i -= 1;
|
|
57
|
+
return whitespaceStart(source, i);
|
|
58
|
+
}
|
|
59
|
+
/** Where a new attribute goes: after the last one, before the tag closes. */
|
|
60
|
+
function attributeInsertPoint(source, element) {
|
|
61
|
+
const close = element.contentStart - (element.selfClosing ? 2 : 1);
|
|
62
|
+
return whitespaceStart(source, close);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A child's identity, for lining up two versions of the same parent.
|
|
66
|
+
*
|
|
67
|
+
* An `id` is the answer whenever there is one, which in BPMN is nearly always.
|
|
68
|
+
* Without one — a `di:waypoint`, a `bpmn:incoming` — the name plus what the
|
|
69
|
+
* element says is enough: two waypoints with the same coordinates really are
|
|
70
|
+
* interchangeable, so pairing them either way round is correct.
|
|
71
|
+
*/
|
|
72
|
+
function childKey(element) {
|
|
73
|
+
const id = element.attributes.get("id");
|
|
74
|
+
if (id !== undefined)
|
|
75
|
+
return `#${id.value}`;
|
|
76
|
+
const attributes = [...element.attributes]
|
|
77
|
+
.map(([name, attribute]) => `${name}=${attribute.value}`)
|
|
78
|
+
.sort()
|
|
79
|
+
.join(" ");
|
|
80
|
+
return `${element.name} ${attributes} ${element.text.trim()}`;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Lines up two sequences by longest common subsequence.
|
|
84
|
+
*
|
|
85
|
+
* Returns, for each index in `a`, the index in `b` it pairs with, or -1. An
|
|
86
|
+
* alignment rather than a set of pairs, because reordered children have to come
|
|
87
|
+
* out reordered: matching on keys alone would rewrite each element where it
|
|
88
|
+
* stands and silently keep the old order.
|
|
89
|
+
*/
|
|
90
|
+
function align(a, b) {
|
|
91
|
+
const rows = a.length;
|
|
92
|
+
const columns = b.length;
|
|
93
|
+
// A standard LCS table. The sequences are one element's children, so the
|
|
94
|
+
// quadratic cost is bounded by how many children a single element has.
|
|
95
|
+
const table = Array.from({ length: rows + 1 }, () => new Array(columns + 1).fill(0));
|
|
96
|
+
for (let i = rows - 1; i >= 0; i -= 1) {
|
|
97
|
+
for (let j = columns - 1; j >= 0; j -= 1) {
|
|
98
|
+
const row = table[i];
|
|
99
|
+
const next = table[i + 1];
|
|
100
|
+
row[j] =
|
|
101
|
+
a[i] === b[j]
|
|
102
|
+
? next[j + 1] + 1
|
|
103
|
+
: Math.max(next[j], row[j + 1]);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const pairing = new Array(rows).fill(-1);
|
|
107
|
+
let i = 0;
|
|
108
|
+
let j = 0;
|
|
109
|
+
while (i < rows && j < columns) {
|
|
110
|
+
if (a[i] === b[j]) {
|
|
111
|
+
pairing[i] = j;
|
|
112
|
+
i += 1;
|
|
113
|
+
j += 1;
|
|
114
|
+
}
|
|
115
|
+
else if ((table[i + 1]?.[j] ?? 0) >= (table[i]?.[j + 1] ?? 0)) {
|
|
116
|
+
i += 1;
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
j += 1;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return pairing;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Pairs each child with the first unused child of the same key, whatever
|
|
126
|
+
* position it holds.
|
|
127
|
+
*
|
|
128
|
+
* Where {@link align} produces the reordering the two sequences differ by, this
|
|
129
|
+
* produces none: an element that moved is patched where it already stands.
|
|
130
|
+
*/
|
|
131
|
+
function matchByKey(a, b) {
|
|
132
|
+
const available = new Map();
|
|
133
|
+
for (const [index, key] of b.entries()) {
|
|
134
|
+
const list = available.get(key);
|
|
135
|
+
if (list === undefined)
|
|
136
|
+
available.set(key, [index]);
|
|
137
|
+
else
|
|
138
|
+
list.push(index);
|
|
139
|
+
}
|
|
140
|
+
return a.map((key) => available.get(key)?.shift() ?? -1);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Pairs up leftovers that share a tag name, in order.
|
|
144
|
+
*
|
|
145
|
+
* The key-based passes above only recognise an element that is *identical* or
|
|
146
|
+
* carries the same `id`. That leaves out an id-less element whose attributes
|
|
147
|
+
* changed — a `dc:Bounds` that moved, a `bpmn:multiInstanceLoopCharacteristics`
|
|
148
|
+
* that lost a flag — and without this those are deleted and written out again,
|
|
149
|
+
* which throws away the formatting of everything inside them. Pairing them
|
|
150
|
+
* turns that back into an attribute edit.
|
|
151
|
+
*
|
|
152
|
+
* A pair where *both* sides carry an `id` is left alone, and that restriction is
|
|
153
|
+
* what keeps this from undoing a deliberate move: two elements with ids that
|
|
154
|
+
* the earlier pass could not put together are two different elements, and one
|
|
155
|
+
* of them really did change position.
|
|
156
|
+
*
|
|
157
|
+
* One side having an id and the other not is a different situation, and pairing
|
|
158
|
+
* them is right. They cannot have been matched by id in the first place, so
|
|
159
|
+
* there is no move to preserve — and it is the everyday case wherever a model
|
|
160
|
+
* does not carry an id the file has. A DMN file names its `DMNDiagram` and
|
|
161
|
+
* `DMNShape`; the model does not; without this the whole diagram section is
|
|
162
|
+
* deleted and written out again on every save.
|
|
163
|
+
*
|
|
164
|
+
* Both lists are walked forward only, so the pairs this adds never cross the
|
|
165
|
+
* ones already made and the resulting edits stay in document order.
|
|
166
|
+
*/
|
|
167
|
+
function pairRemainingByName(a, b, pairing) {
|
|
168
|
+
const taken = new Set(pairing.filter((index) => index >= 0));
|
|
169
|
+
let cursor = 0;
|
|
170
|
+
for (const [index, child] of a.entries()) {
|
|
171
|
+
if ((pairing[index] ?? -1) >= 0) {
|
|
172
|
+
// Never pair across an existing match: doing so would reorder edits.
|
|
173
|
+
cursor = Math.max(cursor, pairing[index] + 1);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
for (let j = cursor; j < b.length; j += 1) {
|
|
177
|
+
const candidate = b[j];
|
|
178
|
+
if (taken.has(j) || candidate.name !== child.name)
|
|
179
|
+
continue;
|
|
180
|
+
if (child.attributes.has("id") && candidate.attributes.has("id"))
|
|
181
|
+
continue;
|
|
182
|
+
pairing[index] = j;
|
|
183
|
+
taken.add(j);
|
|
184
|
+
cursor = j + 1;
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Everything that has to change inside one matched pair of elements. */
|
|
190
|
+
function diffElement(original, updated, a, b, edits, settings) {
|
|
191
|
+
if (a.name !== b.name) {
|
|
192
|
+
// The pairing put two different elements together — a renamed tag, or an
|
|
193
|
+
// id reused for something else. Neither can be patched attribute by
|
|
194
|
+
// attribute, so the whole element is replaced.
|
|
195
|
+
edits.push({ start: a.start, end: a.end, text: updated.slice(b.start, b.end) });
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
diffAttributes(original, a, b, edits, settings);
|
|
199
|
+
if (a.children.length === 0 && b.children.length === 0) {
|
|
200
|
+
diffText(a, b, edits);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
diffChildren(original, updated, a, b, edits, settings);
|
|
204
|
+
}
|
|
205
|
+
function diffAttributes(original, a, b, edits, settings) {
|
|
206
|
+
for (const [name, wanted] of b.attributes) {
|
|
207
|
+
const present = a.attributes.get(name);
|
|
208
|
+
if (present === undefined) {
|
|
209
|
+
const at = attributeInsertPoint(original, a);
|
|
210
|
+
edits.push({ start: at, end: at, text: ` ${name}="${escapeAttr(wanted.value)}"` });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
// Compare decoded values. ` ` and `
` are the same newline, and
|
|
214
|
+
// rewriting one into the other is a diff that says nothing.
|
|
215
|
+
if (present.value === wanted.value)
|
|
216
|
+
continue;
|
|
217
|
+
edits.push({ start: present.start, end: present.end, text: escapeAttr(wanted.value) });
|
|
218
|
+
}
|
|
219
|
+
if (settings.droppedAttributes === "keep")
|
|
220
|
+
return;
|
|
221
|
+
for (const [name, present] of a.attributes) {
|
|
222
|
+
if (b.attributes.has(name))
|
|
223
|
+
continue;
|
|
224
|
+
edits.push({ start: attributeStart(original, present.start), end: present.end + 1, text: "" });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function diffText(a, b, edits) {
|
|
228
|
+
if (a.text === b.text)
|
|
229
|
+
return;
|
|
230
|
+
// Whitespace-only content on both sides is formatting, not content: an
|
|
231
|
+
// element pretty-printed as `<a>\n</a>` says exactly what `<a></a>` says.
|
|
232
|
+
if (isBlank(a.text) && isBlank(b.text))
|
|
233
|
+
return;
|
|
234
|
+
// There is nothing to replace inside a self-closing tag, so an element that
|
|
235
|
+
// gains content has to be written out again.
|
|
236
|
+
if (a.selfClosing) {
|
|
237
|
+
edits.push({
|
|
238
|
+
start: a.start,
|
|
239
|
+
end: a.end,
|
|
240
|
+
text: `<${a.name}${attributesOf(a, b)}>${escapeText(b.text)}</${a.name}>`,
|
|
241
|
+
});
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
edits.push({ start: a.contentStart, end: a.contentEnd, text: escapeText(b.text) });
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* The attribute list for an element being written out again.
|
|
248
|
+
*
|
|
249
|
+
* Takes `b`'s values in `a`'s order, so an element that has to be regenerated
|
|
250
|
+
* still comes out looking as much like the original as it can.
|
|
251
|
+
*/
|
|
252
|
+
function attributesOf(a, b) {
|
|
253
|
+
const parts = [];
|
|
254
|
+
for (const [name] of a.attributes) {
|
|
255
|
+
const wanted = b.attributes.get(name);
|
|
256
|
+
if (wanted !== undefined)
|
|
257
|
+
parts.push(` ${name}="${escapeAttr(wanted.value)}"`);
|
|
258
|
+
}
|
|
259
|
+
for (const [name, wanted] of b.attributes) {
|
|
260
|
+
if (!a.attributes.has(name))
|
|
261
|
+
parts.push(` ${name}="${escapeAttr(wanted.value)}"`);
|
|
262
|
+
}
|
|
263
|
+
return parts.join("");
|
|
264
|
+
}
|
|
265
|
+
function diffChildren(original, updated, a, b, edits, settings) {
|
|
266
|
+
const aKeys = a.children.map(childKey);
|
|
267
|
+
const bKeys = b.children.map(childKey);
|
|
268
|
+
const pairing = settings.siblingOrder === "keep" ? matchByKey(aKeys, bKeys) : align(aKeys, bKeys);
|
|
269
|
+
pairRemainingByName(a.children, b.children, pairing);
|
|
270
|
+
const matchedInB = new Set(pairing.filter((index) => index >= 0));
|
|
271
|
+
// What indentation new children should take: whatever the existing ones use,
|
|
272
|
+
// and failing that one step in from the parent.
|
|
273
|
+
const sample = a.children[0];
|
|
274
|
+
const indent = sample === undefined
|
|
275
|
+
? `${indentAt(original, a.start)}${indentUnit(original)}`
|
|
276
|
+
: indentAt(original, sample.start);
|
|
277
|
+
for (const [index, child] of a.children.entries()) {
|
|
278
|
+
const match = pairing[index] ?? -1;
|
|
279
|
+
if (match < 0) {
|
|
280
|
+
// Take the whitespace that put the child on its own line with it;
|
|
281
|
+
// anything else between siblings — a comment — stays where it is.
|
|
282
|
+
edits.push({ start: whitespaceStart(original, child.start), end: child.end, text: "" });
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
diffElement(original, updated, child, b.children[match], edits, settings);
|
|
286
|
+
}
|
|
287
|
+
for (const [index, child] of b.children.entries()) {
|
|
288
|
+
if (matchedInB.has(index))
|
|
289
|
+
continue;
|
|
290
|
+
const at = insertionPoint(original, a, pairing, b, index);
|
|
291
|
+
const written = reindent(updated.slice(child.start, child.end), indentAt(updated, child.start), indent, indentUnit(updated), indentUnit(original));
|
|
292
|
+
edits.push({ start: at, end: at, text: `\n${indent}${written}` });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** Where a new child belongs in the original text. */
|
|
296
|
+
function insertionPoint(original, a, pairing, b, index) {
|
|
297
|
+
// Straight after the original sibling paired with the nearest kept child
|
|
298
|
+
// before it.
|
|
299
|
+
for (let before = index - 1; before >= 0; before -= 1) {
|
|
300
|
+
const inA = pairing.indexOf(before);
|
|
301
|
+
if (inA >= 0)
|
|
302
|
+
return a.children[inA].end;
|
|
303
|
+
}
|
|
304
|
+
// Nothing kept before it, so in front of the first surviving child — or at
|
|
305
|
+
// the end of the parent's content, when none survive.
|
|
306
|
+
for (let after = index + 1; after < b.children.length; after += 1) {
|
|
307
|
+
const inA = pairing.indexOf(after);
|
|
308
|
+
if (inA >= 0)
|
|
309
|
+
return whitespaceStart(original, a.children[inA].start);
|
|
310
|
+
}
|
|
311
|
+
return whitespaceStart(original, a.contentEnd);
|
|
312
|
+
}
|
|
313
|
+
/** The document's own indentation step, read from its first indented line. */
|
|
314
|
+
function indentUnit(source) {
|
|
315
|
+
const match = /\n([ \t]+)\S/.exec(source);
|
|
316
|
+
return match?.[1] ?? " ";
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Re-indents a block written at one depth so it sits at another.
|
|
320
|
+
*
|
|
321
|
+
* By depth, not by string replacement: the two documents may not indent with
|
|
322
|
+
* the same characters at all, and a block moved from a two-space update into a
|
|
323
|
+
* tab-indented file has to have its *inner* lines converted too, or it arrives
|
|
324
|
+
* with tabs outside and spaces inside.
|
|
325
|
+
*/
|
|
326
|
+
function reindent(text, from, to, fromUnit, toUnit) {
|
|
327
|
+
if (from === to && fromUnit === toUnit)
|
|
328
|
+
return text;
|
|
329
|
+
const lines = text.split("\n");
|
|
330
|
+
return lines
|
|
331
|
+
.map((line, index) => {
|
|
332
|
+
if (index === 0)
|
|
333
|
+
return line;
|
|
334
|
+
const body = line.trimStart();
|
|
335
|
+
const indent = line.slice(0, line.length - body.length);
|
|
336
|
+
if (!indent.startsWith(from))
|
|
337
|
+
return line;
|
|
338
|
+
const deeper = indent.slice(from.length);
|
|
339
|
+
const depth = fromUnit === "" ? 0 : Math.floor(deeper.length / fromUnit.length);
|
|
340
|
+
return `${to}${toUnit.repeat(depth)}${body}`;
|
|
341
|
+
})
|
|
342
|
+
.join("\n");
|
|
343
|
+
}
|
|
344
|
+
/** Applies edits to the source, refusing any pair that overlaps. */
|
|
345
|
+
function applyEdits(source, edits) {
|
|
346
|
+
const ordered = [...edits].sort((x, y) => x.start - y.start || x.end - y.end);
|
|
347
|
+
const parts = [];
|
|
348
|
+
let cursor = 0;
|
|
349
|
+
for (const edit of ordered) {
|
|
350
|
+
if (edit.start < cursor) {
|
|
351
|
+
// Two edits claiming the same characters mean the walk paired one
|
|
352
|
+
// element with two, and the result would be nonsense. Refuse to produce
|
|
353
|
+
// it; the caller falls back to the plain serialization.
|
|
354
|
+
throw new Error("overlapping edits");
|
|
355
|
+
}
|
|
356
|
+
parts.push(source.slice(cursor, edit.start), edit.text);
|
|
357
|
+
cursor = edit.end;
|
|
358
|
+
}
|
|
359
|
+
parts.push(source.slice(cursor));
|
|
360
|
+
return parts.join("");
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Rewrites `original` to say what `updated` says, changing as little as it can.
|
|
364
|
+
*
|
|
365
|
+
* The result is `updated`'s document — the same elements, attributes and text —
|
|
366
|
+
* written with `original`'s formatting wherever the two agree. An element
|
|
367
|
+
* nobody touched comes back byte for byte, comments and all; a moved shape
|
|
368
|
+
* comes back as two changed numbers.
|
|
369
|
+
*
|
|
370
|
+
* Falls back to returning `updated` unchanged whenever it cannot do better:
|
|
371
|
+
* either document failing to parse, a different root element, or an alignment
|
|
372
|
+
* that would produce overlapping edits. The result is then exactly what the
|
|
373
|
+
* caller would have written anyway, so calling this is never worse than not.
|
|
374
|
+
*
|
|
375
|
+
* @param original - The document as it stands.
|
|
376
|
+
* @param updated - The same document as the serializer would write it now.
|
|
377
|
+
* @param options - `siblingOrder` decides what happens to children that appear
|
|
378
|
+
* in both documents in a different order. See {@link SiblingOrder}.
|
|
379
|
+
*
|
|
380
|
+
* @example
|
|
381
|
+
* ```typescript
|
|
382
|
+
* const onDisk = await readFile("order.bpmn", "utf8");
|
|
383
|
+
* const next = preserveFormatting(onDisk, Bpmn.export(edited));
|
|
384
|
+
* // `next` differs from `onDisk` only where `edited` differs from what it held.
|
|
385
|
+
* ```
|
|
386
|
+
*/
|
|
387
|
+
export function preserveFormatting(original, updated, options = {}) {
|
|
388
|
+
let before;
|
|
389
|
+
let after;
|
|
390
|
+
try {
|
|
391
|
+
before = parseXmlSpans(original);
|
|
392
|
+
after = parseXmlSpans(updated);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return updated;
|
|
396
|
+
}
|
|
397
|
+
if (before.name !== after.name)
|
|
398
|
+
return updated;
|
|
399
|
+
try {
|
|
400
|
+
const edits = [];
|
|
401
|
+
diffElement(original, updated, before, after, edits, {
|
|
402
|
+
siblingOrder: options.siblingOrder ?? "follow",
|
|
403
|
+
droppedAttributes: options.droppedAttributes ?? "remove",
|
|
404
|
+
});
|
|
405
|
+
if (edits.length === 0)
|
|
406
|
+
return original;
|
|
407
|
+
return applyEdits(original, edits);
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return updated;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Preserves as much of `original` as a reader of the document will allow.
|
|
415
|
+
*
|
|
416
|
+
* The choices {@link preserveFormatting} cannot make safely on its own —
|
|
417
|
+
* whether sibling order carries meaning, whether an attribute the update
|
|
418
|
+
* dropped was a schema default — are made here by *trying and checking*. Each
|
|
419
|
+
* candidate is parsed with the caller's own reader and compared against the
|
|
420
|
+
* update; the first that reads the same is used, and the update itself is the
|
|
421
|
+
* floor. So the aggressive strategies are never assumed to be safe for a
|
|
422
|
+
* particular schema, only observed to be safe for a particular document.
|
|
423
|
+
*
|
|
424
|
+
* @param original - The document as it stands.
|
|
425
|
+
* @param updated - The same document as the serializer would write it now.
|
|
426
|
+
* @param read - Parses a document into something comparable with
|
|
427
|
+
* `JSON.stringify`. Anything it cannot parse counts as a failed check.
|
|
428
|
+
*/
|
|
429
|
+
export function preserveFormattingVerified(original, updated, read) {
|
|
430
|
+
let wanted;
|
|
431
|
+
try {
|
|
432
|
+
wanted = JSON.stringify(read(updated));
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
return { xml: updated, outcome: "rewritten" };
|
|
436
|
+
}
|
|
437
|
+
// Most to least faithful to the file.
|
|
438
|
+
const attempts = [
|
|
439
|
+
["preserved", { siblingOrder: "keep", droppedAttributes: "keep" }],
|
|
440
|
+
["preserved", { siblingOrder: "keep" }],
|
|
441
|
+
["reordered", { siblingOrder: "follow" }],
|
|
442
|
+
];
|
|
443
|
+
for (const [outcome, options] of attempts) {
|
|
444
|
+
const candidate = preserveFormatting(original, updated, options);
|
|
445
|
+
// `preserveFormatting` returns the update when it cannot do better, which
|
|
446
|
+
// needs no checking: it is the floor already.
|
|
447
|
+
if (candidate === updated)
|
|
448
|
+
continue;
|
|
449
|
+
try {
|
|
450
|
+
if (JSON.stringify(read(candidate)) === wanted)
|
|
451
|
+
return { xml: candidate, outcome };
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// A candidate that will not parse is simply not a candidate.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return { xml: updated, outcome: "rewritten" };
|
|
458
|
+
}
|
|
459
|
+
//# sourceMappingURL=xml-patch.js.map
|