swagger-typescript-api 13.0.8 → 13.0.10

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 (67) hide show
  1. package/README.md +1 -1
  2. package/cli/index.d.ts +7 -6
  3. package/dist/chunk-3S356DIU.cjs +105 -0
  4. package/dist/chunk-3S356DIU.cjs.map +1 -0
  5. package/dist/chunk-MTWJNW6B.js +65 -0
  6. package/dist/chunk-MTWJNW6B.js.map +1 -0
  7. package/dist/cli.cjs +43 -0
  8. package/dist/cli.cjs.map +1 -0
  9. package/dist/cli.js +36 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/lib.cjs +21 -0
  12. package/dist/lib.cjs.map +1 -0
  13. package/dist/lib.js +4 -0
  14. package/dist/lib.js.map +1 -0
  15. package/package.json +30 -16
  16. package/cli/constants.js +0 -10
  17. package/cli/execute.js +0 -182
  18. package/cli/index.js +0 -96
  19. package/cli/operations/display-help.js +0 -179
  20. package/cli/operations/display-version.js +0 -5
  21. package/cli/parse-args.js +0 -26
  22. package/cli/process-option.js +0 -77
  23. package/index.js +0 -349
  24. package/src/code-formatter.js +0 -116
  25. package/src/code-gen-process.js +0 -571
  26. package/src/commands/generate-templates/configuration.js +0 -33
  27. package/src/commands/generate-templates/index.js +0 -16
  28. package/src/commands/generate-templates/templates-gen-process.js +0 -204
  29. package/src/component-type-name-resolver.js +0 -44
  30. package/src/configuration.js +0 -448
  31. package/src/constants.js +0 -65
  32. package/src/index.js +0 -26
  33. package/src/schema-components-map.js +0 -78
  34. package/src/schema-parser/base-schema-parsers/array.js +0 -43
  35. package/src/schema-parser/base-schema-parsers/complex.js +0 -51
  36. package/src/schema-parser/base-schema-parsers/discriminator.js +0 -307
  37. package/src/schema-parser/base-schema-parsers/enum.js +0 -158
  38. package/src/schema-parser/base-schema-parsers/object.js +0 -105
  39. package/src/schema-parser/base-schema-parsers/primitive.js +0 -63
  40. package/src/schema-parser/complex-schema-parsers/all-of.js +0 -26
  41. package/src/schema-parser/complex-schema-parsers/any-of.js +0 -27
  42. package/src/schema-parser/complex-schema-parsers/not.js +0 -9
  43. package/src/schema-parser/complex-schema-parsers/one-of.js +0 -27
  44. package/src/schema-parser/mono-schema-parser.js +0 -48
  45. package/src/schema-parser/schema-formatters.js +0 -166
  46. package/src/schema-parser/schema-parser-fabric.js +0 -132
  47. package/src/schema-parser/schema-parser.js +0 -300
  48. package/src/schema-parser/schema-utils.js +0 -322
  49. package/src/schema-parser/util/enum-key-resolver.js +0 -26
  50. package/src/schema-routes/schema-routes.js +0 -1213
  51. package/src/schema-routes/util/specific-arg-name-resolver.js +0 -26
  52. package/src/schema-walker.js +0 -93
  53. package/src/swagger-schema-resolver.js +0 -197
  54. package/src/templates-worker.js +0 -243
  55. package/src/translators/javascript.js +0 -83
  56. package/src/translators/translator.js +0 -35
  57. package/src/type-name-formatter.js +0 -113
  58. package/src/util/file-system.js +0 -95
  59. package/src/util/id.js +0 -9
  60. package/src/util/internal-case.js +0 -5
  61. package/src/util/logger.js +0 -144
  62. package/src/util/name-resolver.js +0 -105
  63. package/src/util/object-assign.js +0 -19
  64. package/src/util/pascal-case.js +0 -5
  65. package/src/util/random.js +0 -14
  66. package/src/util/request.js +0 -65
  67. package/src/util/sort-by-property.js +0 -17
@@ -1,26 +0,0 @@
1
- const { NameResolver } = require("../../util/name-resolver");
2
-
3
- class SpecificArgNameResolver extends NameResolver {
4
- counter = 1;
5
- /**
6
- * @param {CodeGenConfig} config;
7
- * @param {Logger} logger;
8
- * @param {string[]} reservedNames
9
- */
10
- constructor(config, logger, reservedNames) {
11
- super(config, logger, reservedNames, (variants) => {
12
- const generatedVariant =
13
- (variants[0] && `${variants[0]}${this.counter++}`) ||
14
- `${this.config.specificArgNameResolverName}${this.counter++}`;
15
- this.logger.debug(
16
- "generated fallback type name for specific arg - ",
17
- generatedVariant,
18
- );
19
- return generatedVariant;
20
- });
21
- }
22
- }
23
-
24
- module.exports = {
25
- SpecificArgNameResolver,
26
- };
@@ -1,93 +0,0 @@
1
- const _ = require("lodash");
2
-
3
- // TODO: WIP
4
- // this class will be needed to walk by schema everywhere
5
- class SchemaWalker {
6
- /** @type {Logger} */
7
- logger;
8
- /** @type {CodeGenConfig} */
9
- config;
10
- /** @type {SwaggerSchemaResolver} */
11
- swaggerSchemaResolver;
12
- /** @type {Map<string, Record<string, any>>} */
13
- schemas = new Map();
14
- /** @type {Map<string, Record<string, any>>} */
15
- caches = new Map();
16
-
17
- constructor({ config, logger }) {
18
- this.logger = logger;
19
- this.config = config;
20
- }
21
-
22
- /**
23
- * @param name {string}
24
- * @param schema {Record<string, any>}
25
- */
26
- addSchema = (name, schema) => {
27
- this.schemas.set(name, _.cloneDeep(schema));
28
- };
29
-
30
- /**
31
- * @param ref {string}
32
- * @returns {any}
33
- */
34
- findByRef = (ref) => {
35
- this.logger.debug("try to resolve ref by path", ref);
36
-
37
- if (this.caches.has(ref)) {
38
- return this.caches.get(ref);
39
- }
40
-
41
- const schemas = Array.from(this.schemas.values());
42
- if (this._isLocalRef(ref)) {
43
- for (const schema of schemas) {
44
- const refData = this._getRefDataFromSchema(schema, ref);
45
- if (refData) {
46
- return refData;
47
- }
48
- }
49
- } else if (this._isRemoteRef(ref)) {
50
- this.logger.debug("remote refs not supported", ref);
51
- return null;
52
- } else {
53
- const [address, path] = path.split("#");
54
- let swaggerSchemaObject;
55
-
56
- if (this.schemas.has(address)) {
57
- swaggerSchemaObject = this.schemas.get(address);
58
- } else {
59
- const pathToSchema = path.resolve(process.cwd(), address);
60
- const swaggerSchemaFile =
61
- this.swaggerSchemaResolver.getSwaggerSchemaByPath(pathToSchema);
62
- swaggerSchemaObject =
63
- this.swaggerSchemaResolver.processSwaggerSchemaFile(
64
- swaggerSchemaFile,
65
- );
66
- this.schemas.set(address, swaggerSchemaObject);
67
- }
68
-
69
- return this._getRefDataFromSchema(swaggerSchemaObject, path);
70
- }
71
- };
72
-
73
- _isLocalRef = (ref) => {
74
- return ref.startsWith("#");
75
- };
76
-
77
- _isRemoteRef = (ref) => {
78
- return ref.startsWith("http://") || ref.startsWith("https://");
79
- };
80
-
81
- _getRefDataFromSchema = (schema, ref) => {
82
- const path = ref.replace("#", "").split("/");
83
- const refData = _.get(schema, path);
84
- if (refData) {
85
- this.caches.set(ref, refData);
86
- }
87
- return refData;
88
- };
89
- }
90
-
91
- module.exports = {
92
- SchemaWalker,
93
- };
@@ -1,197 +0,0 @@
1
- const _ = require("lodash");
2
- const converter = require("swagger2openapi");
3
- const yaml = require("js-yaml");
4
- const { Request } = require("./util/request");
5
-
6
- class SwaggerSchemaResolver {
7
- /**
8
- * @type {CodeGenConfig}
9
- */
10
- config;
11
- /**
12
- * @type {Logger}
13
- */
14
- logger;
15
- /**
16
- * @type {FileSystem}
17
- */
18
- fileSystem;
19
- /**
20
- * @type {Request}
21
- */
22
- request;
23
-
24
- constructor({ config, logger, fileSystem }) {
25
- this.config = config;
26
- this.logger = logger;
27
- this.fileSystem = fileSystem;
28
- this.request = new Request(config, logger);
29
- }
30
-
31
- /**
32
- *
33
- * @returns {Promise<{usageSchema: Record<string, *>, originalSchema: Record<string, *>}>}
34
- */
35
- async create() {
36
- const {
37
- spec,
38
- patch,
39
- input,
40
- url,
41
- disableStrictSSL,
42
- disableProxy,
43
- authorizationToken,
44
- } = this.config;
45
-
46
- if (this.config.spec) {
47
- return await this.convertSwaggerObject(spec, { patch });
48
- }
49
-
50
- const swaggerSchemaFile = await this.fetchSwaggerSchemaFile(
51
- input,
52
- url,
53
- disableStrictSSL,
54
- disableProxy,
55
- authorizationToken,
56
- );
57
- const swaggerSchemaObject =
58
- this.processSwaggerSchemaFile(swaggerSchemaFile);
59
- return await this.convertSwaggerObject(swaggerSchemaObject, { patch });
60
- }
61
-
62
- /**
63
- *
64
- * @param swaggerSchema {Record<string, any>}
65
- * @param converterOptions {{ patch?: boolean }}
66
- * @returns {Promise<{ usageSchema: Record<string, any>, originalSchema: Record<string, any>}>}
67
- */
68
- convertSwaggerObject(swaggerSchema, converterOptions) {
69
- return new Promise((resolve) => {
70
- const result = _.cloneDeep(swaggerSchema);
71
- result.info = _.merge(
72
- {
73
- title: "No title",
74
- version: "",
75
- },
76
- result.info,
77
- );
78
-
79
- if (!result.openapi) {
80
- result.paths = _.merge({}, result.paths);
81
-
82
- converter.convertObj(
83
- result,
84
- {
85
- ...converterOptions,
86
- warnOnly: true,
87
- refSiblings: "preserve",
88
- rbname: "requestBodyName",
89
- },
90
- (err, options) => {
91
- const parsedSwaggerSchema = _.get(
92
- err,
93
- "options.openapi",
94
- _.get(options, "openapi"),
95
- );
96
- if (!parsedSwaggerSchema && err) {
97
- throw new Error(err);
98
- }
99
- this.config.update({ convertedFromSwagger2: true });
100
- resolve({
101
- usageSchema: parsedSwaggerSchema,
102
- originalSchema: result,
103
- });
104
- },
105
- );
106
- } else {
107
- resolve({
108
- usageSchema: result,
109
- originalSchema: _.cloneDeep(result),
110
- });
111
- }
112
- });
113
- }
114
-
115
- getSwaggerSchemaByPath = (pathToSwagger) => {
116
- this.logger.log(`try to get swagger by path "${pathToSwagger}"`);
117
- return this.fileSystem.getFileContent(pathToSwagger);
118
- };
119
-
120
- async fetchSwaggerSchemaFile(
121
- pathToSwagger,
122
- urlToSwagger,
123
- disableStrictSSL,
124
- disableProxy,
125
- authToken,
126
- ) {
127
- if (this.fileSystem.pathIsExist(pathToSwagger)) {
128
- return this.getSwaggerSchemaByPath(pathToSwagger);
129
- } else {
130
- this.logger.log(`try to get swagger by URL "${urlToSwagger}"`);
131
- return await this.request.download({
132
- url: urlToSwagger,
133
- disableStrictSSL,
134
- authToken,
135
- disableProxy,
136
- });
137
- }
138
- }
139
-
140
- processSwaggerSchemaFile(file) {
141
- if (typeof file !== "string") return file;
142
-
143
- try {
144
- return JSON.parse(file);
145
- } catch (e) {
146
- return yaml.load(file);
147
- }
148
- }
149
-
150
- fixSwaggerSchema({ usageSchema, originalSchema }) {
151
- const usagePaths = _.get(usageSchema, "paths");
152
- const originalPaths = _.get(originalSchema, "paths");
153
-
154
- // walk by routes
155
- _.each(usagePaths, (usagePathObject, route) => {
156
- const originalPathObject = _.get(originalPaths, route);
157
-
158
- // walk by methods
159
- _.each(usagePathObject, (usageRouteInfo, methodName) => {
160
- const originalRouteInfo = _.get(originalPathObject, methodName);
161
- const usageRouteParams = _.get(usageRouteInfo, "parameters", []);
162
- const originalRouteParams = _.get(originalRouteInfo, "parameters", []);
163
-
164
- if (typeof usageRouteInfo === "object") {
165
- usageRouteInfo.consumes = _.uniq(
166
- _.compact([
167
- ...(usageRouteInfo.consumes || []),
168
- ...(originalRouteInfo.consumes || []),
169
- ]),
170
- );
171
- usageRouteInfo.produces = _.uniq(
172
- _.compact([
173
- ...(usageRouteInfo.produces || []),
174
- ...(originalRouteInfo.produces || []),
175
- ]),
176
- );
177
- }
178
-
179
- _.each(originalRouteParams, (originalRouteParam) => {
180
- const existUsageParam = _.find(
181
- usageRouteParams,
182
- (param) =>
183
- originalRouteParam.in === param.in &&
184
- originalRouteParam.name === param.name,
185
- );
186
- if (!existUsageParam) {
187
- usageRouteParams.push(originalRouteParam);
188
- }
189
- });
190
- });
191
- });
192
- }
193
- }
194
-
195
- module.exports = {
196
- SwaggerSchemaResolver,
197
- };
@@ -1,243 +0,0 @@
1
- const { resolve } = require("node:path");
2
- const _ = require("lodash");
3
- const Eta = require("eta");
4
- const path = require("node:path");
5
-
6
- class TemplatesWorker {
7
- /**
8
- * @type {CodeGenConfig}
9
- */
10
- config;
11
-
12
- /**
13
- * @type {Logger}
14
- */
15
- logger;
16
-
17
- /**
18
- * @type {FileSystem}
19
- */
20
- fileSystem;
21
-
22
- getRenderTemplateData;
23
-
24
- constructor({ config, logger, fileSystem, getRenderTemplateData }) {
25
- this.config = config;
26
- this.logger = logger;
27
- this.fileSystem = fileSystem;
28
- this.getRenderTemplateData = getRenderTemplateData;
29
- }
30
-
31
- /**
32
- *
33
- * @param config {CodeGenConfig}
34
- * @returns {CodeGenConfig.templatePaths}
35
- */
36
- getTemplatePaths = (config) => {
37
- const baseTemplatesPath = resolve(__dirname, "../templates/base");
38
- const defaultTemplatesPath = resolve(__dirname, "../templates/default");
39
- const modularTemplatesPath = resolve(__dirname, "../templates/modular");
40
- const originalTemplatesPath = config.modular
41
- ? modularTemplatesPath
42
- : defaultTemplatesPath;
43
- const customTemplatesPath =
44
- (config.templates && resolve(process.cwd(), config.templates)) || null;
45
-
46
- return {
47
- /** `templates/base` */
48
- base: baseTemplatesPath,
49
- /** `templates/default` */
50
- default: defaultTemplatesPath,
51
- /** `templates/modular` */
52
- modular: modularTemplatesPath,
53
- /** usage path if `--templates` option is not set */
54
- original: originalTemplatesPath,
55
- /** custom path to templates (`--templates`) */
56
- custom: customTemplatesPath,
57
- };
58
- };
59
-
60
- cropExtension = (path) =>
61
- this.config.templateExtensions.reduce(
62
- (path, ext) => (_.endsWith(path, ext) ? path.replace(ext, "") : path),
63
- path,
64
- );
65
-
66
- getTemplateFullPath = (path, fileName) => {
67
- const raw = resolve(path, "./", this.cropExtension(fileName));
68
- const pathVariants = this.config.templateExtensions.map(
69
- (extension) => `${raw}${extension}`,
70
- );
71
-
72
- return pathVariants.find(
73
- (variant) => !!this.fileSystem.pathIsExist(variant),
74
- );
75
- };
76
-
77
- requireFnFromTemplate = (packageOrPath) => {
78
- const isPath =
79
- _.startsWith(packageOrPath, "./") || _.startsWith(packageOrPath, "../");
80
-
81
- if (isPath) {
82
- return require(
83
- path.resolve(
84
- this.config.templatePaths.custom ||
85
- this.config.templatePaths.original,
86
- packageOrPath,
87
- ),
88
- );
89
- }
90
-
91
- return require(packageOrPath);
92
- };
93
-
94
- getTemplate = ({ fileName, name, path }) => {
95
- const { templatePaths } = this.config;
96
-
97
- if (path) {
98
- return this.fileSystem.getFileContent(path);
99
- }
100
-
101
- if (!fileName) return "";
102
-
103
- const customFullPath =
104
- templatePaths.custom &&
105
- this.getTemplateFullPath(templatePaths.custom, fileName);
106
- let fileContent =
107
- customFullPath && this.fileSystem.getFileContent(customFullPath);
108
-
109
- if (fileContent) {
110
- this.logger.log(
111
- `"${_.lowerCase(name)}" template found in "${templatePaths.custom}"`,
112
- );
113
- return fileContent;
114
- }
115
-
116
- const baseFullPath = this.getTemplateFullPath(templatePaths.base, fileName);
117
-
118
- if (baseFullPath) {
119
- fileContent = this.fileSystem.getFileContent(baseFullPath);
120
- } else {
121
- if (templatePaths.custom) {
122
- this.logger.warn(
123
- `"${_.lowerCase(name)}" template not found in "${
124
- templatePaths.custom
125
- }"`,
126
- "\nCode generator will use the default template",
127
- );
128
- } else {
129
- this.logger.log(
130
- `Code generator will use the default template for "${_.lowerCase(
131
- name,
132
- )}"`,
133
- );
134
- }
135
- }
136
-
137
- const originalFullPath = this.getTemplateFullPath(
138
- templatePaths.original,
139
- fileName,
140
- );
141
-
142
- if (originalFullPath) {
143
- fileContent = this.fileSystem.getFileContent(originalFullPath);
144
- }
145
-
146
- return fileContent;
147
- };
148
-
149
- getTemplates = ({ templatePaths }) => {
150
- if (templatePaths.custom) {
151
- this.logger.log(
152
- `try to read templates from directory "${templatePaths.custom}"`,
153
- );
154
- }
155
-
156
- return _.reduce(
157
- this.config.templateInfos,
158
- (acc, { fileName, name }) => ({
159
- ...acc,
160
- [name]: this.getTemplate({ fileName, name }),
161
- }),
162
- {},
163
- );
164
- };
165
-
166
- findTemplateWithExt = (path) => {
167
- const raw = this.cropExtension(path);
168
- const pathVariants = this.config.templateExtensions.map(
169
- (extension) => `${raw}${extension}`,
170
- );
171
- return pathVariants.find((variant) => this.fileSystem.pathIsExist(variant));
172
- };
173
-
174
- getTemplateContent = (path) => {
175
- const foundTemplatePathKey = _.keys(this.config.templatePaths).find((key) =>
176
- _.startsWith(path, `@${key}`),
177
- );
178
-
179
- const rawPath = resolve(
180
- _.replace(
181
- path,
182
- `@${foundTemplatePathKey}`,
183
- this.config.templatePaths[foundTemplatePathKey],
184
- ),
185
- );
186
- const fixedPath = this.findTemplateWithExt(rawPath);
187
-
188
- if (fixedPath) {
189
- return this.fileSystem.getFileContent(fixedPath);
190
- }
191
-
192
- const customPath =
193
- this.config.templatePaths.custom &&
194
- this.findTemplateWithExt(resolve(this.config.templatePaths.custom, path));
195
-
196
- if (customPath) {
197
- return this.fileSystem.getFileContent(customPath);
198
- }
199
-
200
- const originalPath = this.findTemplateWithExt(
201
- resolve(this.config.templatePaths.original, path),
202
- );
203
-
204
- if (originalPath) {
205
- return this.fileSystem.getFileContent(originalPath);
206
- }
207
-
208
- return "";
209
- };
210
-
211
- /**
212
- * @param template
213
- * @param configuration
214
- * @param options
215
- * @returns {Promise<string|string|void>}
216
- */
217
- renderTemplate = (template, configuration, options) => {
218
- if (!template) return "";
219
-
220
- return Eta.render(
221
- template,
222
- {
223
- ...this.getRenderTemplateData(),
224
- ...configuration,
225
- },
226
- {
227
- async: false,
228
- ...(options || {}),
229
- includeFile: (path, configuration, options) => {
230
- return this.renderTemplate(
231
- this.getTemplateContent(path),
232
- configuration,
233
- options,
234
- );
235
- },
236
- },
237
- );
238
- };
239
- }
240
-
241
- module.exports = {
242
- TemplatesWorker,
243
- };
@@ -1,83 +0,0 @@
1
- const ts = require("typescript");
2
- const { Translator } = require("./translator");
3
-
4
- class JavascriptTranslator extends Translator {
5
- /**
6
- * @param {TranslatorIO} input
7
- * @returns {Record<string, string>}
8
- */
9
- compileTSCode = (input) => {
10
- const fileNameFull = `${input.fileName}${input.fileExtension}`;
11
- const output = {};
12
- const host = ts.createCompilerHost(this.config.compilerTsConfig, true);
13
- const fileNames = [fileNameFull];
14
- const originalSourceFileGet = host.getSourceFile.bind(host);
15
- host.getSourceFile = (
16
- sourceFileName,
17
- languageVersion,
18
- onError,
19
- shouldCreateNewSourceFile,
20
- ) => {
21
- if (sourceFileName !== fileNameFull)
22
- return originalSourceFileGet(
23
- sourceFileName,
24
- languageVersion,
25
- onError,
26
- shouldCreateNewSourceFile,
27
- );
28
-
29
- return ts.createSourceFile(
30
- sourceFileName,
31
- input.fileContent,
32
- languageVersion,
33
- true,
34
- ts.ScriptKind.TS,
35
- );
36
- };
37
-
38
- host.writeFile = (fileName, contents) => {
39
- output[fileName] = contents;
40
- };
41
-
42
- ts.createProgram(fileNames, this.config.compilerTsConfig, host).emit();
43
-
44
- return output;
45
- };
46
-
47
- translate = async (input) => {
48
- const compiled = this.compileTSCode(input);
49
-
50
- const jsFileName = `${input.fileName}${ts.Extension.Js}`;
51
- const dtsFileName = `${input.fileName}${ts.Extension.Dts}`;
52
- const sourceContent = compiled[jsFileName];
53
- const tsImportRows = input.fileContent
54
- .split("\n")
55
- .filter((line) => line.startsWith("import "));
56
- const declarationContent = compiled[dtsFileName]
57
- .split("\n")
58
- .map((line) => {
59
- if (line.startsWith("import ")) {
60
- return tsImportRows.shift();
61
- }
62
- return line;
63
- })
64
- .join("\n");
65
-
66
- return [
67
- {
68
- fileName: input.fileName,
69
- fileExtension: ts.Extension.Js,
70
- fileContent: await this.codeFormatter.formatCode(sourceContent),
71
- },
72
- {
73
- fileName: input.fileName,
74
- fileExtension: ts.Extension.Dts,
75
- fileContent: await this.codeFormatter.formatCode(declarationContent),
76
- },
77
- ];
78
- };
79
- }
80
-
81
- module.exports = {
82
- JavascriptTranslator,
83
- };
@@ -1,35 +0,0 @@
1
- /**
2
- * @typedef {{ fileName: string, fileExtension: string, fileContent: string }} TranslatorIO
3
- */
4
-
5
- class Translator {
6
- /** @type {Logger} */
7
- logger;
8
- /** @type {CodeGenConfig} */
9
- config;
10
- /** @type {CodeFormatter} */
11
- codeFormatter;
12
-
13
- /**
14
- * @param codeGenProcess
15
- */
16
- constructor(codeGenProcess) {
17
- this.logger = codeGenProcess.logger;
18
- this.config = codeGenProcess.config;
19
- this.codeFormatter = codeGenProcess.codeFormatter;
20
- }
21
-
22
- /**
23
- *
24
- * @param input {TranslatorIO}
25
- * @return {Promise<TranslatorIO[]>}
26
- */
27
- // eslint-disable-next-line no-unused-vars
28
- translate(input) {
29
- throw new Error("not implemented");
30
- }
31
- }
32
-
33
- module.exports = {
34
- Translator,
35
- };