xmljslib 0.0.0-stage → 1.0.1

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.cjs ADDED
@@ -0,0 +1,1117 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ WSDLTypeGenerator: () => WSDLTypeGenerator,
34
+ XMLBuilder: () => XMLBuilder,
35
+ XMLParser: () => XMLParser
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/lib/wsdlTypeGenerator.ts
40
+ var import_node_fs = __toESM(require("fs"), 1);
41
+ var import_node_path = __toESM(require("path"), 1);
42
+
43
+ // src/utils/createXMLNode.ts
44
+ function createXMLNode(value, attributes = {}, isLeaf = false) {
45
+ const parsePrimitive = (val) => {
46
+ if (val == null) return void 0;
47
+ const v = String(val).trim();
48
+ if (v === "" || v === "null" || v === "undefined") return void 0;
49
+ if (v === "true") return true;
50
+ if (v === "false") return false;
51
+ if (v !== "" && !Number.isNaN(Number(v))) return Number(v);
52
+ return val;
53
+ };
54
+ const parsedValue = parsePrimitive(value);
55
+ if (!isLeaf) {
56
+ const branchObj = {};
57
+ for (const [key, attrVal] of Object.entries(attributes)) {
58
+ branchObj[`$${key}`] = parsePrimitive(attrVal);
59
+ }
60
+ return branchObj;
61
+ }
62
+ const hasAttributes = Object.keys(attributes).length > 0;
63
+ if (!hasAttributes) {
64
+ return parsedValue;
65
+ }
66
+ const targetObj = Object(parsedValue !== void 0 ? parsedValue : "");
67
+ for (const [key, attrVal] of Object.entries(attributes)) {
68
+ targetObj[`$${key}`] = parsePrimitive(attrVal);
69
+ }
70
+ return new Proxy(targetObj, {
71
+ get(target, prop) {
72
+ if (prop === "__isXMLNode") return true;
73
+ if (prop === "valueOf" || prop === Symbol.toPrimitive) {
74
+ return () => parsedValue;
75
+ }
76
+ if (prop === "toString") {
77
+ return () => parsedValue !== void 0 ? String(parsedValue) : "";
78
+ }
79
+ if (prop === /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom") || prop === "toJSON") {
80
+ return () => parsedValue;
81
+ }
82
+ const member = target[prop];
83
+ return typeof member === "function" ? member.bind(target) : member;
84
+ },
85
+ getOwnPropertyDescriptor(target, prop) {
86
+ return Reflect.getOwnPropertyDescriptor(target, prop);
87
+ }
88
+ });
89
+ }
90
+
91
+ // src/utils/removePrefixes.ts
92
+ function removePrefixes(name) {
93
+ return name.includes(":") ? name.split(":").pop() : name;
94
+ }
95
+
96
+ // src/lib/xmlParser.ts
97
+ var XMLParser = class _XMLParser {
98
+ $tree;
99
+ $config;
100
+ constructor(xml, config = {}) {
101
+ Object.defineProperty(this, "$input", {
102
+ value: xml,
103
+ writable: false,
104
+ enumerable: false,
105
+ configurable: false
106
+ });
107
+ this.$config = {
108
+ trimPrefixes: false,
109
+ ...config
110
+ };
111
+ const tree = _XMLParser.buildTagTree(xml, this.$config.trimPrefixes);
112
+ Object.defineProperty(this, "$tree", {
113
+ value: tree,
114
+ writable: false,
115
+ enumerable: false,
116
+ configurable: false
117
+ });
118
+ const obj = this.toObject();
119
+ Object.assign(this, obj);
120
+ }
121
+ toJSON() {
122
+ let result = {};
123
+ if (!this.$tree) return null;
124
+ for (const item of this.$tree) {
125
+ result = _XMLParser.parseTreeJSON(item);
126
+ }
127
+ return result;
128
+ }
129
+ static isXMLTag(xml) {
130
+ const value = xml.trim();
131
+ return /^<[\w:-]+(?:\s+[^>]*)?(?:\/>|>[\s\S]*<\/[\w:-]+>)$/.test(value);
132
+ }
133
+ static parseTreeItem(item) {
134
+ const result = {};
135
+ const attrs = {};
136
+ for (const attr of Object.keys(item.attributes)) {
137
+ attrs[attr] = item.attributes[attr];
138
+ }
139
+ const isLeaf = item.children.length === 0;
140
+ const node = createXMLNode(item.$value, attrs, isLeaf);
141
+ for (const child of item.children) {
142
+ const parsed = _XMLParser.parseTreeItem(child);
143
+ const childValue = parsed[child.tag];
144
+ if (Object.prototype.hasOwnProperty.call(node, child.tag)) {
145
+ if (!Array.isArray(node[child.tag])) {
146
+ node[child.tag] = [node[child.tag]];
147
+ }
148
+ node[child.tag].push(childValue);
149
+ } else {
150
+ node[child.tag] = childValue;
151
+ }
152
+ }
153
+ result[item.tag] = node;
154
+ return result;
155
+ }
156
+ static parseTreeJSON(item) {
157
+ const result = {};
158
+ const node = {};
159
+ for (const attr of Object.keys(item.attributes)) {
160
+ node[`$${attr}`] = item.attributes[attr];
161
+ }
162
+ node.$value = item.$value;
163
+ for (const child of item.children) {
164
+ const parsed = _XMLParser.parseTreeJSON(child);
165
+ const childValue = parsed[child.tag];
166
+ if (Object.prototype.hasOwnProperty.call(node, child.tag)) {
167
+ if (!Array.isArray(node[child.tag])) {
168
+ node[child.tag] = [node[child.tag]];
169
+ }
170
+ node[child.tag].push(childValue);
171
+ } else {
172
+ node[child.tag] = childValue;
173
+ }
174
+ }
175
+ result[item.tag] = node;
176
+ return result;
177
+ }
178
+ toObject() {
179
+ let result = {};
180
+ if (!this.$tree) return null;
181
+ for (const item of this.$tree) {
182
+ result = _XMLParser.parseTreeItem(item);
183
+ }
184
+ return result;
185
+ }
186
+ static buildTagTree(xml, trimPrefixes = false) {
187
+ const stack = [];
188
+ const roots = [];
189
+ const source = xml.replace(/<!--[\s\S]*?-->/g, "");
190
+ let i = 0;
191
+ while (i < source.length) {
192
+ if (source[i] === "<") {
193
+ if (source.startsWith("<?xml", i)) {
194
+ const end = source.indexOf("?>", i);
195
+ if (end === -1) throw new Error("Invalid XML declaration");
196
+ i = end + 2;
197
+ continue;
198
+ }
199
+ if (source.startsWith("<!", i)) {
200
+ const end = source.indexOf(">", i);
201
+ if (end === -1) throw new Error("Invalid XML declaration");
202
+ i = end + 1;
203
+ continue;
204
+ }
205
+ if (source[i + 1] === "/") {
206
+ const close = _XMLParser.readCloseTag(source, i, trimPrefixes);
207
+ const node2 = stack.pop();
208
+ if (!node2) {
209
+ throw new Error(`Unexpected closing tag: </${close.tag}>`);
210
+ }
211
+ if (node2.tag !== close.tag) {
212
+ throw new Error(`XML mismatch: expected </${node2.tag}>, got </${close.tag}>`);
213
+ }
214
+ node2.end = close.end;
215
+ i = close.next;
216
+ continue;
217
+ }
218
+ const open = _XMLParser.readOpenTag(source, i, trimPrefixes);
219
+ const node = {
220
+ tag: open.tag,
221
+ start: i,
222
+ end: -1,
223
+ attributes: open.attributes,
224
+ children: [],
225
+ $value: null
226
+ };
227
+ if (stack.length > 0) {
228
+ stack[stack.length - 1].children.push(node);
229
+ } else {
230
+ roots.push(node);
231
+ }
232
+ if (!open.selfClosing) {
233
+ stack.push(node);
234
+ } else {
235
+ node.end = open.next;
236
+ }
237
+ i = open.next;
238
+ continue;
239
+ }
240
+ let textEnd = source.indexOf("<", i);
241
+ if (textEnd === -1) textEnd = source.length;
242
+ const text = source.slice(i, textEnd).trim();
243
+ if (text && stack.length > 0) {
244
+ const current = stack[stack.length - 1];
245
+ if (current.$value === null) {
246
+ current.$value = text;
247
+ }
248
+ }
249
+ i = textEnd;
250
+ }
251
+ if (stack.length > 0) {
252
+ throw new Error(`Unclosed tags: ${stack.map((s) => s.tag).join(", ")}`);
253
+ }
254
+ return roots;
255
+ }
256
+ static readOpenTag(xml, i, trimPrefixes = false) {
257
+ const end = xml.indexOf(">", i);
258
+ if (end === -1) {
259
+ throw new Error("Invalid XML: open tag not closed");
260
+ }
261
+ const raw = xml.slice(i + 1, end).trim();
262
+ const isSelfClosing = raw.endsWith("/");
263
+ const cleaned = isSelfClosing ? raw.slice(0, -1).trim() : raw;
264
+ const nameEnd = cleaned.search(/\s/);
265
+ const rawTag = nameEnd === -1 ? cleaned : cleaned.slice(0, nameEnd);
266
+ const tag = trimPrefixes ? removePrefixes(rawTag) : rawTag;
267
+ const attrStr = cleaned.slice(rawTag.length).trim();
268
+ const attributes = {};
269
+ const attributeRegex = /([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
270
+ let match = attributeRegex.exec(attrStr);
271
+ while (match !== null) {
272
+ attributes[match[1]] = match[2] ?? match[3];
273
+ match = attributeRegex.exec(attrStr);
274
+ }
275
+ return {
276
+ tag,
277
+ attributes,
278
+ selfClosing: isSelfClosing,
279
+ next: end + 1
280
+ };
281
+ }
282
+ static readCloseTag(xml, i, trimPrefixes = false) {
283
+ const end = xml.indexOf(">", i);
284
+ if (end === -1) {
285
+ throw new Error("Invalid XML: close tag not closed");
286
+ }
287
+ const raw = xml.slice(i + 2, end).trim();
288
+ return {
289
+ tag: trimPrefixes ? removePrefixes(raw) : raw,
290
+ next: end + 1,
291
+ end
292
+ };
293
+ }
294
+ };
295
+
296
+ // src/lib/wsdlTypeGenerator.ts
297
+ var WSDLTypeGenerator = class {
298
+ typeRegistry = /* @__PURE__ */ new Map();
299
+ simpleTypeRegistry = /* @__PURE__ */ new Map();
300
+ simpleTypeDocumentationRegistry = /* @__PURE__ */ new Map();
301
+ portTypeRegistry = /* @__PURE__ */ new Map();
302
+ messageRegistry = /* @__PURE__ */ new Map();
303
+ /**
304
+ * Связывает имя глобального XSD element с TypeScript-типом.
305
+ *
306
+ * Например:
307
+ * FetchBooking -> FetchBookingRequest
308
+ */
309
+ globalElementRegistry = /* @__PURE__ */ new Map();
310
+ baseUrl = "";
311
+ loadedUrls = /* @__PURE__ */ new Set();
312
+ get complexTypeCount() {
313
+ return this.typeRegistry.size;
314
+ }
315
+ get simpleTypeCount() {
316
+ return this.simpleTypeRegistry.size;
317
+ }
318
+ async generate(wsdlUrl, outputFilePath, config = { trimPrefixes: true }) {
319
+ try {
320
+ console.log(`\u{1F4E1} \u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 WSDL \u0441: ${wsdlUrl}...`);
321
+ const response = await fetch(wsdlUrl);
322
+ if (!response.ok) {
323
+ throw new Error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438: ${response.statusText}`);
324
+ }
325
+ const xmlContent = await response.text();
326
+ this.baseUrl = wsdlUrl.substring(0, wsdlUrl.lastIndexOf("/") + 1);
327
+ this.typeRegistry.clear();
328
+ this.simpleTypeRegistry.clear();
329
+ this.simpleTypeDocumentationRegistry.clear();
330
+ this.portTypeRegistry.clear();
331
+ this.messageRegistry.clear();
332
+ this.globalElementRegistry.clear();
333
+ this.loadedUrls.clear();
334
+ console.log("\u{1F4E6} \u041F\u0430\u0440\u0441\u0438\u043D\u0433 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u044B XML...");
335
+ const wsdl = new XMLParser(xmlContent, config);
336
+ console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439...");
337
+ this.extractMessages(wsdl);
338
+ console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 WSDL \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0439...");
339
+ this.extractOperations(wsdl);
340
+ console.log("\u{1F50D} \u0410\u043D\u0430\u043B\u0438\u0437 XSD \u0441\u0445\u0435\u043C \u0432\u043D\u0443\u0442\u0440\u0438 WSDL...");
341
+ await this.extractSchemas(wsdl);
342
+ console.log("\u{1F4BB} \u0421\u0431\u043E\u0440\u043A\u0430 TypeScript \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u043E\u0432...");
343
+ const tsCode = this.compileToTypeScript();
344
+ const dir = import_node_path.default.dirname(outputFilePath);
345
+ if (!import_node_fs.default.existsSync(dir)) {
346
+ import_node_fs.default.mkdirSync(dir, { recursive: true });
347
+ }
348
+ import_node_fs.default.writeFileSync(outputFilePath, tsCode, "utf-8");
349
+ console.log(
350
+ `\u2728 \u0423\u0441\u043F\u0435\u0445! \u0424\u0430\u0439\u043B \u0442\u0438\u043F\u043E\u0432 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D: ${outputFilePath} (\u0421\u043B\u043E\u0436\u043D\u044B\u0445 \u0442\u0438\u043F\u043E\u0432: ${this.typeRegistry.size}, \u043F\u0440\u043E\u0441\u0442\u044B\u0445: ${this.simpleTypeRegistry.size}, WSDL \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439: ${this.messageRegistry.size}, PortTypes: ${this.portTypeRegistry.size})`
351
+ );
352
+ } catch (error) {
353
+ console.error("\u274C \u041E\u0448\u0438\u0431\u043A\u0430 \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438:", error);
354
+ }
355
+ }
356
+ cleanPrefix(name) {
357
+ if (!name) return "";
358
+ return String(name).split(":").pop() || "";
359
+ }
360
+ getChildNode(node, name) {
361
+ if (!node || typeof node !== "object") {
362
+ return void 0;
363
+ }
364
+ const key = Object.keys(node).find((key2) => this.cleanPrefix(key2) === name);
365
+ return key ? node[key] : void 0;
366
+ }
367
+ getAttribute(node, name) {
368
+ if (!node || typeof node !== "object") {
369
+ return void 0;
370
+ }
371
+ const value = node[`$${name}`];
372
+ if (value === null || value === void 0) {
373
+ return void 0;
374
+ }
375
+ const primitive = typeof value.valueOf === "function" ? value.valueOf() : value;
376
+ return String(primitive);
377
+ }
378
+ /**
379
+ * Извлекает текст документации из XML-узла.
380
+ *
381
+ * Поддерживает:
382
+ * - wsdl:documentation
383
+ * - xs:annotation/xs:documentation
384
+ * - XMLLeaf / Proxy с текстовым значением
385
+ */
386
+ extractDocumentation(node) {
387
+ if (!node || typeof node !== "object") {
388
+ return void 0;
389
+ }
390
+ const documentation = [];
391
+ const extractText = (value) => {
392
+ if (Array.isArray(value)) {
393
+ value.forEach(extractText);
394
+ return;
395
+ }
396
+ if (value === null || value === void 0) {
397
+ return;
398
+ }
399
+ if (typeof value === "object") {
400
+ if ("$value" in value) {
401
+ extractText(value.$value);
402
+ return;
403
+ }
404
+ if (typeof value.valueOf === "function") {
405
+ const primitive = value.valueOf();
406
+ if (primitive !== value) {
407
+ extractText(primitive);
408
+ }
409
+ }
410
+ return;
411
+ }
412
+ const text = String(value).trim();
413
+ if (text) {
414
+ documentation.push(text);
415
+ }
416
+ };
417
+ for (const key of Object.keys(node)) {
418
+ const cleanKey = this.cleanPrefix(key);
419
+ if (cleanKey === "documentation") {
420
+ extractText(node[key]);
421
+ }
422
+ if (cleanKey === "annotation") {
423
+ const annotations = Array.isArray(node[key]) ? node[key] : [node[key]];
424
+ for (const annotation of annotations) {
425
+ if (!annotation || typeof annotation !== "object") {
426
+ continue;
427
+ }
428
+ for (const annotationKey of Object.keys(annotation)) {
429
+ if (this.cleanPrefix(annotationKey) === "documentation") {
430
+ extractText(annotation[annotationKey]);
431
+ }
432
+ }
433
+ }
434
+ }
435
+ }
436
+ return documentation.length > 0 ? documentation.join("\n\n") : void 0;
437
+ }
438
+ formatDocumentation(documentation, indent = "") {
439
+ if (!documentation) {
440
+ return "";
441
+ }
442
+ const lines = documentation.replace(/\*\//g, "*\\/").split(/\r?\n/).map((line) => `${indent} * ${line.trimEnd()}`);
443
+ return `${indent}/**
444
+ ${lines.join("\n")}
445
+ ${indent} */
446
+ `;
447
+ }
448
+ /**
449
+ * Извлекает wsdl:message и его wsdl:part.
450
+ */
451
+ extractMessages(node) {
452
+ if (!node || typeof node !== "object") {
453
+ return;
454
+ }
455
+ for (const key of Object.keys(node)) {
456
+ if (this.cleanPrefix(key) === "message") {
457
+ const messages = Array.isArray(node[key]) ? node[key] : [node[key]];
458
+ for (const message of messages) {
459
+ if (!message || typeof message !== "object") {
460
+ continue;
461
+ }
462
+ const name = this.getAttribute(message, "name");
463
+ if (!name) {
464
+ continue;
465
+ }
466
+ const parts = [];
467
+ const partNodes = this.getChildNode(message, "part");
468
+ if (partNodes) {
469
+ const partList = Array.isArray(partNodes) ? partNodes : [partNodes];
470
+ for (const part of partList) {
471
+ if (!part || typeof part !== "object") {
472
+ continue;
473
+ }
474
+ const partName = this.getAttribute(part, "name");
475
+ if (!partName) {
476
+ continue;
477
+ }
478
+ parts.push({
479
+ name: partName,
480
+ element: this.getAttribute(part, "element"),
481
+ type: this.getAttribute(part, "type")
482
+ });
483
+ }
484
+ }
485
+ this.messageRegistry.set(name, {
486
+ name,
487
+ parts
488
+ });
489
+ }
490
+ }
491
+ this.extractMessages(node[key]);
492
+ }
493
+ }
494
+ /**
495
+ * Извлекает wsdl:portType и содержащиеся в них операции.
496
+ */
497
+ extractOperations(node) {
498
+ if (!node || typeof node !== "object") {
499
+ return;
500
+ }
501
+ for (const key of Object.keys(node)) {
502
+ if (this.cleanPrefix(key) === "portType") {
503
+ const portTypes = Array.isArray(node[key]) ? node[key] : [node[key]];
504
+ for (const portType of portTypes) {
505
+ if (!portType || typeof portType !== "object") {
506
+ continue;
507
+ }
508
+ const name = this.getAttribute(portType, "name");
509
+ if (!name) {
510
+ continue;
511
+ }
512
+ const portTypeData = {
513
+ name,
514
+ documentation: this.extractDocumentation(portType),
515
+ operations: []
516
+ };
517
+ const operationNodes = this.getChildNode(portType, "operation");
518
+ if (operationNodes) {
519
+ const operations = Array.isArray(operationNodes) ? operationNodes : [operationNodes];
520
+ for (const operation of operations) {
521
+ if (!operation || typeof operation !== "object") {
522
+ continue;
523
+ }
524
+ const operationName = this.getAttribute(operation, "name");
525
+ if (!operationName) {
526
+ continue;
527
+ }
528
+ const input = this.getChildNode(operation, "input");
529
+ const output = this.getChildNode(operation, "output");
530
+ portTypeData.operations.push({
531
+ name: operationName,
532
+ documentation: this.extractDocumentation(operation),
533
+ inputMessage: this.getAttribute(input, "message"),
534
+ outputMessage: this.getAttribute(output, "message")
535
+ });
536
+ }
537
+ }
538
+ this.portTypeRegistry.set(name, portTypeData);
539
+ }
540
+ }
541
+ this.extractOperations(node[key]);
542
+ }
543
+ }
544
+ /**
545
+ * Разрешает WSDL message в TypeScript-тип.
546
+ *
547
+ * Если сообщение содержит один part:
548
+ * возвращает тип соответствующего element/type.
549
+ *
550
+ * Если несколько:
551
+ * возвращает имя сгенерированного интерфейса сообщения.
552
+ */
553
+ resolveMessageType(messageQName) {
554
+ if (!messageQName) {
555
+ return void 0;
556
+ }
557
+ const messageName = this.cleanPrefix(messageQName);
558
+ const message = this.messageRegistry.get(messageName);
559
+ if (!message) {
560
+ console.warn(`\u26A0\uFE0F WSDL message \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D: ${messageQName}`);
561
+ return void 0;
562
+ }
563
+ if (message.parts.length === 0) {
564
+ return void 0;
565
+ }
566
+ if (message.parts.length === 1) {
567
+ return this.resolveMessagePartType(message.parts[0]);
568
+ }
569
+ return this.getMessageInterfaceName(message.name);
570
+ }
571
+ /**
572
+ * Разрешает wsdl:part в TypeScript-тип.
573
+ */
574
+ resolveMessagePartType(part) {
575
+ if (part.element) {
576
+ const elementName = this.cleanPrefix(part.element);
577
+ return this.globalElementRegistry.get(elementName) || elementName;
578
+ }
579
+ if (part.type) {
580
+ return this.mapXSDTypeToTS(part.type);
581
+ }
582
+ return "unknown";
583
+ }
584
+ /**
585
+ * Имя интерфейса для WSDL message с несколькими part.
586
+ */
587
+ getMessageInterfaceName(messageName) {
588
+ return `${messageName}Message`;
589
+ }
590
+ /**
591
+ * Рекурсивно ищет XSD-схемы внутри WSDL.
592
+ */
593
+ async extractSchemas(node) {
594
+ if (!node || typeof node !== "object") {
595
+ return;
596
+ }
597
+ for (const key of Object.keys(node)) {
598
+ if (this.cleanPrefix(key) === "schema") {
599
+ const schemas = Array.isArray(node[key]) ? node[key] : [node[key]];
600
+ for (const schema of schemas) {
601
+ await this.parseXSDSchema(schema);
602
+ }
603
+ } else {
604
+ await this.extractSchemas(node[key]);
605
+ }
606
+ }
607
+ }
608
+ /**
609
+ * Разбирает XSD-схему.
610
+ */
611
+ async parseXSDSchema(schema) {
612
+ if (!schema) {
613
+ return;
614
+ }
615
+ for (const key of Object.keys(schema)) {
616
+ const cleanKey = this.cleanPrefix(key);
617
+ if (["import", "include"].includes(cleanKey)) {
618
+ const imports = Array.isArray(schema[key]) ? schema[key] : [schema[key]];
619
+ for (const imp of imports) {
620
+ const location = imp.$schemaLocation;
621
+ if (location) {
622
+ await this.loadExternalXSD(location);
623
+ }
624
+ }
625
+ }
626
+ }
627
+ for (const key of Object.keys(schema)) {
628
+ if (this.cleanPrefix(key) !== "complexType") {
629
+ continue;
630
+ }
631
+ const complexTypes = Array.isArray(schema[key]) ? schema[key] : [schema[key]];
632
+ for (const ct of complexTypes) {
633
+ if (!ct?.$name) {
634
+ continue;
635
+ }
636
+ this.parseComplexType(ct.$name, ct);
637
+ }
638
+ }
639
+ for (const key of Object.keys(schema)) {
640
+ if (this.cleanPrefix(key) !== "simpleType") {
641
+ continue;
642
+ }
643
+ const simpleTypes = Array.isArray(schema[key]) ? schema[key] : [schema[key]];
644
+ for (const st of simpleTypes) {
645
+ if (!st?.$name) {
646
+ continue;
647
+ }
648
+ this.parseSimpleType(st.$name, st);
649
+ }
650
+ }
651
+ for (const key of Object.keys(schema)) {
652
+ if (this.cleanPrefix(key) !== "element") {
653
+ continue;
654
+ }
655
+ const elements = Array.isArray(schema[key]) ? schema[key] : [schema[key]];
656
+ for (const element of elements) {
657
+ if (!element?.$name) {
658
+ continue;
659
+ }
660
+ this.parseGlobalElement(element);
661
+ }
662
+ }
663
+ }
664
+ /**
665
+ * Регистрирует глобальный XSD element.
666
+ *
667
+ * Например:
668
+ *
669
+ * <xs:element name="FetchBooking" type="tns:FetchBookingRequest"/>
670
+ *
671
+ * Регистрирует:
672
+ *
673
+ * FetchBooking -> FetchBookingRequest
674
+ */
675
+ parseGlobalElement(element) {
676
+ const name = element.$name;
677
+ if (!name) {
678
+ return;
679
+ }
680
+ let typeName;
681
+ if (element.$type) {
682
+ typeName = this.mapXSDTypeToTS(element.$type);
683
+ } else {
684
+ const inlineComplexType = this.getChildNode(element, "complexType");
685
+ const inlineSimpleType = this.getChildNode(element, "simpleType");
686
+ if (inlineComplexType) {
687
+ typeName = `${name}Type`;
688
+ this.parseComplexType(typeName, inlineComplexType);
689
+ } else if (inlineSimpleType) {
690
+ typeName = `${name}Type`;
691
+ this.parseSimpleType(typeName, inlineSimpleType);
692
+ } else {
693
+ typeName = "unknown";
694
+ }
695
+ }
696
+ this.globalElementRegistry.set(name, typeName);
697
+ }
698
+ /**
699
+ * Загружает внешнюю XSD-схему.
700
+ */
701
+ async loadExternalXSD(relativeUrl) {
702
+ const fullUrl = new URL(relativeUrl, this.baseUrl).toString();
703
+ if (this.loadedUrls.has(fullUrl)) {
704
+ return;
705
+ }
706
+ this.loadedUrls.add(fullUrl);
707
+ try {
708
+ console.log(`\u{1F4E5} \u0421\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u0435 \u0432\u043D\u0435\u0448\u043D\u0435\u0439 \u0441\u0445\u0435\u043C\u044B: ${relativeUrl}...`);
709
+ const response = await fetch(fullUrl);
710
+ if (!response.ok) {
711
+ console.warn(`\u26A0\uFE0F \u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0441\u0445\u0435\u043C\u0443 (HTTP ${response.status}): ${fullUrl}`);
712
+ return;
713
+ }
714
+ const contentType = response.headers.get("content-type") || "";
715
+ if (contentType.includes("text/html")) {
716
+ console.warn(`\u26A0\uFE0F \u0421\u0435\u0440\u0432\u0435\u0440 \u0432\u0435\u0440\u043D\u0443\u043B HTML \u0432\u043C\u0435\u0441\u0442\u043E XSD: ${fullUrl}`);
717
+ return;
718
+ }
719
+ const xsdContent = await response.text();
720
+ const normalizedContent = xsdContent.trim();
721
+ if (normalizedContent.startsWith("<!DOCTYPE html>") || normalizedContent.startsWith("<html")) {
722
+ console.warn(`\u26A0\uFE0F \u041E\u0431\u043D\u0430\u0440\u0443\u0436\u0435\u043D HTML \u0432\u043C\u0435\u0441\u0442\u043E XSD: ${fullUrl}`);
723
+ return;
724
+ }
725
+ const xsdObj = new XMLParser(xsdContent, { trimPrefixes: true });
726
+ const schemaKey = Object.keys(xsdObj).find((key) => this.cleanPrefix(key) === "schema");
727
+ if (schemaKey) {
728
+ await this.parseXSDSchema(xsdObj[schemaKey]);
729
+ }
730
+ } catch (error) {
731
+ console.error(`\u274C \u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0435 \u0432\u043D\u0435\u0448\u043D\u0435\u0439 \u0441\u0445\u0435\u043C\u044B ${fullUrl}:`, error);
732
+ }
733
+ }
734
+ /**
735
+ * Разбирает XSD simpleType.
736
+ */
737
+ parseSimpleType(name, stNode) {
738
+ const values = [];
739
+ let documentation = this.extractDocumentation(stNode);
740
+ const restriction = this.getChildNode(stNode, "restriction");
741
+ if (!documentation && restriction) {
742
+ documentation = this.extractDocumentation(restriction);
743
+ }
744
+ if (documentation) {
745
+ this.simpleTypeDocumentationRegistry.set(name, documentation);
746
+ }
747
+ if (restriction) {
748
+ const enumeration = this.getChildNode(restriction, "enumeration");
749
+ if (enumeration) {
750
+ const enumerations = Array.isArray(enumeration) ? enumeration : [enumeration];
751
+ for (const item of enumerations) {
752
+ if (item?.$value !== void 0) {
753
+ values.push(String(item.$value));
754
+ }
755
+ }
756
+ }
757
+ }
758
+ if (values.length > 0) {
759
+ this.simpleTypeRegistry.set(name, values);
760
+ }
761
+ }
762
+ /**
763
+ * Разбирает XSD complexType.
764
+ */
765
+ parseComplexType(name, ctNode) {
766
+ const complexType = {
767
+ name,
768
+ elements: [],
769
+ attributes: [],
770
+ documentation: this.extractDocumentation(ctNode)
771
+ };
772
+ let baseType;
773
+ const findElementsAndAttributes = (node) => {
774
+ if (!node || typeof node !== "object") {
775
+ return;
776
+ }
777
+ for (const key of Object.keys(node)) {
778
+ const cleanKey = this.cleanPrefix(key);
779
+ if (cleanKey === "extension") {
780
+ if (node[key]?.$base) {
781
+ baseType = this.mapXSDTypeToTS(node[key].$base);
782
+ }
783
+ }
784
+ if (["sequence", "choice", "all"].includes(cleanKey)) {
785
+ const groupNode = node[key];
786
+ if (!groupNode || typeof groupNode !== "object") {
787
+ continue;
788
+ }
789
+ for (const groupKey of Object.keys(groupNode)) {
790
+ if (this.cleanPrefix(groupKey) !== "element") {
791
+ continue;
792
+ }
793
+ const elements = Array.isArray(groupNode[groupKey]) ? groupNode[groupKey] : [groupNode[groupKey]];
794
+ for (const element of elements) {
795
+ const fieldName = element.$name || element.$ref;
796
+ if (!fieldName) {
797
+ continue;
798
+ }
799
+ const inlineComplexType = this.getChildNode(element, "complexType");
800
+ const inlineSimpleType = this.getChildNode(element, "simpleType");
801
+ let elementType = element.$type || element.$ref;
802
+ if (inlineComplexType) {
803
+ elementType = `${this.cleanPrefix(fieldName)}Type`;
804
+ this.parseComplexType(elementType, inlineComplexType);
805
+ } else if (inlineSimpleType) {
806
+ elementType = `${this.cleanPrefix(fieldName)}Type`;
807
+ this.parseSimpleType(elementType, inlineSimpleType);
808
+ }
809
+ complexType.elements.push({
810
+ name: this.cleanPrefix(fieldName),
811
+ type: this.mapXSDTypeToTS(elementType || "string"),
812
+ isArray: element.$maxOccurs === "unbounded" || Number(element.$maxOccurs) > 1,
813
+ isOptional: element.$minOccurs === "0" || !element.$minOccurs,
814
+ attributes: this.extractAttributes(element),
815
+ documentation: this.extractDocumentation(element)
816
+ });
817
+ }
818
+ }
819
+ }
820
+ if (cleanKey === "attribute") {
821
+ complexType.attributes.push(
822
+ ...this.extractAttributes({
823
+ [key]: node[key]
824
+ })
825
+ );
826
+ }
827
+ if (cleanKey !== "element" && cleanKey !== "attribute") {
828
+ const nextNodes = Array.isArray(node[key]) ? node[key] : [node[key]];
829
+ for (const nextNode of nextNodes) {
830
+ findElementsAndAttributes(nextNode);
831
+ }
832
+ }
833
+ }
834
+ };
835
+ findElementsAndAttributes(ctNode);
836
+ complexType.base = baseType;
837
+ this.typeRegistry.set(name, complexType);
838
+ }
839
+ /**
840
+ * Извлекает XSD-атрибуты.
841
+ */
842
+ extractAttributes(node) {
843
+ const attributes = [];
844
+ if (!node || typeof node !== "object") {
845
+ return attributes;
846
+ }
847
+ for (const key of Object.keys(node)) {
848
+ if (this.cleanPrefix(key) !== "attribute") {
849
+ continue;
850
+ }
851
+ const attributeNodes = Array.isArray(node[key]) ? node[key] : [node[key]];
852
+ for (const attribute of attributeNodes) {
853
+ if (!attribute?.$name) {
854
+ continue;
855
+ }
856
+ attributes.push({
857
+ name: `$${this.cleanPrefix(attribute.$name)}`,
858
+ type: this.mapXSDTypeToTS(attribute.$type || "string"),
859
+ documentation: this.extractDocumentation(attribute)
860
+ });
861
+ }
862
+ }
863
+ return attributes;
864
+ }
865
+ /**
866
+ * Преобразует XSD-типы в TypeScript-типы.
867
+ */
868
+ mapXSDTypeToTS(xsdType) {
869
+ const type = this.cleanPrefix(xsdType);
870
+ switch (type) {
871
+ case "string":
872
+ case "duration":
873
+ case "Text":
874
+ case "anyURI":
875
+ case "dateTime":
876
+ case "date":
877
+ case "time":
878
+ case "token":
879
+ case "normalizedString":
880
+ case "language":
881
+ case "Name":
882
+ case "NCName":
883
+ case "NMTOKEN":
884
+ case "NMTOKENS":
885
+ case "ID":
886
+ case "IDREF":
887
+ case "IDREFS":
888
+ case "ENTITY":
889
+ case "ENTITIES":
890
+ case "QName":
891
+ case "NOTATION":
892
+ case "base64Binary":
893
+ case "hexBinary":
894
+ return "string";
895
+ case "byte":
896
+ case "int":
897
+ case "integer":
898
+ case "long":
899
+ case "short":
900
+ case "decimal":
901
+ case "float":
902
+ case "double":
903
+ case "nonNegativeInteger":
904
+ case "positiveInteger":
905
+ case "nonPositiveInteger":
906
+ case "negativeInteger":
907
+ case "unsignedByte":
908
+ case "unsignedInt":
909
+ case "unsignedLong":
910
+ case "unsignedShort":
911
+ return "number";
912
+ case "boolean":
913
+ return "boolean";
914
+ case "anyType":
915
+ return "any";
916
+ default:
917
+ return type;
918
+ }
919
+ }
920
+ /**
921
+ * Генерирует интерфейсы для WSDL message с несколькими part.
922
+ */
923
+ compileMessageInterfaces() {
924
+ let code = "";
925
+ for (const message of this.messageRegistry.values()) {
926
+ if (message.parts.length <= 1) {
927
+ continue;
928
+ }
929
+ const interfaceName = this.getMessageInterfaceName(message.name);
930
+ code += `export interface ${interfaceName} {
931
+ `;
932
+ for (const part of message.parts) {
933
+ const type = this.resolveMessagePartType(part);
934
+ code += ` ${JSON.stringify(part.name)}: ${type};
935
+ `;
936
+ }
937
+ code += "}\n\n";
938
+ }
939
+ return code;
940
+ }
941
+ /**
942
+ * Генерирует TypeScript-код.
943
+ */
944
+ compileToTypeScript() {
945
+ let code = "/**\n * \u0422\u0418\u041F\u042B \u0421\u0413\u0415\u041D\u0415\u0420\u0418\u0420\u041E\u0412\u0410\u041D\u042B \u0410\u0412\u0422\u041E\u041C\u0410\u0422\u0418\u0427\u0415\u0421\u041A\u0418 \u041D\u0410 \u041E\u0421\u041D\u041E\u0412\u0415 WSDL/XSD\n * \u041F\u041E\u0414 \u0410\u0420\u0425\u0418\u0422\u0415\u041A\u0422\u0423\u0420\u0423 \u0423\u041C\u041D\u042B\u0425 \u041F\u0420\u0418\u041C\u0418\u0422\u0418\u0412\u041E\u0412\n */\n\n";
946
+ code += "type XMLNamespaces = {[K in `$xmlns${string}`]?: string;};\n\n";
947
+ code += "type XMLLeaf<T extends string | number | boolean | undefined, Attrs = {}> = [keyof Attrs] extends [never] ? T : { $value?: T } & Attrs & XMLNamespaces;\n\n";
948
+ code += "type XMLBranch<Fields, Attrs = {}> = Fields & Attrs & XMLNamespaces;\n";
949
+ code += "type canBeArray<T> = T | T[];\n\n";
950
+ code += this.compileMessageInterfaces();
951
+ if (this.portTypeRegistry.size > 0) {
952
+ code += "export interface WSDLPortTypes {\n";
953
+ for (const portType of this.portTypeRegistry.values()) {
954
+ code += this.formatDocumentation(portType.documentation, " ");
955
+ code += ` ${JSON.stringify(portType.name)}: {
956
+ `;
957
+ for (const operation of portType.operations) {
958
+ code += this.formatDocumentation(operation.documentation, " ");
959
+ code += ` ${JSON.stringify(operation.name)}: {
960
+ `;
961
+ const inputType = this.resolveMessageType(operation.inputMessage);
962
+ const outputType = this.resolveMessageType(operation.outputMessage);
963
+ if (inputType) {
964
+ code += ` input: ${inputType};
965
+ `;
966
+ }
967
+ if (outputType) {
968
+ code += ` output: ${outputType};
969
+ `;
970
+ }
971
+ code += " };\n";
972
+ }
973
+ code += " };\n";
974
+ }
975
+ code += "}\n\n";
976
+ }
977
+ for (const [name, values] of this.simpleTypeRegistry.entries()) {
978
+ const documentation = this.simpleTypeDocumentationRegistry.get(name);
979
+ code += this.formatDocumentation(documentation);
980
+ const enumValues = values.map((value) => JSON.stringify(value)).join(" | ");
981
+ code += `export type ${name} = ${enumValues};
982
+
983
+ `;
984
+ }
985
+ const builtInPrimitives = ["string", "number", "boolean", "any"];
986
+ for (const [name, complexType] of this.typeRegistry.entries()) {
987
+ code += this.formatDocumentation(complexType.documentation);
988
+ const baseType = complexType.base;
989
+ if (baseType && builtInPrimitives.includes(baseType)) {
990
+ const attrsObj = complexType.attributes.length > 0 ? `{ ${complexType.attributes.map((attribute) => `${attribute.name}?: ${attribute.type}`).join("; ")} }` : "{}";
991
+ code += `export type ${name} = XMLLeaf<${baseType}, ${attrsObj}>;
992
+
993
+ `;
994
+ continue;
995
+ }
996
+ const extendsStr = baseType ? ` extends ${baseType}` : "";
997
+ code += `export interface ${name}${extendsStr} {
998
+ `;
999
+ for (const element of complexType.elements) {
1000
+ code += this.formatDocumentation(element.documentation, " ");
1001
+ const optional = element.isOptional ? "?" : "";
1002
+ let type = element.type;
1003
+ const hasAttributes = element.attributes.length > 0;
1004
+ const isPrimitiveLike = builtInPrimitives.includes(type) || this.simpleTypeRegistry.has(type);
1005
+ if (hasAttributes) {
1006
+ const attributesType = `{ ${element.attributes.map((attribute) => `${attribute.name}: ${attribute.type}`).join("; ")} }`;
1007
+ type = isPrimitiveLike ? `XMLLeaf<${type}, ${attributesType}>` : `XMLBranch<${type}, ${attributesType}>`;
1008
+ }
1009
+ const finalType = element.isArray ? `canBeArray<${type}>` : type;
1010
+ code += ` ${element.name}${optional}: ${finalType};
1011
+ `;
1012
+ }
1013
+ for (const attribute of complexType.attributes) {
1014
+ code += this.formatDocumentation(attribute.documentation, " ");
1015
+ code += ` ${attribute.name}?: ${attribute.type};
1016
+ `;
1017
+ }
1018
+ code += " [key: `$xmlns${string}`]: string | undefined;\n";
1019
+ code += "}\n\n";
1020
+ }
1021
+ return code;
1022
+ }
1023
+ };
1024
+
1025
+ // src/lib/xmlBuilder.ts
1026
+ function escapeXMLText(value) {
1027
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1028
+ }
1029
+ function escapeXMLAttribute(value) {
1030
+ return escapeXMLText(value).replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1031
+ }
1032
+ function isXMLNode(value) {
1033
+ return value !== null && typeof value === "object" && value.__isXMLNode === true;
1034
+ }
1035
+ function getXMLValue(value) {
1036
+ return isXMLNode(value) ? value.valueOf() : value;
1037
+ }
1038
+ function isXMLRecord(value) {
1039
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1040
+ }
1041
+ function getXMLAttributes(value) {
1042
+ return Object.entries(value).filter(([key]) => key.startsWith("$") && key !== "$value" && key !== "$namespace" && !key.startsWith("$xmlns")).map(([key, attrValue]) => {
1043
+ const name = key.slice(1);
1044
+ if (!name || !/^[A-Za-z_][\w.:-]*$/.test(name)) {
1045
+ throw new Error(`Invalid XML attribute name: ${name}`);
1046
+ }
1047
+ if (attrValue === null || attrValue === void 0) {
1048
+ return "";
1049
+ }
1050
+ if (typeof attrValue === "object") {
1051
+ throw new Error(`Invalid XML attribute value: ${name}`);
1052
+ }
1053
+ return ` ${name}="${escapeXMLAttribute(String(attrValue))}"`;
1054
+ }).join("");
1055
+ }
1056
+ function serializeXMLElement(tag, value) {
1057
+ if (!/^[A-Za-z_][\w.:-]*$/.test(tag)) {
1058
+ throw new Error(`Invalid XML tag name: ${tag}`);
1059
+ }
1060
+ if (Array.isArray(value)) {
1061
+ return value.map((item) => serializeXMLElement(tag, item)).join("");
1062
+ }
1063
+ const namespace = isXMLRecord(value) ? value.$namespace : void 0;
1064
+ if (namespace !== void 0) {
1065
+ if (typeof namespace !== "string" || !/^[A-Za-z_][\w.-]*$/.test(namespace)) {
1066
+ throw new Error(`Invalid XML namespace prefix: ${namespace}`);
1067
+ }
1068
+ tag = `${namespace}:${tag}`;
1069
+ }
1070
+ let attributes = "";
1071
+ let content = "";
1072
+ if (isXMLNode(value)) {
1073
+ attributes = getXMLAttributes(value);
1074
+ content = escapeXMLText(String(getXMLValue(value) ?? ""));
1075
+ } else if (isXMLRecord(value)) {
1076
+ attributes = getXMLAttributes(value);
1077
+ const children = Object.entries(value).filter(([key]) => !key.startsWith("$"));
1078
+ if (children.length > 0) {
1079
+ content = children.map(([key, childValue]) => serializeXMLElement(key, childValue)).join("");
1080
+ } else if (attributes) {
1081
+ const text = value.$value;
1082
+ content = text == null ? "" : escapeXMLText(String(text));
1083
+ } else if ("$value" in value) {
1084
+ throw new Error(`XML element "${tag}": $value requires at least one attribute`);
1085
+ }
1086
+ } else {
1087
+ content = value == null ? "" : escapeXMLText(String(value));
1088
+ }
1089
+ if (!content) {
1090
+ return `<${tag}${attributes}/>`;
1091
+ }
1092
+ return `<${tag}${attributes}>${content}</${tag}>`;
1093
+ }
1094
+ var XMLBuilder = class {
1095
+ $input;
1096
+ constructor(obj) {
1097
+ this.$input = obj;
1098
+ }
1099
+ toXML(config = {}) {
1100
+ const entries = Object.entries(this.$input);
1101
+ if (entries.length !== 1) {
1102
+ throw new Error("XML must contain exactly one root element");
1103
+ }
1104
+ const [rootTag, rootValue] = entries[0];
1105
+ const xml = serializeXMLElement(rootTag, rootValue);
1106
+ if (config.declaration) {
1107
+ return `<?xml version="1.0" encoding="UTF-8"?>${xml}`;
1108
+ }
1109
+ return xml;
1110
+ }
1111
+ };
1112
+ // Annotate the CommonJS export names for ESM import in node:
1113
+ 0 && (module.exports = {
1114
+ WSDLTypeGenerator,
1115
+ XMLBuilder,
1116
+ XMLParser
1117
+ });