xmljslib 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +354 -22
- package/dist/index.cjs +444 -45
- package/dist/index.d.cts +133 -2
- package/dist/index.d.ts +133 -2
- package/dist/index.js +442 -44
- package/package.json +63 -62
- package/readme.md +573 -466
- package/readme.ru.md +110 -3
package/dist/index.cjs
CHANGED
|
@@ -32,7 +32,8 @@ var index_exports = {};
|
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
WSDLTypeGenerator: () => WSDLTypeGenerator,
|
|
34
34
|
XMLBuilder: () => XMLBuilder,
|
|
35
|
-
XMLParser: () => XMLParser
|
|
35
|
+
XMLParser: () => XMLParser,
|
|
36
|
+
asArray: () => asArray
|
|
36
37
|
});
|
|
37
38
|
module.exports = __toCommonJS(index_exports);
|
|
38
39
|
|
|
@@ -63,14 +64,25 @@ function createXMLNode(value, attributes = {}, isLeaf = false) {
|
|
|
63
64
|
if (!hasAttributes) {
|
|
64
65
|
return parsedValue;
|
|
65
66
|
}
|
|
66
|
-
const
|
|
67
|
+
const attributeValue = Object.prototype.hasOwnProperty.call(attributes, "value") ? parsePrimitive(attributes.value) : void 0;
|
|
68
|
+
const nodeValue = parsedValue !== void 0 ? parsedValue : attributeValue;
|
|
69
|
+
const targetObj = Object(nodeValue !== void 0 ? nodeValue : "");
|
|
67
70
|
for (const [key, attrVal] of Object.entries(attributes)) {
|
|
71
|
+
if (key === "value") {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
68
74
|
targetObj[`$${key}`] = parsePrimitive(attrVal);
|
|
69
75
|
}
|
|
76
|
+
Object.defineProperty(targetObj, "$value", {
|
|
77
|
+
value: nodeValue,
|
|
78
|
+
writable: true,
|
|
79
|
+
enumerable: true,
|
|
80
|
+
configurable: true
|
|
81
|
+
});
|
|
70
82
|
return new Proxy(targetObj, {
|
|
71
83
|
get(target, prop) {
|
|
72
84
|
if (prop === "__isXMLNode") return true;
|
|
73
|
-
if (prop === "$value") return
|
|
85
|
+
if (prop === "$value") return nodeValue;
|
|
74
86
|
if (prop === "valueOf" || prop === Symbol.toPrimitive) {
|
|
75
87
|
return () => parsedValue;
|
|
76
88
|
}
|
|
@@ -157,10 +169,14 @@ var XMLParser = class _XMLParser {
|
|
|
157
169
|
static parseTreeJSON(item) {
|
|
158
170
|
const result = {};
|
|
159
171
|
const node = {};
|
|
172
|
+
const attributeValue = Object.prototype.hasOwnProperty.call(item.attributes, "value") ? item.attributes.value : void 0;
|
|
173
|
+
node.$value = item.$value !== null ? item.$value : attributeValue ?? null;
|
|
160
174
|
for (const attr of Object.keys(item.attributes)) {
|
|
175
|
+
if (attr === "value") {
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
161
178
|
node[`$${attr}`] = item.attributes[attr];
|
|
162
179
|
}
|
|
163
|
-
node.$value = item.$value;
|
|
164
180
|
for (const child of item.children) {
|
|
165
181
|
const parsed = _XMLParser.parseTreeJSON(child);
|
|
166
182
|
const childValue = parsed[child.tag];
|
|
@@ -295,7 +311,7 @@ var XMLParser = class _XMLParser {
|
|
|
295
311
|
};
|
|
296
312
|
|
|
297
313
|
// src/lib/wsdlTypeGenerator.ts
|
|
298
|
-
var WSDLTypeGenerator = class {
|
|
314
|
+
var WSDLTypeGenerator = class _WSDLTypeGenerator {
|
|
299
315
|
typeRegistry = /* @__PURE__ */ new Map();
|
|
300
316
|
simpleTypeRegistry = /* @__PURE__ */ new Map();
|
|
301
317
|
simpleTypeDocumentationRegistry = /* @__PURE__ */ new Map();
|
|
@@ -310,6 +326,40 @@ var WSDLTypeGenerator = class {
|
|
|
310
326
|
globalElementRegistry = /* @__PURE__ */ new Map();
|
|
311
327
|
baseUrl = "";
|
|
312
328
|
loadedUrls = /* @__PURE__ */ new Set();
|
|
329
|
+
/**
|
|
330
|
+
* Пространства имён, объявленные в документе (`xmlns:*`).
|
|
331
|
+
* Используются и для автоподстановки префиксов, и для объявления `xmlns` в XML.
|
|
332
|
+
*/
|
|
333
|
+
namespaceUriByPrefix = /* @__PURE__ */ new Map();
|
|
334
|
+
namespacePrefixByUri = /* @__PURE__ */ new Map();
|
|
335
|
+
/**
|
|
336
|
+
* Пространства имён элементов: локальное имя элемента -> префикс.
|
|
337
|
+
*
|
|
338
|
+
* Квалифицированные элементы хранятся в `qualifiedElements`,
|
|
339
|
+
* неквалифицированные — в `unqualifiedElements`, чтобы одноимённые элементы
|
|
340
|
+
* из разных схем не конфликтовали: квалифицированный всегда выигрывает.
|
|
341
|
+
*/
|
|
342
|
+
qualifiedElements = /* @__PURE__ */ new Map();
|
|
343
|
+
unqualifiedElements = /* @__PURE__ */ new Set();
|
|
344
|
+
/**
|
|
345
|
+
* Имена элементов, объявленных в нескольких пространствах имён.
|
|
346
|
+
* Для таких элементов одного префикса «по имени» недостаточно —
|
|
347
|
+
* нужен контекст родителя.
|
|
348
|
+
*/
|
|
349
|
+
ambiguousElements = /* @__PURE__ */ new Set();
|
|
350
|
+
/**
|
|
351
|
+
* Тип каждого элемента: имя элемента -> имя типа в реестре complexType.
|
|
352
|
+
* Нужен, чтобы знать состав дочерних элементов.
|
|
353
|
+
*/
|
|
354
|
+
elementTypeRegistry = /* @__PURE__ */ new Map();
|
|
355
|
+
/**
|
|
356
|
+
* Пространства имён типов: имя complexType -> префикс.
|
|
357
|
+
*/
|
|
358
|
+
typeNamespacePrefix = /* @__PURE__ */ new Map();
|
|
359
|
+
/**
|
|
360
|
+
* Пространство имён XML Schema. Не имеет отношения к данным сервиса.
|
|
361
|
+
*/
|
|
362
|
+
static XML_SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema";
|
|
313
363
|
get complexTypeCount() {
|
|
314
364
|
return this.typeRegistry.size;
|
|
315
365
|
}
|
|
@@ -332,8 +382,17 @@ var WSDLTypeGenerator = class {
|
|
|
332
382
|
this.messageRegistry.clear();
|
|
333
383
|
this.globalElementRegistry.clear();
|
|
334
384
|
this.loadedUrls.clear();
|
|
385
|
+
this.namespaceUriByPrefix.clear();
|
|
386
|
+
this.namespacePrefixByUri.clear();
|
|
387
|
+
this.qualifiedElements.clear();
|
|
388
|
+
this.unqualifiedElements.clear();
|
|
389
|
+
this.ambiguousElements.clear();
|
|
390
|
+
this.elementTypeRegistry.clear();
|
|
391
|
+
this.typeNamespacePrefix.clear();
|
|
335
392
|
console.log("\u{1F4E6} \u041F\u0430\u0440\u0441\u0438\u043D\u0433 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u044B XML...");
|
|
336
393
|
const wsdl = new XMLParser(xmlContent, config);
|
|
394
|
+
console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0439 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432 \u0438\u043C\u0451\u043D...");
|
|
395
|
+
this.collectNamespaceDeclarations(wsdl);
|
|
337
396
|
console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439...");
|
|
338
397
|
this.extractMessages(wsdl);
|
|
339
398
|
console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439...");
|
|
@@ -376,6 +435,106 @@ var WSDLTypeGenerator = class {
|
|
|
376
435
|
const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
|
|
377
436
|
return String(primitive);
|
|
378
437
|
}
|
|
438
|
+
/**
|
|
439
|
+
* Приводит значение узла к строке.
|
|
440
|
+
*/
|
|
441
|
+
toPrimitiveString(value) {
|
|
442
|
+
if (value === null || value === void 0) {
|
|
443
|
+
return void 0;
|
|
444
|
+
}
|
|
445
|
+
const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
|
|
446
|
+
if (primitive === null || primitive === void 0) {
|
|
447
|
+
return void 0;
|
|
448
|
+
}
|
|
449
|
+
const text = String(primitive).trim();
|
|
450
|
+
return text.length > 0 ? text : void 0;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Регистрирует связь префикс <-> URI пространства имён.
|
|
454
|
+
* Первые объявления имеют приоритет: префикс не переопределяется.
|
|
455
|
+
*/
|
|
456
|
+
registerNamespacePrefix(prefix, uri) {
|
|
457
|
+
if (!this.namespaceUriByPrefix.has(prefix)) {
|
|
458
|
+
this.namespaceUriByPrefix.set(prefix, uri);
|
|
459
|
+
}
|
|
460
|
+
if (!this.namespacePrefixByUri.has(uri)) {
|
|
461
|
+
this.namespacePrefixByUri.set(uri, prefix);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Собирает объявления пространств имён (`xmlns:*`) из всего документа.
|
|
466
|
+
*/
|
|
467
|
+
collectNamespaceDeclarations(node) {
|
|
468
|
+
if (!node || typeof node !== "object") {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (Array.isArray(node)) {
|
|
472
|
+
for (const item of node) {
|
|
473
|
+
this.collectNamespaceDeclarations(item);
|
|
474
|
+
}
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
for (const [key, value] of Object.entries(node)) {
|
|
478
|
+
if (key.startsWith("$xmlns:")) {
|
|
479
|
+
const prefix = key.slice("$xmlns:".length);
|
|
480
|
+
const uri = this.toPrimitiveString(value);
|
|
481
|
+
if (prefix && uri && uri !== _WSDLTypeGenerator.XML_SCHEMA_NAMESPACE) {
|
|
482
|
+
this.registerNamespacePrefix(prefix, uri);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
this.collectNamespaceDeclarations(value);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Определяет префикс для URI пространства имён.
|
|
490
|
+
*
|
|
491
|
+
* Если префикс не объявлен в документе, подбирается свободный
|
|
492
|
+
* (`tns` или `ns1`, `ns2`, ...), чтобы префикс всегда можно было объявить.
|
|
493
|
+
*/
|
|
494
|
+
resolveNamespacePrefix(uri) {
|
|
495
|
+
if (!uri) {
|
|
496
|
+
return void 0;
|
|
497
|
+
}
|
|
498
|
+
const declared = this.namespacePrefixByUri.get(uri);
|
|
499
|
+
if (declared) {
|
|
500
|
+
return declared;
|
|
501
|
+
}
|
|
502
|
+
if (!this.namespaceUriByPrefix.has("tns")) {
|
|
503
|
+
this.registerNamespacePrefix("tns", uri);
|
|
504
|
+
return "tns";
|
|
505
|
+
}
|
|
506
|
+
let index = 1;
|
|
507
|
+
while (this.namespaceUriByPrefix.has(`ns${index}`)) {
|
|
508
|
+
index++;
|
|
509
|
+
}
|
|
510
|
+
const prefix = `ns${index}`;
|
|
511
|
+
this.registerNamespacePrefix(prefix, uri);
|
|
512
|
+
return prefix;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Регистрирует пространство имён элемента.
|
|
516
|
+
*
|
|
517
|
+
* Квалифицированный элемент всегда выигрывает у неквалифицированного
|
|
518
|
+
* с тем же локальным именем.
|
|
519
|
+
*/
|
|
520
|
+
registerElementNamespace(name, prefix) {
|
|
521
|
+
if (!name) {
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
if (prefix) {
|
|
525
|
+
const known = this.qualifiedElements.get(name);
|
|
526
|
+
if (known === void 0) {
|
|
527
|
+
this.qualifiedElements.set(name, prefix);
|
|
528
|
+
} else if (known !== prefix) {
|
|
529
|
+
this.ambiguousElements.add(name);
|
|
530
|
+
}
|
|
531
|
+
this.unqualifiedElements.delete(name);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
if (!this.qualifiedElements.has(name)) {
|
|
535
|
+
this.unqualifiedElements.add(name);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
379
538
|
/**
|
|
380
539
|
* Извлекает текст документации из XML-узла.
|
|
381
540
|
*
|
|
@@ -613,6 +772,8 @@ ${indent} */
|
|
|
613
772
|
if (!schema) {
|
|
614
773
|
return;
|
|
615
774
|
}
|
|
775
|
+
this.collectNamespaceDeclarations(schema);
|
|
776
|
+
const context = this.createSchemaContext(schema);
|
|
616
777
|
for (const key of Object.keys(schema)) {
|
|
617
778
|
const cleanKey = this.cleanPrefix(key);
|
|
618
779
|
if (["import", "include"].includes(cleanKey)) {
|
|
@@ -634,7 +795,7 @@ ${indent} */
|
|
|
634
795
|
if (!ct?.$name) {
|
|
635
796
|
continue;
|
|
636
797
|
}
|
|
637
|
-
this.parseComplexType(ct.$name, ct);
|
|
798
|
+
this.parseComplexType(ct.$name, ct, context);
|
|
638
799
|
}
|
|
639
800
|
}
|
|
640
801
|
for (const key of Object.keys(schema)) {
|
|
@@ -658,10 +819,51 @@ ${indent} */
|
|
|
658
819
|
if (!element?.$name) {
|
|
659
820
|
continue;
|
|
660
821
|
}
|
|
661
|
-
this.parseGlobalElement(element);
|
|
822
|
+
this.parseGlobalElement(element, context);
|
|
662
823
|
}
|
|
663
824
|
}
|
|
664
825
|
}
|
|
826
|
+
/**
|
|
827
|
+
* Формирует контекст схемы: целевое пространство имён и правила квалификации.
|
|
828
|
+
*/
|
|
829
|
+
createSchemaContext(schema) {
|
|
830
|
+
const targetNamespace = this.getAttribute(schema, "targetNamespace");
|
|
831
|
+
const formDefault = (this.getAttribute(schema, "elementFormDefault") ?? "unqualified").toLowerCase();
|
|
832
|
+
return {
|
|
833
|
+
targetNamespace,
|
|
834
|
+
prefix: this.resolveNamespacePrefix(targetNamespace),
|
|
835
|
+
elementFormDefault: formDefault === "qualified" ? "qualified" : "unqualified"
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Определяет, принадлежит ли элемент целевому пространству имён.
|
|
840
|
+
*
|
|
841
|
+
* Локальные элементы подчиняются `elementFormDefault`,
|
|
842
|
+
* глобальные — всегда квалифицированы.
|
|
843
|
+
*
|
|
844
|
+
* Для ссылок (`ref="pfx:Name"`) берётся пространство имён,
|
|
845
|
+
* объявленное в самом документе, а не пространство текущей схемы.
|
|
846
|
+
*/
|
|
847
|
+
resolveElementPrefix(element, context, isGlobal) {
|
|
848
|
+
const ref = this.getAttribute(element, "ref");
|
|
849
|
+
if (ref) {
|
|
850
|
+
const refPrefix = ref.includes(":") ? ref.split(":")[0] : "";
|
|
851
|
+
const uri = this.namespaceUriByPrefix.get(refPrefix);
|
|
852
|
+
const resolved = uri ? this.namespacePrefixByUri.get(uri) : void 0;
|
|
853
|
+
return resolved ?? context.prefix;
|
|
854
|
+
}
|
|
855
|
+
if (!context.prefix || !context.targetNamespace) {
|
|
856
|
+
return void 0;
|
|
857
|
+
}
|
|
858
|
+
if (isGlobal) {
|
|
859
|
+
return context.prefix;
|
|
860
|
+
}
|
|
861
|
+
const form = this.getAttribute(element, "form");
|
|
862
|
+
if (form) {
|
|
863
|
+
return form.toLowerCase() === "qualified" ? context.prefix : void 0;
|
|
864
|
+
}
|
|
865
|
+
return context.elementFormDefault === "qualified" ? context.prefix : void 0;
|
|
866
|
+
}
|
|
665
867
|
/**
|
|
666
868
|
* Регистрирует глобальный XSD element.
|
|
667
869
|
*
|
|
@@ -673,11 +875,12 @@ ${indent} */
|
|
|
673
875
|
*
|
|
674
876
|
* FetchBooking -> FetchBookingRequest
|
|
675
877
|
*/
|
|
676
|
-
parseGlobalElement(element) {
|
|
878
|
+
parseGlobalElement(element, context) {
|
|
677
879
|
const name = element.$name;
|
|
678
880
|
if (!name) {
|
|
679
881
|
return;
|
|
680
882
|
}
|
|
883
|
+
this.registerElementNamespace(name, this.resolveElementPrefix(element, context, true));
|
|
681
884
|
let typeName;
|
|
682
885
|
if (element.$type) {
|
|
683
886
|
typeName = this.mapXSDTypeToTS(element.$type);
|
|
@@ -686,7 +889,7 @@ ${indent} */
|
|
|
686
889
|
const inlineSimpleType = this.getChildNode(element, "simpleType");
|
|
687
890
|
if (inlineComplexType) {
|
|
688
891
|
typeName = `${name}Type`;
|
|
689
|
-
this.parseComplexType(typeName, inlineComplexType);
|
|
892
|
+
this.parseComplexType(typeName, inlineComplexType, context);
|
|
690
893
|
} else if (inlineSimpleType) {
|
|
691
894
|
typeName = `${name}Type`;
|
|
692
895
|
this.parseSimpleType(typeName, inlineSimpleType);
|
|
@@ -695,6 +898,7 @@ ${indent} */
|
|
|
695
898
|
}
|
|
696
899
|
}
|
|
697
900
|
this.globalElementRegistry.set(name, typeName);
|
|
901
|
+
this.elementTypeRegistry.set(name, typeName);
|
|
698
902
|
}
|
|
699
903
|
/**
|
|
700
904
|
* Загружает внешнюю XSD-схему.
|
|
@@ -763,13 +967,16 @@ ${indent} */
|
|
|
763
967
|
/**
|
|
764
968
|
* Разбирает XSD complexType.
|
|
765
969
|
*/
|
|
766
|
-
parseComplexType(name, ctNode) {
|
|
970
|
+
parseComplexType(name, ctNode, context) {
|
|
767
971
|
const complexType = {
|
|
768
972
|
name,
|
|
769
973
|
elements: [],
|
|
770
974
|
attributes: [],
|
|
771
975
|
documentation: this.extractDocumentation(ctNode)
|
|
772
976
|
};
|
|
977
|
+
if (context.prefix) {
|
|
978
|
+
this.typeNamespacePrefix.set(name, context.prefix);
|
|
979
|
+
}
|
|
773
980
|
let baseType;
|
|
774
981
|
const findElementsAndAttributes = (node) => {
|
|
775
982
|
if (!node || typeof node !== "object") {
|
|
@@ -797,23 +1004,28 @@ ${indent} */
|
|
|
797
1004
|
if (!fieldName) {
|
|
798
1005
|
continue;
|
|
799
1006
|
}
|
|
1007
|
+
const elementName = this.cleanPrefix(fieldName);
|
|
1008
|
+
const elementNamespace = this.resolveElementPrefix(element, context, false);
|
|
1009
|
+
this.registerElementNamespace(elementName, elementNamespace);
|
|
800
1010
|
const inlineComplexType = this.getChildNode(element, "complexType");
|
|
801
1011
|
const inlineSimpleType = this.getChildNode(element, "simpleType");
|
|
802
1012
|
let elementType = element.$type || element.$ref;
|
|
803
1013
|
if (inlineComplexType) {
|
|
804
1014
|
elementType = `${this.cleanPrefix(fieldName)}Type`;
|
|
805
|
-
this.parseComplexType(elementType, inlineComplexType);
|
|
1015
|
+
this.parseComplexType(elementType, inlineComplexType, context);
|
|
806
1016
|
} else if (inlineSimpleType) {
|
|
807
1017
|
elementType = `${this.cleanPrefix(fieldName)}Type`;
|
|
808
1018
|
this.parseSimpleType(elementType, inlineSimpleType);
|
|
809
1019
|
}
|
|
1020
|
+
this.elementTypeRegistry.set(elementName, this.cleanPrefix(elementType || "string"));
|
|
810
1021
|
complexType.elements.push({
|
|
811
|
-
name:
|
|
1022
|
+
name: elementName,
|
|
812
1023
|
type: this.mapXSDTypeToTS(elementType || "string"),
|
|
813
1024
|
isArray: element.$maxOccurs === "unbounded" || Number(element.$maxOccurs) > 1,
|
|
814
1025
|
isOptional: element.$minOccurs === "0" || !element.$minOccurs,
|
|
815
1026
|
attributes: this.extractAttributes(element),
|
|
816
|
-
documentation: this.extractDocumentation(element)
|
|
1027
|
+
documentation: this.extractDocumentation(element),
|
|
1028
|
+
namespace: elementNamespace
|
|
817
1029
|
});
|
|
818
1030
|
}
|
|
819
1031
|
}
|
|
@@ -987,18 +1199,22 @@ ${indent} */
|
|
|
987
1199
|
for (const [name, complexType] of this.typeRegistry.entries()) {
|
|
988
1200
|
code += this.formatDocumentation(complexType.documentation);
|
|
989
1201
|
const baseType = complexType.base;
|
|
1202
|
+
const namespaceField = this.compileNamespaceField(complexType);
|
|
990
1203
|
if (baseType && builtInPrimitives.includes(baseType)) {
|
|
991
|
-
const
|
|
1204
|
+
const attrs = [...complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`)];
|
|
1205
|
+
const namespaceAttribute = namespaceField.trim();
|
|
1206
|
+
if (namespaceAttribute) {
|
|
1207
|
+
attrs.push(namespaceAttribute);
|
|
1208
|
+
}
|
|
1209
|
+
const attrsObj = attrs.length > 0 ? `{ ${attrs.join("; ")} }` : "{}";
|
|
992
1210
|
code += `export type ${name} = XMLLeaf<${baseType}, ${attrsObj}>;
|
|
993
1211
|
|
|
994
1212
|
`;
|
|
995
1213
|
continue;
|
|
996
1214
|
}
|
|
997
|
-
|
|
998
|
-
code += `export interface ${name}${extendsStr} {
|
|
999
|
-
`;
|
|
1215
|
+
let fields = namespaceField;
|
|
1000
1216
|
for (const element of complexType.elements) {
|
|
1001
|
-
|
|
1217
|
+
fields += this.formatDocumentation(element.documentation, " ");
|
|
1002
1218
|
const optional = element.isOptional ? "?" : "";
|
|
1003
1219
|
let type = element.type;
|
|
1004
1220
|
const hasAttributes = element.attributes.length > 0;
|
|
@@ -1008,17 +1224,134 @@ ${indent} */
|
|
|
1008
1224
|
type = isPrimitiveLike ? `XMLLeaf<${type}, ${attributesType}>` : `XMLBranch<${type}, ${attributesType}>`;
|
|
1009
1225
|
}
|
|
1010
1226
|
const finalType = element.isArray ? `canBeArray<${type}>` : type;
|
|
1011
|
-
|
|
1227
|
+
fields += ` ${element.name}${optional}: ${finalType};
|
|
1012
1228
|
`;
|
|
1013
1229
|
}
|
|
1014
1230
|
for (const attribute of complexType.attributes) {
|
|
1015
|
-
|
|
1016
|
-
|
|
1231
|
+
fields += this.formatDocumentation(attribute.documentation, " ");
|
|
1232
|
+
fields += ` ${attribute.name}?: ${attribute.type};
|
|
1017
1233
|
`;
|
|
1018
1234
|
}
|
|
1019
|
-
|
|
1020
|
-
|
|
1235
|
+
const body = baseType ? `${baseType} & {
|
|
1236
|
+
${fields}}` : `{
|
|
1237
|
+
${fields}}`;
|
|
1238
|
+
code += `export type ${name} = XMLBranch<${body}>;
|
|
1239
|
+
|
|
1240
|
+
`;
|
|
1241
|
+
}
|
|
1242
|
+
code += this.compileNamespaceRegistry();
|
|
1243
|
+
return code;
|
|
1244
|
+
}
|
|
1245
|
+
/**
|
|
1246
|
+
* Поле `$namespace` для типа: префикс пространства имён, в котором объявлен тип.
|
|
1247
|
+
*
|
|
1248
|
+
* Поле пропускается, если в типе уже есть XSD-атрибут с именем `namespace`:
|
|
1249
|
+
* иначе возник бы конфликт имён.
|
|
1250
|
+
*/
|
|
1251
|
+
compileNamespaceField(complexType) {
|
|
1252
|
+
const prefix = this.typeNamespacePrefix.get(complexType.name);
|
|
1253
|
+
if (!prefix) {
|
|
1254
|
+
return "";
|
|
1255
|
+
}
|
|
1256
|
+
if (complexType.attributes.some((attribute) => attribute.name === "$namespace")) {
|
|
1257
|
+
return "";
|
|
1258
|
+
}
|
|
1259
|
+
return ` $namespace?: '${prefix}';
|
|
1260
|
+
`;
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
* Генерирует реестр пространств имён для XMLBuilder.
|
|
1264
|
+
*
|
|
1265
|
+
* Реестр сопоставляет локальные имена элементов с префиксами пространств имён,
|
|
1266
|
+
* поэтому XMLBuilder может подставлять префиксы и объявлять `xmlns` автоматически.
|
|
1267
|
+
*/
|
|
1268
|
+
compileNamespaceRegistry() {
|
|
1269
|
+
if (this.qualifiedElements.size === 0 && this.namespaceUriByPrefix.size === 0) {
|
|
1270
|
+
return "";
|
|
1021
1271
|
}
|
|
1272
|
+
let code = "";
|
|
1273
|
+
code += "/**\n";
|
|
1274
|
+
code += " * \u041F\u0420\u041E\u0421\u0422\u0420\u0410\u041D\u0421\u0422\u0412\u0410 \u0418\u041C\u0401\u041D, \u0418\u0417\u0412\u041B\u0415\u0427\u0401\u041D\u041D\u042B\u0415 \u0418\u0417 WSDL/XSD\n";
|
|
1275
|
+
code += " *\n";
|
|
1276
|
+
code += " * \u0420\u0435\u0435\u0441\u0442\u0440 \u043C\u043E\u0436\u043D\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u0442\u044C \u0432 XMLBuilder, \u0438 \u0442\u043E\u0433\u0434\u0430 \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u044B \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432 \u0438\u043C\u0451\u043D\n";
|
|
1277
|
+
code += " * \u0431\u0443\u0434\u0443\u0442 \u043F\u043E\u0434\u0441\u0442\u0430\u0432\u043B\u044F\u0442\u044C\u0441\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438, \u0430 \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u044F `xmlns:*` \u2014 \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0442\u044C\u0441\u044F\n";
|
|
1278
|
+
code += " * \u0432 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442:\n";
|
|
1279
|
+
code += " *\n";
|
|
1280
|
+
code += " * new XMLBuilder(request, { namespaces: XMLNamespaceRegistry }).toXML();\n";
|
|
1281
|
+
code += " */\n\n";
|
|
1282
|
+
code += "export const XMLNamespacePrefixes = {\n";
|
|
1283
|
+
for (const [prefix, uri] of this.namespaceUriByPrefix.entries()) {
|
|
1284
|
+
code += ` ${JSON.stringify(prefix)}: ${JSON.stringify(uri)},
|
|
1285
|
+
`;
|
|
1286
|
+
}
|
|
1287
|
+
code += "} as const;\n\n";
|
|
1288
|
+
code += "export const XMLNamespaceElements = {\n";
|
|
1289
|
+
for (const [element, prefix] of this.qualifiedElements.entries()) {
|
|
1290
|
+
code += ` ${JSON.stringify(element)}: ${JSON.stringify(prefix)},
|
|
1291
|
+
`;
|
|
1292
|
+
}
|
|
1293
|
+
code += "} as const;\n\n";
|
|
1294
|
+
const children = this.compileNamespaceChildren();
|
|
1295
|
+
if (children) {
|
|
1296
|
+
code += "/**\n";
|
|
1297
|
+
code += " * \u041F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430 \u0438\u043C\u0451\u043D \u0434\u043E\u0447\u0435\u0440\u043D\u0438\u0445 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432: \u0440\u043E\u0434\u0438\u0442\u0435\u043B\u044C -> { \u044D\u043B\u0435\u043C\u0435\u043D\u0442 -> \u043F\u0440\u0435\u0444\u0438\u043A\u0441 }.\n";
|
|
1298
|
+
code += " *\n";
|
|
1299
|
+
code += " * \u0417\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F \u0434\u043B\u044F \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432, \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u043D\u044B\u0445 \u0441\u0440\u0430\u0437\u0443 \u0432 \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u0438\u0445 \u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0430\u0445 \u0438\u043C\u0451\u043D:\n";
|
|
1300
|
+
code += " * \u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0438\u043C\u0435\u043D\u0438 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u043F\u0440\u0435\u0444\u0438\u043A\u0441 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u043E\u0434\u043D\u043E\u0437\u043D\u0430\u0447\u043D\u043E \u043D\u0435\u043B\u044C\u0437\u044F,\n";
|
|
1301
|
+
code += " * \u043F\u043E\u044D\u0442\u043E\u043C\u0443 \u0443\u0447\u0438\u0442\u044B\u0432\u0430\u0435\u0442\u0441\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u0440\u043E\u0434\u0438\u0442\u0435\u043B\u044F.\n";
|
|
1302
|
+
code += " */\n\n";
|
|
1303
|
+
code += children;
|
|
1304
|
+
}
|
|
1305
|
+
code += "export const XMLNamespaceRegistry = {\n";
|
|
1306
|
+
code += " prefixes: XMLNamespacePrefixes,\n";
|
|
1307
|
+
code += " elements: XMLNamespaceElements,\n";
|
|
1308
|
+
if (children) {
|
|
1309
|
+
code += " children: XMLNamespaceChildren,\n";
|
|
1310
|
+
}
|
|
1311
|
+
code += "} as const;\n\n";
|
|
1312
|
+
return code;
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* Собирает карту «родитель -> { дочерний элемент -> префикс }».
|
|
1316
|
+
*
|
|
1317
|
+
* В карту попадают только неоднозначные элементы — те, что объявлены
|
|
1318
|
+
* в нескольких пространствах имён. Для остальных достаточно общего реестра.
|
|
1319
|
+
*/
|
|
1320
|
+
compileNamespaceChildren() {
|
|
1321
|
+
const children = {};
|
|
1322
|
+
for (const [elementName, typeName] of this.elementTypeRegistry.entries()) {
|
|
1323
|
+
const type = this.typeRegistry.get(typeName);
|
|
1324
|
+
if (!type) {
|
|
1325
|
+
continue;
|
|
1326
|
+
}
|
|
1327
|
+
const map = {};
|
|
1328
|
+
for (const element of type.elements) {
|
|
1329
|
+
if (!element.namespace) {
|
|
1330
|
+
continue;
|
|
1331
|
+
}
|
|
1332
|
+
if (!this.ambiguousElements.has(element.name)) {
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
map[element.name] = element.namespace;
|
|
1336
|
+
}
|
|
1337
|
+
if (Object.keys(map).length > 0) {
|
|
1338
|
+
children[elementName] = map;
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
if (Object.keys(children).length === 0) {
|
|
1342
|
+
return "";
|
|
1343
|
+
}
|
|
1344
|
+
let code = "export const XMLNamespaceChildren = {\n";
|
|
1345
|
+
for (const [parent, map] of Object.entries(children)) {
|
|
1346
|
+
code += ` ${JSON.stringify(parent)}: {
|
|
1347
|
+
`;
|
|
1348
|
+
for (const [child, prefix] of Object.entries(map)) {
|
|
1349
|
+
code += ` ${JSON.stringify(child)}: ${JSON.stringify(prefix)},
|
|
1350
|
+
`;
|
|
1351
|
+
}
|
|
1352
|
+
code += " },\n";
|
|
1353
|
+
}
|
|
1354
|
+
code += "} as const;\n\n";
|
|
1022
1355
|
return code;
|
|
1023
1356
|
}
|
|
1024
1357
|
};
|
|
@@ -1039,12 +1372,17 @@ function getXMLValue(value) {
|
|
|
1039
1372
|
function isXMLRecord(value) {
|
|
1040
1373
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1041
1374
|
}
|
|
1042
|
-
function getXMLAttributes(value) {
|
|
1375
|
+
function getXMLAttributes(value, ctx) {
|
|
1043
1376
|
return Object.entries(value).filter(([key]) => key.startsWith("$") && key !== "$value" && key !== "$namespace").map(([key, attrValue]) => {
|
|
1044
1377
|
const name = key.slice(1);
|
|
1045
1378
|
if (!name || !/^[A-Za-z_][\w.:-]*$/.test(name)) {
|
|
1046
1379
|
throw new Error(`Invalid XML attribute name: ${name}`);
|
|
1047
1380
|
}
|
|
1381
|
+
if (key.startsWith("$xmlns:")) {
|
|
1382
|
+
ctx.declaredPrefixes.add(key.slice("$xmlns:".length));
|
|
1383
|
+
} else if (key === "$xmlns") {
|
|
1384
|
+
ctx.declaredPrefixes.add("");
|
|
1385
|
+
}
|
|
1048
1386
|
if (attrValue === null || attrValue === void 0) {
|
|
1049
1387
|
return "";
|
|
1050
1388
|
}
|
|
@@ -1054,65 +1392,126 @@ function getXMLAttributes(value) {
|
|
|
1054
1392
|
return ` ${name}="${escapeXMLAttribute(String(attrValue))}"`;
|
|
1055
1393
|
}).join("");
|
|
1056
1394
|
}
|
|
1057
|
-
function
|
|
1058
|
-
if (
|
|
1059
|
-
|
|
1395
|
+
function resolveElementPrefix(tag, value, ctx, parentTag) {
|
|
1396
|
+
if (isXMLRecord(value) && value.$namespace !== void 0) {
|
|
1397
|
+
const namespace = value.$namespace;
|
|
1398
|
+
if (typeof namespace !== "string" || namespace !== "" && !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
|
|
1399
|
+
throw new Error(`Invalid XML namespace prefix: ${namespace}`);
|
|
1400
|
+
}
|
|
1401
|
+
return namespace;
|
|
1060
1402
|
}
|
|
1061
|
-
if (
|
|
1062
|
-
return
|
|
1403
|
+
if (tag.includes(":")) {
|
|
1404
|
+
return void 0;
|
|
1063
1405
|
}
|
|
1064
|
-
const
|
|
1065
|
-
if (
|
|
1066
|
-
|
|
1067
|
-
|
|
1406
|
+
const contextual = parentTag ? ctx.children[parentTag]?.[tag] : void 0;
|
|
1407
|
+
if (contextual !== void 0) {
|
|
1408
|
+
return contextual;
|
|
1409
|
+
}
|
|
1410
|
+
const mapped = ctx.elements[tag];
|
|
1411
|
+
return mapped === void 0 ? void 0 : mapped;
|
|
1412
|
+
}
|
|
1413
|
+
function buildNamespaceDeclarations(ctx) {
|
|
1414
|
+
let declarations = "";
|
|
1415
|
+
for (const prefix of ctx.usedPrefixes) {
|
|
1416
|
+
if (ctx.declaredPrefixes.has(prefix)) {
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
const uri = ctx.prefixes[prefix];
|
|
1420
|
+
if (!uri) {
|
|
1421
|
+
continue;
|
|
1068
1422
|
}
|
|
1069
|
-
|
|
1423
|
+
declarations += ` xmlns:${prefix}="${escapeXMLAttribute(uri)}"`;
|
|
1424
|
+
}
|
|
1425
|
+
return declarations;
|
|
1426
|
+
}
|
|
1427
|
+
function serializeElementParts(tag, value, ctx, parentTag) {
|
|
1428
|
+
if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
|
|
1429
|
+
throw new Error(`Invalid XML tag name: ${tag}`);
|
|
1070
1430
|
}
|
|
1431
|
+
const prefix = resolveElementPrefix(tag, value, ctx, parentTag);
|
|
1432
|
+
if (prefix) {
|
|
1433
|
+
ctx.usedPrefixes.add(prefix);
|
|
1434
|
+
}
|
|
1435
|
+
const tagName = prefix ? `${prefix}:${tag}` : tag;
|
|
1071
1436
|
let attributes = "";
|
|
1072
1437
|
let content = "";
|
|
1073
1438
|
if (isXMLNode(value)) {
|
|
1074
|
-
attributes = getXMLAttributes(value);
|
|
1439
|
+
attributes = getXMLAttributes(value, ctx);
|
|
1075
1440
|
content = escapeXMLText(String(getXMLValue(value) ?? ""));
|
|
1076
1441
|
} else if (isXMLRecord(value)) {
|
|
1077
|
-
attributes = getXMLAttributes(value);
|
|
1442
|
+
attributes = getXMLAttributes(value, ctx);
|
|
1078
1443
|
const children = Object.entries(value).filter(([key]) => !key.startsWith("$"));
|
|
1079
1444
|
if (children.length > 0) {
|
|
1080
|
-
content = children.map(([key, childValue]) => serializeXMLElement(key, childValue)).join("");
|
|
1445
|
+
content = children.map(([key, childValue]) => serializeXMLElement(key, childValue, ctx, tag)).join("");
|
|
1081
1446
|
} else if (attributes) {
|
|
1082
1447
|
const text = value.$value;
|
|
1083
1448
|
content = text == null ? "" : escapeXMLText(String(text));
|
|
1084
1449
|
} else if ("$value" in value) {
|
|
1085
|
-
throw new Error(`XML element "${
|
|
1450
|
+
throw new Error(`XML element "${tagName}": $value requires at least one attribute`);
|
|
1086
1451
|
}
|
|
1087
1452
|
} else {
|
|
1088
1453
|
content = value == null ? "" : escapeXMLText(String(value));
|
|
1089
1454
|
}
|
|
1090
|
-
|
|
1091
|
-
|
|
1455
|
+
return { tagName, attributes, content };
|
|
1456
|
+
}
|
|
1457
|
+
function composeElement(parts) {
|
|
1458
|
+
if (!parts.content) {
|
|
1459
|
+
return `<${parts.tagName}${parts.attributes}/>`;
|
|
1460
|
+
}
|
|
1461
|
+
return `<${parts.tagName}${parts.attributes}>${parts.content}</${parts.tagName}>`;
|
|
1462
|
+
}
|
|
1463
|
+
function serializeXMLElement(tag, value, ctx, parentTag) {
|
|
1464
|
+
if (Array.isArray(value)) {
|
|
1465
|
+
return value.map((item) => serializeXMLElement(tag, item, ctx, parentTag)).join("");
|
|
1092
1466
|
}
|
|
1093
|
-
return
|
|
1467
|
+
return composeElement(serializeElementParts(tag, value, ctx, parentTag));
|
|
1094
1468
|
}
|
|
1095
1469
|
var XMLBuilder = class {
|
|
1096
1470
|
$input;
|
|
1097
|
-
|
|
1471
|
+
$options;
|
|
1472
|
+
constructor(obj, options = {}) {
|
|
1098
1473
|
this.$input = obj;
|
|
1474
|
+
this.$options = options;
|
|
1099
1475
|
}
|
|
1100
1476
|
toXML(config = {}) {
|
|
1477
|
+
const options = { ...this.$options, ...config };
|
|
1478
|
+
const registry = options.namespaces ?? {};
|
|
1479
|
+
const ctx = {
|
|
1480
|
+
prefixes: registry.prefixes ?? {},
|
|
1481
|
+
elements: registry.elements ?? {},
|
|
1482
|
+
children: registry.children ?? {},
|
|
1483
|
+
usedPrefixes: /* @__PURE__ */ new Set(),
|
|
1484
|
+
declaredPrefixes: /* @__PURE__ */ new Set()
|
|
1485
|
+
};
|
|
1101
1486
|
const entries = Object.entries(this.$input);
|
|
1102
1487
|
if (entries.length !== 1) {
|
|
1103
1488
|
throw new Error("XML must contain exactly one root element");
|
|
1104
1489
|
}
|
|
1105
1490
|
const [rootTag, rootValue] = entries[0];
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1491
|
+
const rootParts = Array.isArray(rootValue) ? rootValue.map((item) => serializeElementParts(rootTag, item, ctx)) : [serializeElementParts(rootTag, rootValue, ctx)];
|
|
1492
|
+
const declarations = buildNamespaceDeclarations(ctx);
|
|
1493
|
+
if (rootParts.length > 0) {
|
|
1494
|
+
rootParts[0] = {
|
|
1495
|
+
...rootParts[0],
|
|
1496
|
+
attributes: `${rootParts[0].attributes}${declarations}`
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
const xml = rootParts.map((parts) => composeElement(parts)).join("");
|
|
1500
|
+
if (options.declaration) {
|
|
1108
1501
|
return `<?xml version="1.0" encoding="UTF-8"?>${xml}`;
|
|
1109
1502
|
}
|
|
1110
1503
|
return xml;
|
|
1111
1504
|
}
|
|
1112
1505
|
};
|
|
1506
|
+
|
|
1507
|
+
// src/utils/asArray.ts
|
|
1508
|
+
var asArray = (value) => {
|
|
1509
|
+
return Array.isArray(value) ? value : [value];
|
|
1510
|
+
};
|
|
1113
1511
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1114
1512
|
0 && (module.exports = {
|
|
1115
1513
|
WSDLTypeGenerator,
|
|
1116
1514
|
XMLBuilder,
|
|
1117
|
-
XMLParser
|
|
1515
|
+
XMLParser,
|
|
1516
|
+
asArray
|
|
1118
1517
|
});
|