@moccona/apicodegen 0.0.1

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