@bpmnkit/core 0.1.2 → 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.
Files changed (63) hide show
  1. package/README.md +30 -1
  2. package/dist/bpmn/bpmn-builder.d.ts +209 -3
  3. package/dist/bpmn/bpmn-builder.js +456 -16
  4. package/dist/bpmn/bpmn-model.d.ts +110 -0
  5. package/dist/bpmn/bpmn-parser.js +1413 -528
  6. package/dist/bpmn/bpmn-serializer.js +171 -19
  7. package/dist/bpmn/compact.d.ts +17 -2
  8. package/dist/bpmn/compact.js +3 -3
  9. package/dist/bpmn/diagram-diff.d.ts +71 -0
  10. package/dist/bpmn/diagram-diff.js +124 -0
  11. package/dist/bpmn/full-operations.d.ts +89 -0
  12. package/dist/bpmn/full-operations.js +478 -0
  13. package/dist/bpmn/index.d.ts +19 -0
  14. package/dist/bpmn/index.js +21 -0
  15. package/dist/bpmn/lint.d.ts +97 -0
  16. package/dist/bpmn/lint.js +135 -0
  17. package/dist/bpmn/optimize/feel.js +2 -2
  18. package/dist/bpmn/optimize/patterns.js +23 -16
  19. package/dist/bpmn/optimize/tasks.js +30 -7
  20. package/dist/bpmn/optimize/utils.js +2 -4
  21. package/dist/bpmn/optimize/variable-flow.js +58 -67
  22. package/dist/bpmn/preserving-writer.d.ts +64 -0
  23. package/dist/bpmn/preserving-writer.js +70 -0
  24. package/dist/bpmn/semantic-hash.d.ts +93 -0
  25. package/dist/bpmn/semantic-hash.js +155 -0
  26. package/dist/bpmn/sha256.d.ts +17 -0
  27. package/dist/bpmn/sha256.js +95 -0
  28. package/dist/bpmn/zeebe-extensions.d.ts +56 -0
  29. package/dist/bpmn/zeebe-extensions.js +79 -0
  30. package/dist/bpmn/zeebe-placement.d.ts +12 -0
  31. package/dist/bpmn/zeebe-placement.js +140 -0
  32. package/dist/dmn/dmn-serializer.js +7 -2
  33. package/dist/dmn/preserving-writer.d.ts +31 -0
  34. package/dist/dmn/preserving-writer.js +36 -0
  35. package/dist/errors.d.ts +40 -1
  36. package/dist/errors.js +41 -0
  37. package/dist/form/preserving-writer.d.ts +47 -0
  38. package/dist/form/preserving-writer.js +50 -0
  39. package/dist/index.d.ts +22 -5
  40. package/dist/index.js +14 -4
  41. package/dist/json/index.d.ts +5 -0
  42. package/dist/json/index.js +3 -0
  43. package/dist/json/json-patch.d.ts +65 -0
  44. package/dist/json/json-patch.js +416 -0
  45. package/dist/json/json-spans.d.ts +48 -0
  46. package/dist/json/json-spans.js +153 -0
  47. package/dist/layout/semantic/graph.d.ts +9 -1
  48. package/dist/layout/semantic/graph.js +42 -17
  49. package/dist/layout/semantic/route.js +102 -42
  50. package/dist/node/index.d.ts +10 -0
  51. package/dist/node/index.js +9 -0
  52. package/dist/node/write.d.ts +81 -0
  53. package/dist/node/write.js +167 -0
  54. package/dist/types/id-generator.js +11 -3
  55. package/dist/xml/index.d.ts +7 -1
  56. package/dist/xml/index.js +4 -1
  57. package/dist/xml/xml-parser.d.ts +71 -0
  58. package/dist/xml/xml-parser.js +437 -145
  59. package/dist/xml/xml-patch.d.ts +109 -0
  60. package/dist/xml/xml-patch.js +459 -0
  61. package/dist/xml/xml-spans.d.ts +45 -0
  62. package/dist/xml/xml-spans.js +74 -0
  63. package/package.json +8 -1
@@ -1,153 +1,414 @@
1
1
  // ---------------------------------------------------------------------------
2
- // Parser
2
+ // Event scanner
3
3
  // ---------------------------------------------------------------------------
4
+ /** What a sink wants the scanner to do with an element after its start tag. */
5
+ export const Visit = {
6
+ /** Report child elements and character data. */
7
+ All: 0,
8
+ /**
9
+ * Skip the element's content: the scanner fast-forwards past the matching
10
+ * end tag without building attributes or decoding text for anything inside,
11
+ * and `end` is not called for it.
12
+ */
13
+ Skip: 1,
14
+ /** Report child elements but drop character data without decoding it. */
15
+ ElementsOnly: 2,
16
+ };
17
+ /**
18
+ * Scan an XML document, reporting the root element and everything inside it to
19
+ * `sink`. Returns false when the document has no root element. Content after
20
+ * the root element is ignored.
21
+ */
22
+ export function scanXml(xml, sink) {
23
+ return new XmlScanner(xml).scan(sink);
24
+ }
4
25
  /**
5
26
  * Parse an XML string into an XmlElement tree.
6
27
  * Returns the root element with all namespace prefixes preserved.
7
28
  * @throws Error if the XML has no root element.
8
29
  */
9
30
  export function parseXml(xml) {
10
- const p = new XmlReader(xml);
11
- const root = p.parseDocument();
12
- if (!root)
31
+ const builder = new TreeBuilder();
32
+ if (!scanXml(xml, builder) || builder.root === undefined) {
13
33
  throw new Error("Failed to parse XML: no root element found");
14
- return root;
34
+ }
35
+ return builder.root;
15
36
  }
16
- class XmlReader {
37
+ /** Sink that materialises the document as an XmlElement tree. */
38
+ class TreeBuilder {
39
+ root;
40
+ stack = [];
41
+ start(name, _local, attributes) {
42
+ const el = { name, attributes, children: [] };
43
+ const parent = this.stack[this.stack.length - 1];
44
+ if (parent)
45
+ parent.children.push(el);
46
+ else
47
+ this.root = el;
48
+ this.stack.push(el);
49
+ return Visit.All;
50
+ }
51
+ text(text) {
52
+ const el = this.stack[this.stack.length - 1];
53
+ el.text = el.text === undefined ? text : el.text + text;
54
+ }
55
+ end() {
56
+ this.stack.pop();
57
+ }
58
+ }
59
+ // Character codes the scanner switches on. Comparing codes avoids allocating a
60
+ // one-character string for every position visited.
61
+ const LT = 0x3c; // <
62
+ const GT = 0x3e; // >
63
+ const SLASH = 0x2f; // /
64
+ const EQ = 0x3d; // =
65
+ const QUESTION = 0x3f; // ?
66
+ const BANG = 0x21; // !
67
+ const DQUOTE = 0x22; // "
68
+ const SQUOTE = 0x27; // '
69
+ const COLON = 0x3a; // :
70
+ const SPACE = 0x20;
71
+ const TAB = 0x09;
72
+ const LF = 0x0a;
73
+ const CR = 0x0d;
74
+ class XmlScanner {
17
75
  s;
76
+ n;
18
77
  i = 0;
78
+ /** Index of the first ":" in the name most recently read, or -1. */
79
+ colon = -1;
80
+ /** Position of the next "&" at or after the last place we looked, or -1 for none. */
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
+ }
19
93
  constructor(source) {
20
94
  this.s = source;
95
+ this.n = source.length;
21
96
  }
22
- parseDocument() {
23
- let root;
24
- while (this.i < this.s.length) {
97
+ scan(sink) {
98
+ if (sink.cursor !== undefined) {
99
+ this.wantSpans = true;
100
+ sink.cursor(this);
101
+ }
102
+ while (this.i < this.n) {
25
103
  this.skipWhitespace();
26
- if (this.i >= this.s.length)
104
+ if (this.i >= this.n)
27
105
  break;
28
- if (this.s[this.i] !== "<") {
106
+ if (this.s.charCodeAt(this.i) !== LT) {
29
107
  // text outside root — skip
30
108
  this.i++;
31
109
  continue;
32
110
  }
33
- if (this.startsWith("<?")) {
111
+ const next = this.s.charCodeAt(this.i + 1);
112
+ if (next === QUESTION) {
34
113
  this.skipPi();
35
114
  }
36
- else if (this.startsWith("<!--")) {
37
- this.skipComment();
115
+ else if (next === BANG) {
116
+ if (this.s.startsWith("<!--", this.i))
117
+ this.skipComment();
118
+ else
119
+ this.skipBang();
120
+ }
121
+ else {
122
+ this.element(sink);
123
+ return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+ /** Scan the element starting at `i` (which is "<") and everything inside it. */
129
+ element(sink) {
130
+ const s = this.s;
131
+ // Open elements, innermost last, with whether each one wants character data.
132
+ const open = [];
133
+ const wantText = [];
134
+ if (this.openTag(sink, open, wantText) === 0)
135
+ return;
136
+ while (open.length > 0) {
137
+ if (this.i >= this.n)
138
+ throw new Error(`Expected "</" at position ${this.i}`);
139
+ const c = s.charCodeAt(this.i);
140
+ if (c !== LT) {
141
+ if (wantText[wantText.length - 1])
142
+ sink.text(this.readText());
143
+ else
144
+ this.skipText();
145
+ continue;
146
+ }
147
+ const next = s.charCodeAt(this.i + 1);
148
+ if (next === SLASH) {
149
+ const endTagStart = this.i;
150
+ this.i += 2;
151
+ const closing = this.readName();
152
+ const name = open[open.length - 1];
153
+ if (closing !== name) {
154
+ throw new Error(`Mismatched closing tag: expected </${name}>, got </${closing}>`);
155
+ }
156
+ this.skipWhitespace();
157
+ this.expectChar(GT, ">");
158
+ open.pop();
159
+ wantText.pop();
160
+ if (this.wantSpans) {
161
+ this.endTagStart = endTagStart;
162
+ this.endTagEnd = this.i;
163
+ }
164
+ sink.end(name);
38
165
  }
39
- else if (this.startsWith("<!")) {
40
- this.skipBang();
166
+ else if (next === BANG) {
167
+ if (s.startsWith("<!--", this.i)) {
168
+ this.skipComment();
169
+ }
170
+ else if (s.startsWith("<![CDATA[", this.i)) {
171
+ if (wantText[wantText.length - 1])
172
+ sink.text(this.readCData());
173
+ else
174
+ this.skipCData();
175
+ }
176
+ else {
177
+ // Unknown declaration inside content — treat it as an element and
178
+ // let the name reader fail on it, as before.
179
+ this.openTag(sink, open, wantText);
180
+ }
181
+ }
182
+ else if (next === QUESTION) {
183
+ this.skipPi();
41
184
  }
42
185
  else {
43
- root = this.parseElement();
44
- break;
186
+ this.openTag(sink, open, wantText);
45
187
  }
46
188
  }
47
- return root;
48
189
  }
49
- parseElement() {
50
- this.expect("<");
190
+ /**
191
+ * Read a start tag at `i`, report it, and push it onto `open` unless it was
192
+ * self-closing or the sink skipped it. Returns the new depth of `open`.
193
+ */
194
+ openTag(sink, open, wantText) {
195
+ const s = this.s;
196
+ const tagStart = this.i;
197
+ this.i++; // <
51
198
  const name = this.readName();
199
+ const local = this.colon >= 0 ? s.substring(this.colon + 1, this.i) : name;
52
200
  const attributes = {};
201
+ if (this.wantSpans)
202
+ this.attrSpans.clear();
53
203
  this.readAttributes(attributes);
54
204
  this.skipWhitespace();
55
- if (this.s[this.i] === "/" && this.s[this.i + 1] === ">") {
56
- // self-closing
205
+ if (s.charCodeAt(this.i) === SLASH && s.charCodeAt(this.i + 1) === GT) {
57
206
  this.i += 2;
58
- return { name, attributes, children: [] };
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
+ }
215
+ if (sink.start(name, local, attributes, true) !== Visit.Skip)
216
+ sink.end(name);
217
+ return open.length;
59
218
  }
60
- this.expect(">");
61
- const children = [];
62
- let text;
63
- while (this.i < this.s.length) {
64
- if (this.startsWith("</"))
65
- break;
66
- if (this.s[this.i] === "<") {
67
- if (this.startsWith("<!--")) {
68
- this.skipComment();
69
- }
70
- else if (this.startsWith("<![CDATA[")) {
71
- const cd = this.readCData();
72
- text = text === undefined ? cd : text + cd;
73
- }
74
- else if (this.startsWith("<?")) {
75
- this.skipPi();
219
+ this.expectChar(GT, ">");
220
+ if (this.wantSpans) {
221
+ this.tagStart = tagStart;
222
+ this.tagEnd = this.i;
223
+ }
224
+ const visit = sink.start(name, local, attributes, false);
225
+ if (visit === Visit.Skip) {
226
+ this.skipContent(name);
227
+ return open.length;
228
+ }
229
+ open.push(name);
230
+ wantText.push(visit === Visit.All);
231
+ return open.length;
232
+ }
233
+ /**
234
+ * Fast-forward past the content and end tag of the element `name` whose
235
+ * start tag was just consumed, validating nesting but allocating nothing.
236
+ */
237
+ skipContent(name) {
238
+ const s = this.s;
239
+ // Open elements below `name`, as (start, length) spans into the source.
240
+ const spans = [];
241
+ let depth = 1;
242
+ while (depth > 0) {
243
+ const lt = s.indexOf("<", this.i);
244
+ if (lt === -1)
245
+ throw new Error(`Expected "</" at position ${this.n}`);
246
+ this.i = lt;
247
+ const next = s.charCodeAt(lt + 1);
248
+ if (next === SLASH) {
249
+ this.i += 2;
250
+ const start = this.i;
251
+ this.skipName();
252
+ const length = this.i - start;
253
+ if (spans.length === 0) {
254
+ if (length !== name.length || !s.startsWith(name, start)) {
255
+ throw new Error(`Mismatched closing tag: expected </${name}>, got </${s.substring(start, this.i)}>`);
256
+ }
76
257
  }
77
258
  else {
78
- children.push(this.parseElement());
259
+ const openLength = spans.pop();
260
+ const openStart = spans.pop();
261
+ if (!this.sameSpan(openStart, openLength, start, length)) {
262
+ throw new Error(`Mismatched closing tag: expected </${s.substring(openStart, openStart + openLength)}>, got </${s.substring(start, this.i)}>`);
263
+ }
79
264
  }
265
+ this.skipWhitespace();
266
+ this.expectChar(GT, ">");
267
+ depth--;
268
+ }
269
+ else if (next === BANG && s.startsWith("<!--", lt)) {
270
+ this.skipComment();
271
+ }
272
+ else if (next === BANG && s.startsWith("<![CDATA[", lt)) {
273
+ const end = s.indexOf("]]>", lt + 9);
274
+ if (end === -1)
275
+ throw new Error("Unterminated CDATA section");
276
+ this.i = end + 3;
277
+ }
278
+ else if (next === QUESTION) {
279
+ this.skipPi();
80
280
  }
81
281
  else {
82
- const t = this.readText();
83
- if (t.length > 0) {
84
- text = text === undefined ? t : text + t;
282
+ this.i++;
283
+ const start = this.i;
284
+ this.skipName();
285
+ const length = this.i - start;
286
+ this.skipAttributes();
287
+ this.skipWhitespace();
288
+ if (s.charCodeAt(this.i) === SLASH && s.charCodeAt(this.i + 1) === GT) {
289
+ this.i += 2;
290
+ continue;
85
291
  }
292
+ this.expectChar(GT, ">");
293
+ spans.push(start, length);
294
+ depth++;
86
295
  }
87
296
  }
88
- // closing tag </name>
89
- this.expect("</");
90
- const closing = this.readName();
91
- if (closing !== name) {
92
- throw new Error(`Mismatched closing tag: expected </${name}>, got </${closing}>`);
297
+ }
298
+ sameSpan(aStart, aLength, bStart, bLength) {
299
+ if (aLength !== bLength)
300
+ return false;
301
+ const s = this.s;
302
+ for (let k = 0; k < aLength; k++) {
303
+ if (s.charCodeAt(aStart + k) !== s.charCodeAt(bStart + k))
304
+ return false;
93
305
  }
94
- this.skipWhitespace();
95
- this.expect(">");
96
- const el = { name, attributes, children };
97
- if (text !== undefined)
98
- el.text = text;
99
- return el;
306
+ return true;
100
307
  }
101
308
  readAttributes(attrs) {
102
- while (this.i < this.s.length) {
309
+ const s = this.s;
310
+ while (this.i < this.n) {
103
311
  this.skipWhitespace();
104
- const ch = this.s[this.i];
105
- if (ch === ">" || ch === "/")
312
+ const ch = s.charCodeAt(this.i);
313
+ if (ch === GT || ch === SLASH)
106
314
  return;
107
315
  const key = this.readName();
108
316
  this.skipWhitespace();
109
- this.expect("=");
317
+ this.expectChar(EQ, "=");
110
318
  this.skipWhitespace();
111
- const value = this.readAttrValue();
112
- attrs[key] = value;
319
+ const valueStart = this.i + 1;
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 });
324
+ }
325
+ }
326
+ /** Like readAttributes, but validates only; nothing is built. */
327
+ skipAttributes() {
328
+ const s = this.s;
329
+ while (this.i < this.n) {
330
+ this.skipWhitespace();
331
+ const ch = s.charCodeAt(this.i);
332
+ if (ch === GT || ch === SLASH)
333
+ return;
334
+ this.skipName();
335
+ this.skipWhitespace();
336
+ this.expectChar(EQ, "=");
337
+ this.skipWhitespace();
338
+ const quote = s.charCodeAt(this.i);
339
+ if (quote !== DQUOTE && quote !== SQUOTE) {
340
+ throw new Error(`Expected quote at position ${this.i}`);
341
+ }
342
+ this.i++;
343
+ const end = s.indexOf(quote === DQUOTE ? '"' : "'", this.i);
344
+ this.i = end === -1 ? this.n + 1 : end + 1;
113
345
  }
114
346
  }
115
347
  readAttrValue() {
116
- const quote = this.s[this.i];
117
- if (quote !== '"' && quote !== "'") {
348
+ const quote = this.s.charCodeAt(this.i);
349
+ if (quote !== DQUOTE && quote !== SQUOTE) {
118
350
  throw new Error(`Expected quote at position ${this.i}`);
119
351
  }
120
352
  this.i++;
121
353
  const start = this.i;
122
- while (this.i < this.s.length && this.s[this.i] !== quote) {
123
- this.i++;
354
+ let end = this.s.indexOf(quote === DQUOTE ? '"' : "'", start);
355
+ if (end === -1)
356
+ end = this.n;
357
+ this.i = end + 1; // skip closing quote
358
+ return this.slice(start, end);
359
+ }
360
+ /**
361
+ * Substring with entities decoded. Values rarely contain "&", so instead of
362
+ * scanning each one, the position of the next "&" is remembered and only
363
+ * refreshed once the scan has moved past it.
364
+ */
365
+ slice(start, end) {
366
+ let amp = this.nextAmp;
367
+ if (amp !== -1 && amp < start) {
368
+ amp = this.s.indexOf("&", start);
369
+ this.nextAmp = amp;
124
370
  }
125
- const value = this.s.substring(start, this.i);
126
- this.i++; // skip closing quote
127
- return decodeXmlEntities(value);
371
+ const value = this.s.substring(start, end);
372
+ return amp !== -1 && amp < end ? decodeXmlEntities(value) : value;
128
373
  }
129
374
  readText() {
130
375
  const start = this.i;
131
- while (this.i < this.s.length && this.s[this.i] !== "<") {
132
- this.i++;
133
- }
134
- return decodeXmlEntities(this.s.substring(start, this.i));
376
+ let end = this.s.indexOf("<", start);
377
+ if (end === -1)
378
+ end = this.n;
379
+ this.i = end;
380
+ return this.slice(start, end);
381
+ }
382
+ skipText() {
383
+ const end = this.s.indexOf("<", this.i);
384
+ this.i = end === -1 ? this.n : end;
385
+ }
386
+ skipCData() {
387
+ const end = this.s.indexOf("]]>", this.i + 9);
388
+ if (end === -1)
389
+ throw new Error("Unterminated CDATA section");
390
+ this.i = end + 3;
135
391
  }
136
392
  readName() {
137
393
  const start = this.i;
138
- while (this.i < this.s.length) {
139
- const c = this.s[this.i];
140
- if (c === " " ||
141
- c === "\t" ||
142
- c === "\n" ||
143
- c === "\r" ||
144
- c === ">" ||
145
- c === "/" ||
146
- c === "=")
394
+ this.skipName();
395
+ return this.s.substring(start, this.i);
396
+ }
397
+ /** Advance past a name, recording the position of its first ":" in `colon`. */
398
+ skipName() {
399
+ const s = this.s;
400
+ let i = this.i;
401
+ let colon = -1;
402
+ while (i < this.n) {
403
+ const c = s.charCodeAt(i);
404
+ if (c === SPACE || c === TAB || c === LF || c === CR || c === GT || c === SLASH || c === EQ)
147
405
  break;
148
- this.i++;
406
+ if (c === COLON && colon === -1)
407
+ colon = i;
408
+ i++;
149
409
  }
150
- return this.s.substring(start, this.i);
410
+ this.colon = colon;
411
+ this.i = i;
151
412
  }
152
413
  readCData() {
153
414
  this.i += 9; // skip <![CDATA[
@@ -161,65 +422,68 @@ class XmlReader {
161
422
  skipPi() {
162
423
  this.i += 2; // skip <?
163
424
  const end = this.s.indexOf("?>", this.i);
164
- this.i = end === -1 ? this.s.length : end + 2;
425
+ this.i = end === -1 ? this.n : end + 2;
165
426
  }
166
427
  skipComment() {
167
428
  this.i += 4; // skip <!--
168
429
  const end = this.s.indexOf("-->", this.i);
169
- this.i = end === -1 ? this.s.length : end + 3;
430
+ this.i = end === -1 ? this.n : end + 3;
170
431
  }
171
432
  skipBang() {
172
433
  // Skip <!DOCTYPE ...> and similar
173
434
  this.i += 2;
174
435
  let depth = 1;
175
- while (this.i < this.s.length && depth > 0) {
176
- if (this.s[this.i] === "<")
436
+ while (this.i < this.n && depth > 0) {
437
+ const c = this.s.charCodeAt(this.i);
438
+ if (c === LT)
177
439
  depth++;
178
- else if (this.s[this.i] === ">")
440
+ else if (c === GT)
179
441
  depth--;
180
442
  this.i++;
181
443
  }
182
444
  }
183
445
  skipWhitespace() {
184
- while (this.i < this.s.length) {
185
- const c = this.s[this.i];
186
- if (c !== " " && c !== "\t" && c !== "\n" && c !== "\r")
446
+ const s = this.s;
447
+ let i = this.i;
448
+ while (i < this.n) {
449
+ const c = s.charCodeAt(i);
450
+ if (c !== SPACE && c !== TAB && c !== LF && c !== CR)
187
451
  break;
188
- this.i++;
452
+ i++;
189
453
  }
454
+ this.i = i;
190
455
  }
191
- expect(str) {
192
- if (!this.s.startsWith(str, this.i)) {
193
- throw new Error(`Expected "${str}" at position ${this.i}`);
456
+ expectChar(code, shown) {
457
+ if (this.s.charCodeAt(this.i) !== code) {
458
+ throw new Error(`Expected "${shown}" at position ${this.i}`);
194
459
  }
195
- this.i += str.length;
196
- }
197
- startsWith(prefix) {
198
- return this.s.startsWith(prefix, this.i);
460
+ this.i++;
199
461
  }
200
462
  }
201
463
  // ---------------------------------------------------------------------------
202
464
  // Entity helpers
203
465
  // ---------------------------------------------------------------------------
466
+ const ENTITY_RE = /&(?:amp|lt|gt|quot|apos|#x[0-9a-fA-F]+|#[0-9]+);/g;
467
+ function decodeEntity(m) {
468
+ if (m === "&amp;")
469
+ return "&";
470
+ if (m === "&lt;")
471
+ return "<";
472
+ if (m === "&gt;")
473
+ return ">";
474
+ if (m === "&quot;")
475
+ return '"';
476
+ if (m === "&apos;")
477
+ return "'";
478
+ if (m.startsWith("&#x"))
479
+ return String.fromCodePoint(Number.parseInt(m.slice(3, -1), 16));
480
+ return String.fromCodePoint(Number.parseInt(m.slice(2, -1), 10));
481
+ }
204
482
  /** Decode XML predefined and numeric character entities in a string. */
205
483
  function decodeXmlEntities(s) {
206
484
  if (!s.includes("&"))
207
485
  return s;
208
- return s.replace(/&(?:amp|lt|gt|quot|apos|#x[0-9a-fA-F]+|#[0-9]+);/g, (m) => {
209
- if (m === "&amp;")
210
- return "&";
211
- if (m === "&lt;")
212
- return "<";
213
- if (m === "&gt;")
214
- return ">";
215
- if (m === "&quot;")
216
- return '"';
217
- if (m === "&apos;")
218
- return "'";
219
- if (m.startsWith("&#x"))
220
- return String.fromCodePoint(Number.parseInt(m.slice(3, -1), 16));
221
- return String.fromCodePoint(Number.parseInt(m.slice(2, -1), 10));
222
- });
486
+ return s.replace(ENTITY_RE, decodeEntity);
223
487
  }
224
488
  // ---------------------------------------------------------------------------
225
489
  // Serializer
@@ -229,48 +493,76 @@ function decodeXmlEntities(s) {
229
493
  * Produces a well-formed XML document with declaration.
230
494
  */
231
495
  export function serializeXml(element) {
232
- const parts = ['<?xml version="1.0" encoding="UTF-8"?>\n'];
233
- writeElement(parts, element, 0);
234
- parts.push("\n");
235
- return parts.join("");
496
+ return `<?xml version="1.0" encoding="UTF-8"?>\n${writeElement(element, 0)}\n`;
497
+ }
498
+ /** Indentation strings by depth, built once and reused across documents. */
499
+ const INDENTS = [];
500
+ function indentFor(depth) {
501
+ let s = INDENTS[depth];
502
+ if (s === undefined) {
503
+ s = " ".repeat(depth);
504
+ INDENTS[depth] = s;
505
+ }
506
+ return s;
236
507
  }
237
- function writeElement(parts, el, depth) {
238
- const indent = " ".repeat(depth);
239
- parts.push(indent, "<", el.name);
240
- for (const [key, value] of Object.entries(el.attributes)) {
508
+ function writeElement(el, depth) {
509
+ const indent = indentFor(depth);
510
+ let out = `${indent}<${el.name}`;
511
+ const attributes = el.attributes;
512
+ for (const key in attributes) {
513
+ const value = attributes[key];
241
514
  // el.attributes is typed Record<string, string>, but content built from
242
515
  // generated/untyped code can leave a value undefined at runtime — skip
243
516
  // rather than crash the whole serialization on one bad attribute.
244
517
  if (typeof value !== "string")
245
518
  continue;
246
- parts.push(" ", key, '="', escapeAttr(value), '"');
519
+ out += ` ${key}="${escapeAttr(value)}"`;
247
520
  }
248
- const hasChildren = el.children.length > 0;
521
+ const children = el.children;
522
+ const hasChildren = children.length > 0;
249
523
  const hasText = el.text !== undefined;
250
- if (!hasChildren && !hasText) {
251
- parts.push("/>\n");
252
- return;
253
- }
254
- parts.push(">");
255
- if (hasText) {
256
- parts.push(escapeText(el.text));
257
- }
524
+ if (!hasChildren && !hasText)
525
+ return `${out}/>\n`;
526
+ out += ">";
527
+ if (hasText)
528
+ out += escapeText(el.text);
258
529
  if (hasChildren) {
259
- parts.push("\n");
260
- for (const child of el.children) {
261
- writeElement(parts, child, depth + 1);
262
- }
263
- parts.push(indent);
530
+ out += "\n";
531
+ for (const child of children)
532
+ out += writeElement(child, depth + 1);
533
+ out += indent;
264
534
  }
265
- parts.push("</", el.name, ">\n");
535
+ return `${out}</${el.name}>\n`;
266
536
  }
267
- function escapeAttr(value) {
268
- let s = value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll('"', "&quot;");
269
- // Re-encode whitespace that XML parsers would normalize in attribute values
270
- s = s.replaceAll("\n", "&#10;").replaceAll("\r", "&#13;").replaceAll("\t", "&#9;");
271
- return s;
537
+ // One regex test decides whether a value needs escaping at all; most do not,
538
+ // and the ones that do are rewritten in a single pass instead of six.
539
+ const ATTR_ESCAPE_RE = /[&<"\n\r\t]/;
540
+ const ATTR_ESCAPE_ALL_RE = /[&<"\n\r\t]/g;
541
+ const TEXT_ESCAPE_RE = /[&<>]/;
542
+ const TEXT_ESCAPE_ALL_RE = /[&<>]/g;
543
+ const ESCAPES = {
544
+ "&": "&amp;",
545
+ "<": "&lt;",
546
+ ">": "&gt;",
547
+ '"': "&quot;",
548
+ // Whitespace that XML parsers would normalize in attribute values.
549
+ "\n": "&#10;",
550
+ "\r": "&#13;",
551
+ "\t": "&#9;",
552
+ };
553
+ function escapeChar(ch) {
554
+ return ESCAPES[ch] ?? ch;
555
+ }
556
+ /** Escapes a value for use between attribute quotes. */
557
+ export function escapeAttr(value) {
558
+ if (!ATTR_ESCAPE_RE.test(value))
559
+ return value;
560
+ return value.replace(ATTR_ESCAPE_ALL_RE, escapeChar);
272
561
  }
273
- function escapeText(value) {
274
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
562
+ /** Escapes a value for use as character data. */
563
+ export function escapeText(value) {
564
+ if (!TEXT_ESCAPE_RE.test(value))
565
+ return value;
566
+ return value.replace(TEXT_ESCAPE_ALL_RE, escapeChar);
275
567
  }
276
568
  //# sourceMappingURL=xml-parser.js.map