@moccona/apicodegen 0.0.3 → 0.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/npm/index.js DELETED
@@ -1,2367 +0,0 @@
1
- // src/core/base/Adaptor.ts
2
- var Adapter = class {
3
- };
4
-
5
- // src/core/constants/keywords.ts
6
- var typescriptKeywords = /* @__PURE__ */ new Set([
7
- "break",
8
- "case",
9
- "catch",
10
- "class",
11
- "const",
12
- "continue",
13
- "debugger",
14
- "default",
15
- "delete",
16
- "do",
17
- "else",
18
- "enum",
19
- "export",
20
- "extends",
21
- "false",
22
- "finally",
23
- "for",
24
- "function",
25
- "if",
26
- "import",
27
- "in",
28
- "instanceof",
29
- "new",
30
- "null",
31
- "return",
32
- "super",
33
- "switch",
34
- "this",
35
- "throw",
36
- "true",
37
- "try",
38
- "typeof",
39
- "var",
40
- "void",
41
- "while",
42
- "with",
43
- "as",
44
- "implements",
45
- "interface",
46
- "let",
47
- "package",
48
- "private",
49
- "protected",
50
- "public",
51
- "static",
52
- "yield",
53
- "abstract",
54
- "any",
55
- "async",
56
- "await",
57
- "constructor",
58
- "declare",
59
- "from",
60
- "get",
61
- "is",
62
- "module",
63
- "namespace",
64
- "never",
65
- "require",
66
- "set",
67
- "type",
68
- "unknown",
69
- "readonly",
70
- "of",
71
- "asserts",
72
- "infer",
73
- "keyof",
74
- "boolean",
75
- "number",
76
- "string",
77
- "symbol",
78
- "object",
79
- "undefined",
80
- "bigint"
81
- ]);
82
-
83
- // src/core/interface.ts
84
- var SchemaType = /* @__PURE__ */ ((SchemaType2) => {
85
- SchemaType2["schemas"] = "schemas";
86
- SchemaType2["parameters"] = "parameters";
87
- SchemaType2["responses"] = "responses";
88
- SchemaType2["requestBodies"] = "requestBodies";
89
- return SchemaType2;
90
- })(SchemaType || {});
91
- var NonArraySchemaType = /* @__PURE__ */ ((NonArraySchemaType2) => {
92
- NonArraySchemaType2["object"] = "object";
93
- NonArraySchemaType2["string"] = "string";
94
- NonArraySchemaType2["number"] = "number";
95
- NonArraySchemaType2["boolean"] = "boolean";
96
- NonArraySchemaType2["integer"] = "integer";
97
- NonArraySchemaType2["enum"] = "enum";
98
- NonArraySchemaType2["file"] = "file";
99
- return NonArraySchemaType2;
100
- })(NonArraySchemaType || {});
101
- var ArraySchemaType = /* @__PURE__ */ ((ArraySchemaType2) => {
102
- ArraySchemaType2["array"] = "array";
103
- return ArraySchemaType2;
104
- })(ArraySchemaType || {});
105
- var SchemaFormatType = /* @__PURE__ */ ((SchemaFormatType3) => {
106
- SchemaFormatType3["string"] = "string";
107
- SchemaFormatType3["number"] = "number";
108
- SchemaFormatType3["boolean"] = "boolean";
109
- SchemaFormatType3["file"] = "file";
110
- SchemaFormatType3["binary"] = "binary";
111
- SchemaFormatType3["blob"] = "blob";
112
- return SchemaFormatType3;
113
- })(SchemaFormatType || {});
114
- var ParameterIn = /* @__PURE__ */ ((ParameterIn3) => {
115
- ParameterIn3["header"] = "header";
116
- ParameterIn3["body"] = "body";
117
- ParameterIn3["query"] = "query";
118
- ParameterIn3["cookie"] = "cookie";
119
- ParameterIn3["path"] = "path";
120
- ParameterIn3["formData"] = "formData";
121
- return ParameterIn3;
122
- })(ParameterIn || {});
123
- var MediaTypes = /* @__PURE__ */ ((MediaTypes2) => {
124
- MediaTypes2["JSON"] = "application/json";
125
- MediaTypes2["TEXT"] = "text";
126
- MediaTypes2["IMAGE"] = "image";
127
- MediaTypes2["AUDIO"] = "audio";
128
- MediaTypes2["VIDEO"] = "video";
129
- return MediaTypes2;
130
- })(MediaTypes || {});
131
- var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
132
- HttpMethods2["GET"] = "get";
133
- HttpMethods2["PUT"] = "put";
134
- HttpMethods2["POST"] = "post";
135
- HttpMethods2["DELETE"] = "delete";
136
- HttpMethods2["OPTIONS"] = "options";
137
- HttpMethods2["HEAD"] = "head";
138
- HttpMethods2["PATCH"] = "patch";
139
- HttpMethods2["TRACE"] = "trace";
140
- return HttpMethods2;
141
- })(HttpMethods || {});
142
- var Adaptors = /* @__PURE__ */ ((Adaptors2) => {
143
- Adaptors2["fetch"] = "fetch";
144
- Adaptors2["axios"] = "axios";
145
- return Adaptors2;
146
- })(Adaptors || {});
147
-
148
- // src/core/base/Base.ts
149
- import { Agent, request } from "undici";
150
- var SuccessHttpStatusCode = {
151
- "200": "200",
152
- // OK
153
- "201": "201",
154
- // Created
155
- "202": "202",
156
- // Accepted
157
- "203": "203",
158
- // Non-Authoritative Information
159
- "204": "204",
160
- // No Content
161
- "205": "205",
162
- // Reset Content
163
- "206": "206",
164
- // Partial Content
165
- "207": "207",
166
- // Multi_Status
167
- "208": "208",
168
- // Already_Reported
169
- "226": "226"
170
- // IM Used
171
- };
172
- var Base = class _Base {
173
- constructor() {
174
- if (new.target === _Base) {
175
- throw new Error("Cannot instantiate abstract class");
176
- }
177
- }
178
- /**
179
- * Converts a reference string to a meaningful name.
180
- * @param ref - The reference string to process.
181
- * @param [doc] - Optional document reference for context.
182
- * @returns - The processed name.
183
- */
184
- static ref2name(ref, doc) {
185
- const paths = ref.replace(/^#/, "").split("/").filter(Boolean);
186
- if (!doc) {
187
- return paths.slice(-1)[0];
188
- }
189
- let temporary = doc;
190
- let lastPath = "";
191
- for (const path of paths) {
192
- const adjustedPath = path.replaceAll("~1", "/");
193
- temporary = temporary[adjustedPath];
194
- lastPath = adjustedPath;
195
- }
196
- if (!temporary) {
197
- return "unknown";
198
- }
199
- return temporary.$ref ? this.ref2name(temporary.$ref, doc) : lastPath;
200
- }
201
- /**
202
- * Converts an API path to a function name.
203
- * @param path - The API endpoint path.
204
- * @param [method] - The HTTP method (e.g., GET, POST).
205
- * @param [operationId] - Unique identifier for the operation.
206
- * @returns - The generated function name.
207
- */
208
- static pathToFnName(path, method, _operationId = "") {
209
- const name = this.normalize(this.camelCase(this.normalize(path)));
210
- const suffix = method ? this.capitalize(this.upperCamelCase(`using_${method}`)) : "";
211
- return name + suffix;
212
- }
213
- /**
214
- * Normalizes a string by replacing special characters and avoiding TypeScript keywords.
215
- * @param text - Input text to normalize.
216
- * @returns - The normalized string.
217
- */
218
- static normalize(text) {
219
- if (typescriptKeywords.has(text)) {
220
- text += "_";
221
- }
222
- return text.replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d./gm, "").replaceAll("...", "");
223
- }
224
- /**
225
- * Capitalizes the first character of a string.
226
- * @param text - Input string.
227
- * @returns - Capitalized string.
228
- */
229
- static capitalize(text) {
230
- text = text.trim();
231
- return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
232
- }
233
- /**
234
- * Converts a string to camelCase.
235
- * @param text - Input string.
236
- * @returns - CamelCase string.
237
- */
238
- static camelCase(text) {
239
- text = text.trim();
240
- return text.split("_").filter(Boolean).map((t4, index) => index === 0 ? t4 : this.capitalize(t4)).join("");
241
- }
242
- /**
243
- * Converts a string to UpperCamelCase.
244
- * @param text - Input string.
245
- * @returns - UpperCamelCase string.
246
- */
247
- static upperCamelCase(text) {
248
- return this.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(this.capitalize).join("");
249
- }
250
- /**
251
- * Fetches documentation from a given URL.
252
- * @param url - The URL to fetch the documentation from.
253
- * @param requestInit - Additional request parameters.
254
- * @returns - A promise resolving to the fetched documentation data.
255
- */
256
- static async fetchDoc(url, requestInit = {}) {
257
- const agent = new Agent({
258
- connect: { rejectUnauthorized: false }
259
- });
260
- const { body, statusCode } = await request(url, {
261
- method: "GET",
262
- dispatcher: agent,
263
- ...requestInit
264
- });
265
- if (statusCode >= 400) {
266
- throw new Error(
267
- `Failed to fetch OpenAPI documentation from ${url}: HTTP ${statusCode}`
268
- );
269
- }
270
- try {
271
- return body.json();
272
- } catch (error) {
273
- throw new Error(
274
- `Failed to parse JSON response from ${url}: ${error instanceof Error ? error.message : String(error)}`
275
- );
276
- }
277
- }
278
- /**
279
- * Determines the media type from a given media type string.
280
- * @param mediaType - The media type string to evaluate.
281
- * @returns - The matched MediaTypes or null.
282
- */
283
- static getMediaType(mediaType) {
284
- const mediaTypeValues = Object.values(MediaTypes);
285
- const found = mediaTypeValues.find(
286
- (type) => mediaType.includes(type)
287
- );
288
- return found;
289
- }
290
- /**
291
- * Checks if a schema is a valid enum type that isn't boolean.
292
- * @param a - The schema object to evaluate.
293
- * @returns - True if the schema is a valid non-boolean enum.
294
- */
295
- static isValidEnumType(a) {
296
- return a.type !== "boolean" && !this.isBooleanEnum(a);
297
- }
298
- /**
299
- * Checks if a schema represents a boolean enum.
300
- * @param a - The schema object to evaluate.
301
- * @returns - True if the schema is a boolean enum.
302
- */
303
- static isBooleanEnum(a) {
304
- return a.type === "boolean" || !!a.enum?.some(
305
- (member) => typeof member === "boolean"
306
- );
307
- }
308
- /**
309
- * Checks if two enum schemas are identical.
310
- * @param a - First enum schema to compare.
311
- * @param b - Second enum schema to compare.
312
- * @returns - True if the enums are identical.
313
- */
314
- static isSameEnum(a, b) {
315
- return a.enum.length === b.enum.length && a.enum.sort().every((v, index) => v === b.enum.sort()[index]);
316
- }
317
- /**
318
- * Filters out duplicate enum schemas from an array.
319
- * @param enums - Array of enum schemas to process.
320
- * @returns - Array of unique enum schemas.
321
- */
322
- static uniqueEnums(enums) {
323
- const enumMap = /* @__PURE__ */ new Map();
324
- for (const e of enums) {
325
- const existing = enumMap.get(e.name);
326
- if (existing) {
327
- for (const value of e.enum) {
328
- existing.add(value);
329
- }
330
- } else {
331
- enumMap.set(e.name, new Set(e.enum));
332
- }
333
- }
334
- return Array.from(enumMap.entries()).map(([name, values]) => ({
335
- name,
336
- enum: Array.from(values)
337
- }));
338
- }
339
- /**
340
- * Finds the first occurrence of a matching enum schema in an array.
341
- * @param a - The enum schema to find.
342
- * @param enums - Array of enum schemas to search.
343
- * @returns - The found schema or undefined.
344
- */
345
- static findSameSchema(a, enums) {
346
- return enums.find((b) => this.isSameEnum(b, a));
347
- }
348
- /**
349
- * Checks if an object is a reference object.
350
- * @param schema - The object to check.
351
- * @returns - True if the object is a reference.
352
- */
353
- static isRef(schema) {
354
- return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
355
- }
356
- };
357
-
358
- // src/core/base/Provider.ts
359
- var Provider = class {
360
- /** collection of enum schemas */
361
- enums = [];
362
- /** collection of schemas indexed by name */
363
- schemas = {};
364
- /** collection of parameters indexed by name */
365
- parameters = {};
366
- /** collection of API responses indexed by name */
367
- responses = {};
368
- /** collection of request bodies indexed by name */
369
- requestBodies = {};
370
- /** collection of API endpoints (operations) indexed by path */
371
- apis = {};
372
- /** URL for fetching API documentation */
373
- docURL;
374
- /** base URL for API endpoints */
375
- baseURL;
376
- /** output directory for generated code */
377
- output;
378
- /** request options for API documentation fetch */
379
- requestOptions;
380
- /** source path for imported client */
381
- importClientSource;
382
- /**
383
- * Provider Constructor.
384
- * @param {ProviderInitOptions} initOptions - Initial configuration for the provider.
385
- * @param {unknown} doc - Raw API documentation data to be parsed.
386
- */
387
- constructor(initOptions, doc) {
388
- this.docURL = initOptions.docURL;
389
- this.baseURL = initOptions.baseURL ?? "";
390
- this.output = initOptions.output ?? ".";
391
- this.requestOptions = initOptions.requestOptions ?? {};
392
- this.importClientSource = initOptions.importClientSource ?? "";
393
- const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
394
- this.enums = enums;
395
- this.schemas = schemas;
396
- this.responses = responses;
397
- this.parameters = parameters;
398
- this.requestBodies = requestBodies;
399
- this.apis = apis;
400
- }
401
- };
402
-
403
- // src/core/generator/index.ts
404
- import { writeFile } from "fs/promises";
405
- import { format } from "prettier";
406
- import {
407
- addSyntheticLeadingComment,
408
- createPrinter,
409
- factory as t,
410
- NodeFlags,
411
- SyntaxKind
412
- } from "typescript";
413
- var Generator = class _Generator {
414
- /**
415
- * Converts an array of TypeScript statements into a formatted string of code.
416
- *
417
- * @param statements - The array of TypeScript statement nodes.
418
- * @returns Formatted code as a string.
419
- * @throws {Error} If no valid statements are provided.
420
- */
421
- static toCode(statements) {
422
- if (statements.length === 0) {
423
- return "// No api declaration found.";
424
- }
425
- const sourceFile = t.createSourceFile(
426
- statements,
427
- t.createToken(SyntaxKind.EndOfFileToken),
428
- NodeFlags.None
429
- );
430
- return createPrinter().printFile(sourceFile);
431
- }
432
- static async write(code, filepath) {
433
- try {
434
- await writeFile(filepath, code);
435
- } catch (error) {
436
- console.error(error);
437
- }
438
- }
439
- /**
440
- * Converts a path string with parameters into a TypeScript template expression.
441
- * Handles query parameters and path placeholders.
442
- *
443
- * @param path - The base path string containing placeholders.
444
- * @param parameters - Array of parameter objects defining the parameters.
445
- * @param basePath - Optional base path to prepend (default: "").
446
- * @returns A TypeScript template expressi
447
- */
448
- static toUrlTemplate(path, parameters, basePath = "") {
449
- const queryParameters = parameters.filter(
450
- (p) => p.in === "query" /* query */
451
- );
452
- if (queryParameters.length > 0) {
453
- const queryString = queryParameters.map(
454
- (qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.camelCase(Base.normalize(qp.name))}}`
455
- ).join("");
456
- path += queryString;
457
- }
458
- const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
459
- if (pathSegments.length === 1) {
460
- return t.createNoSubstitutionTemplateLiteral(basePath + path);
461
- }
462
- return t.createTemplateExpression(
463
- t.createTemplateHead(basePath + pathSegments[0]),
464
- pathSegments.slice(1).map((segment, index) => {
465
- const match = /^{(.+)}(.+)?/gm.exec(segment);
466
- const isLastSegment = index === pathSegments.length - 2;
467
- if (!match) {
468
- throw new Error(`Invalid path segment: ${segment}`);
469
- }
470
- return t.createTemplateSpan(
471
- t.createIdentifier(match[1]),
472
- !isLastSegment ? t.createTemplateMiddle(match[2]) : t.createTemplateTail(match[2] || "")
473
- );
474
- })
475
- );
476
- }
477
- /**
478
- * Adds synthetic comments to a TypeScript AST node.
479
- *
480
- * @param node - The target AST node.
481
- * @param comments - Array of comment objects to add.
482
- */
483
- static addComments(node, comments) {
484
- if (!Array.isArray(comments) || comments.filter(Boolean).length === 0)
485
- return;
486
- const formatComment = (comment) => {
487
- return comment.tag ? ` @${comment.tag} ${comment.comment ?? ""}` : ` ${comment.comment}`;
488
- };
489
- const formattedComments = "*\n" + comments.map(formatComment).join("\n").trim() + "\n";
490
- addSyntheticLeadingComment(
491
- node,
492
- SyntaxKind.MultiLineCommentTrivia,
493
- formattedComments,
494
- true
495
- );
496
- }
497
- /**
498
- * Checks if a schema represents a binary type.
499
- *
500
- * @param schema - The schema object to check.
501
- * @returns true if the schema is a binary type, false otherwise.
502
- */
503
- static isBinarySchema(schema) {
504
- if (schema.type === "array") {
505
- const arraySchema = schema;
506
- return this.isBinarySchema(arraySchema.items);
507
- }
508
- const nonArraySchema = schema;
509
- return nonArraySchema.format === "blob" /* blob */ || nonArraySchema.format === "binary" /* binary */ || nonArraySchema.type === "file" /* file */;
510
- }
511
- static toRequestBodyTypeNode(schema) {
512
- return t.createParameterDeclaration(
513
- void 0,
514
- void 0,
515
- t.createIdentifier("req"),
516
- void 0,
517
- this.toTypeNode(schema)
518
- );
519
- }
520
- static toTypeNode(schema) {
521
- const { type, ref } = schema;
522
- if (ref) {
523
- const identify = Base.ref2name(ref);
524
- return t.createTypeReferenceNode(
525
- t.createIdentifier(
526
- identify === "unknown" ? identify : Base.upperCamelCase(identify)
527
- )
528
- );
529
- }
530
- switch (type) {
531
- case "array" /* array */:
532
- const { items } = schema;
533
- return t.createArrayTypeNode(this.toTypeNode(items));
534
- case "object" /* object */:
535
- const propsCount = Object.keys(schema.properties ?? {}).length;
536
- if (!schema.properties || propsCount === 0) {
537
- return t.createTypeReferenceNode(t.createIdentifier("Record"), [
538
- t.createToken(SyntaxKind.StringKeyword),
539
- t.createToken(SyntaxKind.UnknownKeyword)
540
- ]);
541
- }
542
- const props = Object.keys(schema.properties);
543
- return t.createTypeLiteralNode(
544
- props.map((propKey) => {
545
- const propSchema = schema.properties[propKey];
546
- return t.createPropertySignature(
547
- void 0,
548
- t.createStringLiteral(propKey),
549
- // When field is required, a refrence or binary value, don't add question mark.
550
- schema.required || schema.ref || this.isBinarySchema(schema) ? void 0 : t.createToken(SyntaxKind.QuestionToken),
551
- this.toTypeNode(propSchema)
552
- );
553
- })
554
- );
555
- case "integer" /* integer */:
556
- case "number" /* number */:
557
- if (schema.enum) {
558
- return t.createUnionTypeNode(
559
- schema.enum.map(
560
- (e) => t.createLiteralTypeNode(t.createNumericLiteral(e))
561
- )
562
- );
563
- }
564
- return t.createToken(SyntaxKind.NumberKeyword);
565
- // case NonArraySchemaType.string:
566
- case "boolean" /* boolean */:
567
- return t.createToken(SyntaxKind.BooleanKeyword);
568
- case "file" /* file */:
569
- return t.createTypeReferenceNode(t.createIdentifier("Blob"));
570
- default:
571
- const {
572
- format: format2,
573
- oneOf,
574
- allOf,
575
- anyOf,
576
- type: type2,
577
- enum: enum_
578
- } = schema;
579
- switch (format2) {
580
- case "number" /* number */:
581
- return t.createToken(SyntaxKind.NumberKeyword);
582
- case "string" /* string */:
583
- return t.createToken(SyntaxKind.StringKeyword);
584
- case "boolean" /* boolean */:
585
- return t.createToken(SyntaxKind.BooleanKeyword);
586
- case "blob" /* blob */:
587
- case "binary" /* binary */:
588
- return t.createTypeReferenceNode(t.createIdentifier("Blob"));
589
- default:
590
- }
591
- if (enum_) {
592
- return t.createUnionTypeNode(
593
- enum_.map(
594
- (e) => t.createLiteralTypeNode(t.createStringLiteral(e))
595
- )
596
- );
597
- }
598
- if (type2 === "string" /* string */) {
599
- return t.createToken(SyntaxKind.StringKeyword);
600
- }
601
- if (oneOf) {
602
- return t.createUnionTypeNode(
603
- oneOf.map((schema2) => this.toTypeNode(schema2))
604
- );
605
- }
606
- if (anyOf) {
607
- return t.createUnionTypeNode(
608
- anyOf.map((schema2) => this.toTypeNode(schema2))
609
- );
610
- }
611
- if (allOf) {
612
- return t.createIntersectionTypeNode(
613
- allOf.map((schema2) => this.toTypeNode(schema2))
614
- );
615
- }
616
- if (type2 && typeof type2 === "string") {
617
- return t.createTypeReferenceNode(
618
- type2 !== "unknown" && type2 !== "null" ? t.createIdentifier(Base.upperCamelCase(type2)) : type2
619
- );
620
- }
621
- }
622
- return t.createToken(SyntaxKind.UnknownKeyword);
623
- }
624
- static toDeclarationNodes(parameters) {
625
- const objectElements = [];
626
- const typeObjectElements = [];
627
- const refParameters = [];
628
- for (const parameter of parameters) {
629
- if (parameter.ref) {
630
- const refName = Base.ref2name(parameter.ref);
631
- refParameters.push(
632
- t.createParameterDeclaration(
633
- void 0,
634
- void 0,
635
- t.createIdentifier(Base.camelCase(Base.normalize(refName))),
636
- void 0,
637
- t.createTypeReferenceNode(
638
- t.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))
639
- ),
640
- void 0
641
- )
642
- );
643
- } else {
644
- const { name, schema, required } = parameter;
645
- objectElements.push(
646
- t.createBindingElement(
647
- void 0,
648
- void 0,
649
- t.createIdentifier(Base.camelCase(Base.normalize(name)))
650
- )
651
- );
652
- typeObjectElements.push(
653
- t.createPropertySignature(
654
- [],
655
- t.createIdentifier(Base.camelCase(Base.normalize(name))),
656
- required ? void 0 : t.createToken(SyntaxKind.QuestionToken),
657
- !schema ? t.createToken(SyntaxKind.UnknownKeyword) : this.toTypeNode(schema)
658
- )
659
- );
660
- }
661
- }
662
- if (objectElements.length > 0) {
663
- const objectParam = t.createParameterDeclaration(
664
- void 0,
665
- void 0,
666
- t.createObjectBindingPattern(objectElements),
667
- void 0,
668
- t.createTypeLiteralNode(typeObjectElements),
669
- void 0
670
- );
671
- return [objectParam, ...refParameters];
672
- }
673
- return refParameters;
674
- }
675
- static toFormDataStatement(parameters, requestBody) {
676
- const statements = [];
677
- const fdDeclaration = t.createVariableStatement(
678
- void 0,
679
- t.createVariableDeclarationList(
680
- [
681
- t.createVariableDeclaration(
682
- t.createIdentifier("fd"),
683
- void 0,
684
- void 0,
685
- t.createNewExpression(
686
- t.createIdentifier("FormData"),
687
- void 0,
688
- []
689
- )
690
- )
691
- ],
692
- NodeFlags.Const
693
- )
694
- );
695
- statements.push(fdDeclaration);
696
- parameters.forEach((parameter) => {
697
- statements.push(
698
- t.createExpressionStatement(
699
- t.createBinaryExpression(
700
- t.createIdentifier(parameter.name),
701
- t.createToken(SyntaxKind.AmpersandAmpersandToken),
702
- t.createCallExpression(
703
- t.createPropertyAccessExpression(
704
- t.createIdentifier("fd"),
705
- t.createIdentifier("append")
706
- ),
707
- void 0,
708
- [
709
- t.createStringLiteral(parameter.name),
710
- t.createIdentifier(parameter.name)
711
- ]
712
- )
713
- )
714
- )
715
- );
716
- });
717
- if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
718
- Object.keys(requestBody.properties).forEach((key) => {
719
- const schemaByKey = requestBody.properties[key];
720
- if (schemaByKey.type === "array" /* array */ && this.isBinarySchema(schemaByKey)) {
721
- statements.push(
722
- t.createForOfStatement(
723
- void 0,
724
- t.createVariableDeclarationList(
725
- [t.createVariableDeclaration("file")],
726
- NodeFlags.Const
727
- ),
728
- t.createElementAccessExpression(
729
- t.createIdentifier("req"),
730
- t.createStringLiteral(key)
731
- ),
732
- t.createBlock([
733
- t.createExpressionStatement(
734
- t.createCallExpression(
735
- t.createPropertyAccessExpression(
736
- t.createIdentifier("fd"),
737
- t.createIdentifier("append")
738
- ),
739
- [],
740
- [
741
- t.createStringLiteral(key),
742
- t.createIdentifier("file"),
743
- t.createPropertyAccessExpression(
744
- t.createAsExpression(
745
- t.createIdentifier("file"),
746
- t.createTypeReferenceNode(
747
- t.createIdentifier("File"),
748
- void 0
749
- )
750
- ),
751
- t.createIdentifier("name")
752
- )
753
- ]
754
- )
755
- )
756
- ])
757
- )
758
- );
759
- } else {
760
- if (schemaByKey.required) {
761
- statements.push(
762
- t.createExpressionStatement(
763
- t.createCallExpression(
764
- t.createPropertyAccessExpression(
765
- t.createIdentifier("fd"),
766
- t.createIdentifier("append")
767
- ),
768
- void 0,
769
- [
770
- t.createStringLiteral(key),
771
- schemaByKey.type === "string" ? t.createElementAccessExpression(
772
- t.createIdentifier("req"),
773
- t.createStringLiteral(key)
774
- ) : t.createCallExpression(
775
- t.createIdentifier("String"),
776
- void 0,
777
- [
778
- t.createElementAccessExpression(
779
- t.createIdentifier("req"),
780
- t.createStringLiteral(key)
781
- )
782
- ]
783
- )
784
- ]
785
- )
786
- )
787
- );
788
- } else {
789
- statements.push(
790
- t.createExpressionStatement(
791
- t.createBinaryExpression(
792
- t.createElementAccessExpression(
793
- t.createIdentifier("req"),
794
- t.createStringLiteral(key)
795
- ),
796
- t.createToken(SyntaxKind.AmpersandAmpersandToken),
797
- t.createCallExpression(
798
- t.createPropertyAccessExpression(
799
- t.createIdentifier("fd"),
800
- t.createIdentifier("append")
801
- ),
802
- void 0,
803
- [
804
- t.createStringLiteral(key),
805
- schemaByKey.type === "string" ? t.createElementAccessExpression(
806
- t.createIdentifier("req"),
807
- t.createStringLiteral(key)
808
- ) : t.createCallExpression(
809
- t.createIdentifier("String"),
810
- void 0,
811
- [
812
- t.createElementAccessExpression(
813
- t.createIdentifier("req"),
814
- t.createStringLiteral(key)
815
- )
816
- ]
817
- )
818
- ]
819
- )
820
- )
821
- )
822
- );
823
- }
824
- }
825
- });
826
- }
827
- return statements;
828
- }
829
- static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
830
- const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(
831
- requestBody.type
832
- );
833
- const shouldParseResponseToJSON = "application/json" === response?.type;
834
- const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" /* array */ && this.isBinarySchema(requestBody.schema);
835
- const parametersShouldPutInFormData = parameters.filter(
836
- (p) => p.in === "formData" /* formData */ || p.schema && this.isBinarySchema(p.schema)
837
- );
838
- const parametersShouldNotPutInFormData = parameters.filter(
839
- (p) => !parametersShouldPutInFormData.includes(p)
840
- );
841
- const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some(
842
- (p) => this.isBinarySchema(p)
843
- );
844
- const hasBinaryInParameters = parameters.some(
845
- (p) => p?.schema && this.isBinarySchema(p.schema)
846
- );
847
- const shouldPutParametersOrBodyInFormData = isFormDataRequest || isRequestBodyBinary || hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0;
848
- return t.createBlock([
849
- ...shouldPutParametersOrBodyInFormData ? this.toFormDataStatement(
850
- parametersShouldPutInFormData,
851
- requestBody?.schema
852
- ) : [],
853
- ...adapter.client(
854
- uri,
855
- method,
856
- parametersShouldNotPutInFormData,
857
- requestBody,
858
- response,
859
- adapter,
860
- shouldPutParametersOrBodyInFormData,
861
- shouldParseResponseToJSON
862
- )
863
- ]);
864
- }
865
- static schemaToStatemets(parsedDoc, adaptor, options) {
866
- const statements = [];
867
- const { apis, schemas = {}, enums } = parsedDoc;
868
- const enumNames = [];
869
- for (const enumObject of enums) {
870
- enumNames.push(Base.capitalize(enumObject.name));
871
- statements.push(
872
- t.createEnumDeclaration(
873
- [t.createToken(SyntaxKind.ExportKeyword)],
874
- t.createIdentifier(Base.upperCamelCase(enumObject.name)),
875
- enumObject.enum.map((member) => {
876
- return t.createEnumMember(
877
- t.createStringLiteral(
878
- typeof member === "string" ? member : `${member}_`
879
- ),
880
- typeof member === "string" ? t.createStringLiteral(member) : t.createNumericLiteral(member)
881
- );
882
- })
883
- )
884
- );
885
- }
886
- for (const schemaKey in schemas) {
887
- if (Object.hasOwnProperty.call(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
888
- const schema = schemas[schemaKey];
889
- statements.push(
890
- t.createTypeAliasDeclaration(
891
- [t.createModifier(SyntaxKind.ExportKeyword)],
892
- t.createIdentifier(Base.upperCamelCase(schemaKey)),
893
- void 0,
894
- this.toTypeNode(schema)
895
- )
896
- );
897
- }
898
- }
899
- for (const uri in apis) {
900
- const operations = apis[uri];
901
- for (const operation of operations) {
902
- const {
903
- method,
904
- operationId,
905
- requestBody = [],
906
- responses = [],
907
- summary,
908
- deprecated,
909
- description
910
- } = operation;
911
- let { parameters = [] } = operation;
912
- parameters = parameters.filter((p) => p.in !== "cookie");
913
- if (requestBody.length === 0) {
914
- requestBody.push({ type: "application/json" /* JSON */ });
915
- }
916
- const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
917
- for (const req of requestBody) {
918
- const statement = t.createFunctionDeclaration(
919
- [
920
- t.createModifier(SyntaxKind.ExportKeyword),
921
- t.createModifier(SyntaxKind.AsyncKeyword)
922
- ],
923
- void 0,
924
- Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.capitalize(req.type.split("/")[1]) : ""),
925
- void 0,
926
- [
927
- ...parameters.length > 0 ? _Generator.toDeclarationNodes(parameters) : [],
928
- ...req?.schema ? [_Generator.toRequestBodyTypeNode(req.schema)] : []
929
- ].filter(Boolean),
930
- void 0,
931
- this.bodyBlock(
932
- options.baseURL + uri,
933
- method,
934
- parameters,
935
- req,
936
- responses[0],
937
- adaptor
938
- )
939
- );
940
- this.addComments(
941
- statement,
942
- [
943
- description && {
944
- comment: description
945
- },
946
- summary && {
947
- comment: summary
948
- },
949
- deprecated && {
950
- tag: "deprecated"
951
- }
952
- ].filter(Boolean)
953
- );
954
- statements.push(statement);
955
- }
956
- }
957
- }
958
- return statements;
959
- }
960
- static async prettier(code) {
961
- return await format(code, {
962
- parser: "typescript"
963
- });
964
- }
965
- static async genCode(schema, initOptions, adaptor) {
966
- const { importClientSource } = initOptions;
967
- const statements = this.schemaToStatemets(schema, adaptor, {
968
- baseURL: initOptions.baseURL ?? ""
969
- });
970
- let code = this.toCode(statements);
971
- if (importClientSource) {
972
- code = importClientSource + "\n\n" + code;
973
- }
974
- return await this.prettier(code);
975
- }
976
- };
977
-
978
- // src/core/client/axios.ts
979
- import { factory as t2 } from "typescript";
980
- var AxiosAdapter = class extends Adapter {
981
- /**
982
- * Name of the field used to specify the HTTP method in the request configuration.
983
- */
984
- methodFieldName = "method";
985
- /**
986
- * Name of the field used to specify the request body (data) in the request configuration.
987
- */
988
- bodyFieldName = "data";
989
- /**
990
- * Name of the field used to specify the request headers in the request configuration.
991
- */
992
- headersFieldName = "headers";
993
- /**
994
- * Name of the field used to specify the query parameters in the request configuration.
995
- */
996
- queryFieldName = "params";
997
- /**
998
- * The name of the client this adapter is configured for, which is 'axios' in this case.
999
- */
1000
- name = "axios";
1001
- /**
1002
- * Method that should generate and return the client-specific configuration statements.
1003
- *
1004
- * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
1005
- *
1006
- * @throws {Error} Indicates that the method is not yet implemented and needs to be filled in.
1007
- */
1008
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData) {
1009
- const statements = [];
1010
- const inBody = parameters.filter((p) => !p.in || p.in === "body");
1011
- const inHeader = parameters.filter((p) => p.in === "header");
1012
- const toLiterlExpression = () => {
1013
- return t2.createObjectLiteralExpression(
1014
- [
1015
- // Set the HTTP method
1016
- t2.createPropertyAssignment(
1017
- t2.createIdentifier(adapter.methodFieldName),
1018
- t2.createStringLiteral(method.toUpperCase())
1019
- )
1020
- ].concat(
1021
- // Add headers if there are any
1022
- inHeader.length > 0 ? t2.createPropertyAssignment(
1023
- t2.createIdentifier(adapter.headersFieldName),
1024
- t2.createObjectLiteralExpression(
1025
- inHeader.map(
1026
- (p) => t2.createPropertyAssignment(
1027
- t2.createStringLiteral(p.name),
1028
- t2.createCallExpression(
1029
- t2.createIdentifier("encodeURIComponent"),
1030
- void 0,
1031
- [
1032
- t2.createCallExpression(
1033
- t2.createIdentifier("String"),
1034
- void 0,
1035
- [
1036
- t2.createIdentifier(
1037
- Base.camelCase(Base.normalize(p.name))
1038
- )
1039
- ]
1040
- )
1041
- ]
1042
- )
1043
- )
1044
- )
1045
- )
1046
- ) : []
1047
- ).concat(
1048
- shouldUseFormData || inBody.length > 0 || requestBody?.schema ? t2.createPropertyAssignment(
1049
- t2.createIdentifier(adapter.bodyFieldName),
1050
- shouldUseFormData ? t2.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? t2.createIdentifier("req") : t2.createIdentifier("req")
1051
- ) : []
1052
- ),
1053
- true
1054
- );
1055
- };
1056
- statements.push(
1057
- t2.createReturnStatement(
1058
- t2.createCallExpression(
1059
- t2.createIdentifier(adapter.name),
1060
- response?.schema ? [
1061
- Generator.toTypeNode(
1062
- response.schema
1063
- )
1064
- ] : void 0,
1065
- [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]
1066
- )
1067
- )
1068
- );
1069
- return statements;
1070
- }
1071
- };
1072
-
1073
- // src/core/client/fetch.ts
1074
- import { factory as t3, SyntaxKind as SyntaxKind2 } from "typescript";
1075
- var FetchAdapter = class extends Adapter {
1076
- methodFieldName = "method";
1077
- bodyFieldName = "body";
1078
- headersFieldName = "headers";
1079
- queryFieldName = "";
1080
- name = "fetch";
1081
- /**
1082
- * Generates client code for making API requests using the Fetch API.
1083
- * @param uri - The API endpoint URI
1084
- * @param method - The HTTP method (GET, POST, etc.)
1085
- * @param parameters - Array of parameters to include in the request
1086
- * @param requestBody - The request body media type definition
1087
- * @param response - The response media type definition
1088
- * @param adapter - The adapter instance
1089
- * @param shouldUseFormData - Flag to use FormData for the request body
1090
- * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
1091
- * @return - An array of generated TypeScript statements
1092
- */
1093
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse) {
1094
- const statements = [];
1095
- const inBody = parameters.filter((p) => !p.in || p.in === "body");
1096
- const inHeader = parameters.filter((p) => p.in === "header");
1097
- const toLiterlExpression = () => {
1098
- return t3.createObjectLiteralExpression(
1099
- [
1100
- // Set the HTTP method
1101
- t3.createPropertyAssignment(
1102
- t3.createIdentifier(adapter.methodFieldName),
1103
- t3.createStringLiteral(method.toUpperCase())
1104
- )
1105
- ].concat(
1106
- // Add headers if there are any
1107
- inHeader.length > 0 ? t3.createPropertyAssignment(
1108
- t3.createIdentifier(adapter.headersFieldName),
1109
- t3.createObjectLiteralExpression(
1110
- inHeader.map(
1111
- (p) => t3.createPropertyAssignment(
1112
- t3.createStringLiteral(p.name),
1113
- t3.createCallExpression(
1114
- t3.createIdentifier("encodeURIComponent"),
1115
- void 0,
1116
- [
1117
- t3.createCallExpression(
1118
- t3.createIdentifier("String"),
1119
- void 0,
1120
- [
1121
- t3.createIdentifier(
1122
- Base.camelCase(Base.normalize(p.name))
1123
- )
1124
- ]
1125
- )
1126
- ]
1127
- )
1128
- )
1129
- )
1130
- )
1131
- ) : []
1132
- ).concat(
1133
- shouldUseFormData || inBody.length > 0 || requestBody?.schema ? t3.createPropertyAssignment(
1134
- t3.createIdentifier(adapter.bodyFieldName),
1135
- shouldUseFormData ? t3.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? t3.createCallExpression(
1136
- t3.createPropertyAccessExpression(
1137
- t3.createIdentifier("JSON"),
1138
- t3.createIdentifier("stringify")
1139
- ),
1140
- [],
1141
- [
1142
- requestBody ? t3.createIdentifier("req") : t3.createObjectLiteralExpression(
1143
- inBody.map(
1144
- (b) => t3.createShorthandPropertyAssignment(
1145
- t3.createIdentifier(b.name)
1146
- )
1147
- ),
1148
- true
1149
- )
1150
- ]
1151
- ) : (
1152
- // One File parameter
1153
- t3.createIdentifier("req")
1154
- )
1155
- ) : []
1156
- ),
1157
- true
1158
- );
1159
- };
1160
- statements.push(
1161
- t3.createReturnStatement(
1162
- shouldUseJSONResponse ? (
1163
- // Handle JSON response with proper type checking
1164
- t3.createCallExpression(
1165
- t3.createPropertyAccessExpression(
1166
- t3.createCallExpression(
1167
- t3.createIdentifier(adapter.name),
1168
- void 0,
1169
- [
1170
- Generator.toUrlTemplate(uri, parameters),
1171
- toLiterlExpression()
1172
- ]
1173
- ),
1174
- t3.createIdentifier("then")
1175
- ),
1176
- void 0,
1177
- [
1178
- t3.createArrowFunction(
1179
- [t3.createModifier(SyntaxKind2.AsyncKeyword)],
1180
- [],
1181
- [
1182
- t3.createParameterDeclaration(
1183
- void 0,
1184
- void 0,
1185
- t3.createIdentifier("response")
1186
- )
1187
- ],
1188
- void 0,
1189
- t3.createToken(SyntaxKind2.EqualsGreaterThanToken),
1190
- response?.schema ? t3.createAsExpression(
1191
- t3.createParenthesizedExpression(
1192
- t3.createAwaitExpression(
1193
- t3.createCallExpression(
1194
- t3.createPropertyAccessExpression(
1195
- t3.createIdentifier("response"),
1196
- t3.createIdentifier("json")
1197
- ),
1198
- void 0,
1199
- []
1200
- )
1201
- )
1202
- ),
1203
- response?.schema ? Generator.toTypeNode(response.schema) : t3.createToken(SyntaxKind2.UnknownKeyword)
1204
- ) : t3.createParenthesizedExpression(
1205
- t3.createAwaitExpression(
1206
- t3.createCallExpression(
1207
- t3.createPropertyAccessExpression(
1208
- t3.createIdentifier("response"),
1209
- t3.createIdentifier("json")
1210
- ),
1211
- void 0,
1212
- []
1213
- )
1214
- )
1215
- )
1216
- )
1217
- ]
1218
- )
1219
- ) : (
1220
- // Simple fetch call without JSON parsing
1221
- t3.createCallExpression(
1222
- t3.createIdentifier(adapter.name),
1223
- void 0,
1224
- [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]
1225
- )
1226
- )
1227
- )
1228
- );
1229
- return statements;
1230
- }
1231
- };
1232
-
1233
- // src/openapi/index.ts
1234
- import { createScopedLogger } from "@moccona/logger";
1235
-
1236
- // src/openapi/V2.ts
1237
- var V2 = class {
1238
- doc;
1239
- constructor(doc) {
1240
- this.doc = doc;
1241
- }
1242
- /**
1243
- * Is array schema.
1244
- */
1245
- isOpenAPIArraySchema(schema) {
1246
- return typeof schema === "object" && schema.type === "array";
1247
- }
1248
- /**
1249
- * OpenAPI schema to base schema.
1250
- */
1251
- getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1252
- let refName = "";
1253
- if (Base.isRef(schema)) {
1254
- refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1255
- if (reserveRef) {
1256
- return {
1257
- type: upLevelSchemaKey + refName
1258
- };
1259
- }
1260
- if (!this.doc.definitions) {
1261
- this.doc.definitions = {};
1262
- }
1263
- schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
1264
- }
1265
- return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1266
- }
1267
- /**
1268
- * Transform all OpenAPI schema to Base Schema
1269
- */
1270
- toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1271
- if (!schema) {
1272
- return {
1273
- type: "unknown"
1274
- };
1275
- }
1276
- if (Base.isRef(schema)) {
1277
- return this.getSchemaByRef(schema, true);
1278
- }
1279
- if (this.isOpenAPIArraySchema(schema)) {
1280
- const { type, description, items, required } = schema;
1281
- return {
1282
- type,
1283
- required: !!required,
1284
- description,
1285
- items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1286
- };
1287
- } else {
1288
- const {
1289
- required = [],
1290
- allOf,
1291
- anyOf,
1292
- description,
1293
- enum: enum_,
1294
- format: format2,
1295
- oneOf,
1296
- properties = {}
1297
- } = schema;
1298
- let { type } = schema;
1299
- if (enum_ && type !== "boolean") {
1300
- const name = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(schemaKey);
1301
- const enumObject = {
1302
- name,
1303
- enum: [...new Set(enum_)]
1304
- };
1305
- const sameObject = Base.findSameSchema(enumObject, enums);
1306
- if (!sameObject && Base.isValidEnumType(schema)) {
1307
- enums.push(enumObject);
1308
- }
1309
- return {
1310
- type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1311
- required,
1312
- description
1313
- };
1314
- }
1315
- if (type === void 0 && Object.keys(properties).length > 0) {
1316
- type = "object" /* object */;
1317
- }
1318
- return {
1319
- type,
1320
- required,
1321
- description,
1322
- enum: enum_,
1323
- format: format2,
1324
- allOf: allOf?.map(
1325
- (s) => Base.isRef(s) ? {
1326
- ...s,
1327
- ref: s.$ref,
1328
- type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc))
1329
- } : this.toBaseSchema(s, enums)
1330
- ),
1331
- anyOf: anyOf?.map(
1332
- (s) => Base.isRef(s) ? {
1333
- ...s,
1334
- ref: s.$ref,
1335
- type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc))
1336
- } : this.toBaseSchema(s, enums)
1337
- ),
1338
- oneOf: oneOf?.map(
1339
- (s) => Base.isRef(s) ? {
1340
- ...s,
1341
- ref: s.$ref,
1342
- type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc))
1343
- } : this.toBaseSchema(s, enums)
1344
- ),
1345
- properties: Object.keys(properties).reduce((acc, p) => {
1346
- const propSchema = properties[p];
1347
- return {
1348
- ...acc,
1349
- [p]: Base.isRef(propSchema) ? {
1350
- type: Base.upperCamelCase(
1351
- Base.ref2name(propSchema.$ref, this.doc)
1352
- )
1353
- } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1354
- };
1355
- }, {})
1356
- };
1357
- }
1358
- }
1359
- /**
1360
- * OpenAPI parameter to base parameter.
1361
- */
1362
- getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
1363
- if (Base.isRef(parameter)) {
1364
- parameter = this.doc.parameters[Base.ref2name(parameter.$ref, this.doc)];
1365
- }
1366
- const {
1367
- name,
1368
- required,
1369
- description,
1370
- type,
1371
- items,
1372
- enum: enum_,
1373
- properties,
1374
- schema
1375
- } = parameter;
1376
- if (enum_) {
1377
- const type2 = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(name);
1378
- const enumSchema = {
1379
- name: type2,
1380
- enum: [...new Set(enum_)]
1381
- };
1382
- const sameEnum = Base.findSameSchema(enumSchema, enums);
1383
- if (!sameEnum && Base.isValidEnumType({ type: type2, enum: enums })) {
1384
- enums.push(enumSchema);
1385
- }
1386
- return {
1387
- name,
1388
- required,
1389
- description,
1390
- in: parameter.in,
1391
- schema: {
1392
- type: sameEnum?.name ?? type2
1393
- }
1394
- };
1395
- }
1396
- if (items) {
1397
- return {
1398
- name,
1399
- required,
1400
- description,
1401
- in: parameter.in,
1402
- schema: {
1403
- type,
1404
- items
1405
- }
1406
- };
1407
- }
1408
- if (schema && Base.isRef(schema)) {
1409
- return {
1410
- name,
1411
- required,
1412
- description,
1413
- in: parameter.in,
1414
- schema: {
1415
- type: Base.upperCamelCase(Base.ref2name(schema.$ref))
1416
- }
1417
- };
1418
- }
1419
- return {
1420
- name,
1421
- required,
1422
- description,
1423
- in: parameter.in,
1424
- schema: {
1425
- type,
1426
- properties
1427
- }
1428
- };
1429
- }
1430
- /**
1431
- * OpenAPI schema to base response
1432
- */
1433
- getResponseByRef(schema) {
1434
- if (Base.isRef(schema)) {
1435
- schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1436
- }
1437
- const { schema: responseSchema } = schema;
1438
- return [
1439
- {
1440
- type: "application/json" /* JSON */,
1441
- schema: responseSchema && this.getSchemaByRef(responseSchema, true)
1442
- }
1443
- ];
1444
- }
1445
- init() {
1446
- const { definitions = {}, responses = {}, paths = {} } = this.doc;
1447
- const enums = [];
1448
- const definitions_ = Object.keys(definitions).reduce((acc, key) => {
1449
- const schema = definitions[key];
1450
- return {
1451
- ...acc,
1452
- [key]: this.getSchemaByRef(schema, false, enums, key)
1453
- };
1454
- }, {});
1455
- const responses_ = Object.keys(responses).reduce((acc, key) => {
1456
- const response = responses[key];
1457
- return {
1458
- ...acc,
1459
- [key]: this.getResponseByRef(response)
1460
- };
1461
- }, {});
1462
- const apis = Object.keys(paths).reduce((acc, path) => {
1463
- const pathObject = paths[path] ?? {};
1464
- const { $ref } = pathObject;
1465
- const methodApis = [];
1466
- if ($ref) {
1467
- } else {
1468
- const { parameters = [] } = pathObject;
1469
- Object.values(HttpMethods).forEach((method) => {
1470
- const methodObject = pathObject[method];
1471
- if (methodObject) {
1472
- const {
1473
- deprecated,
1474
- operationId,
1475
- summary: summary_,
1476
- description: description_,
1477
- responses: responses2 = {}
1478
- } = methodObject;
1479
- const { parameters: parameters_ = [] } = methodObject;
1480
- const baseParameters = [...parameters, ...parameters_].map(
1481
- (parameter) => this.getParameterByRef(parameter, enums)
1482
- );
1483
- const uniqueParameterName = [
1484
- ...new Set(baseParameters.map((p) => p.name))
1485
- ];
1486
- if (Object.keys(responses2).length === 0) {
1487
- Object.assign(responses2, {
1488
- 200: {
1489
- description: "Successful response"
1490
- }
1491
- });
1492
- }
1493
- const inBody = baseParameters.filter(
1494
- (p) => p.in === "body" || p.in === "formData"
1495
- );
1496
- const notInBody = baseParameters.filter(
1497
- (p) => p.in !== "body" && p.in !== "formData"
1498
- );
1499
- const httpCodes = Object.keys(responses2);
1500
- for (const code of httpCodes) {
1501
- if (code in responses2) {
1502
- const response = responses2[code];
1503
- const responseSchema = this.getResponseByRef(response);
1504
- const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
1505
- methodApis.push({
1506
- method,
1507
- operationId,
1508
- summary: summary_,
1509
- deprecated,
1510
- description: description_,
1511
- parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
1512
- responses: responseSchema,
1513
- requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [
1514
- {
1515
- type: "application/json" /* JSON */,
1516
- schema: inBody[0].schema
1517
- }
1518
- ] : [
1519
- {
1520
- type: "application/json" /* JSON */,
1521
- schema: {
1522
- type: "object" /* object */,
1523
- properties: inBody.reduce((a, p) => {
1524
- return {
1525
- ...a,
1526
- [p.name]: {
1527
- type: p.schema?.type ?? "unknown",
1528
- required: p.schema?.required,
1529
- // @ts-expect-error items can be undefined
1530
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1531
- items: p.schema?.items,
1532
- description: p.schema?.description
1533
- }
1534
- };
1535
- }, {})
1536
- }
1537
- }
1538
- ] : void 0
1539
- });
1540
- break;
1541
- }
1542
- }
1543
- }
1544
- });
1545
- }
1546
- return {
1547
- ...acc,
1548
- [path]: methodApis
1549
- };
1550
- }, {});
1551
- return {
1552
- enums: Base.uniqueEnums(enums),
1553
- schemas: definitions_,
1554
- responses: responses_,
1555
- parameters: {},
1556
- requestBodies: {},
1557
- apis
1558
- };
1559
- }
1560
- };
1561
-
1562
- // src/openapi/V3.ts
1563
- var V3 = class {
1564
- doc;
1565
- constructor(doc) {
1566
- this.doc = doc;
1567
- }
1568
- /**
1569
- * Is array schema.
1570
- */
1571
- isOpenAPIArraySchema(schema) {
1572
- return typeof schema === "object" && schema.type === "array";
1573
- }
1574
- /**
1575
- * OpenAPI schema to base schema.
1576
- */
1577
- getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1578
- let refName = "";
1579
- if (Base.isRef(schema)) {
1580
- refName = Base.capitalize(Base.ref2name(schema.$ref));
1581
- if (reserveRef) {
1582
- return {
1583
- type: upLevelSchemaKey + refName
1584
- };
1585
- }
1586
- const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1587
- if (!resolvedSchema) {
1588
- return { type: "unknown" };
1589
- }
1590
- schema = resolvedSchema;
1591
- }
1592
- return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1593
- }
1594
- /**
1595
- * OpenAPI parameter to base parameter.
1596
- */
1597
- getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1598
- if (Base.isRef(schema)) {
1599
- const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1600
- if (!resolvedSchema) {
1601
- return {
1602
- name: "unknown",
1603
- in: "query"
1604
- };
1605
- }
1606
- schema = resolvedSchema;
1607
- }
1608
- const {
1609
- name,
1610
- required,
1611
- deprecated,
1612
- description,
1613
- schema: parameterSchema
1614
- } = schema;
1615
- if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1616
- const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1617
- const enumSchema = {
1618
- name: type,
1619
- enum: [...new Set(parameterSchema.enum)]
1620
- };
1621
- const sameEnum = Base.findSameSchema(enumSchema, enums);
1622
- if (!sameEnum && Base.isValidEnumType(parameterSchema)) {
1623
- enums.push(enumSchema);
1624
- }
1625
- return {
1626
- name,
1627
- required,
1628
- description,
1629
- deprecated,
1630
- in: schema.in,
1631
- schema: {
1632
- type: sameEnum?.name ?? type
1633
- }
1634
- };
1635
- }
1636
- return {
1637
- name,
1638
- required,
1639
- description,
1640
- deprecated,
1641
- in: schema.in,
1642
- schema: schema.schema && this.getSchemaByRef(
1643
- schema.schema,
1644
- false,
1645
- enums,
1646
- upLevelSchemaKey + Base.capitalize(name)
1647
- )
1648
- };
1649
- }
1650
- /**
1651
- * OpenAPI schema to base response
1652
- */
1653
- getResponseByRef(schema) {
1654
- if (Base.isRef(schema)) {
1655
- const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1656
- if (!resolvedSchema) {
1657
- return [];
1658
- }
1659
- schema = resolvedSchema;
1660
- }
1661
- const { content = {} } = schema;
1662
- return Object.keys(content).map((c) => ({
1663
- type: c,
1664
- schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1665
- }));
1666
- }
1667
- /**
1668
- * OpenAPI schema to requestBody.
1669
- */
1670
- getRequestBodyByRef(schema, enums = []) {
1671
- if (Base.isRef(schema)) {
1672
- const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1673
- if (!resolvedSchema) {
1674
- return [];
1675
- }
1676
- schema = resolvedSchema;
1677
- }
1678
- const { content = {} } = schema;
1679
- return Object.keys(content).map((c) => ({
1680
- type: c,
1681
- schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
1682
- }));
1683
- }
1684
- /**
1685
- * Transform all OpenAPI schema to Base Schema
1686
- */
1687
- toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1688
- if (!schema) {
1689
- return {
1690
- type: "unknown"
1691
- };
1692
- }
1693
- if (Base.isRef(schema)) {
1694
- return this.getSchemaByRef(schema, true);
1695
- }
1696
- if (this.isOpenAPIArraySchema(schema)) {
1697
- const { type, description, items, required } = schema;
1698
- return {
1699
- type,
1700
- required: !!required,
1701
- description,
1702
- items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1703
- };
1704
- } else {
1705
- const {
1706
- required = [],
1707
- allOf,
1708
- anyOf,
1709
- description,
1710
- deprecated,
1711
- enum: enum_,
1712
- format: format2,
1713
- oneOf,
1714
- properties = {}
1715
- } = schema;
1716
- let { type } = schema;
1717
- if (enum_ && type !== "boolean") {
1718
- const name = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey));
1719
- const enumObject = {
1720
- name,
1721
- enum: [...new Set(enum_)]
1722
- };
1723
- const sameObject = Base.findSameSchema(enumObject, enums);
1724
- if (!sameObject && Base.isValidEnumType(schema)) {
1725
- enums.push(enumObject);
1726
- }
1727
- return {
1728
- type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1729
- required,
1730
- description,
1731
- deprecated
1732
- };
1733
- }
1734
- if (type === void 0 && Object.keys(properties).length > 0) {
1735
- type = "object" /* object */;
1736
- }
1737
- return {
1738
- type,
1739
- required,
1740
- description,
1741
- deprecated,
1742
- enum: enum_,
1743
- format: format2,
1744
- allOf: allOf?.map(
1745
- (s) => Base.isRef(s) ? {
1746
- ...s,
1747
- ref: s.$ref,
1748
- type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1749
- } : this.toBaseSchema(s, enums)
1750
- ),
1751
- anyOf: anyOf?.map(
1752
- (s) => Base.isRef(s) ? {
1753
- ...s,
1754
- ref: s.$ref,
1755
- type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1756
- } : this.toBaseSchema(s, enums)
1757
- ),
1758
- oneOf: oneOf?.map(
1759
- (s) => Base.isRef(s) ? {
1760
- ...s,
1761
- ref: s.$ref,
1762
- type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1763
- } : this.toBaseSchema(s, enums)
1764
- ),
1765
- properties: Object.keys(properties).reduce((acc, p) => {
1766
- const propSchema = properties[p];
1767
- return {
1768
- ...acc,
1769
- [p]: Base.isRef(propSchema) ? {
1770
- type: Base.capitalize(
1771
- Base.ref2name(propSchema.$ref, this.doc)
1772
- )
1773
- } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1774
- };
1775
- }, {})
1776
- };
1777
- }
1778
- }
1779
- init() {
1780
- const { components = {}, paths = {} } = this.doc;
1781
- const enums = [];
1782
- const {
1783
- requestBodies = {},
1784
- responses = {},
1785
- parameters = {},
1786
- schemas = {}
1787
- } = components;
1788
- const schemas_ = Object.keys(schemas).reduce((acc, key) => {
1789
- const schema = schemas[key];
1790
- return {
1791
- ...acc,
1792
- [key]: this.getSchemaByRef(schema, false, enums, key)
1793
- };
1794
- }, {});
1795
- const parameters_ = Object.keys(parameters).reduce((acc, key) => {
1796
- const parameter = parameters[key];
1797
- return {
1798
- ...acc,
1799
- [key]: this.getParameterByRef(parameter, enums, key)
1800
- };
1801
- }, {});
1802
- const responses_ = Object.keys(responses).reduce((acc, key) => {
1803
- const response = responses[key];
1804
- return {
1805
- ...acc,
1806
- [key]: this.getResponseByRef(response)
1807
- };
1808
- }, {});
1809
- const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
1810
- const requestBody = requestBodies[key];
1811
- return {
1812
- ...acc,
1813
- [key]: this.getRequestBodyByRef(requestBody, enums)
1814
- };
1815
- }, {});
1816
- const apis = Object.keys(paths).reduce((acc, path) => {
1817
- const pathObject = paths[path] ?? {};
1818
- const { $ref } = pathObject;
1819
- const methodApis = [];
1820
- if ($ref) {
1821
- } else {
1822
- const { parameters: parameters2 = [], description, summary } = pathObject;
1823
- Object.values(HttpMethods).forEach((method) => {
1824
- const methodObject = pathObject[method];
1825
- if (methodObject) {
1826
- const {
1827
- deprecated,
1828
- operationId,
1829
- responses: responses2 = {},
1830
- summary: summary_,
1831
- description: description_,
1832
- requestBody = { content: {} }
1833
- } = methodObject;
1834
- const { parameters: parameters_2 = [] } = methodObject;
1835
- const baseParameters = [...parameters2, ...parameters_2].map(
1836
- (parameter) => this.getParameterByRef(parameter, enums)
1837
- );
1838
- const baseRequestBody = this.getRequestBodyByRef(
1839
- requestBody,
1840
- enums
1841
- );
1842
- const uniqueParameterName = [
1843
- ...new Set(baseParameters.map((p) => p.name))
1844
- ];
1845
- if (Object.keys(responses2).length === 0) {
1846
- Object.assign(responses2, {
1847
- 200: {
1848
- description: "Successful response"
1849
- }
1850
- });
1851
- }
1852
- const httpCodes = Object.keys(responses2);
1853
- for (const code of httpCodes) {
1854
- if (code in responses2) {
1855
- const response = responses2[code];
1856
- const responseSchema = this.getResponseByRef(response);
1857
- methodApis.push({
1858
- method,
1859
- operationId,
1860
- summary: summary_ ?? summary,
1861
- description: description_ ?? description,
1862
- deprecated,
1863
- parameters: uniqueParameterName.map(
1864
- (name) => baseParameters.find((p) => p.name === name)
1865
- ),
1866
- responses: responseSchema,
1867
- requestBody: baseRequestBody
1868
- });
1869
- break;
1870
- }
1871
- }
1872
- }
1873
- });
1874
- }
1875
- return {
1876
- ...acc,
1877
- [path]: methodApis
1878
- };
1879
- }, {});
1880
- return {
1881
- enums: Base.uniqueEnums(enums),
1882
- schemas: schemas_,
1883
- responses: responses_,
1884
- parameters: parameters_,
1885
- requestBodies: requestBodies_,
1886
- apis
1887
- };
1888
- }
1889
- };
1890
-
1891
- // src/openapi/V3_1.ts
1892
- var V3_1 = class {
1893
- doc;
1894
- constructor(doc) {
1895
- this.doc = doc;
1896
- }
1897
- /**
1898
- * Is array schema.
1899
- */
1900
- isOpenAPIArraySchema(schema) {
1901
- return typeof schema === "object" && schema.type === "array";
1902
- }
1903
- /**
1904
- * OpenAPI schema to base schema.
1905
- */
1906
- getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1907
- let refName = "";
1908
- if (Base.isRef(schema)) {
1909
- refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1910
- if (reserveRef) {
1911
- return {
1912
- type: upLevelSchemaKey + refName
1913
- };
1914
- }
1915
- if (!this.doc.components) {
1916
- this.doc.components = {
1917
- schemas: {}
1918
- };
1919
- }
1920
- schema = this.doc.components.schemas[Base.ref2name(schema.$ref, this.doc)];
1921
- }
1922
- return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1923
- }
1924
- /**
1925
- * OpenAPI parameter to base parameter.
1926
- */
1927
- getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1928
- if (Base.isRef(schema)) {
1929
- schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1930
- }
1931
- const {
1932
- name,
1933
- required,
1934
- deprecated,
1935
- description,
1936
- schema: parameterSchema
1937
- } = schema;
1938
- if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
1939
- const type = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(name);
1940
- const enumSchema = {
1941
- name: type,
1942
- enum: [...new Set(parameterSchema.enum)]
1943
- };
1944
- const sameEnum = Base.findSameSchema(enumSchema, enums);
1945
- if (!sameEnum && Base.isValidEnumType(parameterSchema)) {
1946
- enums.push(enumSchema);
1947
- }
1948
- return {
1949
- name,
1950
- required,
1951
- description,
1952
- deprecated,
1953
- in: schema.in,
1954
- schema: {
1955
- type: sameEnum?.name ?? type
1956
- }
1957
- };
1958
- }
1959
- return {
1960
- name,
1961
- required,
1962
- description,
1963
- deprecated,
1964
- in: schema.in,
1965
- schema: schema.schema && this.getSchemaByRef(
1966
- schema.schema,
1967
- false,
1968
- enums,
1969
- upLevelSchemaKey + Base.capitalize(name)
1970
- )
1971
- };
1972
- }
1973
- /**
1974
- * OpenAPI schema to base response
1975
- */
1976
- getResponseByRef(schema) {
1977
- if (Base.isRef(schema)) {
1978
- schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1979
- }
1980
- const { content = {} } = schema;
1981
- return Object.keys(content).map((c) => ({
1982
- type: c,
1983
- schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1984
- }));
1985
- }
1986
- /**
1987
- * OpenAPI schema to requestBody.
1988
- */
1989
- getRequestBodyByRef(schema, enums = [], reserveRef = false) {
1990
- if (Base.isRef(schema)) {
1991
- schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1992
- }
1993
- const { content = {} } = schema;
1994
- return Object.keys(content).map((c) => ({
1995
- type: c,
1996
- schema: content[c].schema && this.getSchemaByRef(content[c].schema, reserveRef, enums)
1997
- }));
1998
- }
1999
- /**
2000
- * Transform all OpenAPI schema to Base Schema
2001
- */
2002
- toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
2003
- if (!schema) {
2004
- return {
2005
- type: "unknown"
2006
- };
2007
- }
2008
- if (Base.isRef(schema)) {
2009
- return this.getSchemaByRef(schema, true);
2010
- }
2011
- if (this.isOpenAPIArraySchema(schema)) {
2012
- const { type, description, items, required } = schema;
2013
- return {
2014
- type,
2015
- required: !!required,
2016
- description,
2017
- items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
2018
- };
2019
- } else {
2020
- const {
2021
- required = [],
2022
- allOf,
2023
- anyOf,
2024
- description,
2025
- deprecated,
2026
- enum: enum_,
2027
- format: format2,
2028
- oneOf,
2029
- properties = {}
2030
- } = schema;
2031
- let { type } = schema;
2032
- if (enum_ && type !== "boolean") {
2033
- const name = Base.upperCamelCase(upLevelSchemaKey) + Base.upperCamelCase(schemaKey);
2034
- const enumObject = {
2035
- name,
2036
- enum: [...new Set(enum_)]
2037
- };
2038
- const sameObject = Base.findSameSchema(enumObject, enums);
2039
- if (!sameObject && Base.isValidEnumType(schema)) {
2040
- enums.push(enumObject);
2041
- }
2042
- return {
2043
- type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
2044
- required,
2045
- description,
2046
- deprecated
2047
- };
2048
- }
2049
- if (type === void 0 && Object.keys(properties).length > 0) {
2050
- type = "object" /* object */;
2051
- }
2052
- return {
2053
- type,
2054
- required,
2055
- description,
2056
- deprecated,
2057
- enum: enum_,
2058
- format: format2,
2059
- allOf: allOf?.map(
2060
- (s) => Base.isRef(s) ? {
2061
- ...s,
2062
- ref: s.$ref,
2063
- type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc))
2064
- } : this.toBaseSchema(s, enums)
2065
- ),
2066
- anyOf: anyOf?.map(
2067
- (s) => Base.isRef(s) ? {
2068
- ...s,
2069
- ref: s.$ref,
2070
- type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc))
2071
- } : this.toBaseSchema(s, enums)
2072
- ),
2073
- oneOf: oneOf?.map(
2074
- (s) => Base.isRef(s) ? {
2075
- ...s,
2076
- ref: s.$ref,
2077
- type: Base.upperCamelCase(Base.ref2name(s.$ref, this.doc))
2078
- } : this.toBaseSchema(s, enums)
2079
- ),
2080
- properties: Object.keys(properties).reduce((acc, p) => {
2081
- const propSchema = properties[p];
2082
- return {
2083
- ...acc,
2084
- [p]: Base.isRef(propSchema) ? {
2085
- type: Base.upperCamelCase(
2086
- Base.ref2name(propSchema.$ref, this.doc)
2087
- )
2088
- } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
2089
- };
2090
- }, {})
2091
- };
2092
- }
2093
- }
2094
- init() {
2095
- const { components = {}, paths = {} } = this.doc;
2096
- const enums = [];
2097
- const {
2098
- requestBodies = {},
2099
- responses = {},
2100
- parameters = {},
2101
- schemas = {}
2102
- } = components;
2103
- const schemas_ = Object.keys(schemas).reduce((acc, key) => {
2104
- const schema = schemas[key];
2105
- return {
2106
- ...acc,
2107
- [key]: this.getSchemaByRef(schema, false, enums, key)
2108
- };
2109
- }, {});
2110
- const parameters_ = Object.keys(parameters).reduce((acc, key) => {
2111
- const parameter = parameters[key];
2112
- return {
2113
- ...acc,
2114
- [key]: this.getParameterByRef(parameter, enums, key)
2115
- };
2116
- }, {});
2117
- const responses_ = Object.keys(responses).reduce((acc, key) => {
2118
- const response = responses[key];
2119
- return {
2120
- ...acc,
2121
- [key]: this.getResponseByRef(response)
2122
- };
2123
- }, {});
2124
- const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
2125
- const requestBody = requestBodies[key];
2126
- return {
2127
- ...acc,
2128
- [key]: this.getRequestBodyByRef(requestBody, enums)
2129
- };
2130
- }, {});
2131
- const apis = Object.keys(paths).reduce((acc, path) => {
2132
- const pathObject = paths[path] ?? {};
2133
- const { $ref } = pathObject;
2134
- const methodApis = [];
2135
- if ($ref) {
2136
- } else {
2137
- const { parameters: parameters2 = [], description, summary } = pathObject;
2138
- Object.values(HttpMethods).forEach((method) => {
2139
- const methodObject = pathObject[method];
2140
- if (methodObject) {
2141
- const {
2142
- deprecated,
2143
- operationId,
2144
- summary: summary_,
2145
- description: description_,
2146
- responses: responses2 = {},
2147
- requestBody = { content: {} }
2148
- } = methodObject;
2149
- const { parameters: parameters_2 = [] } = methodObject;
2150
- const baseParameters = [...parameters2, ...parameters_2].map(
2151
- (parameter) => this.getParameterByRef(parameter, enums)
2152
- );
2153
- const baseRequestBody = this.getRequestBodyByRef(
2154
- requestBody,
2155
- enums,
2156
- true
2157
- );
2158
- const uniqueParameterName = [
2159
- ...new Set(baseParameters.map((p) => p.name))
2160
- ];
2161
- if (Object.keys(responses2).length === 0) {
2162
- Object.assign(responses2, {
2163
- 200: {
2164
- description: "Successful response"
2165
- }
2166
- });
2167
- }
2168
- const httpCodes = Object.keys(responses2);
2169
- for (const code of httpCodes) {
2170
- if (code in responses2) {
2171
- const response = responses2[code];
2172
- const responseSchema = this.getResponseByRef(response);
2173
- methodApis.push({
2174
- method,
2175
- operationId,
2176
- summary: summary_ ?? summary,
2177
- description: description_ ?? description,
2178
- deprecated,
2179
- parameters: uniqueParameterName.map(
2180
- (name) => baseParameters.find((p) => p.name === name)
2181
- ),
2182
- responses: responseSchema,
2183
- requestBody: baseRequestBody
2184
- });
2185
- break;
2186
- }
2187
- }
2188
- }
2189
- });
2190
- }
2191
- return {
2192
- ...acc,
2193
- [path]: methodApis
2194
- };
2195
- }, {});
2196
- return {
2197
- enums: Base.uniqueEnums(enums),
2198
- schemas: schemas_,
2199
- responses: responses_,
2200
- parameters: parameters_,
2201
- requestBodies: requestBodies_,
2202
- apis
2203
- };
2204
- }
2205
- };
2206
-
2207
- // src/openapi/index.ts
2208
- var logger = createScopedLogger("OpenAPI");
2209
- var OpenAPIVersion = /* @__PURE__ */ ((OpenAPIVersion2) => {
2210
- OpenAPIVersion2["v2"] = "v2";
2211
- OpenAPIVersion2["v3"] = "v3";
2212
- OpenAPIVersion2["v3_1"] = "v3_1";
2213
- OpenAPIVersion2["unknown"] = "unknown";
2214
- return OpenAPIVersion2;
2215
- })(OpenAPIVersion || {});
2216
- function getDocVersion(doc) {
2217
- const version = (doc.openapi || doc.swagger).slice(0, 3);
2218
- switch (version) {
2219
- case "2.0":
2220
- return "v2" /* v2 */;
2221
- case "3.0":
2222
- return "v3" /* v3 */;
2223
- case "3.1":
2224
- return "v3_1" /* v3_1 */;
2225
- default:
2226
- return "unknown" /* unknown */;
2227
- }
2228
- }
2229
- var OpenAPIProvider = class extends Provider {
2230
- parse(doc) {
2231
- const version = getDocVersion(doc);
2232
- logger.debug(`openapi version ${version}`);
2233
- let returnValue;
2234
- switch (version) {
2235
- case "v2" /* v2 */:
2236
- returnValue = new V2(doc).init();
2237
- break;
2238
- case "v3" /* v3 */:
2239
- returnValue = new V3(doc).init();
2240
- break;
2241
- case "v3_1" /* v3_1 */:
2242
- returnValue = new V3_1(doc).init();
2243
- break;
2244
- default:
2245
- logger.error(`Not a valid OpenAPI version ${version}`);
2246
- process.exit(1);
2247
- }
2248
- return returnValue;
2249
- }
2250
- };
2251
- function getAdaptor(type) {
2252
- switch (type) {
2253
- case "axios" /* axios */:
2254
- return new AxiosAdapter();
2255
- case "fetch" /* fetch */:
2256
- return new FetchAdapter();
2257
- default:
2258
- throw TypeError(`Not Supported Adaptor ${type}`);
2259
- }
2260
- }
2261
- async function codeGen(initOptions) {
2262
- const { verbose } = initOptions;
2263
- if (verbose) {
2264
- logger.setLevel("debug");
2265
- } else {
2266
- logger.setLevel("info");
2267
- }
2268
- logger.info(`Fech document from ${initOptions.docURL}`);
2269
- const doc = await Base.fetchDoc(
2270
- initOptions.docURL,
2271
- initOptions.requestOptions
2272
- );
2273
- const provider = new OpenAPIProvider(initOptions, doc);
2274
- const { enums, schemas, parameters, responses, requestBodies, apis } = provider;
2275
- const adaptor = getAdaptor(initOptions.adaptor ?? "fetch" /* fetch */);
2276
- const code = await Generator.genCode(
2277
- {
2278
- enums,
2279
- schemas,
2280
- parameters,
2281
- responses,
2282
- requestBodies,
2283
- apis
2284
- },
2285
- initOptions,
2286
- adaptor
2287
- );
2288
- if (process.env.NODE_ENV === "test") {
2289
- await Generator.write(code, initOptions.output);
2290
- }
2291
- return code;
2292
- }
2293
-
2294
- // src/vite-plugin/index.ts
2295
- import { createScopedLogger as createScopedLogger2 } from "@moccona/logger";
2296
- import { execaCommand } from "execa";
2297
- import fs from "fs-extra";
2298
- var PLUGIN_NAME = "apiCodeGen";
2299
- var logger2 = createScopedLogger2("api-codegen-vite-plugin");
2300
- var tsc = async (path) => {
2301
- await execaCommand(`npx tsc ${path} --noEmit`);
2302
- };
2303
- function apiCodeGenPlugin(options) {
2304
- let firstRun = true;
2305
- return {
2306
- name: PLUGIN_NAME,
2307
- async config(config) {
2308
- if (!firstRun) return;
2309
- firstRun = false;
2310
- logger2.info("-------> api codegen start <--------");
2311
- const proxies = await options.reduce(
2312
- async (proxiesPromise_, option) => {
2313
- const proxies_ = await proxiesPromise_;
2314
- const { proxy = {}, name, ...codeGenInitOptions } = option;
2315
- try {
2316
- const code = await codeGen(codeGenInitOptions);
2317
- await fs.createFile(codeGenInitOptions.output);
2318
- await fs.writeFile(codeGenInitOptions.output, code);
2319
- try {
2320
- await tsc(codeGenInitOptions.output);
2321
- } catch (error) {
2322
- logger2.error(error);
2323
- }
2324
- } catch (error) {
2325
- logger2.error(`Failed to generate api ${name}: ${error}`);
2326
- }
2327
- return {
2328
- ...proxies_,
2329
- ...proxy
2330
- };
2331
- },
2332
- Promise.resolve({})
2333
- );
2334
- logger2.info("-------> api codegen finished <--------");
2335
- return {
2336
- ...config,
2337
- server: {
2338
- ...config.server ?? {},
2339
- proxy: Object.assign({}, config.server?.proxy ?? {}, proxies)
2340
- }
2341
- };
2342
- }
2343
- };
2344
- }
2345
- export {
2346
- Adapter,
2347
- Adaptors,
2348
- ArraySchemaType,
2349
- AxiosAdapter,
2350
- Base,
2351
- FetchAdapter,
2352
- Generator,
2353
- HttpMethods,
2354
- MediaTypes,
2355
- NonArraySchemaType,
2356
- OpenAPIProvider,
2357
- OpenAPIVersion,
2358
- ParameterIn,
2359
- Provider,
2360
- SchemaFormatType,
2361
- SchemaType,
2362
- SuccessHttpStatusCode,
2363
- apiCodeGenPlugin,
2364
- codeGen,
2365
- tsc
2366
- };
2367
- //# sourceMappingURL=index.js.map