-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwig.js
1331 lines (1188 loc) · 42.5 KB
/
twig.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const SAX = 'sax';
const EXPAT = ['expat', 'node-expat'];
const SAXOPHONE = 'saxophone';
let tree;
let current;
/**
* @external XMLWriter
* @see {@link https://www.npmjs.com/package/xml-writer|xml-writer}
*/
/**
* @external sax
* @see {@link https://www.npmjs.com/package/sax|sax}
*/
/**
* @external node-expat
* @see {@link https://www.npmjs.com/package/node-expat|node-expat}
*/
/**
* @external saxophone
* @see {@link https://www.npmjs.com/package/saxophone|saxophone}
* @see {@link https://www.npmjs.com/package/@alexbosworth/saxophone|@alexbosworth/saxophone}
* @see {@link https://www.npmjs.com/package/@pirxpilot/saxophone|@pirxpilot/saxophone}
*/
/**
* @external libxmljs
* Though module looks promising, it is not implemented, because it does not support Streams.
* According to {@link https://github.com/libxmljs/libxmljs/issues/390|Stream Support} it was requested in 2016, i.e. 8 years ago.
* Apart from that, documentation is very sparse.
* @see {@link https://www.npmjs.com/package/libxmljs|libxmljs}
*/
/*
* Other parsers I had a look at:
* {@link https://www.npmjs.com/package/sax-wasm|sax-wasm}: not a 'stream.Writable'
* {@link https://www.npmjs.com/package/@rubensworks/saxes|saxes}: not a 'stream.Writable'
* {@link https://www.npmjs.com/package/node-xml-stream|node-xml-stream}: Lacks comment and processinginstruction and maybe self closing tags
* {@link https://www.npmjs.com/package/node-xml-stream-parser|node-xml-stream-parser}: Lacks comment and processinginstruction
* {@link https://www.npmjs.com/package/saxes-stream|saxes-stream}: not a 'stream.Writable'
* {@link https://www.npmjs.com/package/xml-streamer|xml-streamer}: based on 'node-expat', does not add any benefit
*/
class RootHandler { }
class AnyHandler { }
/**
* @constant {RootHandler} Root
* @type {RootHandler}
*/
const Root = new RootHandler();
/**
* @constant {AnyHandler} Any
* @type {AnyHandler}
*/
const Any = new AnyHandler();
/**
* Optional settings for the Twig parser
* @typedef ParserOptions
* @property {'sax' | 'expat' | 'saxophone'} [method] - The underlying parser. Either `'sax'`, `'expat'` or `'saxophone'`.
* @property {boolean} [xmlns] - If `true`, then namespaces are accessible by `namespace` property.
* @property {boolean} [trim] - If `true`, then turn any whitespace into a single space. Text and comments are trimmed.
* @property {boolean} [resumeAfterError] - If `true` then parser continues reading after an error. Otherwise it throws exception.
* @property {boolean} [partial] - If `true` then unhandled elements are purged.
* @example { method: 'expat', xmlns: true }
* @default { method: 'sax', xmlns: false, trim: true, resumeAfterError: false, partial: false }
*/
/**
* Reference to handler functions for Twig objects.<br>
* Element can be specified as string, Regular Expression, custom function, `Twig.Root` or `Twig.Any`<br>
* You can specify a `function` or a `event` name
* @typedef TwigHandler
* @property {HandlerCondition} tag - Element specification
* @property {HandlerFunction} [function] - Definition of handler function, either anonymous or explicit function
* @property {string} [event] - Type of the event to be emitted
*/
/**
* Condition to specify when handler shall be called<br>
* - If `string` then the element name must be equal to the string
* - If `string[]` then the element name must be included in string array
* - If `RegExp` then the element name must match the Regular Expression
* - If [HandlerConditionFilter](#HandlerConditionFilter) then function must return `true`
* - Use `Twig.Root` to call the handler on root element, i.e. when the end of document is reached
* - Use `Twig.Any` to call the handler on every element
* @typedef {string|string[]|RegExp|HandlerConditionFilter|Root|Any} HandlerCondition
*/
/**
* Handler function for Twig objects, i.e. the way you like to use the XML element.
* @typedef {function} HandlerFunction
* @param {Twig} elt - The current Twig element on which the function was called.
*/
/**
* Custom filter function to specify when handler shall be called
* @typedef {function} HandlerConditionFilter
* @param {string} name - Name of the element
* @returns {boolean} If the function returns `true`, then it is included in the filter
*/
/**
* Optional condition to get elements<br>
* - If `undefined`, then all elements are returned.<br>
* - If `string` then the element name must be equal to the string
* - If `RegExp` then the element name must match the Regular Expression
* - If [ElementConditionFilter](#ElementConditionFilter) then function must return `true`
* - Use [Twig](#Twig) object to find a specific element
* @typedef {string|RegExp|ElementConditionFilter|Twig|undefined} ElementCondition
*/
/**
* Custom filter function to select desired elements
* @typedef {function} ElementConditionFilter
* @param {string} name - Name of the element
* @param {Twig} elt - The Twig object
* @returns {boolean} If the function returns `true`, then it is included in the filter
*/
/**
* @typedef Parser
* @property {number} [currentLine] - The currently processed line in the XML-File.<br/>Not available on `saxophone` parser.
* @property {number} [currentColumn] - The currently processed column in the XML-File.<br/>Not available on `saxophone` parser.
* @returns {external:sax|external:node-expat|external:saxophone} The parser Object
*/
/**
* Create a new Twig parser
* @param {TwigHandler|TwigHandler[]} handler - Object or array of element specification and function to handle elements
* @param {ParserOptions} [options] - Object of optional options
* @throws {UnsupportedParser} - For an unsupported parser. Currently `expat` and `sax` (default) are supported.
* @returns {Parser} The parser Object
*/
function createParser(handler, options = {}) {
options = Object.assign({ method: SAX, xmlns: false, trim: true, resumeAfterError: false, partial: false }, options);
let parser;
let namespaces = {};
const handlerCheck = Array.isArray(handler) ? handler : [handler];
if (handlerCheck.find(x => x.tag === undefined) != null || handlerCheck.find(x => x.tag.length == 0) != null)
throw new ReferenceError(`'handler.tag' is not defined`);
if (options.partial && handlerCheck.find(x => x.tag instanceof AnyHandler) != null)
console.warn(`Using option '{ partial: true }' and handler '{ tag: Any, function: ${any.function.toString()} }' does not make much sense`);
// `parser.on("...", err => {...}` does not work, because I need access to 'this'
if (options.method === SAX) {
// Set options to have the same behavior as in expat
parser = require("sax").createStream(true, { strictEntities: true, position: true, xmlns: options.xmlns, trim: options.trim });
Object.defineProperty(parser, 'currentLine', {
enumerable: true,
get() { return parser._parser.line + 1; }
});
Object.defineProperty(parser, 'currentColumn', {
enumerable: true,
get() { return parser._parser.column + 1; }
});
parser.on("closetag", onClose.bind(null, handler, options));
parser.on("opentagstart", onStart.bind(null, {
handler: Array.isArray(handler) ? handler : [handler],
options: options,
namespaces: namespaces
}));
parser.on("processinginstruction", function (pi) {
if (pi.name === 'xml') {
// SAX parser handles XML declaration as Processing Instruction
let declaration = {};
for (let item of pi.body.split(' ')) {
let [k, v] = item.split('=');
declaration[k] = v.replaceAll('"', '').replaceAll("'", '');
}
tree = new Twig(null);
Object.defineProperty(tree, 'declaration', {
value: declaration,
writable: false,
enumerable: true
});
} else if (tree.PI === undefined) {
Object.defineProperty(tree, 'PI', {
value: { target: pi.name, data: pi.body },
writable: false,
enumerable: true
});
}
});
parser.on("attribute", function (attr) {
if (options.xmlns && (attr.uri ?? '') !== '' && attr.local !== undefined) {
namespaces[attr.local] = attr.uri;
if (current.name.includes(':')) {
Object.defineProperty(current, 'namespace', {
value: { local: attr.local, uri: attr.uri },
writable: false,
enumerable: true
});
} else {
current.attribute(attr.name, attr.value);
}
} else {
current.attribute(attr.name, attr.value);
}
});
parser.on("cdata", function (str) {
current.text = options.trim ? str.trim() : str;
});
parser.on('end', function () {
tree = undefined;
current = undefined;
parser.emit("finish");
parser.emit("close");
});
} else if (EXPAT.includes(options.method)) {
parser = require("node-expat").createParser();
Object.defineProperty(parser, 'currentLine', {
enumerable: true,
get() { return parser.parser.getCurrentLineNumber(); }
});
Object.defineProperty(parser, 'currentColumn', {
enumerable: true,
get() { return parser.parser.getCurrentColumnNumber(); }
});
parser.on("endElement", onClose.bind(null, handler, options));
parser.on("startElement", onStart.bind(null, {
handler: Array.isArray(handler) ? handler : [handler],
options: options,
namespaces: namespaces
}));
parser.on('xmlDecl', function (version, encoding, standalone) {
tree = new Twig(null);
let dec = {};
if (version !== undefined) dec.version = version;
if (encoding !== undefined) dec.encoding = encoding;
if (standalone !== undefined) dec.standalone = standalone;
Object.defineProperty(tree, 'declaration', {
value: dec,
writable: false,
enumerable: true
});
});
parser.on('processingInstruction', function (target, data) {
tree.PI = { target: target, data: data };
});
parser.on('end', function () {
tree = undefined;
current = undefined;
parser.emit("finish");
});
} else if (options.method === SAXOPHONE) {
const Saxophone = require('saxophone');
//const Saxophone = require('@alexbosworth/saxophone');
//const Saxophone = require('@pirxpilot/saxophone');
parser = new Saxophone();
parser.on("tagclose", onClose.bind(null, handler, options));
parser.on("tagopen", onStart.bind(null, {
handler: Array.isArray(handler) ? handler : [handler],
options: options,
namespaces: namespaces,
parser: parser,
Saxophone: Saxophone
}));
parser.on("cdata", function (str) {
current.text = options.trim ? str.contents.trim() : str.contents;
});
parser.on('processinginstruction', function (pi) {
if (pi.contents.startsWith('xml ')) {
let declaration = {};
for (let item of pi.contents.split(' ')) {
let [k, v] = item.split('=');
if (k === 'xml') continue;
declaration[k] = v.replaceAll('"', '').replaceAll("'", '');
}
tree = new Twig(null);
Object.defineProperty(tree, 'declaration', {
value: declaration,
writable: false,
enumerable: true
});
} else if (tree.PI === undefined) {
let instruction = { body: {} };
for (let item of pi.contents.split(' ')) {
let [k, v] = item.split('=');
if (v === undefined) {
instruction.name = k;
} else {
instruction.body[k] = v.replaceAll('"', '').replaceAll("'", '');
}
}
Object.defineProperty(tree, 'PI', {
value: { target: instruction.name, data: instruction.body },
writable: false,
enumerable: true
});
}
});
parser.on('finish', function () {
// saxophone parser does not emit 'end' Event
tree = undefined;
current = undefined;
});
} else {
throw new UnsupportedParser(options.method);
}
Object.defineProperty(parser, 'method', {
value: options.method,
writable: false,
enumerable: true
});
// Common events
parser.on('text', function (str) {
if (current === undefined || current === null) return;
if (options.method === SAXOPHONE) {
current.text = options.trim ? str.contents.trim() : str.contents;
} else {
current.text = options.trim ? str.trim() : str;
}
});
parser.on("comment", function (str) {
if (options.method === SAXOPHONE)
str = str.contents;
if (current.hasOwnProperty('comment')) {
if (typeof current.comment === 'string') {
current.comment = [current.comment, str.trim()];
} else {
current.comment.push(str.trim());
}
} else {
Object.defineProperty(current, 'comment', {
value: str.trim(),
writable: true,
enumerable: true,
configurable: true
});
}
});
parser.on('error', function (err) {
if (options.method === SAXOPHONE) {
console.error(err);
} else {
console.error(`error at line [${parser.currentLine}], column [${parser.currentColumn}]`, err);
if (options.resumeAfterError) {
parser.underlyingParser.error = null;
parser.underlyingParser.resume();
}
}
});
return parser;
}
/**
* Common Event hanlder for starting tag
* @param {object} binds - Additional parameter object
* @param {object|string} node - Node or Node name
* @param {object} attrs - Node Attributes
*/
function onStart(binds, node, attrs) {
const name = typeof node === 'string' ? node : node.name;
const handler = binds.handler;
const options = binds.options;
let namespaces = binds.namespaces;
if (attrs === undefined && options.method === SAXOPHONE)
attrs = binds.Saxophone.parseAttrs(node.attrs);
let attrNS = {};
if (options.xmlns && attrs !== undefined) {
for (let key of Object.keys(attrs).filter(x => !(x.startsWith('xmlns:') && name.includes(':'))))
attrNS[key] = attrs[key];
}
if (tree === undefined) {
tree = new Twig(name, current, options.xmlns ? attrNS : attrs);
} else {
if (current.isRoot && current.name === undefined) {
current.setRoot(name);
if (attrs !== undefined) {
for (let [key, val] of Object.entries(options.xmlns ? attrNS : attrs))
current.attribute(key, val);
}
} else {
let elt = new Twig(name, current, options.xmlns ? attrNS : attrs);
if (options.partial) {
for (let hndl of handler) {
if (typeof hndl.tag === 'string' && name === hndl.tag) {
elt.pin();
break;
} else if (Array.isArray(hndl.tag) && hndl.tag.includes(name)) {
elt.pin();
break;
} else if (hndl.tag instanceof RegExp && hndl.tag.test(name)) {
elt.pin();
break;
} else if (typeof hndl.tag === 'function' && hndl.tag(name, current ?? tree)) {
elt.pin();
break;
}
}
}
}
}
if (options.xmlns) {
if (EXPAT.concat(SAXOPHONE).includes(options.method)) {
for (let key of Object.keys(attrs).filter(x => x.startsWith('xmlns:')))
namespaces[key.split(':')[1]] = attrs[key];
}
if (name.includes(':')) {
let prefix = name.split(':')[0];
if (namespaces[prefix] !== undefined) {
Object.defineProperty(current, 'namespace', {
value: { local: prefix, uri: namespaces[prefix] },
writable: false,
enumerable: true
});
}
}
}
if (options.method === SAXOPHONE && node.isSelfClosing)
binds.parser.emit("tagclose", node);
}
/**
* Common Event hanlder for closing tag
* @param {TwigHandler|TwigHandler[]} handler - Object or array of element specification and function to handle elements
* @param {ParserOptions} options - Object of optional options
* @param {string} name - Event handler parameter
*/
function onClose(handler, options, name) {
current.close();
let purge = true;
if (options.method === SAXOPHONE)
name = name.name;
for (let hndl of Array.isArray(handler) ? handler : [handler]) {
if (hndl.tag instanceof AnyHandler) {
if (typeof hndl.function === 'function') hndl.function(current ?? tree);
if (typeof hndl.event === 'string') parser.emit(hndl.event, current ?? tree);
purge = false;
} else if (hndl.tag instanceof RootHandler && current.isRoot) {
if (typeof hndl.function === 'function') hndl.function(tree);
if (typeof hndl.event === 'string') parser.emit(hndl.event, tree);
purge = false;
} else if (Array.isArray(hndl.tag) && hndl.tag.includes(name)) {
if (typeof hndl.function === 'function') hndl.function(current ?? tree);
if (typeof hndl.event === 'string') parser.emit(hndl.event, current ?? tree);
purge = false;
} else if (typeof hndl.tag === 'string' && name === hndl.tag) {
if (typeof hndl.function === 'function') hndl.function(current ?? tree);
if (typeof hndl.event === 'string') parser.emit(hndl.event, current ?? tree);
purge = false;
} else if (hndl.tag instanceof RegExp && hndl.tag.test(name)) {
if (typeof hndl.function === 'function') hndl.function(current ?? tree);
if (typeof hndl.event === 'string') parser.emit(hndl.event, current ?? tree);
purge = false;
} else if (typeof hndl.tag === 'function' && hndl.tag(name, current ?? tree)) {
if (typeof hndl.function === 'function') hndl.function(current ?? tree);
if (typeof hndl.event === 'string') parser.emit(hndl.event, current ?? tree);
purge = false;
}
}
if (options.partial && purge && !current.pinned && !current.isRoot)
current.purge();
current = current.parent();
}
/**
* Generic class modeling a XML Node
* @class Twig
*/
class Twig {
/**
* Optional condition to get attributes<br>
* - If `undefined`, then all attributes are returned.<br>
* - If `string` then the attribute name must be equal to the string
* - If `RegExp` then the attribute name must match the Regular Expression
* - If [AttributeConditionFilter](#AttributeConditionFilter) then the attribute must filter function
* @typedef {string|RegExp|AttributeConditionFilter} AttributeCondition
*/
/**
* Custom filter function to get desired attributes
* @typedef {function} AttributeConditionFilter
* @param {string} name - Name of the attribute
* @param {string|number} value - Value of the attribute
*/
/**
* XML Processing Instruction object, exist only on root
* @typedef {object} #PI
*/
/**
* XML Declaration object, exist only on root
* @typedef {object} #declaration
*/
/**
* XML namespace of element. Exist onl when parsed with `xmlns: true`
* @typedef {object} #namespace
*/
/**
* Comment or array of comments inside the XML Elements
* @typedef {string|string[]} #comment
*/
/**
* XML attribute `{ <attribute 1>: <value 1>, <attribute 2>: <value 2>, ... }`
* @type {?object}
*/
#attributes = {};
/**
* Content of XML Element
* @type {?string|number}
*/
#text = null;
/**
* The XML tag name
* @type {string}
*/
#name;
/**
* Child XML Elements
* @type {Twig[]}
*/
#children = [];
/**
* The parent object. Undefined on root element
* @type {Twig | undefined}
*/
#parent;
/**
* Determines whether twig is needed in partial load
* @type {boolean}
*/
#pinned = false;
/**
* Create a new Twig object
* @param {?string} name - The name of the XML element
* @param {Twig} [parent] - The parent object
* @param {object} [attributes] - Attribute object
* @param {string|number} [index] - Position name 'first', 'last' or the position in the current `children` array.<br>Defaults to 'last'
*/
constructor(name, parent, attributes, index) {
if (index === undefined)
current = this;
if (name === null) {
// Root element not available yet
tree = this;
} else {
this.#name = name;
if (attributes !== undefined)
this.#attributes = attributes;
if (parent === undefined) {
// Root element
tree = this;
} else {
this.#parent = parent;
if (this.#parent.#pinned)
this.#pinned = true;
if (index === 'last' || index === undefined) {
parent.#children.push(this);
} else if (index === 'first') {
parent.#children.unshift(this);
} else if (typeof index === 'number') {
parent.#children = parent.#children.slice(0, index).concat(this, parent.#children.slice(index));
} else {
parent.#children.push(this);
}
}
}
}
/**
* Purges the current, typically used after element has been processed.<br>The root object cannot be purged.
*/
purge = function () {
if (!this.isRoot)
this.#parent.#children = this.#parent.#children.filter(x => !Object.is(this, x));
};
/**
* Purges up to the elt element. This allows you to keep part of the tree in memory when you purge.<br>
* The `elt` object is not purged. If you like to purge including `elt`, use `.purgeUpTo(elt.previous())`
* @param {Twig} [elt] - Up to this element the tree will be purged.
* If `undefined` then the current element is purged (i.e. `purge()`)
*/
purgeUpTo = function (elt) {
if (elt === undefined) {
this.purge();
} else {
let toPurge = this;
while (toPurge !== null && !Object.is(toPurge, elt)) {
const prev = toPurge.previous();
toPurge.purge();
toPurge = prev;
}
}
};
/**
* Escapes special XML characters. According W3C specification these are only `&, <, >, ", '` - this is a XML parser, not HTML!
* @param {string} text - Input text to be escaped
*/
escapeEntity = function (text) {
return text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
};
/**
* Sets the name of root element. In some cases the root is created before the XML-Root element is available<br>
* Used internally!
* @param {string} name - The element name
* @private
*/
setRoot(name) {
if (this.isRoot)
this.#name = name;
}
/**
* Returns `true` if the element is empty, otherwise `false`.
* An empty element has no text nor any child elements, however empty elements can have attributes.
* @returns {boolean} true if empty element
*/
get isEmpty() {
return this.#text === null && this.#children.length == 0;
}
/**
* Returns the level of the element. Root element has 0, children have 1, grand-children 2 and so on
* @returns {number} The level of the element.
*/
get level() {
let ret = 0;
let p = this.#parent;
while (p !== undefined) {
p = p.#parent;
ret++;
}
return ret;
}
/**
* Returns `true` if element is the root object
* @returns {boolean} true if root element
*/
get isRoot() {
return this.#parent === undefined;
}
/**
* Returns `true` if element has child elements
* @returns {boolean} true if has child elements exists
*/
get hasChildren() {
return this.#children.length > 0;
}
/**
* The position in `#children` array. For root object 0
* @returns {number} Position of element in parent
*/
get index() {
return this.isRoot ? 0 : this.#parent.#children.indexOf(this);
}
/**
* Returns the name of the element.
* @returns {string} Element name
*/
get name() {
return this.#name;
}
/**
* Returns the name of the element. Synonym for `twig.name`
* @returns {string} Element name
*/
get tag() {
return this.#name;
}
/**
* The text of the element. No matter if given as text or CDATA entity
* @returns {string} Element text or empty string
*/
get text() {
return this.#text ?? '';
}
/**
* Update the text of the element
* @param {string|number|bigint|boolean} value - New text of the element
* @throws {UnsupportedType} - If value is not a string, boolean or numeric type
*/
set text(value) {
if (this.#text === null) this.#text = '';
if (typeof value === 'string')
this.#text += value;
else if (['number', 'bigint', 'boolean'].includes(typeof value))
this.#text += value.toString();
else
throw new UnsupportedType(value);
}
/**
* Pins the current element. Used for partial reading.
*/
pin = function () {
this.#pinned = true;
};
/**
* Checks if element is pinned
* @returns {boolean} `true` when the element is pinned
*/
get pinned() {
return this.#pinned;
}
/**
* Closes the element
*/
close = function () {
Object.seal(this);
};
/**
* XML-Twig for dummies :-)
* @returns {string} The XML-Tree which is currently available in RAM - no valid XML Structure
*/
debug = function () {
return this.root().writer(true, true).output;
};
/**
* Returns XML string of the element
* @returns {string} The XML-Element as string
*/
toString = function () {
return this.writer(true).toString();
};
/**
* Internal recursive function used by `writer()`
* @param {external:XMLWriter} xw - The writer object
* @param {Twig[]} childArray - Array of child elements
*/
#addChild = function (xw, childArray, cur, debug) {
for (let elt of childArray) {
xw.startElement(elt.name);
for (let [key, val] of Object.entries(elt.attributes))
xw.writeAttribute(key, val);
if (elt.text !== null)
xw.text(elt.text);
this.#addChild(xw, elt.children(), elt, debug);
}
if (!debug || Object.isSealed(cur)) xw.endElement();
};
/**
* Creates xml-writer from current element
* @param {?boolean|string|external:XMLWriter} par - `true` or intention character or an already created XMLWriter
* @returns {external:XMLWriter}
*/
writer = function (par, debug) {
const XMLWriter = require('xml-writer');
let xw = par instanceof XMLWriter ? par : new XMLWriter(par);
xw.startElement(this.#name);
for (let [key, val] of Object.entries(this.#attributes))
xw.writeAttribute(key, val);
if (this.#text !== null)
xw.text(this.#text);
this.#addChild(xw, this.#children, this, debug);
if (!debug || Object.isSealed(this)) xw.endElement();
return xw;
};
/**
* Returns attribute value or `null` if not found.<br>
* If more than one matches the condition, then it returns object as [attribute()](#attribute)
* @param {AttributeCondition} [condition] - Optional condition to select attribute
* @returns {?string|number|object} - The value of the attribute or `null` if the does not exist
*/
attr = function (condition) {
let attr = this.attribute(condition);
if (attr === null)
return null;
return Object.keys(attr).length === 1 ? attr[Object.keys(attr)[0]] : attr;
};
/**
* Returns all attributes of the element
* @returns {object} All XML Attributes
*/
get attributes() {
return this.#attributes;
}
/**
* Check if the attribute exist or not
* @param {string} name - The name of the attribute
* @returns {boolean} - Returns `true` if the attribute exists, else `false`
*/
hasAttribute = function (name) {
return this.#attributes[name] !== undefined;
};
/**
* Retrieve or update XML attribute. For update, the condition must be a string, i.e. must match to one attribute only.
* @param {AttributeCondition} [condition] - Optional condition to select attributes
* @param {string|number|bigint|boolean} [value] - New value of the attribute.<br>If `undefined` then existing attributes is returned.
* @returns {object} Attributes or `null` if no matching attribute found
* @example attribute((name, val) => { return name === 'age' && val > 50})
* attribute((name) => { return ['firstName', 'lastName'].includes(name) })
* attribute('firstName')
* attribute(/name/i)
*/
attribute = function (condition, value) {
if (value === undefined) {
let attr;
if (condition === undefined) {
attr = this.#attributes;
} else if (typeof condition === 'function') {
attr = Object.fromEntries(Object.entries(this.#attributes).filter(([key, val]) => condition(key, val)));
} else if (typeof condition === 'string') {
attr = this.attribute(key => key === condition);
} else if (condition instanceof RegExp) {
attr = this.attribute(key => condition.test(key));
} else if (condition instanceof Twig) {
throw new UnsupportedCondition(condition, ['string', 'RegEx', 'function']);
} else {
return this.attribute();
}
return attr === null || Object.keys(attr).length == 0 ? null : attr;
} else if (typeof condition === 'string') {
if (typeof value === 'string')
this.#attributes[condition] = value;
else if (['number', 'bigint', 'boolean'].includes(typeof value))
this.#attributes[condition] = value.toString();
else
throw new UnsupportedType(value);
} else {
console.warn('Condition must be a `string` if you like to update an attribute');
}
};
/**
* Delete the attribute
* @param {string} name - The attribute name
*/
deleteAttribute = function (name) {
delete this.#attributes[name];
};
/**
* Returns the root object
* @returns {Twig} The root element of XML tree
*/
root = function () {
if (this.isRoot) {
return this;
} else {
let ret = this.#parent;
while (!ret.isRoot) {
ret = ret.#parent;
}
return ret;
}
};
/**
* Returns the parent element or null if root element
* @returns {Twig} The parament element
*/
parent = function () {
return this.isRoot ? null : this.#parent;
};
/**
* @returns {Twig} - The current element
*/
self = function () {
return this;
};
/**
* Common function to filter Twig elements from array
* @param {Twig|Twig[]} elements - Array of elements you like to filter or a single element
* @param {ElementCondition} [condition] - The filter condition
* @returns {Twig[]} List of matching elements or empty array
*/
filterElements(elements, condition) {
if (!Array.isArray(elements))
return this.filterElements([elements], condition);
if (condition !== undefined) {
if (typeof condition === 'string') {
return elements.filter(x => x.name === condition);
} else if (condition instanceof RegExp) {
return elements.filter(x => condition.test(x.name));
} else if (condition instanceof Twig) {
return elements.filter(x => Object.is(x, condition));
} else if (typeof condition === 'function') {
return elements.filter(x => condition(x.name, x));
}
}
return elements;
}
/**
* Common function to filter Twig element
* @param {Twig} element - Element you like to filter
* @param {ElementCondition} [condition] - The filter condition
* @returns {boolean} `true` if the condition matches
*/
testElement(element, condition) {
if (condition === undefined) {
return true;
} else if (typeof condition === 'string') {
return element.name === condition;
} else if (condition instanceof RegExp) {
return condition.test(element.name);
} else if (condition instanceof Twig) {
return Object.is(element, condition);
} else if (typeof condition === 'function') {
return condition(element.name, element);
}
return false;
}
/**
* All children, optionally matching `condition` of the current element or empty array
* @param {ElementCondition} [condition] - Optional condition
* @returns {Twig[]}
*/
children = function (condition) {
return this.filterElements(this.#children, condition);
};
/**
* Returns the next matching element.
* @param {ElementCondition} [condition] - Optional condition
* @returns {?Twig} - The next element
* @see https://www.w3.org/TR/xpath-datamodel-31/#document-order
*/
next = function (condition) {
if (this === null)
return null;
let elt;
if (this.hasChildren) {