xmljslib 0.0.0-stage → 1.0.0

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