-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathindex.ts
1451 lines (1269 loc) · 47.3 KB
/
index.ts
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
/*
* Copyright (c) 2011 Vinay Pulim <vinay@milewise.com>
* MIT Licensed
*
*/
/*jshint proto:true*/
import { ok as assert } from 'assert';
import debugBuilder from 'debug';
import * as fs from 'fs';
import * as _ from 'lodash';
import * as path from 'path';
import * as sax from 'sax';
import * as stripBom from 'strip-bom';
import * as url from 'url';
import { HttpClient } from '../http';
import { NamespaceContext } from '../nscontext';
import { IOptions } from '../types';
import { findPrefix, splitQName, TNS_PREFIX, xmlEscape } from '../utils';
import * as elements from './elements';
const debug = debugBuilder('node-soap');
const XSI_URI = 'http://www.w3.org/2001/XMLSchema-instance';
export function trim(text) {
return text.trim();
}
function deepMerge<A, B>(destination: A, source: B): A & B {
return _.mergeWith(destination, source, (a, b) => {
return Array.isArray(a) ? a.concat(b) : undefined;
});
}
function appendColon(ns: string): string {
return (ns && ns.charAt(ns.length - 1) !== ':') ? ns + ':' : ns;
}
function noColonNameSpace(ns: string): string {
return (ns && ns.charAt(ns.length - 1) === ':') ? ns.substring(0, ns.length - 1) : ns;
}
interface IInitializedOptions extends IOptions {
ignoredNamespaces?: string[];
}
export class WSDL {
public ignoredNamespaces = ['tns', 'targetNamespace', 'typedNamespace'];
public ignoreBaseNameSpaces = false;
public valueKey = '$value';
public xmlKey = '$xml';
public xmlnsInEnvelope: string;
public xmlnsInHeader: string;
public uri: string;
public definitions: elements.DefinitionsElement;
public options: IInitializedOptions;
/** @internal */
public WSDL_CACHE;
private callback: (err: Error, caller?) => void;
private services: { [name: string]: elements.ServiceElement };
private xml: string;
private _includesWsdl;
private _originalIgnoredNamespaces;
constructor(definition: any, uri: string, options: IOptions) {
let fromFunc;
this.uri = uri;
this.callback = () => { };
this._includesWsdl = [];
// initialize WSDL cache
this.WSDL_CACHE = {};
if (options && options.WSDL_CACHE) {
this.WSDL_CACHE = options.WSDL_CACHE;
}
this._initializeOptions(options);
if (typeof definition === 'string') {
definition = stripBom(definition);
fromFunc = this._fromXML;
} else if (typeof definition === 'object') {
fromFunc = this._fromServices;
} else {
throw new Error('WSDL constructor takes either an XML string or service definition');
}
process.nextTick(() => {
try {
fromFunc.call(this, definition);
} catch (e) {
return this.callback(e);
}
this.processIncludes((err) => {
let name;
if (err) {
return this.callback(err);
}
try {
this.definitions.deleteFixedAttrs();
const services = this.services = this.definitions.services;
if (services) {
for (name in services) {
services[name].postProcess(this.definitions);
}
}
const complexTypes = this.definitions.complexTypes;
if (complexTypes) {
for (name in complexTypes) {
complexTypes[name].deleteFixedAttrs();
}
}
// for document style, for every binding, prepare input message element name to (methodName, output message element name) mapping
const bindings = this.definitions.bindings;
for (const bindingName in bindings) {
const binding = bindings[bindingName];
if (typeof binding.style === 'undefined') {
binding.style = 'document';
}
const methods = binding.methods;
const topEls: elements.ITopElements = binding.topElements = {};
for (const methodName in methods) {
if ((methods[methodName].style || binding.style) !== 'document') {
continue;
}
if (methods[methodName].input) {
const inputName = methods[methodName].input.$name;
let outputName = '';
if (methods[methodName].output) {
outputName = methods[methodName].output.$name;
}
topEls[inputName] = { methodName: methodName, outputName: outputName };
}
}
}
// prepare soap envelope xmlns definition string
this.xmlnsInEnvelope = this._xmlnsMap();
this.callback(err, this);
} catch (e) {
this.callback(e);
}
});
});
}
public onReady(callback: (err: Error) => void): void {
if (callback) {
this.callback = callback;
}
}
public processIncludes(callback) {
const schemas = this.definitions.schemas;
let includes: elements.IInclude[] = [];
for (const ns in schemas) {
const schema = schemas[ns];
includes = includes.concat(schema.includes || []);
}
this._processNextInclude(includes, callback);
}
public describeServices() {
const services = {};
for (const name in this.services) {
const service = this.services[name];
services[name] = service.description(this.definitions);
}
return services;
}
public toXML() {
return this.xml || '';
}
public getSaxStream(xml) {
const saxStream = sax.createStream(true, null);
xml.pipe(saxStream);
return saxStream;
}
public xmlToObject(xml, callback?) {
const p: any = typeof callback === 'function' ? {} : sax.parser(true, null);
let objectName = null;
const root: any = {};
const schema = {
Envelope: {
Header: {
Security: {
UsernameToken: {
Username: 'string',
Password: 'string',
},
},
},
Body: {
Fault: {
faultcode: 'string',
faultstring: 'string',
detail: 'string',
},
},
},
};
const stack: any[] = [{ name: null, object: root, schema: schema }];
const xmlns: any = {};
const refs = {};
let id; // {id:{hrefs:[],obj:}, ...}
p.onopentag = (node) => {
const nsName = node.name;
const attrs: any = node.attributes;
let name = splitQName(nsName).name;
let attributeName;
const top = stack[stack.length - 1];
let topSchema = top.schema;
const elementAttributes = {};
let hasNonXmlnsAttribute = false;
let hasNilAttribute = false;
const obj = {};
const originalName = name;
if (!objectName && top.name === 'Body' && name !== 'Fault') {
let message = this.definitions.messages[name];
// Support RPC/literal messages where response body contains one element named
// after the operation + 'Response'. See http://www.w3.org/TR/wsdl#_names
if (!message) {
try {
// Determine if this is request or response
let isInput = false;
let isOutput = false;
if ((/Response$/).test(name)) {
isOutput = true;
name = name.replace(/Response$/, '');
} else if ((/Request$/).test(name)) {
isInput = true;
name = name.replace(/Request$/, '');
} else if ((/Solicit$/).test(name)) {
isInput = true;
name = name.replace(/Solicit$/, '');
}
// Look up the appropriate message as given in the portType's operations
const portTypes = this.definitions.portTypes;
const portTypeNames = Object.keys(portTypes);
// Currently this supports only one portType definition.
const portType = portTypes[portTypeNames[0]];
if (isInput) {
name = portType.methods[name].input.$name;
} else {
name = portType.methods[name].output.$name;
}
message = this.definitions.messages[name];
// 'cache' this alias to speed future lookups
this.definitions.messages[originalName] = this.definitions.messages[name];
} catch (e) {
if (this.options.returnFault) {
p.onerror(e);
}
}
}
topSchema = message.description(this.definitions);
objectName = originalName;
}
if (attrs.href) {
id = attrs.href.substr(1);
if (!refs[id]) {
refs[id] = { hrefs: [], obj: null };
}
refs[id].hrefs.push({ par: top.object, key: name, obj: obj });
}
if (id = attrs.id) {
if (!refs[id]) {
refs[id] = { hrefs: [], obj: null };
}
}
// Handle element attributes
for (attributeName in attrs) {
if (/^xmlns:|^xmlns$/.test(attributeName)) {
xmlns[splitQName(attributeName).name] = attrs[attributeName];
continue;
}
hasNonXmlnsAttribute = true;
elementAttributes[attributeName] = attrs[attributeName];
}
for (attributeName in elementAttributes) {
const res = splitQName(attributeName);
if (res.name === 'nil' && xmlns[res.prefix] === XSI_URI && elementAttributes[attributeName] &&
(elementAttributes[attributeName].toLowerCase() === 'true' || elementAttributes[attributeName] === '1')
) {
hasNilAttribute = true;
break;
}
}
if (hasNonXmlnsAttribute) {
obj[this.options.attributesKey] = elementAttributes;
}
// Pick up the schema for the type specified in element's xsi:type attribute.
let xsiTypeSchema;
let xsiType;
for (const prefix in xmlns) {
if (xmlns[prefix] === XSI_URI && (`${prefix}:type` in elementAttributes)) {
xsiType = elementAttributes[`${prefix}:type`];
break;
}
}
if (xsiType) {
const type = splitQName(xsiType);
let typeURI;
if (type.prefix === TNS_PREFIX) {
// In case of xsi:type = "MyType"
typeURI = xmlns[type.prefix] || xmlns.xmlns;
} else {
typeURI = xmlns[type.prefix];
}
const typeDef = this.findSchemaObject(typeURI, type.name);
if (typeDef) {
xsiTypeSchema = typeDef.description(this.definitions);
}
}
if (topSchema && topSchema[name + '[]']) {
name = name + '[]';
}
stack.push({ name: originalName, object: obj, schema: (xsiTypeSchema || (topSchema && topSchema[name])), id: attrs.id, nil: hasNilAttribute });
};
p.onclosetag = (nsName) => {
const cur: any = stack.pop();
let obj = cur.object;
const top = stack[stack.length - 1];
const topObject = top.object;
const topSchema = top.schema;
const name = splitQName(nsName).name;
if (typeof cur.schema === 'string' && (cur.schema === 'string' || cur.schema.split(':')[1] === 'string')) {
if (typeof obj === 'object' && Object.keys(obj).length === 0) {
obj = cur.object = (this.options.preserveWhitespace ? cur.text || '' : '');
}
}
if (cur.nil === true) {
if (this.options.handleNilAsNull) {
obj = null;
} else {
return;
}
}
if (_.isPlainObject(obj) && !Object.keys(obj).length) {
obj = null;
}
if (topSchema && topSchema[name + '[]']) {
if (!topObject[name]) {
topObject[name] = [];
}
topObject[name].push(obj);
} else if (name in topObject) {
if (!Array.isArray(topObject[name])) {
topObject[name] = [topObject[name]];
}
topObject[name].push(obj);
} else {
topObject[name] = obj;
}
if (cur.id) {
refs[cur.id].obj = obj;
}
};
p.oncdata = (text) => {
const originalText = text;
text = trim(text);
if (!text.length) {
return;
}
if (/<\?xml[\s\S]+\?>/.test(text)) {
const top = stack[stack.length - 1];
const value = this.xmlToObject(text);
if (top.object[this.options.attributesKey]) {
top.object[this.options.valueKey] = value;
} else {
top.object = value;
}
} else {
p.ontext(originalText);
}
};
p.onerror = (e) => {
p.resume();
throw {
Fault: {
faultcode: 500,
faultstring: 'Invalid XML',
detail: new Error(e).message,
statusCode: 500,
},
};
};
p.ontext = (text) => {
const top = stack[stack.length - 1];
const originalText = text;
text = trim(text);
if (!text.length) {
if (this.options.preserveWhitespace) {
top.text = (top.text || '') + originalText;
}
return;
}
const name = splitQName(top.schema).name;
let value;
if (this.options && this.options.customDeserializer && this.options.customDeserializer[name]) {
value = this.options.customDeserializer[name](text, top);
} else {
if (name === 'int' || name === 'integer' || name === 'short' || name === 'long') {
value = parseInt(text, 10);
} else if (name === 'double' || name === 'float' || name === 'decimal') {
value = Number(text);
} else if (name === 'bool' || name === 'boolean') {
value = text.toLowerCase() === 'true' || text === '1';
} else if (name === 'dateTime' || name === 'date') {
value = new Date(text);
} else {
if (this.options.preserveWhitespace) {
text = originalText;
}
// handle string or other types
if (typeof top.object !== 'string') {
value = text;
} else {
value = top.object + text;
}
}
}
if (top.object[this.options.attributesKey]) {
top.object[this.options.valueKey] = value;
} else {
top.object = value;
}
};
if (typeof callback === 'function') {
// we be streaming
const saxStream = sax.createStream(true, null);
saxStream.on('opentag', p.onopentag);
saxStream.on('closetag', p.onclosetag);
saxStream.on('cdata', p.oncdata);
saxStream.on('text', p.ontext);
xml.pipe(saxStream)
.on('error', (err) => {
callback(err);
})
.on('end', () => {
let r;
try {
r = finish();
} catch (e) {
return callback(e);
}
callback(null, r);
});
return;
}
p.write(xml).close();
return finish();
function finish() {
// MultiRef support: merge objects instead of replacing
for (const n in refs) {
const ref = refs[n];
for (const href of ref.hrefs) {
Object.assign(href.obj, ref.obj);
}
}
if (root.Envelope) {
const body = root.Envelope.Body;
if (body && body.Fault) {
const fault = body.Fault;
let code = fault.faultcode && fault.faultcode.$value;
let string = fault.faultstring && fault.faultstring.$value;
let detail = fault.detail && fault.detail.$value;
code = code || fault.faultcode;
string = string || fault.faultstring;
detail = detail || fault.detail;
// SOAP 1.2
code = code || fault.Code && `${fault.Code.Value}: ${fault.Code.Subcode && fault.Code.Subcode.Value}`;
string = string || fault.Reason && fault.Reason.Text.$value;
string = string || fault.Reason && fault.Reason.Text;
detail = detail || fault.Detail;
const error: any = new Error(code + ': ' + string + (detail ? ': ' + JSON.stringify(detail) : ''));
error.root = root;
throw error;
}
return root.Envelope;
}
return root;
}
}
/**
* Look up a XSD type or element by namespace URI and name
* @param {String} nsURI Namespace URI
* @param {String} qname Local or qualified name
* @returns {*} The XSD type/element definition
*/
public findSchemaObject(nsURI: string, qname: string) {
if (!nsURI || !qname) {
return null;
}
let def = null;
if (this.definitions.schemas) {
const schema = this.definitions.schemas[nsURI];
if (schema) {
if (qname.indexOf(':') !== -1) {
qname = qname.substring(qname.indexOf(':') + 1, qname.length);
}
// if the client passed an input element which has a `$lookupType` property instead of `$type`
// the `def` is found in `schema.elements`.
def = schema.complexTypes[qname] || schema.types[qname] || schema.elements[qname];
}
}
return def;
}
/**
* Create document style xml string from the parameters
* @param {String} name
* @param {*} params
* @param {String} nsPrefix
* @param {String} nsURI
* @param {String} type
*/
public objectToDocumentXML(name: string, params, nsPrefix: string, nsURI?: string, type?: string) {
// If user supplies XML already, just use that. XML Declaration should not be present.
if (params && params._xml) {
return params._xml;
}
const args = {};
args[name] = params;
const parameterTypeObj = type ? this.findSchemaObject(nsURI, type) : null;
return this.objectToXML(args, null, nsPrefix, nsURI, true, null, parameterTypeObj);
}
/**
* Create RPC style xml string from the parameters
* @param {String} name
* @param {*} params
* @param {String} nsPrefix
* @param {String} nsURI
* @returns {string}
*/
public objectToRpcXML(name: string, params, nsPrefix: string, nsURI: string, isParts?: boolean) {
const parts = [];
const defs = this.definitions;
const nsAttrName = '_xmlns';
nsPrefix = nsPrefix || findPrefix(defs.xmlns, nsURI);
nsURI = nsURI || defs.xmlns[nsPrefix];
nsPrefix = nsPrefix === TNS_PREFIX ? '' : (nsPrefix + ':');
parts.push(['<', nsPrefix, name, '>'].join(''));
for (const key in params) {
if (!params.hasOwnProperty(key)) {
continue;
}
if (key !== nsAttrName) {
const value = params[key];
const prefixedKey = (isParts ? '' : nsPrefix) + key;
const attributes = [];
if (typeof value === 'object' && value.hasOwnProperty(this.options.attributesKey)) {
const attrs = value[this.options.attributesKey];
for (const n in attrs) {
attributes.push(' ' + n + '=' + '"' + attrs[n] + '"');
}
}
parts.push(['<', prefixedKey].concat(attributes).concat('>').join(''));
parts.push((typeof value === 'object') ? this.objectToXML(value, key, nsPrefix, nsURI) : xmlEscape(value));
parts.push(['</', prefixedKey, '>'].join(''));
}
}
parts.push(['</', nsPrefix, name, '>'].join(''));
return parts.join('');
}
public isIgnoredNameSpace(ns: string): boolean {
return this.options.ignoredNamespaces.indexOf(ns) > -1;
}
public filterOutIgnoredNameSpace(ns: string): string {
const namespace = noColonNameSpace(ns);
return this.isIgnoredNameSpace(namespace) ? '' : namespace;
}
/**
* Convert an object to XML. This is a recursive method as it calls itself.
*
* @param {Object} obj the object to convert.
* @param {String} name the name of the element (if the object being traversed is
* an element).
* @param {String} nsPrefix the namespace prefix of the object I.E. xsd.
* @param {String} nsURI the full namespace of the object I.E. http://w3.org/schema.
* @param {Boolean} isFirst whether or not this is the first item being traversed.
* @param {?} xmlnsAttr
* @param {?} parameterTypeObject
* @param {NamespaceContext} nsContext Namespace context
*/
public objectToXML(obj, name: string, nsPrefix: any, nsURI: string, isFirst?: boolean, xmlnsAttr?, schemaObject?, nsContext?: NamespaceContext) {
const schema = this.definitions.schemas[nsURI];
let parentNsPrefix = nsPrefix ? nsPrefix.parent : undefined;
if (typeof parentNsPrefix !== 'undefined') {
// we got the parentNsPrefix for our array. setting the namespace-variable back to the current namespace string
nsPrefix = nsPrefix.current;
}
parentNsPrefix = noColonNameSpace(parentNsPrefix);
if (this.isIgnoredNameSpace(parentNsPrefix)) {
parentNsPrefix = '';
}
const soapHeader = !schema;
const qualified = schema && schema.$elementFormDefault === 'qualified';
const parts = [];
const prefixNamespace = (nsPrefix || qualified) && nsPrefix !== TNS_PREFIX;
let xmlnsAttrib = '';
if (nsURI && isFirst) {
if (this.options.overrideRootElement && this.options.overrideRootElement.xmlnsAttributes) {
this.options.overrideRootElement.xmlnsAttributes.forEach((attribute) => {
xmlnsAttrib += ' ' + attribute.name + '="' + attribute.value + '"';
});
} else {
if (prefixNamespace && !this.isIgnoredNameSpace(nsPrefix)) {
// resolve the prefix namespace
xmlnsAttrib += ' xmlns:' + nsPrefix + '="' + nsURI + '"';
}
// only add default namespace if the schema elementFormDefault is qualified
if (qualified || soapHeader) { xmlnsAttrib += ' xmlns="' + nsURI + '"'; }
}
}
if (!nsContext) {
nsContext = new NamespaceContext();
nsContext.declareNamespace(nsPrefix, nsURI);
} else {
nsContext.pushContext();
}
// explicitly use xmlns attribute if available
if (xmlnsAttr && !(this.options.overrideRootElement && this.options.overrideRootElement.xmlnsAttributes)) {
xmlnsAttrib = xmlnsAttr;
}
let ns = '';
if (this.options.overrideRootElement && isFirst) {
ns = this.options.overrideRootElement.namespace;
} else if (prefixNamespace && (qualified || isFirst || soapHeader) && !this.isIgnoredNameSpace(nsPrefix)) {
ns = nsPrefix;
}
let i;
let n;
// start building out XML string.
if (Array.isArray(obj)) {
let nonSubNameSpace = '';
let emptyNonSubNameSpaceForArray = false;
const nameWithNsRegex = /^([^:]+):([^:]+)$/.exec(name);
if (nameWithNsRegex) {
nonSubNameSpace = nameWithNsRegex[1];
name = nameWithNsRegex[2];
} else if (name[0] === ':') {
emptyNonSubNameSpaceForArray = true;
name = name.substr(1);
}
for (i = 0, n = obj.length; i < n; i++) {
const item = obj[i];
const arrayAttr = this.processAttributes(item, nsContext);
const correctOuterNsPrefix = nonSubNameSpace || parentNsPrefix || ns; // using the parent namespace prefix if given
const body = this.objectToXML(item, name, nsPrefix, nsURI, false, null, schemaObject, nsContext);
let openingTagParts = ['<', name, arrayAttr, xmlnsAttrib];
if (!emptyNonSubNameSpaceForArray) {
openingTagParts = ['<', appendColon(correctOuterNsPrefix), name, arrayAttr, xmlnsAttrib];
}
if (body === '' && this.options.useEmptyTag) {
// Use empty (self-closing) tags if no contents
openingTagParts.push(' />');
parts.push(openingTagParts.join(''));
} else {
openingTagParts.push('>');
if (this.options.namespaceArrayElements || i === 0) {
parts.push(openingTagParts.join(''));
}
parts.push(body);
if (this.options.namespaceArrayElements || i === n - 1) {
if (emptyNonSubNameSpaceForArray) {
parts.push(['</', name, '>'].join(''));
} else {
parts.push(['</', appendColon(correctOuterNsPrefix), name, '>'].join(''));
}
}
}
}
} else if (typeof obj === 'object') {
let currentChildXmlnsAttrib = '';
for (name in obj) {
// Happens when Object.create(null) is used, it will not inherit the Object prototype
if (!obj.hasOwnProperty) {
obj = Object.assign({}, obj);
}
if (!obj.hasOwnProperty(name)) { continue; }
// don't process attributes as element
if (name === this.options.attributesKey) {
continue;
}
// Its the value of a xml object. Return it directly.
if (name === this.options.xmlKey) {
nsContext.popContext();
return obj[name];
}
// Its the value of an item. Return it directly.
if (name === this.options.valueKey) {
nsContext.popContext();
return xmlEscape(obj[name]);
}
const child = obj[name];
if (typeof child === 'undefined') {
continue;
}
const attr = this.processAttributes(child, nsContext);
let value = '';
let nonSubNameSpace = '';
let emptyNonSubNameSpace = false;
const nameWithNsRegex = /^([^:]+):([^:]+)$/.exec(name);
if (nameWithNsRegex) {
nonSubNameSpace = nameWithNsRegex[1] + ':';
name = nameWithNsRegex[2];
} else if (name[0] === ':') {
emptyNonSubNameSpace = true;
name = name.substr(1);
}
if (isFirst) {
value = this.objectToXML(child, name, nsPrefix, nsURI, false, null, schemaObject, nsContext);
} else {
if (this.definitions.schemas) {
if (schema) {
const childSchemaObject = this.findChildSchemaObject(schemaObject, name);
// find sub namespace if not a primitive
if (childSchemaObject &&
((childSchemaObject.$type && (childSchemaObject.$type.indexOf('xsd:') === -1)) ||
childSchemaObject.$ref || childSchemaObject.$name)) {
/*if the base name space of the children is not in the ingoredSchemaNamspaces we use it.
This is because in some services the child nodes do not need the baseNameSpace.
*/
let childNsPrefix: any = '';
let childName = '';
let childNsURI;
let childXmlnsAttrib = '';
let elementQName = childSchemaObject.$ref || childSchemaObject.$name;
if (elementQName) {
elementQName = splitQName(elementQName);
childName = elementQName.name;
if (elementQName.prefix === TNS_PREFIX) {
// Local element
childNsURI = childSchemaObject.$targetNamespace;
childNsPrefix = nsContext.registerNamespace(childNsURI);
if (this.isIgnoredNameSpace(childNsPrefix)) {
childNsPrefix = nsPrefix;
}
} else {
childNsPrefix = elementQName.prefix;
if (this.isIgnoredNameSpace(childNsPrefix)) {
childNsPrefix = nsPrefix;
}
childNsURI = schema.xmlns[childNsPrefix] || this.definitions.xmlns[childNsPrefix];
}
let unqualified = false;
// Check qualification form for local elements
if (childSchemaObject.$name && childSchemaObject.targetNamespace === undefined) {
if (childSchemaObject.$form === 'unqualified') {
unqualified = true;
} else if (childSchemaObject.$form === 'qualified') {
unqualified = false;
} else {
unqualified = schema.$elementFormDefault !== 'qualified';
}
}
if (unqualified) {
childNsPrefix = '';
}
if (childNsURI && childNsPrefix) {
if (nsContext.declareNamespace(childNsPrefix, childNsURI)) {
childXmlnsAttrib = ' xmlns:' + childNsPrefix + '="' + childNsURI + '"';
if (!xmlnsAttrib.includes(childNsPrefix)) {
currentChildXmlnsAttrib = childXmlnsAttrib;
xmlnsAttrib += childXmlnsAttrib;
}
}
}
}
let resolvedChildSchemaObject;
if (childSchemaObject.$type) {
const typeQName = splitQName(childSchemaObject.$type);
const typePrefix = childSchemaObject.$baseNameSpace || typeQName.prefix;
const typeURI = schema.xmlns[typePrefix] || this.definitions.xmlns[typePrefix];
childNsURI = typeURI;
if (typeURI !== 'http://www.w3.org/2001/XMLSchema' && typePrefix !== TNS_PREFIX) {
// Add the prefix/namespace mapping, but not declare it
nsContext.addNamespace(typePrefix, typeURI);
}
resolvedChildSchemaObject =
this.findSchemaType(typeQName.name, typeURI) || childSchemaObject;
} else {
resolvedChildSchemaObject =
this.findSchemaObject(childNsURI, childName) || childSchemaObject;
}
if (childSchemaObject.$baseNameSpace && this.options.ignoreBaseNameSpaces) {
childNsPrefix = nsPrefix;
childNsURI = nsURI;
}
if (this.options.ignoreBaseNameSpaces) {
childNsPrefix = '';
childNsURI = '';
}
ns = childNsPrefix;
if (Array.isArray(child)) {
// for arrays, we need to remember the current namespace
childNsPrefix = {
current: childNsPrefix,
parent: ns,
};
childXmlnsAttrib = childXmlnsAttrib && childXmlnsAttrib.length ? childXmlnsAttrib : currentChildXmlnsAttrib;
} else {
// parent (array) already got the namespace
childXmlnsAttrib = null;
}
value = this.objectToXML(child, name, childNsPrefix, childNsURI,
false, childXmlnsAttrib, resolvedChildSchemaObject, nsContext);
} else if (obj[this.options.attributesKey] && obj[this.options.attributesKey].xsi_type) {
// if parent object has complex type defined and child not found in parent
const completeChildParamTypeObject = this.findChildSchemaObject(
obj[this.options.attributesKey].xsi_type.type,
obj[this.options.attributesKey].xsi_type.xmlns);
nonSubNameSpace = obj[this.options.attributesKey].xsi_type.prefix;
nsContext.addNamespace(obj[this.options.attributesKey].xsi_type.prefix,
obj[this.options.attributesKey].xsi_type.xmlns);
value = this.objectToXML(child, name, obj[this.options.attributesKey].xsi_type.prefix,
obj[this.options.attributesKey].xsi_type.xmlns, false, null, null, nsContext);
} else {
if (Array.isArray(child)) {
if (emptyNonSubNameSpace) {
name = ':' + name;
} else {
name = nonSubNameSpace + name;
}
}
value = this.objectToXML(child, name, nsPrefix, nsURI, false, null, null, nsContext);
}
} else {
value = this.objectToXML(child, name, nsPrefix, nsURI, false, null, null, nsContext);
}
}
}
ns = noColonNameSpace(ns);
if (prefixNamespace && !qualified && isFirst && !this.options.overrideRootElement) {
ns = nsPrefix;
} else if (this.isIgnoredNameSpace(ns)) {
ns = '';
}
const useEmptyTag = !value && this.options.useEmptyTag;
if (!Array.isArray(child)) {
// start tag
parts.push(['<', emptyNonSubNameSpace ? '' : appendColon(nonSubNameSpace || ns), name, attr, xmlnsAttrib,
(child === null ? ' xsi:nil="true"' : ''),
useEmptyTag ? ' />' : '>',
].join(''));
}
if (!useEmptyTag) {
parts.push(value);
if (!Array.isArray(child)) {
// end tag
parts.push(['</', emptyNonSubNameSpace ? '' : appendColon(nonSubNameSpace || ns), name, '>'].join(''));
}
}
}
} else if (obj !== undefined) {
parts.push((this.options.escapeXML) ? xmlEscape(obj) : obj);
}
nsContext.popContext();
return parts.join('');
}
public processAttributes(child: any, nsContext: NamespaceContext): string {
let attr = '';
if (child === null || child === undefined) {
child = [];
}
const attrObj = child[this.options.attributesKey] || {};
if (attrObj && attrObj.xsi_type) {
const xsiType = attrObj.xsi_type;
let prefix = xsiType.prefix || xsiType.namespace;
if (xsiType.xmlns) {
// Generate a new namespace for complex extension if one not provided
if (!prefix) {
prefix = nsContext.registerNamespace(xsiType.xmlns);
} else {
nsContext.declareNamespace(prefix, xsiType.xmlns);
}
xsiType.prefix = prefix;
}
}
Object.keys(attrObj).forEach((k) => {
const v = attrObj[k];
if (k === 'xsi_type') {
let name = v.type;
if (v.prefix) {
name = `${v.prefix}:${name}`;
}
attr += ` xsi:type="${name}"`;
if (v.xmlns) {
attr += ` xmlns:${v.prefix}="${v.xmlns}"`;
}
} else {
attr += ` ${k}="${xmlEscape(v)}"`;
}
});
return attr;
}
/**
* Look up a schema type definition