/
write.js
837 lines (632 loc) · 17.2 KB
/
write.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
import {
map,
forEach,
isString,
filter,
assign
} from 'min-dash';
import {
isSimpleType,
parseNameNS
} from 'moddle';
import {
hasLowerCaseAlias,
serializeAsType,
serializeAsProperty,
DEFAULT_NS_MAP,
XSI_TYPE
} from './common';
var XML_PREAMBLE = '<?xml version="1.0" encoding="UTF-8"?>\n';
var ESCAPE_ATTR_CHARS = /<|>|'|"|&|\n\r|\n/g;
var ESCAPE_CHARS = /<|>|&/g;
export function Namespaces(parent) {
var prefixMap = {};
var uriMap = {};
var used = {};
var wellknown = [];
var custom = [];
// API
this.byUri = function(uri) {
return uriMap[uri] || (
parent && parent.byUri(uri)
);
};
this.add = function(ns, isWellknown) {
uriMap[ns.uri] = ns;
if (isWellknown) {
wellknown.push(ns);
} else {
custom.push(ns);
}
this.mapPrefix(ns.prefix, ns.uri);
};
this.uriByPrefix = function(prefix) {
return prefixMap[prefix || 'xmlns'];
};
this.mapPrefix = function(prefix, uri) {
prefixMap[prefix || 'xmlns'] = uri;
};
this.logUsed = function(ns) {
var uri = ns.uri;
used[uri] = this.byUri(uri);
};
this.getUsed = function(ns) {
function isUsed(ns) {
return used[ns.uri];
}
var allNs = [].concat(wellknown, custom);
return allNs.filter(isUsed);
};
}
function lower(string) {
return string.charAt(0).toLowerCase() + string.slice(1);
}
function nameToAlias(name, pkg) {
if (hasLowerCaseAlias(pkg)) {
return lower(name);
} else {
return name;
}
}
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
function nsName(ns) {
if (isString(ns)) {
return ns;
} else {
return (ns.prefix ? ns.prefix + ':' : '') + ns.localName;
}
}
function getNsAttrs(namespaces) {
return map(namespaces.getUsed(), function(ns) {
var name = 'xmlns' + (ns.prefix ? ':' + ns.prefix : '');
return { name: name, value: ns.uri };
});
}
function getElementNs(ns, descriptor) {
if (descriptor.isGeneric) {
return assign({ localName: descriptor.ns.localName }, ns);
} else {
return assign({ localName: nameToAlias(descriptor.ns.localName, descriptor.$pkg) }, ns);
}
}
function getPropertyNs(ns, descriptor) {
return assign({ localName: descriptor.ns.localName }, ns);
}
function getSerializableProperties(element) {
var descriptor = element.$descriptor;
return filter(descriptor.properties, function(p) {
var name = p.name;
if (p.isVirtual) {
return false;
}
// do not serialize defaults
if (!element.hasOwnProperty(name)) {
return false;
}
var value = element[name];
// do not serialize default equals
if (value === p.default) {
return false;
}
// do not serialize null properties
if (value === null) {
return false;
}
return p.isMany ? value.length : true;
});
}
var ESCAPE_ATTR_MAP = {
'\n': '#10',
'\n\r': '#10',
'"': '#34',
'\'': '#39',
'<': '#60',
'>': '#62',
'&': '#38'
};
var ESCAPE_MAP = {
'<': 'lt',
'>': 'gt',
'&': 'amp'
};
function escape(str, charPattern, replaceMap) {
// ensure we are handling strings here
str = isString(str) ? str : '' + str;
return str.replace(charPattern, function(s) {
return '&' + replaceMap[s] + ';';
});
}
/**
* Escape a string attribute to not contain any bad values (line breaks, '"', ...)
*
* @param {String} str the string to escape
* @return {String} the escaped string
*/
function escapeAttr(str) {
return escape(str, ESCAPE_ATTR_CHARS, ESCAPE_ATTR_MAP);
}
function escapeBody(str) {
return escape(str, ESCAPE_CHARS, ESCAPE_MAP);
}
function filterAttributes(props) {
return filter(props, function(p) { return p.isAttr; });
}
function filterContained(props) {
return filter(props, function(p) { return !p.isAttr; });
}
function ReferenceSerializer(tagName) {
this.tagName = tagName;
}
ReferenceSerializer.prototype.build = function(element) {
this.element = element;
return this;
};
ReferenceSerializer.prototype.serializeTo = function(writer) {
writer
.appendIndent()
.append('<' + this.tagName + '>' + this.element.id + '</' + this.tagName + '>')
.appendNewLine();
};
function BodySerializer() {}
BodySerializer.prototype.serializeValue =
BodySerializer.prototype.serializeTo = function(writer) {
writer.append(
this.escape
? escapeBody(this.value)
: this.value
);
};
BodySerializer.prototype.build = function(prop, value) {
this.value = value;
if (prop.type === 'String' && value.search(ESCAPE_CHARS) !== -1) {
this.escape = true;
}
return this;
};
function ValueSerializer(tagName) {
this.tagName = tagName;
}
inherits(ValueSerializer, BodySerializer);
ValueSerializer.prototype.serializeTo = function(writer) {
writer
.appendIndent()
.append('<' + this.tagName + '>');
this.serializeValue(writer);
writer
.append('</' + this.tagName + '>')
.appendNewLine();
};
function ElementSerializer(parent, propertyDescriptor) {
this.body = [];
this.attrs = [];
this.parent = parent;
this.propertyDescriptor = propertyDescriptor;
}
ElementSerializer.prototype.build = function(element) {
this.element = element;
var elementDescriptor = element.$descriptor,
propertyDescriptor = this.propertyDescriptor;
var otherAttrs,
properties;
var isGeneric = elementDescriptor.isGeneric;
if (isGeneric) {
otherAttrs = this.parseGeneric(element);
} else {
otherAttrs = this.parseNsAttributes(element);
}
if (propertyDescriptor) {
this.ns = this.nsPropertyTagName(propertyDescriptor);
} else {
this.ns = this.nsTagName(elementDescriptor);
}
// compute tag name
this.tagName = this.addTagName(this.ns);
if (!isGeneric) {
properties = getSerializableProperties(element);
this.parseAttributes(filterAttributes(properties));
this.parseContainments(filterContained(properties));
}
this.parseGenericAttributes(element, otherAttrs);
return this;
};
ElementSerializer.prototype.nsTagName = function(descriptor) {
var effectiveNs = this.logNamespaceUsed(descriptor.ns);
return getElementNs(effectiveNs, descriptor);
};
ElementSerializer.prototype.nsPropertyTagName = function(descriptor) {
var effectiveNs = this.logNamespaceUsed(descriptor.ns);
return getPropertyNs(effectiveNs, descriptor);
};
ElementSerializer.prototype.isLocalNs = function(ns) {
return ns.uri === this.ns.uri;
};
/**
* Get the actual ns attribute name for the given element.
*
* @param {Object} element
* @param {Boolean} [element.inherited=false]
*
* @return {Object} nsName
*/
ElementSerializer.prototype.nsAttributeName = function(element) {
var ns;
if (isString(element)) {
ns = parseNameNS(element);
} else {
ns = element.ns;
}
// return just local name for inherited attributes
if (element.inherited) {
return { localName: ns.localName };
}
// parse + log effective ns
var effectiveNs = this.logNamespaceUsed(ns);
// LOG ACTUAL namespace use
this.getNamespaces().logUsed(effectiveNs);
// strip prefix if same namespace like parent
if (this.isLocalNs(effectiveNs)) {
return { localName: ns.localName };
} else {
return assign({ localName: ns.localName }, effectiveNs);
}
};
ElementSerializer.prototype.parseGeneric = function(element) {
var self = this,
body = this.body;
var attributes = [];
forEach(element, function(val, key) {
var nonNsAttr;
if (key === '$body') {
body.push(new BodySerializer().build({ type: 'String' }, val));
} else
if (key === '$children') {
forEach(val, function(child) {
body.push(new ElementSerializer(self).build(child));
});
} else
if (key.indexOf('$') !== 0) {
nonNsAttr = self.parseNsAttribute(element, key, val);
if (nonNsAttr) {
attributes.push({ name: key, value: val });
}
}
});
return attributes;
};
ElementSerializer.prototype.parseNsAttribute = function(element, name, value) {
var model = element.$model;
var nameNs = parseNameNS(name);
var ns;
// parse xmlns:foo="http://foo.bar"
if (nameNs.prefix === 'xmlns') {
ns = { prefix: nameNs.localName, uri: value };
}
// parse xmlns="http://foo.bar"
if (!nameNs.prefix && nameNs.localName === 'xmlns') {
ns = { uri: value };
}
if (!ns) {
return {
name: name,
value: value
};
}
if (model && model.getPackage(value)) {
// register well known namespace
this.logNamespace(ns, true, true);
} else {
// log custom namespace directly as used
var actualNs = this.logNamespaceUsed(ns, true);
this.getNamespaces().logUsed(actualNs);
}
};
/**
* Parse namespaces and return a list of left over generic attributes
*
* @param {Object} element
* @return {Array<Object>}
*/
ElementSerializer.prototype.parseNsAttributes = function(element, attrs) {
var self = this;
var genericAttrs = element.$attrs;
var attributes = [];
// parse namespace attributes first
// and log them. push non namespace attributes to a list
// and process them later
forEach(genericAttrs, function(value, name) {
var nonNsAttr = self.parseNsAttribute(element, name, value);
if (nonNsAttr) {
attributes.push(nonNsAttr);
}
});
return attributes;
};
ElementSerializer.prototype.parseGenericAttributes = function(element, attributes) {
var self = this;
forEach(attributes, function(attr) {
// do not serialize xsi:type attribute
// it is set manually based on the actual implementation type
if (attr.name === XSI_TYPE) {
return;
}
try {
self.addAttribute(self.nsAttributeName(attr.name), attr.value);
} catch (e) {
console.warn(
'missing namespace information for ',
attr.name, '=', attr.value, 'on', element,
e);
}
});
};
ElementSerializer.prototype.parseContainments = function(properties) {
var self = this,
body = this.body,
element = this.element;
forEach(properties, function(p) {
var value = element.get(p.name),
isReference = p.isReference,
isMany = p.isMany;
if (!isMany) {
value = [ value ];
}
if (p.isBody) {
body.push(new BodySerializer().build(p, value[0]));
} else
if (isSimpleType(p.type)) {
forEach(value, function(v) {
body.push(new ValueSerializer(self.addTagName(self.nsPropertyTagName(p))).build(p, v));
});
} else
if (isReference) {
forEach(value, function(v) {
body.push(new ReferenceSerializer(self.addTagName(self.nsPropertyTagName(p))).build(v));
});
} else {
// allow serialization via type
// rather than element name
var asType = serializeAsType(p),
asProperty = serializeAsProperty(p);
forEach(value, function(v) {
var serializer;
if (asType) {
serializer = new TypeSerializer(self, p);
} else
if (asProperty) {
serializer = new ElementSerializer(self, p);
} else {
serializer = new ElementSerializer(self);
}
body.push(serializer.build(v));
});
}
});
};
ElementSerializer.prototype.getNamespaces = function(local) {
var namespaces = this.namespaces,
parent = this.parent,
parentNamespaces;
if (!namespaces) {
parentNamespaces = parent && parent.getNamespaces();
if (local || !parentNamespaces) {
this.namespaces = namespaces = new Namespaces(parentNamespaces);
} else {
namespaces = parentNamespaces;
}
}
return namespaces;
};
ElementSerializer.prototype.logNamespace = function(ns, wellknown, local) {
var namespaces = this.getNamespaces(local);
var nsUri = ns.uri,
nsPrefix = ns.prefix;
var existing = namespaces.byUri(nsUri);
if (!existing) {
namespaces.add(ns, wellknown);
}
namespaces.mapPrefix(nsPrefix, nsUri);
return ns;
};
ElementSerializer.prototype.logNamespaceUsed = function(ns, local) {
var element = this.element,
model = element.$model,
namespaces = this.getNamespaces(local);
// ns may be
//
// * prefix only
// * prefix:uri
// * localName only
var prefix = ns.prefix,
uri = ns.uri,
newPrefix, idx,
wellknownUri;
// handle anonymous namespaces (elementForm=unqualified), cf. #23
if (!prefix && !uri) {
return { localName: ns.localName };
}
wellknownUri = DEFAULT_NS_MAP[prefix] || model && (model.getPackage(prefix) || {}).uri;
uri = uri || wellknownUri || namespaces.uriByPrefix(prefix);
if (!uri) {
throw new Error('no namespace uri given for prefix <' + prefix + '>');
}
ns = namespaces.byUri(uri);
if (!ns) {
newPrefix = prefix;
idx = 1;
// find a prefix that is not mapped yet
while (namespaces.uriByPrefix(newPrefix)) {
newPrefix = prefix + '_' + idx++;
}
ns = this.logNamespace({ prefix: newPrefix, uri: uri }, wellknownUri === uri);
}
if (prefix) {
namespaces.mapPrefix(prefix, uri);
}
return ns;
};
ElementSerializer.prototype.parseAttributes = function(properties) {
var self = this,
element = this.element;
forEach(properties, function(p) {
var value = element.get(p.name);
if (p.isReference) {
if (!p.isMany) {
value = value.id;
}
else {
var values = [];
forEach(value, function(v) {
values.push(v.id);
});
// IDREFS is a whitespace-separated list of references.
value = values.join(' ');
}
}
self.addAttribute(self.nsAttributeName(p), value);
});
};
ElementSerializer.prototype.addTagName = function(nsTagName) {
var actualNs = this.logNamespaceUsed(nsTagName);
this.getNamespaces().logUsed(actualNs);
return nsName(nsTagName);
};
ElementSerializer.prototype.addAttribute = function(name, value) {
var attrs = this.attrs;
if (isString(value)) {
value = escapeAttr(value);
}
attrs.push({ name: name, value: value });
};
ElementSerializer.prototype.serializeAttributes = function(writer) {
var attrs = this.attrs,
namespaces = this.namespaces;
if (namespaces) {
attrs = getNsAttrs(namespaces).concat(attrs);
}
forEach(attrs, function(a) {
writer
.append(' ')
.append(nsName(a.name)).append('="').append(a.value).append('"');
});
};
ElementSerializer.prototype.serializeTo = function(writer) {
var firstBody = this.body[0],
indent = firstBody && firstBody.constructor !== BodySerializer;
writer
.appendIndent()
.append('<' + this.tagName);
this.serializeAttributes(writer);
writer.append(firstBody ? '>' : ' />');
if (firstBody) {
if (indent) {
writer
.appendNewLine()
.indent();
}
forEach(this.body, function(b) {
b.serializeTo(writer);
});
if (indent) {
writer
.unindent()
.appendIndent();
}
writer.append('</' + this.tagName + '>');
}
writer.appendNewLine();
};
/**
* A serializer for types that handles serialization of data types
*/
function TypeSerializer(parent, propertyDescriptor) {
ElementSerializer.call(this, parent, propertyDescriptor);
}
inherits(TypeSerializer, ElementSerializer);
TypeSerializer.prototype.parseNsAttributes = function(element) {
// extracted attributes
var attributes = ElementSerializer.prototype.parseNsAttributes.call(this, element);
var descriptor = element.$descriptor;
// only serialize xsi:type if necessary
if (descriptor.name === this.propertyDescriptor.type) {
return attributes;
}
var typeNs = this.typeNs = this.nsTagName(descriptor);
this.getNamespaces().logUsed(this.typeNs);
// add xsi:type attribute to represent the elements
// actual type
var pkg = element.$model.getPackage(typeNs.uri),
typePrefix = (pkg.xml && pkg.xml.typePrefix) || '';
this.addAttribute(
this.nsAttributeName(XSI_TYPE),
(typeNs.prefix ? typeNs.prefix + ':' : '') + typePrefix + descriptor.ns.localName
);
return attributes;
};
TypeSerializer.prototype.isLocalNs = function(ns) {
return ns.uri === (this.typeNs || this.ns).uri;
};
function SavingWriter() {
this.value = '';
this.write = function(str) {
this.value += str;
};
}
function FormatingWriter(out, format) {
var indent = [''];
this.append = function(str) {
out.write(str);
return this;
};
this.appendNewLine = function() {
if (format) {
out.write('\n');
}
return this;
};
this.appendIndent = function() {
if (format) {
out.write(indent.join(' '));
}
return this;
};
this.indent = function() {
indent.push('');
return this;
};
this.unindent = function() {
indent.pop();
return this;
};
}
/**
* A writer for meta-model backed document trees
*
* @param {Object} options output options to pass into the writer
*/
export function Writer(options) {
options = assign({ format: false, preamble: true }, options || {});
function toXML(tree, writer) {
var internalWriter = writer || new SavingWriter();
var formatingWriter = new FormatingWriter(internalWriter, options.format);
if (options.preamble) {
formatingWriter.append(XML_PREAMBLE);
}
new ElementSerializer().build(tree).serializeTo(formatingWriter);
if (!writer) {
return internalWriter.value;
}
}
return {
toXML: toXML
};
}