swaggular 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/dist/app/get-parse-args.js +48 -0
  4. package/dist/app/parse-variables.js +24 -0
  5. package/dist/builders/build-comments.js +25 -0
  6. package/dist/cli/args.d.ts +2 -0
  7. package/dist/cli/args.js +48 -0
  8. package/dist/cli/variables.d.ts +2 -0
  9. package/dist/cli/variables.js +23 -0
  10. package/dist/core/state/interface-state.d.ts +17 -0
  11. package/dist/core/state/interface-state.js +21 -0
  12. package/dist/core/state/service-state.d.ts +9 -0
  13. package/dist/core/state/service-state.js +18 -0
  14. package/dist/core/state/swagger-state.d.ts +14 -0
  15. package/dist/core/state/swagger-state.js +36 -0
  16. package/dist/examples/services/get.example.js +1 -0
  17. package/dist/generators/generate-comments.js +40 -0
  18. package/dist/generators/generate-interface.js +219 -0
  19. package/dist/generators/generate-service.js +302 -0
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.js +45 -0
  22. package/dist/models/file-content.js +2 -0
  23. package/dist/models/grouped-paths.js +2 -0
  24. package/dist/models/interface-data.js +2 -0
  25. package/dist/models/parsed-args.js +2 -0
  26. package/dist/models/service-data.js +2 -0
  27. package/dist/models/types.js +29 -0
  28. package/dist/parsers/path-grouper.d.ts +17 -0
  29. package/dist/parsers/path-grouper.js +207 -0
  30. package/dist/parsers/swagger-parser.d.ts +4 -0
  31. package/dist/parsers/swagger-parser.js +53 -0
  32. package/dist/renderers/generate-comments.d.ts +3 -0
  33. package/dist/renderers/generate-comments.js +40 -0
  34. package/dist/renderers/generate-interface.d.ts +12 -0
  35. package/dist/renderers/generate-interface.js +209 -0
  36. package/dist/renderers/generate-service.d.ts +9 -0
  37. package/dist/renderers/generate-service.js +178 -0
  38. package/dist/stores/interface-data-store.js +62 -0
  39. package/dist/stores/services-store.js +18 -0
  40. package/dist/stores/swagger-store.js +324 -0
  41. package/dist/templates/angular-template.js +23 -0
  42. package/dist/templates/paged-request-template.js +22 -0
  43. package/dist/templates/paged-result-template.js +13 -0
  44. package/dist/templates/services/angular-template.d.ts +15 -0
  45. package/dist/templates/services/angular-template.js +24 -0
  46. package/dist/templates/services/http-params-handler.d.ts +2 -0
  47. package/dist/templates/services/http-params-handler.js +12 -0
  48. package/dist/templates/types/extends-from-types.d.ts +3 -0
  49. package/dist/templates/types/extends-from-types.js +72 -0
  50. package/dist/templates/types/generic-types.d.ts +4 -0
  51. package/dist/templates/types/generic-types.js +72 -0
  52. package/dist/translators/add-import-to-interface.js +21 -0
  53. package/dist/translators/generate-interfaces.js +134 -0
  54. package/dist/translators/generate-services.js +192 -0
  55. package/dist/translators/join-with-templates.js +16 -0
  56. package/dist/translators/splitPaths.js +8 -0
  57. package/dist/types/file-content.d.ts +6 -0
  58. package/dist/types/file-content.js +2 -0
  59. package/dist/types/grouped-paths.d.ts +7 -0
  60. package/dist/types/grouped-paths.js +2 -0
  61. package/dist/types/interface-data.d.ts +13 -0
  62. package/dist/types/interface-data.js +2 -0
  63. package/dist/types/parsed-args.d.ts +9 -0
  64. package/dist/types/parsed-args.js +2 -0
  65. package/dist/types/service-data.d.ts +21 -0
  66. package/dist/types/service-data.js +2 -0
  67. package/dist/types/types.d.ts +23 -0
  68. package/dist/types/types.js +29 -0
  69. package/dist/utils/build-types.d.ts +2 -0
  70. package/dist/utils/build-types.js +66 -0
  71. package/dist/utils/create-file.d.ts +7 -0
  72. package/dist/utils/create-file.js +74 -0
  73. package/dist/utils/generate-imports.js +33 -0
  74. package/dist/utils/grouping-paths.js +68 -0
  75. package/dist/utils/method-builders.js +77 -0
  76. package/dist/utils/object-utils.d.ts +1 -0
  77. package/dist/utils/object-utils.js +11 -0
  78. package/dist/utils/path-utils.d.ts +7 -0
  79. package/dist/utils/path-utils.js +61 -0
  80. package/dist/utils/string-utils.d.ts +13 -0
  81. package/dist/utils/string-utils.js +47 -0
  82. package/dist/utils/to-case.js +47 -0
  83. package/dist/utils/type-guard.d.ts +5 -0
  84. package/dist/utils/type-guard.js +35 -0
  85. package/package.json +64 -0
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getImports = getImports;
4
+ exports.buildInterface = buildInterface;
5
+ exports.buildEnum = buildEnum;
6
+ exports.generateSchemaInterfaces = generateSchemaInterfaces;
7
+ exports.buildComments = buildComments;
8
+ const paged_request_template_1 = require("../templates/paged-request-template");
9
+ const paged_result_template_1 = require("../templates/paged-result-template");
10
+ const build_types_1 = require("../utils/build-types");
11
+ const to_case_1 = require("../utils/to-case");
12
+ function getImports(schema, type) {
13
+ const imports = [];
14
+ if (!schema["$ref"]) {
15
+ return [];
16
+ }
17
+ if (type.startsWith("PagedResultDto")) {
18
+ imports.push("PagedResultDto");
19
+ const splited = type.replaceAll(">", "").split("<");
20
+ splited.forEach((s) => imports.push(s));
21
+ }
22
+ return imports;
23
+ }
24
+ function buildInterface(name, schema) {
25
+ if (name.endsWith("PagedResultDto"))
26
+ return { content: null, imports: [] };
27
+ const lines = [];
28
+ lines.push(`export interface ${name} {`);
29
+ const imports = new Set();
30
+ for (const [prop, def] of Object.entries(schema.properties)) {
31
+ const comments = buildComments(def);
32
+ const tsType = (0, build_types_1.switchTypeJson)(def);
33
+ if (def["$ref"]) {
34
+ getImports(def, tsType).forEach((i) => imports.add(i));
35
+ }
36
+ const optional = def.nullable || !schema.required?.includes(prop);
37
+ const nullable = def.nullable ? " | null" : "";
38
+ lines.push(`${comments}\n\t${(0, to_case_1.lowerFirst)(prop)}${optional ? "?" : ""}: ${tsType}${nullable};`);
39
+ }
40
+ lines.push(`}`);
41
+ return { content: lines.join("\n"), imports: [] };
42
+ }
43
+ function buildEnum(name, schema) {
44
+ const lines = [];
45
+ lines.push(`export enum ${name} {`);
46
+ for (const value of schema.enum) {
47
+ lines.push(`\t${value} = "${value}",`);
48
+ }
49
+ lines.push(`}`);
50
+ return lines.join("\n");
51
+ }
52
+ function generateSchemaInterfaces(schemas, paths, parametersTypes) {
53
+ const interfaces = {};
54
+ for (const [name, schema] of Object.entries(schemas)) {
55
+ if (schema.type === "string" && schema.enum && schema.enum.length > 0) {
56
+ const enumString = buildEnum(name, schema);
57
+ if (!enumString)
58
+ continue;
59
+ interfaces[name] = { content: enumString, imports: [] };
60
+ continue;
61
+ }
62
+ if (schema.type === "object" && schema.properties) {
63
+ const interfaceString = buildInterface(name, schema);
64
+ if (!interfaceString.content)
65
+ continue;
66
+ interfaces[name] = {
67
+ content: interfaceString.content,
68
+ imports: interfaceString.imports,
69
+ };
70
+ continue;
71
+ }
72
+ }
73
+ const defaultPagedRequestDtoKeys = [
74
+ "pageNumber",
75
+ "pageSize",
76
+ "searchTerm",
77
+ "sortBy",
78
+ "sortDescending",
79
+ ];
80
+ const requestImports = new Set();
81
+ for (const value of Object.values(parametersTypes)) {
82
+ const { method, parameterType } = value;
83
+ const path = paths[method];
84
+ if (!path.parameters || path.parameters.length === 0)
85
+ continue;
86
+ const properties = [];
87
+ for (const param of path.parameters) {
88
+ if (defaultPagedRequestDtoKeys.includes(param.name) ||
89
+ param.in !== "query")
90
+ continue;
91
+ const tsType = (0, build_types_1.switchTypeJson)(param.schema);
92
+ if (param.schema["$ref"]) {
93
+ getImports(param.schema, tsType).forEach((i) => requestImports.add(i));
94
+ }
95
+ const comments = buildComments(param.schema);
96
+ properties.push(`${comments}\n\t${(0, to_case_1.lowerFirst)(param.name)}?: ${tsType};`);
97
+ }
98
+ let interfaceTemplate = `export interface ${parameterType} extends PagedRequestDto {
99
+ ${properties.join("\n")}
100
+ }`;
101
+ requestImports.add("PagedRequestDto");
102
+ interfaces[parameterType] = {
103
+ content: interfaceTemplate,
104
+ imports: Array.from(requestImports),
105
+ };
106
+ }
107
+ return {
108
+ ...interfaces,
109
+ ["PagedRequestDto"]: { content: paged_request_template_1.pagedRequestTemplate, imports: [] },
110
+ ["PagedResultDto"]: { content: paged_result_template_1.pagedResultTemplate, imports: [] },
111
+ };
112
+ }
113
+ function buildComments(param) {
114
+ const comments = [];
115
+ if (param.format !== undefined) {
116
+ comments.push(`format: ${param.format}`);
117
+ }
118
+ if (param.minLength !== undefined) {
119
+ comments.push(`minLength: ${param.minLength}`);
120
+ }
121
+ if (param.maxLength !== undefined) {
122
+ comments.push(`maxLength: ${param.maxLength}`);
123
+ }
124
+ if (param.minimum !== undefined) {
125
+ comments.push(`minimum: ${param.minimum}`);
126
+ }
127
+ if (param.maximum !== undefined) {
128
+ comments.push(`maximum: ${param.maximum}`);
129
+ }
130
+ if (comments.length > 0) {
131
+ return ` /**\n * ${comments.join("\n * ")}\n */`;
132
+ }
133
+ return "";
134
+ }
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toCamelCase = toCamelCase;
4
+ exports.toExtra = toExtra;
5
+ exports.generateBaseUrl = generateBaseUrl;
6
+ exports.transformGroupedPathsToAngularServices = transformGroupedPathsToAngularServices;
7
+ const generate_imports_1 = require("../utils/generate-imports");
8
+ const method_builders_1 = require("../utils/method-builders");
9
+ /* ============================================================
10
+ * LOW-LEVEL HELPERS
11
+ * ============================================================ */
12
+ function isVariable(segment) {
13
+ return /^\{.+\}$/.test(segment);
14
+ }
15
+ function kebabToPascal(value) {
16
+ return value
17
+ .split("-")
18
+ .map((v) => v.charAt(0).toUpperCase() + v.slice(1))
19
+ .join("");
20
+ }
21
+ function extractPathVariables(path) {
22
+ return path
23
+ .split("/")
24
+ .filter(isVariable)
25
+ .map((v) => v.slice(1, -1));
26
+ }
27
+ function endsWithVariable(path) {
28
+ const parts = path.split("/").filter(Boolean);
29
+ return isVariable(parts[parts.length - 1]);
30
+ }
31
+ /**
32
+ * Detecta si la ruta es hija del grupo y devuelve el nombre del recurso hijo
33
+ * /A/{id}/B/{x} -> B
34
+ */
35
+ function getChildResource(path, baseSegments) {
36
+ const segments = path
37
+ .split("/")
38
+ .filter(Boolean)
39
+ .filter((s) => s !== "api");
40
+ let count = 0;
41
+ for (const seg of segments) {
42
+ if (isVariable(seg))
43
+ continue;
44
+ count++;
45
+ if (count > baseSegments.length) {
46
+ return seg;
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+ /* ============================================================
52
+ * METHOD NAME RESOLUTION (TU DICCIONARIO)
53
+ * ============================================================ */
54
+ function resolveMethodName(http, endsInVar, child, putNoVarAlreadyExists = false) {
55
+ let base;
56
+ switch (http) {
57
+ case "get":
58
+ base = endsInVar ? "get" : "getAll";
59
+ break;
60
+ case "post":
61
+ base = "create";
62
+ break;
63
+ case "put":
64
+ base = endsInVar
65
+ ? "update"
66
+ : putNoVarAlreadyExists
67
+ ? "updateAll"
68
+ : "update";
69
+ break;
70
+ case "delete":
71
+ base = "delete";
72
+ break;
73
+ case "patch":
74
+ base = "patch";
75
+ break;
76
+ }
77
+ return child ? base + kebabToPascal(child) : base;
78
+ }
79
+ function toCamelCase(value) {
80
+ const firstCharacter = value.at(0);
81
+ return firstCharacter?.toLowerCase() + value.slice(1);
82
+ }
83
+ function toExtra(segments) {
84
+ let path = ``;
85
+ segments.forEach((s) => {
86
+ const isVariable = s.startsWith("{");
87
+ path += isVariable ? `/\${${toCamelCase(s.slice(1, -1))}}` : `/${s}`;
88
+ });
89
+ return path;
90
+ }
91
+ function generateBaseUrl(baseSegments, paths) {
92
+ const splitted = paths[0].split("/").filter(Boolean);
93
+ const foundIndex = splitted.findIndex((s) => s === baseSegments[baseSegments.length - 1]);
94
+ const foundVariable = splitted.findIndex((s) => s.includes("{"));
95
+ if (foundIndex > foundVariable && foundVariable >= 0) {
96
+ const base = "/" + splitted.slice(0, foundVariable).join("/");
97
+ return base;
98
+ }
99
+ return "/" + splitted.slice(0, foundIndex + 1).join("/");
100
+ }
101
+ /* ============================================================
102
+ * 🚀 MAIN TRANSFORMER
103
+ * ============================================================ */
104
+ function transformGroupedPathsToAngularServices(grouped, openApiPaths) {
105
+ const services = [];
106
+ const parametersTypes = {};
107
+ for (const group of Object.values(grouped)) {
108
+ const groupName = group.groupName;
109
+ const baseUrl = generateBaseUrl(group.baseSegments, group.paths);
110
+ const methods = [];
111
+ const imports = [];
112
+ let putWithoutVarExists = false;
113
+ for (const path of group.paths) {
114
+ const ops = openApiPaths[path];
115
+ if (!ops)
116
+ continue;
117
+ const variables = extractPathVariables(path);
118
+ const endsInVar = endsWithVariable(path);
119
+ const child = getChildResource(path, group.baseSegments);
120
+ for (const http of Object.keys(ops)) {
121
+ const op = ops[http];
122
+ const methodName = resolveMethodName(http, endsInVar, child ?? undefined, putWithoutVarExists);
123
+ if (http === "put" && !endsInVar) {
124
+ if (putWithoutVarExists)
125
+ continue;
126
+ putWithoutVarExists = true;
127
+ }
128
+ /* =====================
129
+ * PARAMS
130
+ * ===================== */
131
+ const params = [];
132
+ variables.forEach((v) => params.push(`${v}: string`));
133
+ let hasParameters = false;
134
+ // QUERY PARAMS (group-scoped)
135
+ if (http === "get" && op.parameters?.some((p) => p.in === "query")) {
136
+ hasParameters = true;
137
+ params.push(`parameters?: ${groupName}Parameters`);
138
+ imports.push(`${groupName}Parameters`);
139
+ }
140
+ // REQUEST BODY (group-scoped + validated against schemas)
141
+ let requestBodyType = (0, method_builders_1.computeRequestBodyType)(op.requestBody);
142
+ if (requestBodyType) {
143
+ params.push(`requestBody: ${requestBodyType}`);
144
+ imports.push(requestBodyType);
145
+ if (requestBodyType.endsWith("Parameters")) {
146
+ parametersTypes[methodName] = {
147
+ method: http,
148
+ parameterType: requestBodyType,
149
+ };
150
+ }
151
+ }
152
+ /* =====================
153
+ * RESPONSE TYPE (group-scoped)
154
+ * ===================== */
155
+ let responseType = (0, method_builders_1.computeResponseType)(op.responses?.["200"]);
156
+ imports.push(responseType);
157
+ /* =====================
158
+ * METHOD BODY
159
+ * ===================== */
160
+ let body = "";
161
+ if (http === "get") {
162
+ body = (0, method_builders_1.buildGetContent)(responseType, path, baseUrl, hasParameters);
163
+ }
164
+ if (http === "post") {
165
+ body = (0, method_builders_1.buildPostContent)(responseType, path, baseUrl, !!requestBodyType);
166
+ }
167
+ if (http === "put") {
168
+ body = (0, method_builders_1.buildPutContent)(responseType, path, baseUrl, !!requestBodyType);
169
+ }
170
+ if (http === "patch") {
171
+ body = (0, method_builders_1.buildPatchContent)(responseType, path, baseUrl, !!requestBodyType);
172
+ }
173
+ if (http === "delete") {
174
+ body = (0, method_builders_1.buildDeleteContent)(responseType, path, baseUrl, hasParameters);
175
+ }
176
+ methods.push(`\t${methodName}(${params.join(", ")}): Observable<${responseType}> {
177
+ ${body}
178
+ \t}\n`);
179
+ }
180
+ }
181
+ services.push({
182
+ name: groupName,
183
+ baseUrl,
184
+ methods: methods.join("\n"),
185
+ imports: (0, generate_imports_1.getImports)(imports).join(", "),
186
+ });
187
+ }
188
+ return {
189
+ forTemplate: services,
190
+ parametersTypes,
191
+ };
192
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.joinWithTemplates = joinWithTemplates;
4
+ const angular_template_1 = require("../templates/angular-template");
5
+ function joinWithTemplates(services) {
6
+ const templates = [];
7
+ services.forEach((s) => {
8
+ if (s.baseUrl.trim() === "" ||
9
+ s.methods.trim() === "" ||
10
+ s.name.trim() === "") {
11
+ return;
12
+ }
13
+ templates.push((0, angular_template_1.angularServiceTemplate)(s));
14
+ });
15
+ return templates;
16
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.splitPaths = splitPaths;
4
+ const grouping_paths_1 = require("../utils/grouping-paths");
5
+ function splitPaths(swagger) {
6
+ const groupedPaths = (0, grouping_paths_1.groupPaths)(swagger.paths);
7
+ return groupedPaths;
8
+ }
@@ -0,0 +1,6 @@
1
+ export interface FileContent {
2
+ location: string[];
3
+ name: string;
4
+ content: string;
5
+ extension: string;
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,7 @@
1
+ export type GroupedPaths = Record<string, GroupedPath>;
2
+ export interface GroupedPath {
3
+ groupName: string;
4
+ baseSegments: string[];
5
+ paths: string[];
6
+ baseUrl: string;
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,13 @@
1
+ export interface InterfaceData {
2
+ name: string;
3
+ imports: string[];
4
+ type: 'interface' | 'enum' | 'type';
5
+ properties: InterfaceDataProperty[];
6
+ extendsFrom?: string[];
7
+ }
8
+ export interface InterfaceDataProperty {
9
+ name: string;
10
+ type: string;
11
+ optional: boolean;
12
+ comments: string;
13
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,9 @@
1
+ export type ParsedArgs = {
2
+ args: Record<string, string | boolean>;
3
+ positional: string[];
4
+ };
5
+ export interface ArgsVariables {
6
+ groupingMode: 'tags' | 'path';
7
+ segmentsToIgnore: string[];
8
+ ignoreVariables: boolean;
9
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,21 @@
1
+ import { AngularRequestType } from './types';
2
+ export interface ServiceData {
3
+ name: string;
4
+ imports: string[];
5
+ baseUrl: string;
6
+ methods: ServiceDataMethod[];
7
+ }
8
+ export interface ServiceDataMethod {
9
+ name: string;
10
+ path: string;
11
+ method: AngularRequestType;
12
+ parameters: ServiceDataParameter[];
13
+ responseType: string;
14
+ comments: string;
15
+ }
16
+ export interface ServiceDataParameter {
17
+ name: string;
18
+ in: string;
19
+ required: boolean;
20
+ type: string;
21
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,23 @@
1
+ export declare enum NativeType {
2
+ String = "string",
3
+ Number = "number",
4
+ Boolean = "boolean",
5
+ Array = "Array",
6
+ Date = "Date",
7
+ File = "File",
8
+ Any = "any",
9
+ Void = "void"
10
+ }
11
+ export declare enum AngularResponseType {
12
+ Json = "json",
13
+ Text = "text",
14
+ Blob = "blob",
15
+ ArrayBuffer = "arrayBuffer"
16
+ }
17
+ export declare enum AngularRequestType {
18
+ Get = "get",
19
+ Post = "post",
20
+ Put = "put",
21
+ Delete = "delete",
22
+ Patch = "patch"
23
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AngularRequestType = exports.AngularResponseType = exports.NativeType = void 0;
4
+ var NativeType;
5
+ (function (NativeType) {
6
+ NativeType["String"] = "string";
7
+ NativeType["Number"] = "number";
8
+ NativeType["Boolean"] = "boolean";
9
+ NativeType["Array"] = "Array";
10
+ NativeType["Date"] = "Date";
11
+ NativeType["File"] = "File";
12
+ NativeType["Any"] = "any";
13
+ NativeType["Void"] = "void";
14
+ })(NativeType || (exports.NativeType = NativeType = {}));
15
+ var AngularResponseType;
16
+ (function (AngularResponseType) {
17
+ AngularResponseType["Json"] = "json";
18
+ AngularResponseType["Text"] = "text";
19
+ AngularResponseType["Blob"] = "blob";
20
+ AngularResponseType["ArrayBuffer"] = "arrayBuffer";
21
+ })(AngularResponseType || (exports.AngularResponseType = AngularResponseType = {}));
22
+ var AngularRequestType;
23
+ (function (AngularRequestType) {
24
+ AngularRequestType["Get"] = "get";
25
+ AngularRequestType["Post"] = "post";
26
+ AngularRequestType["Put"] = "put";
27
+ AngularRequestType["Delete"] = "delete";
28
+ AngularRequestType["Patch"] = "patch";
29
+ })(AngularRequestType || (exports.AngularRequestType = AngularRequestType = {}));
@@ -0,0 +1,2 @@
1
+ export declare function buildTypes(masterSchema: any, defaultType?: string): string;
2
+ export declare function switchTypeJson(schema: any): string;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTypes = buildTypes;
4
+ exports.switchTypeJson = switchTypeJson;
5
+ function buildTypes(masterSchema, defaultType = 'any') {
6
+ if (!masterSchema)
7
+ return defaultType;
8
+ const jsonSchema = masterSchema?.['content']?.['application/json'];
9
+ if (!jsonSchema) {
10
+ const formData = masterSchema?.['content']?.['multipart/form-data'];
11
+ if (formData) {
12
+ return 'FormData';
13
+ }
14
+ return defaultType;
15
+ }
16
+ const schema = jsonSchema?.['schema'];
17
+ if (!schema || Object.keys(schema).length === 0)
18
+ return defaultType;
19
+ const ref = schema?.['$ref'];
20
+ if (ref) {
21
+ const iface = ref.split('/').pop();
22
+ const isPagedResultDto = iface.endsWith('PagedResultDto');
23
+ if (isPagedResultDto) {
24
+ return `PagedResultDto<${iface.replace('PagedResultDto', '')}>`;
25
+ }
26
+ return iface;
27
+ }
28
+ return switchTypeJson(schema);
29
+ }
30
+ function switchTypeJson(schema) {
31
+ if (!schema || Object.keys(schema).length === 0)
32
+ return 'any';
33
+ const ref = schema?.['$ref'];
34
+ const type = schema?.['type'];
35
+ const format = schema?.['format'];
36
+ if (ref) {
37
+ const iface = ref.split('/').pop();
38
+ const isPagedResultDto = iface.endsWith('PagedResultDto');
39
+ if (isPagedResultDto) {
40
+ return `PagedResultDto<${iface.replace('PagedResultDto', '')}>`;
41
+ }
42
+ return iface;
43
+ }
44
+ if (type === 'object') {
45
+ return 'any';
46
+ }
47
+ if (type === 'array') {
48
+ return switchTypeJson(schema?.['items']) + '[]';
49
+ }
50
+ if (type === 'number') {
51
+ return 'number';
52
+ }
53
+ if (type === 'integer') {
54
+ return 'number';
55
+ }
56
+ if (type === 'string') {
57
+ if (format === 'binary') {
58
+ return 'Blob';
59
+ }
60
+ return 'string';
61
+ }
62
+ if (type === 'boolean') {
63
+ return 'boolean';
64
+ }
65
+ return 'any';
66
+ }
@@ -0,0 +1,7 @@
1
+ import { FileContent } from '../types/file-content';
2
+ export declare function generateFile(content: string, group: string): void;
3
+ export declare function createFolderWithFiles(folderPath: string, files: string[], filesContent: Record<string, {
4
+ content: string;
5
+ imports: string[];
6
+ }>, withIndex?: boolean): void;
7
+ export declare function createFileFromFileContents(basePath: string, fileContent: FileContent[]): Promise<void>;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateFile = generateFile;
7
+ exports.createFolderWithFiles = createFolderWithFiles;
8
+ exports.createFileFromFileContents = createFileFromFileContents;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const string_utils_1 = require("./string-utils");
12
+ function generateFile(content, group) {
13
+ const dir = `results/${group}`;
14
+ if (fs_1.default.existsSync(dir)) {
15
+ for (const file of fs_1.default.readdirSync(dir)) {
16
+ fs_1.default.unlinkSync(path_1.default.join(dir, file));
17
+ }
18
+ }
19
+ else {
20
+ fs_1.default.mkdirSync(dir, { recursive: true });
21
+ }
22
+ fs_1.default.writeFileSync(path_1.default.join(dir, `${new Date().toISOString().replaceAll(':', '-')}.ts`), content, 'utf8');
23
+ }
24
+ function createFolderWithFiles(folderPath, files, filesContent, withIndex = true) {
25
+ fs_1.default.mkdirSync(folderPath, { recursive: true });
26
+ const exports = [];
27
+ for (const fileName of files) {
28
+ if (!fileName || !filesContent[fileName]) {
29
+ continue;
30
+ }
31
+ const realFileName = (0, string_utils_1.toKebabCase)(fileName);
32
+ const finalName = `${realFileName}.model.ts`;
33
+ const filePath = path_1.default.join(folderPath, finalName);
34
+ fs_1.default.writeFileSync(filePath, filesContent[fileName].content, 'utf8');
35
+ if (withIndex) {
36
+ exports.push(`export * from "./${realFileName}.model";`);
37
+ }
38
+ }
39
+ if (withIndex && exports.length > 0) {
40
+ fs_1.default.writeFileSync(path_1.default.join(folderPath, 'index.ts'), exports.join('\n'), 'utf8');
41
+ }
42
+ }
43
+ async function createFileFromFileContents(basePath, fileContent) {
44
+ const folderExports = new Map();
45
+ for (const file of fileContent) {
46
+ const dir = path_1.default.join(basePath, ...file.location);
47
+ await fs_1.default.promises.mkdir(dir, { recursive: true });
48
+ await fs_1.default.promises.writeFile(path_1.default.join(dir, `${file.name}.${file.extension}`), file.content, 'utf8');
49
+ if (file.extension.endsWith('ts') && file.name !== 'index') {
50
+ if (!folderExports.has(dir)) {
51
+ folderExports.set(dir, new Set());
52
+ }
53
+ folderExports.get(dir).add(file.name);
54
+ }
55
+ const currentLoc = [...file.location];
56
+ while (currentLoc.length > 0) {
57
+ const childName = currentLoc.pop();
58
+ const parentDir = path_1.default.join(basePath, ...currentLoc);
59
+ if (!folderExports.has(parentDir)) {
60
+ folderExports.set(parentDir, new Set());
61
+ }
62
+ folderExports.get(parentDir).add(childName);
63
+ }
64
+ }
65
+ for (const [dir, exports] of folderExports.entries()) {
66
+ const indexContent = Array.from(exports)
67
+ .sort()
68
+ .map((item) => `export * from "./${item}";`)
69
+ .join('\n');
70
+ if (indexContent) {
71
+ await fs_1.default.promises.writeFile(path_1.default.join(dir, 'index.ts'), indexContent + '\n', 'utf8');
72
+ }
73
+ }
74
+ }