xmljslib 1.0.2 → 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/index.js CHANGED
@@ -25,13 +25,25 @@ function createXMLNode(value, attributes = {}, isLeaf = false) {
25
25
  if (!hasAttributes) {
26
26
  return parsedValue;
27
27
  }
28
- const targetObj = Object(parsedValue !== void 0 ? parsedValue : "");
28
+ const attributeValue = Object.prototype.hasOwnProperty.call(attributes, "value") ? parsePrimitive(attributes.value) : void 0;
29
+ const nodeValue = parsedValue !== void 0 ? parsedValue : attributeValue;
30
+ const targetObj = Object(nodeValue !== void 0 ? nodeValue : "");
29
31
  for (const [key, attrVal] of Object.entries(attributes)) {
32
+ if (key === "value") {
33
+ continue;
34
+ }
30
35
  targetObj[`$${key}`] = parsePrimitive(attrVal);
31
36
  }
37
+ Object.defineProperty(targetObj, "$value", {
38
+ value: nodeValue,
39
+ writable: true,
40
+ enumerable: true,
41
+ configurable: true
42
+ });
32
43
  return new Proxy(targetObj, {
33
44
  get(target, prop) {
34
45
  if (prop === "__isXMLNode") return true;
46
+ if (prop === "$value") return nodeValue;
35
47
  if (prop === "valueOf" || prop === Symbol.toPrimitive) {
36
48
  return () => parsedValue;
37
49
  }
@@ -118,10 +130,14 @@ var XMLParser = class _XMLParser {
118
130
  static parseTreeJSON(item) {
119
131
  const result = {};
120
132
  const node = {};
133
+ const attributeValue = Object.prototype.hasOwnProperty.call(item.attributes, "value") ? item.attributes.value : void 0;
134
+ node.$value = item.$value !== null ? item.$value : attributeValue ?? null;
121
135
  for (const attr of Object.keys(item.attributes)) {
136
+ if (attr === "value") {
137
+ continue;
138
+ }
122
139
  node[`$${attr}`] = item.attributes[attr];
123
140
  }
124
- node.$value = item.$value;
125
141
  for (const child of item.children) {
126
142
  const parsed = _XMLParser.parseTreeJSON(child);
127
143
  const childValue = parsed[child.tag];
@@ -256,7 +272,7 @@ var XMLParser = class _XMLParser {
256
272
  };
257
273
 
258
274
  // src/lib/wsdlTypeGenerator.ts
259
- var WSDLTypeGenerator = class {
275
+ var WSDLTypeGenerator = class _WSDLTypeGenerator {
260
276
  typeRegistry = /* @__PURE__ */ new Map();
261
277
  simpleTypeRegistry = /* @__PURE__ */ new Map();
262
278
  simpleTypeDocumentationRegistry = /* @__PURE__ */ new Map();
@@ -271,6 +287,40 @@ var WSDLTypeGenerator = class {
271
287
  globalElementRegistry = /* @__PURE__ */ new Map();
272
288
  baseUrl = "";
273
289
  loadedUrls = /* @__PURE__ */ new Set();
290
+ /**
291
+ * Пространства имён, объявленные в документе (`xmlns:*`).
292
+ * Используются и для автоподстановки префиксов, и для объявления `xmlns` в XML.
293
+ */
294
+ namespaceUriByPrefix = /* @__PURE__ */ new Map();
295
+ namespacePrefixByUri = /* @__PURE__ */ new Map();
296
+ /**
297
+ * Пространства имён элементов: локальное имя элемента -> префикс.
298
+ *
299
+ * Квалифицированные элементы хранятся в `qualifiedElements`,
300
+ * неквалифицированные — в `unqualifiedElements`, чтобы одноимённые элементы
301
+ * из разных схем не конфликтовали: квалифицированный всегда выигрывает.
302
+ */
303
+ qualifiedElements = /* @__PURE__ */ new Map();
304
+ unqualifiedElements = /* @__PURE__ */ new Set();
305
+ /**
306
+ * Имена элементов, объявленных в нескольких пространствах имён.
307
+ * Для таких элементов одного префикса «по имени» недостаточно —
308
+ * нужен контекст родителя.
309
+ */
310
+ ambiguousElements = /* @__PURE__ */ new Set();
311
+ /**
312
+ * Тип каждого элемента: имя элемента -> имя типа в реестре complexType.
313
+ * Нужен, чтобы знать состав дочерних элементов.
314
+ */
315
+ elementTypeRegistry = /* @__PURE__ */ new Map();
316
+ /**
317
+ * Пространства имён типов: имя complexType -> префикс.
318
+ */
319
+ typeNamespacePrefix = /* @__PURE__ */ new Map();
320
+ /**
321
+ * Пространство имён XML Schema. Не имеет отношения к данным сервиса.
322
+ */
323
+ static XML_SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema";
274
324
  get complexTypeCount() {
275
325
  return this.typeRegistry.size;
276
326
  }
@@ -293,8 +343,17 @@ var WSDLTypeGenerator = class {
293
343
  this.messageRegistry.clear();
294
344
  this.globalElementRegistry.clear();
295
345
  this.loadedUrls.clear();
346
+ this.namespaceUriByPrefix.clear();
347
+ this.namespacePrefixByUri.clear();
348
+ this.qualifiedElements.clear();
349
+ this.unqualifiedElements.clear();
350
+ this.ambiguousElements.clear();
351
+ this.elementTypeRegistry.clear();
352
+ this.typeNamespacePrefix.clear();
296
353
  console.log("\u{1F4E6} \u041F\u0430\u0440\u0441\u0438\u043D\u0433 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u044B XML...");
297
354
  const wsdl = new XMLParser(xmlContent, config);
355
+ 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...");
356
+ this.collectNamespaceDeclarations(wsdl);
298
357
  console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439...");
299
358
  this.extractMessages(wsdl);
300
359
  console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439...");
@@ -337,6 +396,106 @@ var WSDLTypeGenerator = class {
337
396
  const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
338
397
  return String(primitive);
339
398
  }
399
+ /**
400
+ * Приводит значение узла к строке.
401
+ */
402
+ toPrimitiveString(value) {
403
+ if (value === null || value === void 0) {
404
+ return void 0;
405
+ }
406
+ const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
407
+ if (primitive === null || primitive === void 0) {
408
+ return void 0;
409
+ }
410
+ const text = String(primitive).trim();
411
+ return text.length > 0 ? text : void 0;
412
+ }
413
+ /**
414
+ * Регистрирует связь префикс <-> URI пространства имён.
415
+ * Первые объявления имеют приоритет: префикс не переопределяется.
416
+ */
417
+ registerNamespacePrefix(prefix, uri) {
418
+ if (!this.namespaceUriByPrefix.has(prefix)) {
419
+ this.namespaceUriByPrefix.set(prefix, uri);
420
+ }
421
+ if (!this.namespacePrefixByUri.has(uri)) {
422
+ this.namespacePrefixByUri.set(uri, prefix);
423
+ }
424
+ }
425
+ /**
426
+ * Собирает объявления пространств имён (`xmlns:*`) из всего документа.
427
+ */
428
+ collectNamespaceDeclarations(node) {
429
+ if (!node || typeof node !== "object") {
430
+ return;
431
+ }
432
+ if (Array.isArray(node)) {
433
+ for (const item of node) {
434
+ this.collectNamespaceDeclarations(item);
435
+ }
436
+ return;
437
+ }
438
+ for (const [key, value] of Object.entries(node)) {
439
+ if (key.startsWith("$xmlns:")) {
440
+ const prefix = key.slice("$xmlns:".length);
441
+ const uri = this.toPrimitiveString(value);
442
+ if (prefix && uri && uri !== _WSDLTypeGenerator.XML_SCHEMA_NAMESPACE) {
443
+ this.registerNamespacePrefix(prefix, uri);
444
+ }
445
+ }
446
+ this.collectNamespaceDeclarations(value);
447
+ }
448
+ }
449
+ /**
450
+ * Определяет префикс для URI пространства имён.
451
+ *
452
+ * Если префикс не объявлен в документе, подбирается свободный
453
+ * (`tns` или `ns1`, `ns2`, ...), чтобы префикс всегда можно было объявить.
454
+ */
455
+ resolveNamespacePrefix(uri) {
456
+ if (!uri) {
457
+ return void 0;
458
+ }
459
+ const declared = this.namespacePrefixByUri.get(uri);
460
+ if (declared) {
461
+ return declared;
462
+ }
463
+ if (!this.namespaceUriByPrefix.has("tns")) {
464
+ this.registerNamespacePrefix("tns", uri);
465
+ return "tns";
466
+ }
467
+ let index = 1;
468
+ while (this.namespaceUriByPrefix.has(`ns${index}`)) {
469
+ index++;
470
+ }
471
+ const prefix = `ns${index}`;
472
+ this.registerNamespacePrefix(prefix, uri);
473
+ return prefix;
474
+ }
475
+ /**
476
+ * Регистрирует пространство имён элемента.
477
+ *
478
+ * Квалифицированный элемент всегда выигрывает у неквалифицированного
479
+ * с тем же локальным именем.
480
+ */
481
+ registerElementNamespace(name, prefix) {
482
+ if (!name) {
483
+ return;
484
+ }
485
+ if (prefix) {
486
+ const known = this.qualifiedElements.get(name);
487
+ if (known === void 0) {
488
+ this.qualifiedElements.set(name, prefix);
489
+ } else if (known !== prefix) {
490
+ this.ambiguousElements.add(name);
491
+ }
492
+ this.unqualifiedElements.delete(name);
493
+ return;
494
+ }
495
+ if (!this.qualifiedElements.has(name)) {
496
+ this.unqualifiedElements.add(name);
497
+ }
498
+ }
340
499
  /**
341
500
  * Извлекает текст документации из XML-узла.
342
501
  *
@@ -574,6 +733,8 @@ ${indent} */
574
733
  if (!schema) {
575
734
  return;
576
735
  }
736
+ this.collectNamespaceDeclarations(schema);
737
+ const context = this.createSchemaContext(schema);
577
738
  for (const key of Object.keys(schema)) {
578
739
  const cleanKey = this.cleanPrefix(key);
579
740
  if (["import", "include"].includes(cleanKey)) {
@@ -595,7 +756,7 @@ ${indent} */
595
756
  if (!ct?.$name) {
596
757
  continue;
597
758
  }
598
- this.parseComplexType(ct.$name, ct);
759
+ this.parseComplexType(ct.$name, ct, context);
599
760
  }
600
761
  }
601
762
  for (const key of Object.keys(schema)) {
@@ -619,10 +780,51 @@ ${indent} */
619
780
  if (!element?.$name) {
620
781
  continue;
621
782
  }
622
- this.parseGlobalElement(element);
783
+ this.parseGlobalElement(element, context);
623
784
  }
624
785
  }
625
786
  }
787
+ /**
788
+ * Формирует контекст схемы: целевое пространство имён и правила квалификации.
789
+ */
790
+ createSchemaContext(schema) {
791
+ const targetNamespace = this.getAttribute(schema, "targetNamespace");
792
+ const formDefault = (this.getAttribute(schema, "elementFormDefault") ?? "unqualified").toLowerCase();
793
+ return {
794
+ targetNamespace,
795
+ prefix: this.resolveNamespacePrefix(targetNamespace),
796
+ elementFormDefault: formDefault === "qualified" ? "qualified" : "unqualified"
797
+ };
798
+ }
799
+ /**
800
+ * Определяет, принадлежит ли элемент целевому пространству имён.
801
+ *
802
+ * Локальные элементы подчиняются `elementFormDefault`,
803
+ * глобальные — всегда квалифицированы.
804
+ *
805
+ * Для ссылок (`ref="pfx:Name"`) берётся пространство имён,
806
+ * объявленное в самом документе, а не пространство текущей схемы.
807
+ */
808
+ resolveElementPrefix(element, context, isGlobal) {
809
+ const ref = this.getAttribute(element, "ref");
810
+ if (ref) {
811
+ const refPrefix = ref.includes(":") ? ref.split(":")[0] : "";
812
+ const uri = this.namespaceUriByPrefix.get(refPrefix);
813
+ const resolved = uri ? this.namespacePrefixByUri.get(uri) : void 0;
814
+ return resolved ?? context.prefix;
815
+ }
816
+ if (!context.prefix || !context.targetNamespace) {
817
+ return void 0;
818
+ }
819
+ if (isGlobal) {
820
+ return context.prefix;
821
+ }
822
+ const form = this.getAttribute(element, "form");
823
+ if (form) {
824
+ return form.toLowerCase() === "qualified" ? context.prefix : void 0;
825
+ }
826
+ return context.elementFormDefault === "qualified" ? context.prefix : void 0;
827
+ }
626
828
  /**
627
829
  * Регистрирует глобальный XSD element.
628
830
  *
@@ -634,11 +836,12 @@ ${indent} */
634
836
  *
635
837
  * FetchBooking -> FetchBookingRequest
636
838
  */
637
- parseGlobalElement(element) {
839
+ parseGlobalElement(element, context) {
638
840
  const name = element.$name;
639
841
  if (!name) {
640
842
  return;
641
843
  }
844
+ this.registerElementNamespace(name, this.resolveElementPrefix(element, context, true));
642
845
  let typeName;
643
846
  if (element.$type) {
644
847
  typeName = this.mapXSDTypeToTS(element.$type);
@@ -647,7 +850,7 @@ ${indent} */
647
850
  const inlineSimpleType = this.getChildNode(element, "simpleType");
648
851
  if (inlineComplexType) {
649
852
  typeName = `${name}Type`;
650
- this.parseComplexType(typeName, inlineComplexType);
853
+ this.parseComplexType(typeName, inlineComplexType, context);
651
854
  } else if (inlineSimpleType) {
652
855
  typeName = `${name}Type`;
653
856
  this.parseSimpleType(typeName, inlineSimpleType);
@@ -656,6 +859,7 @@ ${indent} */
656
859
  }
657
860
  }
658
861
  this.globalElementRegistry.set(name, typeName);
862
+ this.elementTypeRegistry.set(name, typeName);
659
863
  }
660
864
  /**
661
865
  * Загружает внешнюю XSD-схему.
@@ -724,13 +928,16 @@ ${indent} */
724
928
  /**
725
929
  * Разбирает XSD complexType.
726
930
  */
727
- parseComplexType(name, ctNode) {
931
+ parseComplexType(name, ctNode, context) {
728
932
  const complexType = {
729
933
  name,
730
934
  elements: [],
731
935
  attributes: [],
732
936
  documentation: this.extractDocumentation(ctNode)
733
937
  };
938
+ if (context.prefix) {
939
+ this.typeNamespacePrefix.set(name, context.prefix);
940
+ }
734
941
  let baseType;
735
942
  const findElementsAndAttributes = (node) => {
736
943
  if (!node || typeof node !== "object") {
@@ -758,23 +965,28 @@ ${indent} */
758
965
  if (!fieldName) {
759
966
  continue;
760
967
  }
968
+ const elementName = this.cleanPrefix(fieldName);
969
+ const elementNamespace = this.resolveElementPrefix(element, context, false);
970
+ this.registerElementNamespace(elementName, elementNamespace);
761
971
  const inlineComplexType = this.getChildNode(element, "complexType");
762
972
  const inlineSimpleType = this.getChildNode(element, "simpleType");
763
973
  let elementType = element.$type || element.$ref;
764
974
  if (inlineComplexType) {
765
975
  elementType = `${this.cleanPrefix(fieldName)}Type`;
766
- this.parseComplexType(elementType, inlineComplexType);
976
+ this.parseComplexType(elementType, inlineComplexType, context);
767
977
  } else if (inlineSimpleType) {
768
978
  elementType = `${this.cleanPrefix(fieldName)}Type`;
769
979
  this.parseSimpleType(elementType, inlineSimpleType);
770
980
  }
981
+ this.elementTypeRegistry.set(elementName, this.cleanPrefix(elementType || "string"));
771
982
  complexType.elements.push({
772
- name: this.cleanPrefix(fieldName),
983
+ name: elementName,
773
984
  type: this.mapXSDTypeToTS(elementType || "string"),
774
985
  isArray: element.$maxOccurs === "unbounded" || Number(element.$maxOccurs) > 1,
775
986
  isOptional: element.$minOccurs === "0" || !element.$minOccurs,
776
987
  attributes: this.extractAttributes(element),
777
- documentation: this.extractDocumentation(element)
988
+ documentation: this.extractDocumentation(element),
989
+ namespace: elementNamespace
778
990
  });
779
991
  }
780
992
  }
@@ -948,18 +1160,22 @@ ${indent} */
948
1160
  for (const [name, complexType] of this.typeRegistry.entries()) {
949
1161
  code += this.formatDocumentation(complexType.documentation);
950
1162
  const baseType = complexType.base;
1163
+ const namespaceField = this.compileNamespaceField(complexType);
951
1164
  if (baseType && builtInPrimitives.includes(baseType)) {
952
- const attrsObj = complexType.attributes.length > 0 ? `{ ${complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`).join("; ")} }` : "{}";
1165
+ const attrs = [...complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`)];
1166
+ const namespaceAttribute = namespaceField.trim();
1167
+ if (namespaceAttribute) {
1168
+ attrs.push(namespaceAttribute);
1169
+ }
1170
+ const attrsObj = attrs.length > 0 ? `{ ${attrs.join("; ")} }` : "{}";
953
1171
  code += `export type ${name} = XMLLeaf<${baseType}, ${attrsObj}>;
954
1172
 
955
1173
  `;
956
1174
  continue;
957
1175
  }
958
- const extendsStr = baseType ? ` extends ${baseType}` : "";
959
- code += `export interface ${name}${extendsStr} {
960
- `;
1176
+ let fields = namespaceField;
961
1177
  for (const element of complexType.elements) {
962
- code += this.formatDocumentation(element.documentation, " ");
1178
+ fields += this.formatDocumentation(element.documentation, " ");
963
1179
  const optional = element.isOptional ? "?" : "";
964
1180
  let type = element.type;
965
1181
  const hasAttributes = element.attributes.length > 0;
@@ -969,17 +1185,134 @@ ${indent} */
969
1185
  type = isPrimitiveLike ? `XMLLeaf<${type}, ${attributesType}>` : `XMLBranch<${type}, ${attributesType}>`;
970
1186
  }
971
1187
  const finalType = element.isArray ? `canBeArray<${type}>` : type;
972
- code += ` ${element.name}${optional}: ${finalType};
1188
+ fields += ` ${element.name}${optional}: ${finalType};
973
1189
  `;
974
1190
  }
975
1191
  for (const attribute of complexType.attributes) {
976
- code += this.formatDocumentation(attribute.documentation, " ");
977
- code += ` ${attribute.name}?: ${attribute.type};
1192
+ fields += this.formatDocumentation(attribute.documentation, " ");
1193
+ fields += ` ${attribute.name}?: ${attribute.type};
978
1194
  `;
979
1195
  }
980
- code += " [key: `$xmlns${string}`]: string | undefined;\n";
981
- code += "}\n\n";
1196
+ const body = baseType ? `${baseType} & {
1197
+ ${fields}}` : `{
1198
+ ${fields}}`;
1199
+ code += `export type ${name} = XMLBranch<${body}>;
1200
+
1201
+ `;
1202
+ }
1203
+ code += this.compileNamespaceRegistry();
1204
+ return code;
1205
+ }
1206
+ /**
1207
+ * Поле `$namespace` для типа: префикс пространства имён, в котором объявлен тип.
1208
+ *
1209
+ * Поле пропускается, если в типе уже есть XSD-атрибут с именем `namespace`:
1210
+ * иначе возник бы конфликт имён.
1211
+ */
1212
+ compileNamespaceField(complexType) {
1213
+ const prefix = this.typeNamespacePrefix.get(complexType.name);
1214
+ if (!prefix) {
1215
+ return "";
1216
+ }
1217
+ if (complexType.attributes.some((attribute) => attribute.name === "$namespace")) {
1218
+ return "";
1219
+ }
1220
+ return ` $namespace?: '${prefix}';
1221
+ `;
1222
+ }
1223
+ /**
1224
+ * Генерирует реестр пространств имён для XMLBuilder.
1225
+ *
1226
+ * Реестр сопоставляет локальные имена элементов с префиксами пространств имён,
1227
+ * поэтому XMLBuilder может подставлять префиксы и объявлять `xmlns` автоматически.
1228
+ */
1229
+ compileNamespaceRegistry() {
1230
+ if (this.qualifiedElements.size === 0 && this.namespaceUriByPrefix.size === 0) {
1231
+ return "";
982
1232
  }
1233
+ let code = "";
1234
+ code += "/**\n";
1235
+ 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";
1236
+ code += " *\n";
1237
+ 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";
1238
+ 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";
1239
+ code += " * \u0432 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442:\n";
1240
+ code += " *\n";
1241
+ code += " * new XMLBuilder(request, { namespaces: XMLNamespaceRegistry }).toXML();\n";
1242
+ code += " */\n\n";
1243
+ code += "export const XMLNamespacePrefixes = {\n";
1244
+ for (const [prefix, uri] of this.namespaceUriByPrefix.entries()) {
1245
+ code += ` ${JSON.stringify(prefix)}: ${JSON.stringify(uri)},
1246
+ `;
1247
+ }
1248
+ code += "} as const;\n\n";
1249
+ code += "export const XMLNamespaceElements = {\n";
1250
+ for (const [element, prefix] of this.qualifiedElements.entries()) {
1251
+ code += ` ${JSON.stringify(element)}: ${JSON.stringify(prefix)},
1252
+ `;
1253
+ }
1254
+ code += "} as const;\n\n";
1255
+ const children = this.compileNamespaceChildren();
1256
+ if (children) {
1257
+ code += "/**\n";
1258
+ 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";
1259
+ code += " *\n";
1260
+ 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";
1261
+ 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";
1262
+ 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";
1263
+ code += " */\n\n";
1264
+ code += children;
1265
+ }
1266
+ code += "export const XMLNamespaceRegistry = {\n";
1267
+ code += " prefixes: XMLNamespacePrefixes,\n";
1268
+ code += " elements: XMLNamespaceElements,\n";
1269
+ if (children) {
1270
+ code += " children: XMLNamespaceChildren,\n";
1271
+ }
1272
+ code += "} as const;\n\n";
1273
+ return code;
1274
+ }
1275
+ /**
1276
+ * Собирает карту «родитель -> { дочерний элемент -> префикс }».
1277
+ *
1278
+ * В карту попадают только неоднозначные элементы — те, что объявлены
1279
+ * в нескольких пространствах имён. Для остальных достаточно общего реестра.
1280
+ */
1281
+ compileNamespaceChildren() {
1282
+ const children = {};
1283
+ for (const [elementName, typeName] of this.elementTypeRegistry.entries()) {
1284
+ const type = this.typeRegistry.get(typeName);
1285
+ if (!type) {
1286
+ continue;
1287
+ }
1288
+ const map = {};
1289
+ for (const element of type.elements) {
1290
+ if (!element.namespace) {
1291
+ continue;
1292
+ }
1293
+ if (!this.ambiguousElements.has(element.name)) {
1294
+ continue;
1295
+ }
1296
+ map[element.name] = element.namespace;
1297
+ }
1298
+ if (Object.keys(map).length > 0) {
1299
+ children[elementName] = map;
1300
+ }
1301
+ }
1302
+ if (Object.keys(children).length === 0) {
1303
+ return "";
1304
+ }
1305
+ let code = "export const XMLNamespaceChildren = {\n";
1306
+ for (const [parent, map] of Object.entries(children)) {
1307
+ code += ` ${JSON.stringify(parent)}: {
1308
+ `;
1309
+ for (const [child, prefix] of Object.entries(map)) {
1310
+ code += ` ${JSON.stringify(child)}: ${JSON.stringify(prefix)},
1311
+ `;
1312
+ }
1313
+ code += " },\n";
1314
+ }
1315
+ code += "} as const;\n\n";
983
1316
  return code;
984
1317
  }
985
1318
  };
@@ -1000,12 +1333,17 @@ function getXMLValue(value) {
1000
1333
  function isXMLRecord(value) {
1001
1334
  return value !== null && typeof value === "object" && !Array.isArray(value);
1002
1335
  }
1003
- function getXMLAttributes(value) {
1336
+ function getXMLAttributes(value, ctx) {
1004
1337
  return Object.entries(value).filter(([key]) => key.startsWith("$") && key !== "$value" && key !== "$namespace").map(([key, attrValue]) => {
1005
1338
  const name = key.slice(1);
1006
1339
  if (!name || !/^[A-Za-z_][\w.:-]*$/.test(name)) {
1007
1340
  throw new Error(`Invalid XML attribute name: ${name}`);
1008
1341
  }
1342
+ if (key.startsWith("$xmlns:")) {
1343
+ ctx.declaredPrefixes.add(key.slice("$xmlns:".length));
1344
+ } else if (key === "$xmlns") {
1345
+ ctx.declaredPrefixes.add("");
1346
+ }
1009
1347
  if (attrValue === null || attrValue === void 0) {
1010
1348
  return "";
1011
1349
  }
@@ -1015,64 +1353,125 @@ function getXMLAttributes(value) {
1015
1353
  return ` ${name}="${escapeXMLAttribute(String(attrValue))}"`;
1016
1354
  }).join("");
1017
1355
  }
1018
- function serializeXMLElement(tag, value) {
1019
- if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
1020
- throw new Error(`Invalid XML tag name: ${tag}`);
1356
+ function resolveElementPrefix(tag, value, ctx, parentTag) {
1357
+ if (isXMLRecord(value) && value.$namespace !== void 0) {
1358
+ const namespace = value.$namespace;
1359
+ if (typeof namespace !== "string" || namespace !== "" && !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
1360
+ throw new Error(`Invalid XML namespace prefix: ${namespace}`);
1361
+ }
1362
+ return namespace;
1021
1363
  }
1022
- if (Array.isArray(value)) {
1023
- return value.map((item) => serializeXMLElement(tag, item)).join("");
1364
+ if (tag.includes(":")) {
1365
+ return void 0;
1024
1366
  }
1025
- const namespace = isXMLRecord(value) ? value.$namespace : void 0;
1026
- if (namespace !== void 0) {
1027
- if (typeof namespace !== "string" || !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
1028
- throw new Error(`Invalid XML namespace prefix: ${namespace}`);
1367
+ const contextual = parentTag ? ctx.children[parentTag]?.[tag] : void 0;
1368
+ if (contextual !== void 0) {
1369
+ return contextual;
1370
+ }
1371
+ const mapped = ctx.elements[tag];
1372
+ return mapped === void 0 ? void 0 : mapped;
1373
+ }
1374
+ function buildNamespaceDeclarations(ctx) {
1375
+ let declarations = "";
1376
+ for (const prefix of ctx.usedPrefixes) {
1377
+ if (ctx.declaredPrefixes.has(prefix)) {
1378
+ continue;
1379
+ }
1380
+ const uri = ctx.prefixes[prefix];
1381
+ if (!uri) {
1382
+ continue;
1029
1383
  }
1030
- tag = `${namespace}:${tag}`;
1384
+ declarations += ` xmlns:${prefix}="${escapeXMLAttribute(uri)}"`;
1385
+ }
1386
+ return declarations;
1387
+ }
1388
+ function serializeElementParts(tag, value, ctx, parentTag) {
1389
+ if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
1390
+ throw new Error(`Invalid XML tag name: ${tag}`);
1031
1391
  }
1392
+ const prefix = resolveElementPrefix(tag, value, ctx, parentTag);
1393
+ if (prefix) {
1394
+ ctx.usedPrefixes.add(prefix);
1395
+ }
1396
+ const tagName = prefix ? `${prefix}:${tag}` : tag;
1032
1397
  let attributes = "";
1033
1398
  let content = "";
1034
1399
  if (isXMLNode(value)) {
1035
- attributes = getXMLAttributes(value);
1400
+ attributes = getXMLAttributes(value, ctx);
1036
1401
  content = escapeXMLText(String(getXMLValue(value) ?? ""));
1037
1402
  } else if (isXMLRecord(value)) {
1038
- attributes = getXMLAttributes(value);
1403
+ attributes = getXMLAttributes(value, ctx);
1039
1404
  const children = Object.entries(value).filter(([key]) => !key.startsWith("$"));
1040
1405
  if (children.length > 0) {
1041
- content = children.map(([key, childValue]) => serializeXMLElement(key, childValue)).join("");
1406
+ content = children.map(([key, childValue]) => serializeXMLElement(key, childValue, ctx, tag)).join("");
1042
1407
  } else if (attributes) {
1043
1408
  const text = value.$value;
1044
1409
  content = text == null ? "" : escapeXMLText(String(text));
1045
1410
  } else if ("$value" in value) {
1046
- throw new Error(`XML element "${tag}": $value requires at least one attribute`);
1411
+ throw new Error(`XML element "${tagName}": $value requires at least one attribute`);
1047
1412
  }
1048
1413
  } else {
1049
1414
  content = value == null ? "" : escapeXMLText(String(value));
1050
1415
  }
1051
- if (!content) {
1052
- return `<${tag}${attributes}/>`;
1416
+ return { tagName, attributes, content };
1417
+ }
1418
+ function composeElement(parts) {
1419
+ if (!parts.content) {
1420
+ return `<${parts.tagName}${parts.attributes}/>`;
1421
+ }
1422
+ return `<${parts.tagName}${parts.attributes}>${parts.content}</${parts.tagName}>`;
1423
+ }
1424
+ function serializeXMLElement(tag, value, ctx, parentTag) {
1425
+ if (Array.isArray(value)) {
1426
+ return value.map((item) => serializeXMLElement(tag, item, ctx, parentTag)).join("");
1053
1427
  }
1054
- return `<${tag}${attributes}>${content}</${tag}>`;
1428
+ return composeElement(serializeElementParts(tag, value, ctx, parentTag));
1055
1429
  }
1056
1430
  var XMLBuilder = class {
1057
1431
  $input;
1058
- constructor(obj) {
1432
+ $options;
1433
+ constructor(obj, options = {}) {
1059
1434
  this.$input = obj;
1435
+ this.$options = options;
1060
1436
  }
1061
1437
  toXML(config = {}) {
1438
+ const options = { ...this.$options, ...config };
1439
+ const registry = options.namespaces ?? {};
1440
+ const ctx = {
1441
+ prefixes: registry.prefixes ?? {},
1442
+ elements: registry.elements ?? {},
1443
+ children: registry.children ?? {},
1444
+ usedPrefixes: /* @__PURE__ */ new Set(),
1445
+ declaredPrefixes: /* @__PURE__ */ new Set()
1446
+ };
1062
1447
  const entries = Object.entries(this.$input);
1063
1448
  if (entries.length !== 1) {
1064
1449
  throw new Error("XML must contain exactly one root element");
1065
1450
  }
1066
1451
  const [rootTag, rootValue] = entries[0];
1067
- const xml = serializeXMLElement(rootTag, rootValue);
1068
- if (config.declaration) {
1452
+ const rootParts = Array.isArray(rootValue) ? rootValue.map((item) => serializeElementParts(rootTag, item, ctx)) : [serializeElementParts(rootTag, rootValue, ctx)];
1453
+ const declarations = buildNamespaceDeclarations(ctx);
1454
+ if (rootParts.length > 0) {
1455
+ rootParts[0] = {
1456
+ ...rootParts[0],
1457
+ attributes: `${rootParts[0].attributes}${declarations}`
1458
+ };
1459
+ }
1460
+ const xml = rootParts.map((parts) => composeElement(parts)).join("");
1461
+ if (options.declaration) {
1069
1462
  return `<?xml version="1.0" encoding="UTF-8"?>${xml}`;
1070
1463
  }
1071
1464
  return xml;
1072
1465
  }
1073
1466
  };
1467
+
1468
+ // src/utils/asArray.ts
1469
+ var asArray = (value) => {
1470
+ return Array.isArray(value) ? value : [value];
1471
+ };
1074
1472
  export {
1075
1473
  WSDLTypeGenerator,
1076
1474
  XMLBuilder,
1077
- XMLParser
1475
+ XMLParser,
1476
+ asArray
1078
1477
  };