@accelbyte/codegen 3.1.0 → 4.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/PATCHING.md +1 -1
- package/README.md +3 -3
- package/dist/accelbyte-codegen.js +1336 -1200
- package/dist/accelbyte-codegen.js.map +1 -1
- package/dist/accelbyte-codegen.mjs +1248 -1111
- package/dist/accelbyte-codegen.mjs.map +1 -1
- package/package.json +22 -6
- package/scripts/get-swaggers-configs.mjs +54 -0
|
@@ -1,97 +1,180 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var
|
|
6
|
-
var
|
|
7
|
-
var
|
|
8
|
-
var
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
var https = require('https');
|
|
14
|
-
|
|
15
|
-
function _interopNamespaceDefault(e) {
|
|
16
|
-
var n = Object.create(null);
|
|
17
|
-
if (e) {
|
|
18
|
-
Object.keys(e).forEach(function (k) {
|
|
19
|
-
if (k !== 'default') {
|
|
20
|
-
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
21
|
-
Object.defineProperty(n, k, d.get ? d : {
|
|
22
|
-
enumerable: true,
|
|
23
|
-
get: function () { return e[k]; }
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
});
|
|
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 __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
+
for (let key of __getOwnPropNames(from))
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
12
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
27
13
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
14
|
+
return to;
|
|
15
|
+
};
|
|
16
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
17
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
18
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
19
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
20
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
21
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
22
|
+
mod
|
|
23
|
+
));
|
|
31
24
|
|
|
32
|
-
|
|
33
|
-
var
|
|
34
|
-
var
|
|
25
|
+
// src/cli.ts
|
|
26
|
+
var import_yargs = __toESM(require("yargs"));
|
|
27
|
+
var import_path4 = __toESM(require("path"));
|
|
35
28
|
|
|
36
|
-
|
|
37
|
-
|
|
29
|
+
// src/CliParser.ts
|
|
30
|
+
var import_fs = __toESM(require("fs"));
|
|
31
|
+
var path = __toESM(require("path"));
|
|
32
|
+
var import_zod = require("zod");
|
|
33
|
+
var SwaggersConfig = import_zod.z.array(import_zod.z.array(import_zod.z.string()));
|
|
34
|
+
var CliParser = class _CliParser {
|
|
38
35
|
static _instance;
|
|
39
36
|
argv;
|
|
40
|
-
constructor(
|
|
41
|
-
this.argv =
|
|
37
|
+
constructor(yargs2) {
|
|
38
|
+
this.argv = yargs2.parse();
|
|
42
39
|
}
|
|
43
|
-
static createInstance = (
|
|
44
|
-
|
|
45
|
-
return
|
|
40
|
+
static createInstance = (yargs2) => {
|
|
41
|
+
_CliParser._instance = new _CliParser(yargs2);
|
|
42
|
+
return _CliParser._instance;
|
|
46
43
|
};
|
|
47
|
-
static instance = (
|
|
48
|
-
if (!
|
|
49
|
-
return
|
|
44
|
+
static instance = (yargs2) => {
|
|
45
|
+
if (!_CliParser._instance && yargs2) {
|
|
46
|
+
return _CliParser.createInstance(yargs2);
|
|
50
47
|
}
|
|
51
|
-
return
|
|
48
|
+
return _CliParser._instance;
|
|
52
49
|
};
|
|
53
50
|
static getConfigPath = () => {
|
|
54
|
-
return
|
|
51
|
+
return _CliParser.instance().argv.config;
|
|
55
52
|
};
|
|
56
53
|
static getConfigFile = () => {
|
|
57
|
-
const configPath =
|
|
58
|
-
if (!configPath)
|
|
59
|
-
|
|
60
|
-
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
|
|
54
|
+
const configPath = _CliParser.getConfigPath();
|
|
55
|
+
if (!configPath) throw new Error("Missing config file");
|
|
56
|
+
const config = JSON.parse(import_fs.default.readFileSync(configPath, "utf8"));
|
|
61
57
|
if (!SwaggersConfig.safeParse(config).success) {
|
|
62
58
|
throw new Error("Wrong config file format");
|
|
63
59
|
}
|
|
64
60
|
return config;
|
|
65
61
|
};
|
|
66
62
|
static getOutputPath = () => {
|
|
67
|
-
return
|
|
63
|
+
return _CliParser.instance().argv.output;
|
|
68
64
|
};
|
|
69
65
|
static getSwaggersOutputPath = () => {
|
|
70
|
-
return
|
|
66
|
+
return _CliParser.instance().argv.swaggersOutput;
|
|
71
67
|
};
|
|
72
68
|
static getResolvedSwaggersOutputPath = () => {
|
|
73
|
-
return
|
|
69
|
+
return path.resolve(_CliParser.getSwaggersOutputPath());
|
|
74
70
|
};
|
|
75
71
|
static getSnippetOutputPath = () => {
|
|
76
|
-
return
|
|
72
|
+
return _CliParser.instance().argv.snippetOutput;
|
|
77
73
|
};
|
|
78
|
-
static
|
|
79
|
-
return
|
|
74
|
+
static skipReactQuery = () => {
|
|
75
|
+
return _CliParser.instance().argv.skipReactQuery;
|
|
80
76
|
};
|
|
77
|
+
static isGenerateSnippetOnly = () => {
|
|
78
|
+
return _CliParser.instance().argv.snippetOnly;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// src/CodeGenerator.ts
|
|
83
|
+
var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser"));
|
|
84
|
+
var import_fs4 = __toESM(require("fs"));
|
|
85
|
+
var import_path3 = __toESM(require("path"));
|
|
86
|
+
|
|
87
|
+
// src/ParserUtils.ts
|
|
88
|
+
var import_fast_json_patch = require("fast-json-patch");
|
|
89
|
+
var import_fs3 = __toESM(require("fs"));
|
|
90
|
+
var import_lodash = __toESM(require("lodash"));
|
|
91
|
+
var import_path2 = __toESM(require("path"));
|
|
92
|
+
|
|
93
|
+
// src/helpers/utils.ts
|
|
94
|
+
var import_fs2 = __toESM(require("fs"));
|
|
95
|
+
var import_path = __toESM(require("path"));
|
|
96
|
+
var capitalize = (string) => {
|
|
97
|
+
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
98
|
+
};
|
|
99
|
+
function isObject(o) {
|
|
100
|
+
return o instanceof Object && o.constructor === Object;
|
|
81
101
|
}
|
|
102
|
+
var getPermission = (endpoint) => {
|
|
103
|
+
const xSecurity = endpoint["x-security"];
|
|
104
|
+
let xSecurityPerm = void 0;
|
|
105
|
+
if (Array.isArray(xSecurity)) {
|
|
106
|
+
for (const obj of xSecurity) {
|
|
107
|
+
if (obj?.userPermissions) {
|
|
108
|
+
xSecurityPerm = obj.userPermissions;
|
|
109
|
+
}
|
|
110
|
+
if (obj?.groupPermissions) {
|
|
111
|
+
xSecurityPerm = obj.groupPermissions;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
} else if (isObject(xSecurity)) {
|
|
115
|
+
xSecurityPerm = xSecurity?.userPermission;
|
|
116
|
+
}
|
|
117
|
+
return xSecurityPerm;
|
|
118
|
+
};
|
|
119
|
+
var PermissionRegex = /\[(\w+)\]/;
|
|
120
|
+
var getPermissionType = (permission) => {
|
|
121
|
+
if (!permission) return null;
|
|
122
|
+
if (Array.isArray(permission)) {
|
|
123
|
+
const perm = permission?.[0];
|
|
124
|
+
if (!perm) return null;
|
|
125
|
+
const [_3, type2] = perm?.match(PermissionRegex);
|
|
126
|
+
return type2 || null;
|
|
127
|
+
}
|
|
128
|
+
const [_2, type] = permission?.match(PermissionRegex);
|
|
129
|
+
return type || null;
|
|
130
|
+
};
|
|
131
|
+
var removeAdminPrefix = (name) => name.startsWith("Admin") && name !== "Admin" ? name.replace(/^Admin/, "") : name;
|
|
132
|
+
var escapeComment = (string) => string.replace(/\*\//g, "*\\/").replace(/\n/g, "\n * ");
|
|
133
|
+
var generateJsDoc = ({ indentation = 4, lines }) => {
|
|
134
|
+
const indent = " ".repeat(indentation);
|
|
135
|
+
const formattedLines = lines.filter(Boolean).map((line) => `${indent} * ${line}`).join("\n");
|
|
136
|
+
return `${indent}/**
|
|
137
|
+
${formattedLines}
|
|
138
|
+
${indent} */`;
|
|
139
|
+
};
|
|
140
|
+
var extractDescription = (description, options) => {
|
|
141
|
+
const { indentation = 2, responseClasses, other, isDeprecated } = options;
|
|
142
|
+
return description ? generateJsDoc({
|
|
143
|
+
lines: [
|
|
144
|
+
isDeprecated ? "@deprecated" : "",
|
|
145
|
+
escapeComment(description),
|
|
146
|
+
...responseClasses.length > 1 ? [" ", "#### Response type:", ...responseClasses.map((val) => `- \`${val}\``)] : "",
|
|
147
|
+
...options?.other ? other : ""
|
|
148
|
+
],
|
|
149
|
+
indentation
|
|
150
|
+
}) : "";
|
|
151
|
+
};
|
|
152
|
+
var getResponseType = ({
|
|
153
|
+
responseClasses,
|
|
154
|
+
defaultType = "unknown"
|
|
155
|
+
}) => {
|
|
156
|
+
const responseClass = responseClasses.length === 1 ? responseClasses?.[0] : "unknown";
|
|
157
|
+
const responseType = responseClass !== "unknown" ? responseClasses?.[0] : defaultType;
|
|
158
|
+
return {
|
|
159
|
+
responseType,
|
|
160
|
+
responseTypeInAxiosResponse: `Promise<AxiosResponse<${responseType}>>`,
|
|
161
|
+
responseTypeInResponse: `Promise<Response<${responseType}>>`
|
|
162
|
+
};
|
|
163
|
+
};
|
|
82
164
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
165
|
+
// src/templates/template-class.ts
|
|
166
|
+
var getImportableVarMap = () => ({
|
|
167
|
+
"@accelbyte/sdk": ["CodeGenUtil", "Response", "Validate", "SdkSetConfigParam"],
|
|
168
|
+
axios: ["AxiosResponse"],
|
|
86
169
|
zod: ["z"]
|
|
87
170
|
});
|
|
88
|
-
|
|
89
|
-
axios: ["AxiosInstance"],
|
|
171
|
+
var makeNewImportVarMap = () => ({
|
|
172
|
+
axios: ["AxiosInstance", "AxiosRequestConfig"],
|
|
90
173
|
"@accelbyte/sdk": ["SDKRequestConfig"]
|
|
91
174
|
});
|
|
92
|
-
|
|
93
|
-
const usedImportVarMap =
|
|
94
|
-
const importableVarMap =
|
|
175
|
+
var generateImports = (body, importStatements, makeNewImportVarMap3, getImportableVarMap3) => {
|
|
176
|
+
const usedImportVarMap = makeNewImportVarMap3;
|
|
177
|
+
const importableVarMap = getImportableVarMap3;
|
|
95
178
|
for (const [moduleSource, importableVars] of Object.entries(importableVarMap)) {
|
|
96
179
|
for (const importableVar of importableVars) {
|
|
97
180
|
const importVarRegex = new RegExp(`(?<![\\d\\w_])${importableVar}(?![\\d\\w_])`);
|
|
@@ -106,33 +189,125 @@ const generateImports$1 = (body, importStatements, makeNewImportVarMap2, getImpo
|
|
|
106
189
|
return `${generatedImports}
|
|
107
190
|
${importStatements.sort().join("\n")}`;
|
|
108
191
|
};
|
|
109
|
-
|
|
192
|
+
var templateClass = (className, body, importStatements) => {
|
|
110
193
|
return `/**
|
|
111
194
|
* AUTO GENERATED
|
|
112
195
|
*/
|
|
113
|
-
${generateImports
|
|
196
|
+
${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
|
|
114
197
|
|
|
115
198
|
export class ${className} {
|
|
116
199
|
// @ts-ignore
|
|
200
|
+
// prettier-ignore
|
|
117
201
|
constructor(private axiosInstance: AxiosInstance, private namespace: string, private useSchemaValidation = true) {}
|
|
118
202
|
${body}
|
|
119
203
|
}
|
|
120
204
|
`;
|
|
121
205
|
};
|
|
122
206
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
207
|
+
// src/templates/template-api-class.ts
|
|
208
|
+
var getImportableVarMap2 = () => ({
|
|
209
|
+
"@accelbyte/sdk": ["CodeGenUtil", "Response", "Validate", "SdkSetConfigParam", "Network", "AccelByteSDK"],
|
|
210
|
+
axios: ["AxiosDefaults", "HeadersDefaults"]
|
|
211
|
+
});
|
|
212
|
+
var makeNewImportVarMap2 = () => ({
|
|
213
|
+
"@accelbyte/sdk": ["AccelByteSDK", "SdkSetConfigParam", "ApiUtils", "Network"],
|
|
214
|
+
axios: ["AxiosRequestConfig", "AxiosResponse"]
|
|
215
|
+
});
|
|
216
|
+
var templateApiClass = (className, body, importStatements, returnMethods) => {
|
|
217
|
+
const returnsMethodsWithDescription = Object.keys(returnMethods).reduce((acc, key) => {
|
|
218
|
+
acc += `
|
|
219
|
+
${returnMethods[key]}
|
|
220
|
+
${key},`;
|
|
221
|
+
return acc;
|
|
222
|
+
}, "");
|
|
223
|
+
const $className = className.replace(/Api$/, "$");
|
|
224
|
+
return `/**
|
|
225
|
+
* AUTO GENERATED
|
|
226
|
+
*/
|
|
227
|
+
/* eslint-disable camelcase */
|
|
228
|
+
// @ts-ignore -> ts-expect-error TS6133
|
|
229
|
+
${generateImports(body, importStatements, makeNewImportVarMap2(), getImportableVarMap2())}
|
|
230
|
+
${`import { ${$className} } from './endpoints/${$className}.js'
|
|
231
|
+
`}
|
|
232
|
+
|
|
233
|
+
export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
234
|
+
const sdkAssembly = sdk.assembly()
|
|
235
|
+
|
|
236
|
+
const namespace = args?.coreConfig?.namespace ?? sdkAssembly.coreConfig.namespace
|
|
237
|
+
const useSchemaValidation = args?.coreConfig?.useSchemaValidation ?? sdkAssembly.coreConfig.useSchemaValidation
|
|
238
|
+
|
|
239
|
+
let axiosInstance = sdkAssembly.axiosInstance
|
|
240
|
+
const requestConfigOverrides = args?.axiosConfig?.request
|
|
241
|
+
const baseURLOverride = args?.coreConfig?.baseURL
|
|
242
|
+
const interceptorsOverride = args?.axiosConfig?.interceptors ?? []
|
|
243
|
+
|
|
244
|
+
if (requestConfigOverrides || baseURLOverride || interceptorsOverride.length > 0) {
|
|
245
|
+
const requestConfig = ApiUtils.mergeAxiosConfigs(sdkAssembly.axiosInstance.defaults as AxiosRequestConfig, {
|
|
246
|
+
...(baseURLOverride ? { baseURL: baseURLOverride } : {}),
|
|
247
|
+
...requestConfigOverrides
|
|
248
|
+
})
|
|
249
|
+
axiosInstance = Network.create(requestConfig)
|
|
250
|
+
|
|
251
|
+
for (const interceptor of interceptorsOverride) {
|
|
252
|
+
if (interceptor.type === 'request') {
|
|
253
|
+
axiosInstance.interceptors.request.use(interceptor.onRequest, interceptor.onError)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (interceptor.type === 'response') {
|
|
257
|
+
axiosInstance.interceptors.response.use(interceptor.onSuccess, interceptor.onError)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
${body}
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
${returnsMethodsWithDescription}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
`;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// src/ParserQueryUtils.ts
|
|
272
|
+
var ParserQueryUtils = class {
|
|
273
|
+
/**
|
|
274
|
+
* convert csv 'aa,bb' into "aa='aa', bb='bb'"
|
|
275
|
+
*/
|
|
276
|
+
static createQueryKeys(classNameWithoutApi, csvMethodNames, sdkName) {
|
|
277
|
+
const keys = csvMethodNames.split(",");
|
|
278
|
+
const processedKeys = /* @__PURE__ */ new Set();
|
|
279
|
+
const enumString = keys.reduce((acc, key, index) => {
|
|
280
|
+
const trimmedKey = key.trim();
|
|
281
|
+
if (trimmedKey) {
|
|
282
|
+
const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete|post|fetch)[_]?/, "");
|
|
283
|
+
if (!processedKeys.has(cleanedKey)) {
|
|
284
|
+
processedKeys.add(cleanedKey);
|
|
285
|
+
acc += `${cleanedKey} = '${capitalize(sdkName)}.${classNameWithoutApi}.${cleanedKey}'`;
|
|
286
|
+
if (index < keys.length - 1) {
|
|
287
|
+
acc += ",\n";
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return acc;
|
|
292
|
+
}, "");
|
|
293
|
+
return enumString;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
// src/templates/template-query.ts
|
|
298
|
+
var generateImports2 = (body, className) => {
|
|
299
|
+
const generatedImports = `import { AccelByteSDK, SdkSetConfigParam, ApiError } from '@accelbyte/sdk'
|
|
300
|
+
import { AxiosError, AxiosResponse } from 'axios'
|
|
126
301
|
// @ts-ignore
|
|
127
302
|
import { useQuery, UseQueryOptions, UseQueryResult, useMutation, UseMutationOptions, UseMutationResult } from '@tanstack/react-query'
|
|
128
303
|
import { ${className} } from "../${className}.js"
|
|
129
304
|
`;
|
|
130
305
|
return generatedImports;
|
|
131
306
|
};
|
|
132
|
-
|
|
307
|
+
var templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports, sdkName) => {
|
|
133
308
|
const classNameWithoutApi = className.replace("Api", "");
|
|
134
|
-
const queryKeys =
|
|
135
|
-
const generatedImports =
|
|
309
|
+
const queryKeys = ParserQueryUtils.createQueryKeys(classNameWithoutApi, returnMethods, sdkName);
|
|
310
|
+
const generatedImports = generateImports2(body, className);
|
|
136
311
|
return `/**
|
|
137
312
|
* AUTO GENERATED
|
|
138
313
|
*/
|
|
@@ -148,117 +323,19 @@ export enum Key_${classNameWithoutApi} {
|
|
|
148
323
|
`;
|
|
149
324
|
};
|
|
150
325
|
function filterUsedImports(importArr, body) {
|
|
151
|
-
return importArr.filter((
|
|
152
|
-
const start =
|
|
153
|
-
const end =
|
|
326
|
+
return importArr.filter((path7) => {
|
|
327
|
+
const start = path7.indexOf("{") + 1;
|
|
328
|
+
const end = path7.indexOf("}");
|
|
154
329
|
if (start > 0 && end > start) {
|
|
155
|
-
const importName =
|
|
330
|
+
const importName = path7.slice(start, end).trim();
|
|
156
331
|
return body.includes(importName);
|
|
157
332
|
}
|
|
158
333
|
return false;
|
|
159
|
-
}).map((
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const getImportableVarMap = () => ({
|
|
163
|
-
"@accelbyte/sdk": ["CodeGenUtil", "IResponse", "Validate", "ApiArgs", "Network", "AccelbyteSDK"]
|
|
164
|
-
});
|
|
165
|
-
const makeNewImportVarMap = () => ({
|
|
166
|
-
"@accelbyte/sdk": ["AccelbyteSDK", "ApiArgs", "ApiUtils"]
|
|
167
|
-
});
|
|
168
|
-
const templateApiClass = (className, body, importStatements, returnMethods) => {
|
|
169
|
-
const $className = className.replace("Api", "$");
|
|
170
|
-
return `/**
|
|
171
|
-
* AUTO GENERATED
|
|
172
|
-
*/
|
|
173
|
-
/* eslint-disable camelcase */
|
|
174
|
-
// @ts-ignore -> ts-expect-error TS6133
|
|
175
|
-
${generateImports$1(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
|
|
176
|
-
${`import { ${$className} } from './endpoints/${$className}.js'
|
|
177
|
-
`}
|
|
178
|
-
|
|
179
|
-
export function ${className}(sdk: AccelbyteSDK, args?: ApiArgs) {
|
|
180
|
-
const sdkAssembly = sdk.assembly()
|
|
181
|
-
|
|
182
|
-
const namespace = args?.namespace ? args?.namespace : sdkAssembly.namespace
|
|
183
|
-
const requestConfig = ApiUtils.mergedConfigs(sdkAssembly.config, args)
|
|
184
|
-
const useSchemaValidation = sdkAssembly.useSchemaValidation
|
|
185
|
-
${body}
|
|
186
|
-
|
|
187
|
-
return {
|
|
188
|
-
${returnMethods}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
`;
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
const VersionBumpType = zod.z.enum(["CUTOFF", "RELEASE", "HOTFIX", "BREAKING"]);
|
|
195
|
-
class VersionHelpers {
|
|
196
|
-
static getNextVersion = ({
|
|
197
|
-
serviceVersion,
|
|
198
|
-
versionBumpType,
|
|
199
|
-
sdkVersion,
|
|
200
|
-
nextPrereleaseId
|
|
201
|
-
}) => {
|
|
202
|
-
if (versionBumpType !== void 0) {
|
|
203
|
-
const parsed = VersionBumpType.safeParse(versionBumpType);
|
|
204
|
-
if (!parsed.success) {
|
|
205
|
-
throw new Error(`Invalid process.env.VERSION_BUMP_TYPE: ${versionBumpType}`);
|
|
206
|
-
}
|
|
207
|
-
if ((parsed.data === "HOTFIX" || parsed.data === "RELEASE") && nextPrereleaseId) {
|
|
208
|
-
throw new Error(`process.env.PRERELEASE_ID should be empty when process.env.VERSION_BUMP_TYPE is "HOTFIX" or "PRELEASE".`);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
const serviceSemvers = semver.parse(serviceVersion);
|
|
212
|
-
const sdkSemvers = semver.parse(sdkVersion);
|
|
213
|
-
if (serviceSemvers === null) {
|
|
214
|
-
throw new Error(`Invalid service version: ${serviceVersion}`);
|
|
215
|
-
}
|
|
216
|
-
if (sdkSemvers === null) {
|
|
217
|
-
throw new Error(`Invalid sdk version: ${sdkVersion}`);
|
|
218
|
-
}
|
|
219
|
-
const { major: currentMajor, minor: currentMinor, patch: currentPatch, prerelease: currentPrerelease } = sdkSemvers;
|
|
220
|
-
let nextMajor = currentMajor;
|
|
221
|
-
let nextMinor = currentMinor;
|
|
222
|
-
let nextPatch = currentPatch;
|
|
223
|
-
switch (versionBumpType) {
|
|
224
|
-
case VersionBumpType.Enum.BREAKING: {
|
|
225
|
-
nextMajor++;
|
|
226
|
-
nextMinor = 0;
|
|
227
|
-
nextPatch = 0;
|
|
228
|
-
break;
|
|
229
|
-
}
|
|
230
|
-
case VersionBumpType.Enum.CUTOFF: {
|
|
231
|
-
nextMinor++;
|
|
232
|
-
nextPatch = 0;
|
|
233
|
-
break;
|
|
234
|
-
}
|
|
235
|
-
case VersionBumpType.Enum.RELEASE:
|
|
236
|
-
break;
|
|
237
|
-
case VersionBumpType.Enum.HOTFIX: {
|
|
238
|
-
nextPatch++;
|
|
239
|
-
break;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
let nextVersion = [
|
|
243
|
-
nextMajor,
|
|
244
|
-
nextMinor,
|
|
245
|
-
nextPatch
|
|
246
|
-
].join(".");
|
|
247
|
-
if (nextPrereleaseId) {
|
|
248
|
-
if (nextMinor !== currentMinor) {
|
|
249
|
-
nextVersion += `-${nextPrereleaseId}.0`;
|
|
250
|
-
} else {
|
|
251
|
-
if (currentPrerelease.length)
|
|
252
|
-
nextVersion += `-${currentPrerelease.join(".")}`;
|
|
253
|
-
nextVersion = semver.inc(nextVersion, "prerelease", void 0, nextPrereleaseId);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
return nextVersion;
|
|
257
|
-
};
|
|
334
|
+
}).map((path7) => path7).join("\n") + "\n";
|
|
258
335
|
}
|
|
259
336
|
|
|
260
|
-
|
|
261
|
-
|
|
337
|
+
// src/ParserUtils.ts
|
|
338
|
+
var REMOVED_KEYWORDS = [
|
|
262
339
|
"/admin/",
|
|
263
340
|
"/public/",
|
|
264
341
|
"/v1/",
|
|
@@ -270,52 +347,34 @@ const REMOVED_KEYWORDS = [
|
|
|
270
347
|
"/namespaces/",
|
|
271
348
|
"/{namespace}/"
|
|
272
349
|
];
|
|
273
|
-
|
|
274
|
-
static
|
|
275
|
-
const
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
const trimmedKey = key.trim();
|
|
279
|
-
const isDeprecated = key.indexOf("_DEPRECATED") > 0;
|
|
280
|
-
if (trimmedKey && !isDeprecated) {
|
|
281
|
-
const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete)[_]?/, "");
|
|
282
|
-
if (!processedKeys.has(cleanedKey)) {
|
|
283
|
-
processedKeys.add(cleanedKey);
|
|
284
|
-
acc += `${cleanedKey} = '${classNameWithoutApi}.${cleanedKey}'`;
|
|
285
|
-
if (index < keys.length - 1) {
|
|
286
|
-
acc += ",\n";
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
return acc;
|
|
291
|
-
}, "");
|
|
292
|
-
return enumString;
|
|
293
|
-
}
|
|
294
|
-
static addDeprecatedSuffix(isDeprecated, methodName) {
|
|
295
|
-
if (isDeprecated) {
|
|
296
|
-
return methodName + "_DEPRECATED";
|
|
297
|
-
} else {
|
|
298
|
-
return methodName;
|
|
299
|
-
}
|
|
350
|
+
var ParserUtils = class _ParserUtils {
|
|
351
|
+
static getVersionSuffixFromPath(path7) {
|
|
352
|
+
const version2_3_4_etc = path7.match(/\/v([2-9]|[1-9]\d+)\/+/);
|
|
353
|
+
const methodSuffix = version2_3_4_etc ? `_v${version2_3_4_etc[1]}` : "";
|
|
354
|
+
return methodSuffix;
|
|
300
355
|
}
|
|
301
356
|
static replaceAll = (text, search, replace) => {
|
|
302
357
|
return text.split(search).join(replace);
|
|
303
358
|
};
|
|
304
359
|
static generateClassName = (tag, isAdmin) => {
|
|
305
|
-
const className =
|
|
306
|
-
const
|
|
307
|
-
|
|
360
|
+
const className = import_lodash.default.upperFirst(import_lodash.default.camelCase(tag));
|
|
361
|
+
const formattedApiName = removeAdminPrefix(className);
|
|
362
|
+
const classGenName = isAdmin ? formattedApiName + "Admin$" : formattedApiName + "$";
|
|
363
|
+
return { className: formattedApiName, classGenName };
|
|
308
364
|
};
|
|
309
365
|
static generateApiName = (tag, isAdmin) => {
|
|
310
|
-
const apiName =
|
|
311
|
-
const
|
|
366
|
+
const apiName = import_lodash.default.upperFirst(import_lodash.default.camelCase(tag));
|
|
367
|
+
const formattedApiName = removeAdminPrefix(apiName);
|
|
368
|
+
const apiGenName = isAdmin ? formattedApiName + "AdminApi" : formattedApiName + "Api";
|
|
312
369
|
return { apiName, apiGenName };
|
|
313
370
|
};
|
|
314
371
|
static parseQueryParamAttributeDefault = (definition) => {
|
|
315
372
|
const attrName = definition.name.slice(definition.name.lastIndexOf(".") + 1);
|
|
316
373
|
let defaultValue = definition.default;
|
|
317
374
|
if (definition.type === "array" && Array.isArray(definition.default)) {
|
|
318
|
-
const mappedDefaultValue = definition.default.map(
|
|
375
|
+
const mappedDefaultValue = definition.default.map(
|
|
376
|
+
(defaultValue2) => typeof defaultValue2 === "string" ? `'${defaultValue2}'` : defaultValue2
|
|
377
|
+
);
|
|
319
378
|
defaultValue = `[${mappedDefaultValue.join(", ")}]`;
|
|
320
379
|
}
|
|
321
380
|
if (definition.type === "string") {
|
|
@@ -324,24 +383,21 @@ class ParserUtils {
|
|
|
324
383
|
return `${attrName}: ${defaultValue}`;
|
|
325
384
|
};
|
|
326
385
|
static parseType = (pathParam) => {
|
|
327
|
-
if (isSwaggerIntegerType(pathParam.type || pathParam?.schema?.type))
|
|
328
|
-
return "number";
|
|
386
|
+
if (isSwaggerIntegerType(pathParam.type || pathParam?.schema?.type)) return "number";
|
|
329
387
|
if (pathParam.type === "array") {
|
|
330
|
-
if (isSwaggerIntegerType(pathParam.items.type))
|
|
331
|
-
return "number[]";
|
|
388
|
+
if (isSwaggerIntegerType(pathParam.items.type)) return "number[]";
|
|
332
389
|
return `${pathParam.items.type ?? "any"}[]`;
|
|
333
390
|
}
|
|
334
391
|
if (pathParam?.schema?.type === "array") {
|
|
335
|
-
if (isSwaggerIntegerType(pathParam.schema.items.type))
|
|
336
|
-
return "number[]";
|
|
392
|
+
if (isSwaggerIntegerType(pathParam.schema.items.type)) return "number[]";
|
|
337
393
|
return `${pathParam.schema.items.type ?? "any"}[]`;
|
|
338
394
|
}
|
|
339
|
-
if (pathParam?.schema?.type)
|
|
340
|
-
return pathParam.schema.type;
|
|
395
|
+
if (pathParam?.schema?.type) return pathParam.schema.type;
|
|
341
396
|
return pathParam.type;
|
|
342
397
|
};
|
|
343
398
|
static parseQueryParamsType = (queryParams) => {
|
|
344
|
-
|
|
399
|
+
const result = queryParams.map((queryParam) => _ParserUtils.parseAttributeType(queryParam)).join(", ");
|
|
400
|
+
return result;
|
|
345
401
|
};
|
|
346
402
|
static isAnyQueryParamRequired = (queryParams) => {
|
|
347
403
|
return queryParams.some((queryParam) => queryParam.required);
|
|
@@ -356,11 +412,11 @@ class ParserUtils {
|
|
|
356
412
|
return result;
|
|
357
413
|
};
|
|
358
414
|
static parseQueryParamsDefault = (queryParams) => {
|
|
359
|
-
const result = queryParams.filter((queryParam) => !!queryParam.default && !queryParam.required).map(
|
|
415
|
+
const result = queryParams.filter((queryParam) => !!queryParam.default && !queryParam.required).map(_ParserUtils.parseQueryParamAttributeDefault).join(",");
|
|
360
416
|
return result ? `${result},` : "";
|
|
361
417
|
};
|
|
362
418
|
static parseBodyParamsImports = (bodyParams) => {
|
|
363
|
-
return bodyParams.map((bodyParams2) =>
|
|
419
|
+
return bodyParams.map((bodyParams2) => _ParserUtils.parseRefImport(bodyParams2)).filter(Boolean);
|
|
364
420
|
};
|
|
365
421
|
static parseImportDir = ($ref) => {
|
|
366
422
|
let ref = $ref.replace(".", "/");
|
|
@@ -378,7 +434,7 @@ class ParserUtils {
|
|
|
378
434
|
if (!$ref) {
|
|
379
435
|
return null;
|
|
380
436
|
}
|
|
381
|
-
const type =
|
|
437
|
+
const type = _ParserUtils.parseRefType($ref);
|
|
382
438
|
return `import { ${type} } from '../../generated-definitions/${type}.js'`;
|
|
383
439
|
};
|
|
384
440
|
static parseRefType = ($ref) => {
|
|
@@ -387,7 +443,7 @@ class ParserUtils {
|
|
|
387
443
|
ref = ref.slice(0, -1);
|
|
388
444
|
}
|
|
389
445
|
const val = ref.slice(ref.lastIndexOf("/") + 1);
|
|
390
|
-
return
|
|
446
|
+
return import_lodash.default.upperFirst(import_lodash.default.camelCase(val)).replace(/( \w)/g, (group) => group.replace(" ", "").toUpperCase());
|
|
391
447
|
};
|
|
392
448
|
static parseAttributeType = (definition) => {
|
|
393
449
|
const required = definition.required ? "" : "?";
|
|
@@ -396,10 +452,13 @@ class ParserUtils {
|
|
|
396
452
|
const enums = definition.enum.map((enm) => definition.type === "string" ? `'${enm}'` : enm).join(" | ");
|
|
397
453
|
return `${attrName}${required}: ${enums}`;
|
|
398
454
|
}
|
|
399
|
-
if (definition.type &&
|
|
455
|
+
if (definition.type && _ParserUtils.parseType(definition) === "number") {
|
|
400
456
|
return `${attrName}${required}: number`;
|
|
401
457
|
}
|
|
402
|
-
if (definition
|
|
458
|
+
if (definition.type && _ParserUtils.parseType(definition) === "number[]") {
|
|
459
|
+
return `${attrName}${required}: number[]`;
|
|
460
|
+
}
|
|
461
|
+
if (definition?.schema?.type && _ParserUtils.parseType(definition) === "number") {
|
|
403
462
|
return `${attrName}${required}: number`;
|
|
404
463
|
}
|
|
405
464
|
if (definition.type && definition.type === "array") {
|
|
@@ -424,47 +483,44 @@ class ParserUtils {
|
|
|
424
483
|
};
|
|
425
484
|
static parseBodyParamsType = (bodyParams) => {
|
|
426
485
|
const [bodyParam] = bodyParams;
|
|
427
|
-
if (!bodyParam)
|
|
428
|
-
return null;
|
|
486
|
+
if (!bodyParam) return null;
|
|
429
487
|
if (bodyParams.length > 0 && bodyParam?.name !== "body" && !bodyParam?.schema) {
|
|
430
|
-
let retBodyParams = `{${bodyParams.map((bodyParam2) =>
|
|
488
|
+
let retBodyParams = `{${bodyParams.map((bodyParam2) => _ParserUtils.parseAttributeType(bodyParam2)).join(",")}}`;
|
|
431
489
|
retBodyParams = retBodyParams.replace("file?: file", "file?: File");
|
|
432
490
|
return retBodyParams;
|
|
433
491
|
}
|
|
434
492
|
if (bodyParam?.schema?.type === "array" && !bodyParam?.schema?.items?.$ref) {
|
|
435
|
-
if (isSwaggerIntegerType(bodyParam.schema.items.type))
|
|
436
|
-
return "number[]";
|
|
493
|
+
if (isSwaggerIntegerType(bodyParam.schema.items.type)) return "number[]";
|
|
437
494
|
return `${bodyParam.schema.items.type ?? "any"}[]`;
|
|
438
495
|
}
|
|
439
496
|
if (bodyParam?.schema?.type === "array" && bodyParam?.schema?.items?.$ref) {
|
|
440
|
-
return `${
|
|
497
|
+
return `${_ParserUtils.parseRefType(bodyParam.schema.items.$ref)}[]`;
|
|
441
498
|
}
|
|
442
499
|
if (bodyParam?.schema?.$ref) {
|
|
443
|
-
return
|
|
500
|
+
return _ParserUtils.parseRefType(bodyParam.schema.$ref);
|
|
444
501
|
}
|
|
445
502
|
if (bodyParam?.schema?.additionalProperties?.type === "object") {
|
|
446
503
|
return "any";
|
|
447
504
|
}
|
|
448
505
|
return null;
|
|
449
506
|
};
|
|
450
|
-
static
|
|
507
|
+
static get2xxResponses(methodEntity) {
|
|
451
508
|
const keys = Object.keys(methodEntity);
|
|
452
|
-
|
|
453
|
-
keys.
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
} else ;
|
|
509
|
+
const responseClasses = [];
|
|
510
|
+
const statusCodes = keys.filter((key) => String(key).startsWith("2"));
|
|
511
|
+
statusCodes.forEach((key) => {
|
|
512
|
+
const sch = methodEntity[key].schema;
|
|
513
|
+
const schV3 = methodEntity[key].content && methodEntity[key].content["application/json"].schema;
|
|
514
|
+
if (sch?.$ref) {
|
|
515
|
+
responseClasses.push(_ParserUtils.parseRefType(sch.$ref));
|
|
516
|
+
} else if (sch?.type === "array" && sch.items?.$ref) {
|
|
517
|
+
responseClasses.push(`${_ParserUtils.parseRefType(sch.items.$ref)}Array`);
|
|
518
|
+
} else if (schV3?.$ref) {
|
|
519
|
+
responseClasses.push(_ParserUtils.parseRefType(schV3.$ref));
|
|
520
|
+
} else {
|
|
465
521
|
}
|
|
466
522
|
});
|
|
467
|
-
return
|
|
523
|
+
return responseClasses;
|
|
468
524
|
}
|
|
469
525
|
static isFormUrlEncoded(httpMethod, contentTypes) {
|
|
470
526
|
if (!contentTypes || contentTypes.length < 1) {
|
|
@@ -481,17 +537,24 @@ class ParserUtils {
|
|
|
481
537
|
}
|
|
482
538
|
return parameters.filter((parameter) => parameter.in === "path");
|
|
483
539
|
}
|
|
484
|
-
|
|
485
|
-
|
|
540
|
+
/**
|
|
541
|
+
* This method converts this
|
|
542
|
+
* POST `/gdpr/public/namespaces/{namespace}/users/{userId}/requests/{requestDate}/generate`
|
|
543
|
+
*
|
|
544
|
+
* to this
|
|
545
|
+
* `createGenerateByRequestIdByUserId`
|
|
546
|
+
*/
|
|
547
|
+
static generateNaturalLangMethod = ({ servicePrefix, path: path7, httpMethod, isForm, existingMethods, permissionType }) => {
|
|
548
|
+
let path_ = path7;
|
|
486
549
|
path_ = path_.replace(`/${servicePrefix}/`, "/");
|
|
487
550
|
REMOVED_KEYWORDS.forEach((prefix) => {
|
|
488
551
|
path_ = path_.replace(prefix, "/");
|
|
489
552
|
});
|
|
490
553
|
path_ = path_.substring(1);
|
|
491
|
-
const isPlural = httpMethod === "get" && !(
|
|
554
|
+
const isPlural = httpMethod === "get" && !(path7.slice(-1) === "}");
|
|
492
555
|
if (!isPlural) {
|
|
493
|
-
path_ =
|
|
494
|
-
path_ =
|
|
556
|
+
path_ = _ParserUtils.replaceAll(path_, "ies/", "y/");
|
|
557
|
+
path_ = _ParserUtils.replaceAll(path_, "s/", "/");
|
|
495
558
|
if (path_.indexOf("status") < 0) {
|
|
496
559
|
path_ = path_.replace(/ies$/, "y");
|
|
497
560
|
path_ = path_.replace(/s$/, "");
|
|
@@ -518,7 +581,7 @@ class ParserUtils {
|
|
|
518
581
|
foundParam = true;
|
|
519
582
|
let param = item.replace("{", "");
|
|
520
583
|
param = param.replace("}", "");
|
|
521
|
-
param = "Byword" +
|
|
584
|
+
param = "Byword" + import_lodash.default.upperFirst(param);
|
|
522
585
|
listByParams.push(param);
|
|
523
586
|
} else if (!foundParam) {
|
|
524
587
|
if (lastWords.indexOf(item) === -1) {
|
|
@@ -528,10 +591,12 @@ class ParserUtils {
|
|
|
528
591
|
foundParam = false;
|
|
529
592
|
}
|
|
530
593
|
});
|
|
531
|
-
const genPath =
|
|
532
|
-
let generatedMethod =
|
|
533
|
-
generatedMethod =
|
|
534
|
-
|
|
594
|
+
const genPath = import_lodash.default.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
|
|
595
|
+
let generatedMethod = import_lodash.default.camelCase(mappedMethod(httpMethod, isForm, permissionType) + genPath);
|
|
596
|
+
generatedMethod = _ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
|
|
597
|
+
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path7);
|
|
598
|
+
generatedMethod = resolveConflicts({ path: path7, generatedMethod, testedGeneratedMethod, existingMethods });
|
|
599
|
+
generatedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path7);
|
|
535
600
|
return generatedMethod;
|
|
536
601
|
};
|
|
537
602
|
static filterBodyParams(parameters) {
|
|
@@ -547,90 +612,76 @@ class ParserUtils {
|
|
|
547
612
|
return parameters.filter((parameter) => parameter.in === "query");
|
|
548
613
|
}
|
|
549
614
|
static mkdirIfNotExist(dirToCreate) {
|
|
550
|
-
if (!
|
|
551
|
-
|
|
615
|
+
if (!import_fs3.default.existsSync(dirToCreate)) {
|
|
616
|
+
import_fs3.default.mkdirSync(dirToCreate, { recursive: true });
|
|
552
617
|
}
|
|
553
618
|
}
|
|
554
619
|
static writeClassFile(distDir, apiName, apiBuffer, imports) {
|
|
555
620
|
const fileContent = templateClass(apiName, apiBuffer, imports);
|
|
556
|
-
|
|
621
|
+
import_fs3.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
557
622
|
}
|
|
558
623
|
static writeAtomFile(distDir, apiName, fileContent) {
|
|
559
|
-
|
|
560
|
-
|
|
624
|
+
_ParserUtils.mkdirIfNotExist(distDir);
|
|
625
|
+
import_fs3.default.writeFileSync(`${distDir}/${apiName}.atom.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
561
626
|
}
|
|
562
|
-
static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports) {
|
|
627
|
+
static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName) {
|
|
563
628
|
if (apiBuffer.length < 1) {
|
|
564
629
|
return null;
|
|
565
630
|
}
|
|
566
631
|
const queryFileName = `${apiName.replace("Api", "")}.query`;
|
|
567
|
-
|
|
568
|
-
const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports);
|
|
569
|
-
|
|
632
|
+
_ParserUtils.mkdirIfNotExist(distDir);
|
|
633
|
+
const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName);
|
|
634
|
+
import_fs3.default.writeFileSync(`${distDir}/${queryFileName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
570
635
|
return queryFileName;
|
|
571
636
|
}
|
|
572
637
|
static writeXVersion(distDir, xversionJson, apiInfo) {
|
|
573
638
|
if (xversionJson) {
|
|
574
639
|
console.log("x-version:", xversionJson);
|
|
575
|
-
|
|
640
|
+
import_fs3.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
|
|
576
641
|
} else {
|
|
577
642
|
const customVersion = {
|
|
578
643
|
...apiInfo,
|
|
579
644
|
gitHash: apiInfo.version
|
|
580
645
|
};
|
|
581
|
-
console.error(
|
|
582
|
-
|
|
646
|
+
console.error(`!!!! Missing x-version for ${distDir} ${customVersion}`);
|
|
647
|
+
import_fs3.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
|
|
583
648
|
}
|
|
584
649
|
}
|
|
585
|
-
static writeApiFile(distDir, apiName, apiBuffer, imports,
|
|
650
|
+
static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethodsDescription) {
|
|
586
651
|
const newImports = [];
|
|
587
|
-
imports.forEach((el
|
|
652
|
+
imports.forEach((el) => {
|
|
588
653
|
newImports.push(el.replace("../../generated-definitions", "../generated-definitions"));
|
|
589
654
|
});
|
|
590
|
-
const fileContent = templateApiClass(apiName, apiBuffer, newImports,
|
|
591
|
-
|
|
655
|
+
const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethodsDescription);
|
|
656
|
+
import_fs3.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
592
657
|
}
|
|
593
658
|
static writeApiMainFile(distDir, serviceName, fileContent) {
|
|
594
|
-
|
|
659
|
+
import_fs3.default.writeFileSync(`${distDir}/${serviceName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
595
660
|
}
|
|
596
661
|
static writeSnippetFile(distDir, name, docBuffer) {
|
|
597
|
-
let snippetFileName =
|
|
662
|
+
let snippetFileName = _ParserUtils.replaceAll(name, " ", "-").toLowerCase();
|
|
598
663
|
snippetFileName = snippetFileName.replace("justice-", "");
|
|
599
664
|
snippetFileName = "snippet-" + snippetFileName + ".json";
|
|
600
|
-
|
|
665
|
+
import_fs3.default.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
|
|
601
666
|
}
|
|
602
667
|
static writeDefinitionFile(distDir, name, buffer) {
|
|
603
|
-
|
|
604
|
-
|
|
668
|
+
_ParserUtils.mkdirIfNotExist(distDir);
|
|
669
|
+
import_fs3.default.writeFileSync(import_path2.default.join(distDir, `${name}.ts`), _ParserUtils.prependCopyrightHeader(buffer));
|
|
605
670
|
}
|
|
606
671
|
static writeAllImportsFile(distDir, buffer) {
|
|
607
|
-
|
|
608
|
-
|
|
672
|
+
_ParserUtils.mkdirIfNotExist(distDir);
|
|
673
|
+
import_fs3.default.writeFileSync(import_path2.default.join(distDir, "all-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
609
674
|
}
|
|
610
|
-
static
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
const currDir = process.cwd();
|
|
614
|
-
const { packageJSON, pathToPackageJSON } = ParserUtils.getPackageJSONInfo(currDir);
|
|
615
|
-
const nextSemver = VersionHelpers.getNextVersion({
|
|
616
|
-
serviceVersion: apiInfo["x-version"] || apiInfo.version || UNDEFINED_SWAGGER_SEMVER,
|
|
617
|
-
versionBumpType: process.env.VERSION_BUMP_TYPE,
|
|
618
|
-
sdkVersion: packageJSON.version,
|
|
619
|
-
nextPrereleaseId: prereleaseId
|
|
620
|
-
});
|
|
621
|
-
packageJSON.version = nextSemver;
|
|
622
|
-
fs.writeFileSync(pathToPackageJSON, JSON.stringify(packageJSON, null, 2));
|
|
623
|
-
}
|
|
624
|
-
static getPackageJSONInfo(dir) {
|
|
625
|
-
const pathToPackageJSON = path.join(dir, "./package.json");
|
|
626
|
-
return { packageJSON: JSON.parse(fs.readFileSync(pathToPackageJSON, "utf-8")), pathToPackageJSON };
|
|
675
|
+
static writeAllQueryImportsFile(distDir, buffer) {
|
|
676
|
+
_ParserUtils.mkdirIfNotExist(distDir);
|
|
677
|
+
import_fs3.default.writeFileSync(import_path2.default.join(distDir, "all-query-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
627
678
|
}
|
|
628
679
|
static toCamelCase(str) {
|
|
629
680
|
return str.split("/").map(function(word, index) {
|
|
630
681
|
if (index === 0) {
|
|
631
682
|
return word.toLowerCase();
|
|
632
683
|
}
|
|
633
|
-
return
|
|
684
|
+
return _ParserUtils.toCamelCaseWord(word);
|
|
634
685
|
}).join("");
|
|
635
686
|
}
|
|
636
687
|
static toCamelCaseWord(word) {
|
|
@@ -649,15 +700,15 @@ class ParserUtils {
|
|
|
649
700
|
});
|
|
650
701
|
}
|
|
651
702
|
static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
|
|
652
|
-
if (!
|
|
653
|
-
|
|
703
|
+
if (!import_fs3.default.existsSync(swaggerPatchedDir)) {
|
|
704
|
+
import_fs3.default.mkdirSync(swaggerPatchedDir, { recursive: true });
|
|
654
705
|
}
|
|
655
|
-
if (!
|
|
656
|
-
|
|
706
|
+
if (!import_fs3.default.existsSync(possibleSwaggerPatchFilePath)) {
|
|
707
|
+
import_fs3.default.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
|
|
657
708
|
return;
|
|
658
709
|
}
|
|
659
|
-
const swaggerContent = JSON.parse(
|
|
660
|
-
const swaggerPatchFileContent = JSON.parse(
|
|
710
|
+
const swaggerContent = JSON.parse(import_fs3.default.readFileSync(swaggerFilePath, "utf8"));
|
|
711
|
+
const swaggerPatchFileContent = JSON.parse(import_fs3.default.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
|
|
661
712
|
for (const patchEntry of swaggerPatchFileContent) {
|
|
662
713
|
const segments = patchEntry.path.split("/").filter(Boolean);
|
|
663
714
|
let currentNode = swaggerContent;
|
|
@@ -667,29 +718,32 @@ class ParserUtils {
|
|
|
667
718
|
aggregatedPath += `/${segment}`;
|
|
668
719
|
const effectiveSegment = segment.replace(/(~1)/g, "/").replace(/(~0)/g, "~");
|
|
669
720
|
if (!currentNode[effectiveSegment]) {
|
|
670
|
-
if (i + 1 === segments.length && patchEntry.op === "add")
|
|
671
|
-
|
|
672
|
-
|
|
721
|
+
if (i + 1 === segments.length && patchEntry.op === "add") {
|
|
722
|
+
} else {
|
|
723
|
+
throw new Error(
|
|
724
|
+
[
|
|
725
|
+
`JSON patch error: operation "${patchEntry.op}" on path "${aggregatedPath}" fails because the path doesn't exist in ${swaggerFilePath}. This may be caused by:
|
|
673
726
|
`,
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
727
|
+
"1. The related service has patched the service, so patch is no longer needed.",
|
|
728
|
+
"2. There is a breaking change on the service that causes the path to change.\n",
|
|
729
|
+
`In any case, revisit this file: "${possibleSwaggerPatchFilePath}", then try again.
|
|
677
730
|
`
|
|
678
|
-
|
|
731
|
+
].join("\n")
|
|
732
|
+
);
|
|
679
733
|
}
|
|
680
734
|
}
|
|
681
735
|
currentNode = currentNode[effectiveSegment];
|
|
682
736
|
}
|
|
683
737
|
}
|
|
684
|
-
const { newDocument } =
|
|
685
|
-
|
|
738
|
+
const { newDocument } = (0, import_fast_json_patch.applyPatch)(swaggerContent, swaggerPatchFileContent);
|
|
739
|
+
import_fs3.default.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
|
|
686
740
|
}
|
|
687
741
|
static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
|
|
688
742
|
const replaced = srcFolder.replace(/\\/g, "/");
|
|
689
743
|
return replaced.replace(/\\/g, "/").replace(targetSrcFolder, "./");
|
|
690
744
|
}
|
|
691
745
|
static prependCopyrightHeader = (content) => {
|
|
692
|
-
const currentYear = new Date().getFullYear();
|
|
746
|
+
const currentYear = (/* @__PURE__ */ new Date()).getFullYear();
|
|
693
747
|
return `/*
|
|
694
748
|
* Copyright (c) 2022${currentYear > 2022 ? `-${currentYear}` : ""} AccelByte Inc. All Rights Reserved
|
|
695
749
|
* This is licensed software from AccelByte Inc, for limitations
|
|
@@ -697,17 +751,21 @@ class ParserUtils {
|
|
|
697
751
|
*/
|
|
698
752
|
${content}`;
|
|
699
753
|
};
|
|
700
|
-
static sortPathParamsByPath = (pathParams,
|
|
701
|
-
const params =
|
|
754
|
+
static sortPathParamsByPath = (pathParams, path7) => {
|
|
755
|
+
const params = path7.match(/{\w*}/g) || [];
|
|
702
756
|
const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
|
|
703
757
|
return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
|
|
704
758
|
};
|
|
705
|
-
}
|
|
706
|
-
|
|
759
|
+
};
|
|
760
|
+
var mappedMethod = (httpMethod, isForm, permissionType) => {
|
|
707
761
|
if (httpMethod === "get") {
|
|
708
762
|
return "get";
|
|
709
763
|
} else if (httpMethod === "post" && isForm) {
|
|
710
764
|
return "post";
|
|
765
|
+
} else if (httpMethod === "post" && permissionType === "READ") {
|
|
766
|
+
return "fetch";
|
|
767
|
+
} else if (httpMethod === "post" && permissionType === "UPDATE") {
|
|
768
|
+
return "update";
|
|
711
769
|
} else if (httpMethod === "post") {
|
|
712
770
|
return "create";
|
|
713
771
|
} else if (httpMethod === "put") {
|
|
@@ -718,448 +776,317 @@ const mappedMethod = (httpMethod, isForm) => {
|
|
|
718
776
|
return "delete";
|
|
719
777
|
}
|
|
720
778
|
};
|
|
721
|
-
|
|
779
|
+
var resolveConflicts = ({ path: path7, generatedMethod, testedGeneratedMethod, existingMethods }) => {
|
|
780
|
+
let _testedGenMethod = testedGeneratedMethod;
|
|
722
781
|
try {
|
|
723
|
-
testConflict(
|
|
782
|
+
testConflict(path7, _testedGenMethod, existingMethods);
|
|
724
783
|
} catch (e) {
|
|
725
|
-
if (
|
|
784
|
+
if (path7.indexOf("/namespaces/") >= 0) {
|
|
726
785
|
generatedMethod += "_ByNS";
|
|
786
|
+
_testedGenMethod += "_ByNS";
|
|
727
787
|
}
|
|
728
788
|
}
|
|
729
789
|
try {
|
|
730
|
-
testConflict(
|
|
731
|
-
} catch (e) {
|
|
732
|
-
if (path2.indexOf("/v4/") >= 0) {
|
|
733
|
-
generatedMethod += "_v4";
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
try {
|
|
737
|
-
testConflict(path2, generatedMethod, existingMethods);
|
|
738
|
-
} catch (e) {
|
|
739
|
-
if (path2.indexOf("/v3/") >= 0) {
|
|
740
|
-
generatedMethod += "_v3";
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
try {
|
|
744
|
-
testConflict(path2, generatedMethod, existingMethods);
|
|
745
|
-
} catch (e) {
|
|
746
|
-
if (path2.indexOf("/v2/") >= 0) {
|
|
747
|
-
generatedMethod += "_v2";
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
|
-
try {
|
|
751
|
-
testConflict(path2, generatedMethod, existingMethods);
|
|
790
|
+
testConflict(path7, _testedGenMethod, existingMethods);
|
|
752
791
|
} catch (e) {
|
|
753
|
-
if (
|
|
792
|
+
if (path7.indexOf("/admin/") >= 0) {
|
|
754
793
|
generatedMethod += "_admin";
|
|
794
|
+
_testedGenMethod += "_admin";
|
|
755
795
|
}
|
|
756
796
|
}
|
|
757
|
-
testConflict(
|
|
797
|
+
testConflict(path7, _testedGenMethod, existingMethods);
|
|
758
798
|
return generatedMethod;
|
|
759
799
|
};
|
|
760
|
-
|
|
800
|
+
var testConflict = (path7, generatedMethod, existingMethods) => {
|
|
761
801
|
if (existingMethods[generatedMethod]) {
|
|
762
|
-
const conflictingMethod = { path:
|
|
763
|
-
throw Error(
|
|
764
|
-
|
|
802
|
+
const conflictingMethod = { path: path7, generatedMethod };
|
|
803
|
+
throw Error(
|
|
804
|
+
`Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
|
|
805
|
+
existingMethods: ${JSON.stringify(existingMethods, null, 2)}`
|
|
806
|
+
);
|
|
765
807
|
}
|
|
766
808
|
};
|
|
767
|
-
|
|
809
|
+
var isSwaggerIntegerType = (type) => {
|
|
768
810
|
return type === "integer" || type === "int";
|
|
769
811
|
};
|
|
770
812
|
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
813
|
+
// src/Swagger.ts
|
|
814
|
+
var import_zod2 = require("zod");
|
|
815
|
+
var Schema = import_zod2.z.object({
|
|
816
|
+
$ref: import_zod2.z.string().nullish(),
|
|
817
|
+
type: import_zod2.z.union([import_zod2.z.literal("array"), import_zod2.z.literal("object"), import_zod2.z.literal("file"), import_zod2.z.literal("string"), import_zod2.z.literal("boolean"), import_zod2.z.literal("integer")]).nullish(),
|
|
818
|
+
items: import_zod2.z.object({
|
|
819
|
+
$ref: import_zod2.z.string().nullish(),
|
|
820
|
+
type: import_zod2.z.string().nullish()
|
|
821
|
+
}).nullish(),
|
|
822
|
+
properties: import_zod2.z.union([import_zod2.z.array(import_zod2.z.string()).nullish(), import_zod2.z.record(import_zod2.z.object({ type: import_zod2.z.string() })).nullish()]),
|
|
823
|
+
description: import_zod2.z.string().nullish(),
|
|
824
|
+
additionalProperties: import_zod2.z.object({
|
|
825
|
+
type: import_zod2.z.string().nullish()
|
|
826
|
+
}).nullish()
|
|
827
|
+
});
|
|
828
|
+
var Definition = import_zod2.z.object({
|
|
829
|
+
required: import_zod2.z.array(import_zod2.z.string()).nullish(),
|
|
830
|
+
properties: import_zod2.z.record(
|
|
831
|
+
import_zod2.z.object({
|
|
832
|
+
type: import_zod2.z.string()
|
|
833
|
+
})
|
|
834
|
+
).nullish()
|
|
835
|
+
});
|
|
836
|
+
var Definitions = import_zod2.z.record(Definition);
|
|
837
|
+
var EndpointParametersType = import_zod2.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
|
|
838
|
+
var EndpointParametersIn = import_zod2.z.enum(["body", "formData", "header", "path", "query"]);
|
|
839
|
+
var EndpointParameters = import_zod2.z.object({
|
|
840
|
+
type: EndpointParametersType.nullish(),
|
|
841
|
+
description: import_zod2.z.string().nullish(),
|
|
842
|
+
name: import_zod2.z.string(),
|
|
843
|
+
in: EndpointParametersIn,
|
|
844
|
+
required: import_zod2.z.boolean().nullish(),
|
|
845
|
+
schema: Schema.nullish(),
|
|
846
|
+
default: import_zod2.z.union([import_zod2.z.boolean(), import_zod2.z.string(), import_zod2.z.number(), import_zod2.z.array(import_zod2.z.any())]).nullish(),
|
|
847
|
+
enum: import_zod2.z.array(import_zod2.z.union([import_zod2.z.boolean(), import_zod2.z.string(), import_zod2.z.number()])).nullish(),
|
|
848
|
+
items: import_zod2.z.object({
|
|
849
|
+
type: import_zod2.z.string(),
|
|
850
|
+
enum: import_zod2.z.array(import_zod2.z.any()).nullish()
|
|
851
|
+
}).nullish()
|
|
852
|
+
});
|
|
853
|
+
var Endpoint = import_zod2.z.object({
|
|
854
|
+
description: import_zod2.z.string().nullish(),
|
|
855
|
+
consumes: import_zod2.z.array(import_zod2.z.string()).nullish(),
|
|
856
|
+
produces: import_zod2.z.array(import_zod2.z.string()).nullish(),
|
|
857
|
+
tags: import_zod2.z.array(import_zod2.z.string()).nullish(),
|
|
858
|
+
summary: import_zod2.z.string().nullish(),
|
|
859
|
+
operationId: import_zod2.z.string(),
|
|
860
|
+
deprecated: import_zod2.z.boolean().nullish(),
|
|
861
|
+
responses: import_zod2.z.record(
|
|
862
|
+
import_zod2.z.object({
|
|
863
|
+
description: import_zod2.z.string().nullish(),
|
|
864
|
+
schema: Schema.nullish(),
|
|
865
|
+
content: import_zod2.z.object({
|
|
866
|
+
"application/json": import_zod2.z.object({
|
|
867
|
+
schema: Schema.nullish()
|
|
868
|
+
})
|
|
869
|
+
}).nullish()
|
|
870
|
+
})
|
|
871
|
+
),
|
|
872
|
+
parameters: import_zod2.z.array(EndpointParameters).nullish(),
|
|
873
|
+
requestBody: import_zod2.z.object({
|
|
874
|
+
required: import_zod2.z.boolean().nullish(),
|
|
875
|
+
content: import_zod2.z.object({
|
|
876
|
+
"application/json": import_zod2.z.object({
|
|
877
|
+
schema: Schema.nullish()
|
|
878
|
+
}).nullish()
|
|
879
|
+
}).nullish()
|
|
880
|
+
}).nullish(),
|
|
881
|
+
// The proper type is z.array(z.record(z.array(z.string()))).nullish() but somehow there are endpoints with
|
|
882
|
+
// an object type instead of an array type, so, yeah.
|
|
883
|
+
//
|
|
884
|
+
// Services with this error: sdk-iam, sdk-ugc.
|
|
885
|
+
"x-security": import_zod2.z.any().nullish()
|
|
886
|
+
});
|
|
887
|
+
var Operation2 = import_zod2.z.object({
|
|
888
|
+
get: Endpoint.nullish(),
|
|
889
|
+
post: Endpoint.nullish(),
|
|
890
|
+
patch: Endpoint.nullish(),
|
|
891
|
+
delete: Endpoint.nullish(),
|
|
892
|
+
put: Endpoint.nullish()
|
|
893
|
+
});
|
|
894
|
+
var Paths = import_zod2.z.record(Operation2);
|
|
895
|
+
var OpenApiSpec = import_zod2.z.object({
|
|
896
|
+
paths: Paths,
|
|
897
|
+
definitions: Definitions,
|
|
898
|
+
basePath: import_zod2.z.string(),
|
|
899
|
+
info: import_zod2.z.object({
|
|
900
|
+
description: import_zod2.z.string(),
|
|
901
|
+
title: import_zod2.z.string(),
|
|
902
|
+
contact: import_zod2.z.object({
|
|
903
|
+
name: import_zod2.z.string(),
|
|
904
|
+
url: import_zod2.z.string(),
|
|
905
|
+
email: import_zod2.z.string()
|
|
906
|
+
}),
|
|
907
|
+
version: import_zod2.z.string()
|
|
908
|
+
}),
|
|
909
|
+
schemes: import_zod2.z.array(import_zod2.z.string()).nullish(),
|
|
910
|
+
components: import_zod2.z.object({
|
|
911
|
+
schemas: Definitions
|
|
912
|
+
}).nullish()
|
|
913
|
+
});
|
|
914
|
+
|
|
915
|
+
// src/templates/template-api-method.ts
|
|
916
|
+
var templateApiMethod = ({
|
|
917
|
+
classMethod,
|
|
918
|
+
httpMethod,
|
|
919
|
+
path: path7,
|
|
920
|
+
pathParams,
|
|
921
|
+
bodyParams,
|
|
922
|
+
responseClasses,
|
|
923
|
+
classGenName,
|
|
924
|
+
methodParams,
|
|
925
|
+
methodParamsNoTypes,
|
|
926
|
+
xSecurity
|
|
927
|
+
}) => {
|
|
928
|
+
let newPath = `'${path7}'`;
|
|
929
|
+
let snippetMethod = "";
|
|
930
|
+
for (const pathParam of pathParams) {
|
|
931
|
+
const type = ParserUtils.parseType(pathParam);
|
|
932
|
+
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
933
|
+
if (path7.match(`{${pathParam.name}}`)) {
|
|
934
|
+
if (type === "string") {
|
|
935
|
+
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
936
|
+
} else {
|
|
937
|
+
newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
|
|
938
|
+
}
|
|
786
939
|
}
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
} else {
|
|
801
|
-
exportedVariableString = `export const ${fileName} = ${content.schemaString}`;
|
|
802
|
-
exportedTypeString = `export interface ${fileName} extends z.TypeOf<typeof ${fileName}> {}`;
|
|
940
|
+
}
|
|
941
|
+
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path7}'`, "--header 'accept: application/json'"];
|
|
942
|
+
const snippetApiArgs = [];
|
|
943
|
+
if (xSecurity !== void 0 || path7.includes("/admin")) {
|
|
944
|
+
snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
|
|
945
|
+
snippetApiArgs.push("{ axiosConfig: { request: { headers: { Authorization: 'Bearer {access_token}' } } } }".trim());
|
|
946
|
+
}
|
|
947
|
+
if (httpMethod !== "get") {
|
|
948
|
+
const curlParams = bodyParams?.map((ob) => {
|
|
949
|
+
return ` "${ob.name}": ""`;
|
|
950
|
+
});
|
|
951
|
+
if (curlParams.length > 0) {
|
|
952
|
+
snippetShellArgs.push(`--data-raw '{ ${curlParams}}'`);
|
|
803
953
|
}
|
|
804
|
-
|
|
805
|
-
${
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
${
|
|
954
|
+
}
|
|
955
|
+
const snippetShell = `curl ${snippetShellArgs.join(" \\\n ")}`;
|
|
956
|
+
const { responseType, responseTypeInAxiosResponse } = getResponseType({ responseClasses });
|
|
957
|
+
const methodImpl = `
|
|
958
|
+
async function ${classMethod}(${methodParams}): ${responseTypeInAxiosResponse} {
|
|
959
|
+
const $ = new ${classGenName}(axiosInstance, namespace, useSchemaValidation)
|
|
960
|
+
const resp = await $.${classMethod}(${methodParamsNoTypes})
|
|
961
|
+
if (resp.error) throw resp.error
|
|
962
|
+
return resp.response
|
|
963
|
+
}
|
|
810
964
|
`;
|
|
811
|
-
|
|
965
|
+
const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
|
|
966
|
+
snippetMethod += `${classMethod}(${methodParams})
|
|
967
|
+
// return ${snippetPromiseString}`;
|
|
968
|
+
return {
|
|
969
|
+
generatedMethodString: methodImpl,
|
|
970
|
+
snippetApiArgs,
|
|
971
|
+
snippetMethod,
|
|
972
|
+
snippetShell
|
|
812
973
|
};
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
schemaString: `z.array(z.object({${schemaFields.join(",")}}))`,
|
|
839
|
-
typeString: typeFields.join(";")
|
|
840
|
-
};
|
|
841
|
-
}
|
|
842
|
-
return {
|
|
843
|
-
schemaString: `z.object({${schemaFields.join(",")}})`,
|
|
844
|
-
typeString: typeFields.join(";")
|
|
845
|
-
};
|
|
846
|
-
};
|
|
847
|
-
parseToZodAttribute = (name, definition, requiredAttrs) => {
|
|
848
|
-
const isRequired = requiredAttrs.includes(name) || name === "";
|
|
849
|
-
const schemaRequired = isRequired ? "" : ".nullish()";
|
|
850
|
-
const typeRequired = isRequired ? "" : "?";
|
|
851
|
-
const typeNullishability = isRequired ? "" : " | null | undefined";
|
|
852
|
-
const schemaAttribute = name ? `'${name}':` : "";
|
|
853
|
-
const typeAttribute = name ? `'${name}'${typeRequired}:` : "";
|
|
854
|
-
const type = definition?.type;
|
|
855
|
-
if (definition.properties) {
|
|
856
|
-
const result = this.parseToZodSchema(definition, requiredAttrs);
|
|
857
|
-
return {
|
|
858
|
-
schemaString: `${schemaAttribute} ${result.schemaString}${schemaRequired}`,
|
|
859
|
-
typeString: `${typeAttribute} ${result.typeString}${typeNullishability}`
|
|
860
|
-
};
|
|
861
|
-
} else if (type) {
|
|
862
|
-
if (type === "object" && definition.additionalProperties) {
|
|
863
|
-
const zodAttribute = this.parseToZodAttribute("", definition.additionalProperties, [""]);
|
|
864
|
-
return {
|
|
865
|
-
schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
|
|
866
|
-
typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
|
|
867
|
-
};
|
|
868
|
-
}
|
|
869
|
-
if (type === "object" && !definition.additionalProperties && !name) {
|
|
870
|
-
return {
|
|
871
|
-
schemaString: `z.any()`,
|
|
872
|
-
typeString: "any"
|
|
873
|
-
};
|
|
874
|
-
}
|
|
875
|
-
if (type === "object" && !definition.additionalProperties) {
|
|
876
|
-
return {
|
|
877
|
-
schemaString: `${schemaAttribute} z.record(z.any())${schemaRequired}`,
|
|
878
|
-
typeString: `${typeAttribute} Record<string, any>${typeNullishability}`
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
if (type === "integer" || type === "number") {
|
|
882
|
-
const effectiveType = getZodNumberType(type);
|
|
883
|
-
return {
|
|
884
|
-
schemaString: `${schemaAttribute} z.${effectiveType.schemaString}()${schemaRequired}`,
|
|
885
|
-
typeString: `${typeAttribute} ${effectiveType.typeString}${typeNullishability}`
|
|
886
|
-
};
|
|
887
|
-
}
|
|
888
|
-
if (type === "array") {
|
|
889
|
-
const items = definition.items;
|
|
890
|
-
const ref2 = items?.$ref;
|
|
891
|
-
let model2;
|
|
892
|
-
if (ref2) {
|
|
893
|
-
const refType = ParserUtils.parseRefType(ref2);
|
|
894
|
-
this.importClasses.add(refType);
|
|
895
|
-
model2 = {
|
|
896
|
-
schemaString: refType,
|
|
897
|
-
typeString: refType
|
|
898
|
-
};
|
|
899
|
-
} else if (items) {
|
|
900
|
-
if (items.type === "array") {
|
|
901
|
-
const ref3 = items.items?.$ref;
|
|
902
|
-
if (ref3) {
|
|
903
|
-
const refType = ParserUtils.parseRefType(ref3);
|
|
904
|
-
this.importClasses.add(refType);
|
|
905
|
-
model2 = {
|
|
906
|
-
schemaString: refType,
|
|
907
|
-
typeString: refType
|
|
908
|
-
};
|
|
909
|
-
} else if (items.items) {
|
|
910
|
-
model2 = this.parseEnumItems(items.items);
|
|
911
|
-
}
|
|
912
|
-
return {
|
|
913
|
-
schemaString: `${schemaAttribute} z.array(z.array(${model2.schemaString}))${schemaRequired}`,
|
|
914
|
-
typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
|
|
915
|
-
};
|
|
916
|
-
} else {
|
|
917
|
-
model2 = this.parseEnumItems(items);
|
|
918
|
-
}
|
|
919
|
-
} else {
|
|
920
|
-
return {
|
|
921
|
-
schemaString: `${schemaAttribute} z.array(z.any())${schemaRequired}`,
|
|
922
|
-
typeString: `${typeAttribute} any[]${typeNullishability}`
|
|
923
|
-
};
|
|
924
|
-
}
|
|
925
|
-
return {
|
|
926
|
-
schemaString: `${schemaAttribute} z.array(${model2.schemaString})${schemaRequired}`,
|
|
927
|
-
typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
|
|
928
|
-
};
|
|
929
|
-
}
|
|
930
|
-
if (type !== "object") {
|
|
931
|
-
const result = extractEnumObject(type, isRequired, definition.enum);
|
|
932
|
-
return {
|
|
933
|
-
schemaString: `${schemaAttribute} ${result.schemaString}`,
|
|
934
|
-
typeString: `${typeAttribute} ${result.typeString}`
|
|
935
|
-
};
|
|
936
|
-
}
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
// src/templates/template-method.ts
|
|
977
|
+
var templateMethod = ({
|
|
978
|
+
classMethod,
|
|
979
|
+
description,
|
|
980
|
+
httpMethod,
|
|
981
|
+
path: path7,
|
|
982
|
+
pathParams,
|
|
983
|
+
bodyParams,
|
|
984
|
+
queryParams,
|
|
985
|
+
isFormUrlEncoded,
|
|
986
|
+
responseClasses,
|
|
987
|
+
deprecated
|
|
988
|
+
}) => {
|
|
989
|
+
let methodParams = "";
|
|
990
|
+
let methodParamsNoTypes = "";
|
|
991
|
+
let newPath = `'${path7}'`;
|
|
992
|
+
let importStatements = [];
|
|
993
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path7);
|
|
994
|
+
for (const pathParam of sortedPathParams) {
|
|
995
|
+
const type = ParserUtils.parseType(pathParam);
|
|
996
|
+
if (pathParam.name !== "namespace") {
|
|
997
|
+
methodParams += pathParam.name + `:${type}, `;
|
|
998
|
+
methodParamsNoTypes += pathParam.name + ", ";
|
|
937
999
|
}
|
|
938
|
-
const
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
if (this.duplicateFound) {
|
|
945
|
-
model = this.duplicates.get(fullModelName);
|
|
1000
|
+
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1001
|
+
if (path7.match(`{${pathParam.name}}`)) {
|
|
1002
|
+
if (type === "string") {
|
|
1003
|
+
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1004
|
+
} else {
|
|
1005
|
+
newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
|
|
946
1006
|
}
|
|
947
|
-
this.importClasses.add(model);
|
|
948
|
-
model = `${model}`;
|
|
949
|
-
}
|
|
950
|
-
return {
|
|
951
|
-
schemaString: `${schemaAttribute} ${model}${schemaRequired}`,
|
|
952
|
-
typeString: `${typeAttribute} ${model}${typeNullishability}`
|
|
953
|
-
};
|
|
954
|
-
};
|
|
955
|
-
parseEnumItems = (items) => {
|
|
956
|
-
if (items.enum) {
|
|
957
|
-
const enumStr = items.enum.map((e) => {
|
|
958
|
-
return `"${e}"`;
|
|
959
|
-
});
|
|
960
|
-
return {
|
|
961
|
-
schemaString: `z.enum([${enumStr}])`,
|
|
962
|
-
typeString: `(${enumStr.join(" | ")})`
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
if (items.type === "object") {
|
|
966
|
-
return this.parseToZodSchema(items, items.required);
|
|
967
1007
|
}
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
};
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
1008
|
+
}
|
|
1009
|
+
let dataType = null;
|
|
1010
|
+
if (httpMethod !== "get") {
|
|
1011
|
+
dataType = ParserUtils.parseBodyParamsType(bodyParams);
|
|
1012
|
+
importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
|
|
1013
|
+
methodParams += dataType ? `data: ${dataType},` : "";
|
|
1014
|
+
methodParamsNoTypes += dataType ? `data,` : "";
|
|
1015
|
+
}
|
|
1016
|
+
const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
|
|
1017
|
+
const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
|
|
1018
|
+
const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as AxiosRequestConfig` : "const params = {} as AxiosRequestConfig";
|
|
1019
|
+
const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
|
|
1020
|
+
const isDelete = ["delete"].includes(httpMethod);
|
|
1021
|
+
let dataPayload = "{params}";
|
|
1022
|
+
const descriptionText = extractDescription(description, { isDeprecated: deprecated, responseClasses });
|
|
1023
|
+
let formPayloadString = "";
|
|
1024
|
+
if (isFormUrlEncoded) {
|
|
1025
|
+
formPayloadString = ``;
|
|
1026
|
+
const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
|
|
1027
|
+
dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
|
|
1028
|
+
} else if (isPostPutPatch) {
|
|
1029
|
+
dataPayload = dataType ? `data, {params}` : "null, {params}";
|
|
1030
|
+
} else if (isDelete) {
|
|
1031
|
+
dataPayload = dataType ? `{data, params}` : "{params}";
|
|
1032
|
+
}
|
|
1033
|
+
const isFileUpload = methodParams.indexOf("data: {file") > -1;
|
|
1034
|
+
const { responseType, responseTypeInResponse } = getResponseType({ responseClasses });
|
|
1035
|
+
const resolvedResponseClassValidated = responseType !== "unknown" ? `${responseType}` : "z.unknown()";
|
|
1036
|
+
methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
|
|
1037
|
+
methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
|
|
1038
|
+
const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
|
|
1039
|
+
const generatedMethodName = `${classMethod}(${methodParams}): ${responseTypeInResponse}`;
|
|
1040
|
+
let methodImpl = `${descriptionText}
|
|
1041
|
+
${generatedMethodName} {
|
|
1042
|
+
${queryParamsDefault}
|
|
1043
|
+
const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
|
|
1044
|
+
const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
|
|
987
1045
|
|
|
988
|
-
|
|
1046
|
+
${` return Validate.validateOrReturnResponse(this.useSchemaValidation, () => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')`}
|
|
1047
|
+
}
|
|
989
1048
|
`;
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
}
|
|
993
|
-
const getZodNumberType = (type) => {
|
|
994
|
-
if (type === "integer") {
|
|
995
|
-
return {
|
|
996
|
-
schemaString: "number().int",
|
|
997
|
-
typeString: "number"
|
|
998
|
-
};
|
|
1049
|
+
if (!isGuardInvoked) {
|
|
1050
|
+
methodImpl = ``;
|
|
999
1051
|
}
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1052
|
+
const res = {
|
|
1053
|
+
methodImpl,
|
|
1054
|
+
methodParams,
|
|
1055
|
+
methodParamsNoTypes,
|
|
1056
|
+
importStatements
|
|
1003
1057
|
};
|
|
1058
|
+
return res;
|
|
1004
1059
|
};
|
|
1005
|
-
const extractEnumObject = (type, isRequired, enumArr) => {
|
|
1006
|
-
const schemaRequired = isRequired ? "" : ".nullish()";
|
|
1007
|
-
const typeNullishability = isRequired ? "" : " | null | undefined";
|
|
1008
|
-
if (enumArr) {
|
|
1009
|
-
const enumStr = enumArr.map((e) => {
|
|
1010
|
-
return `"${e}"`;
|
|
1011
|
-
});
|
|
1012
|
-
return {
|
|
1013
|
-
schemaString: `z.enum([${enumStr}])${schemaRequired}`,
|
|
1014
|
-
typeString: `(${enumStr.join(" | ")}${typeNullishability})`
|
|
1015
|
-
};
|
|
1016
|
-
}
|
|
1017
|
-
return {
|
|
1018
|
-
schemaString: `z.${type}()${schemaRequired}`,
|
|
1019
|
-
typeString: `${type}${typeNullishability}`
|
|
1020
|
-
};
|
|
1021
|
-
};
|
|
1022
|
-
|
|
1023
|
-
const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
|
|
1024
|
-
let imports = "";
|
|
1025
|
-
let returnStatement = "";
|
|
1026
|
-
for (const cl of apiList) {
|
|
1027
|
-
const dir = cl.toLowerCase().includes("admin") && cl !== "AdminApi" ? "generated-admin" : "generated-public";
|
|
1028
|
-
imports += `
|
|
1029
|
-
import { ${cl} } from './${dir}/${cl}.js'`;
|
|
1030
|
-
returnStatement += `
|
|
1031
|
-
${cl}, `;
|
|
1032
|
-
}
|
|
1033
|
-
return `/**
|
|
1034
|
-
* AUTO GENERATED
|
|
1035
|
-
*/
|
|
1036
|
-
${imports}
|
|
1037
|
-
|
|
1038
|
-
const apis = {
|
|
1039
|
-
${returnStatement}
|
|
1040
|
-
}
|
|
1041
|
-
|
|
1042
|
-
export const ${serviceNameTitle} = apis
|
|
1043
|
-
`;
|
|
1044
|
-
};
|
|
1045
|
-
|
|
1046
|
-
const Schema = zod.z.object({
|
|
1047
|
-
$ref: zod.z.string().nullish(),
|
|
1048
|
-
type: zod.z.union([zod.z.literal("array"), zod.z.literal("object"), zod.z.literal("file"), zod.z.literal("string"), zod.z.literal("boolean"), zod.z.literal("integer")]).nullish(),
|
|
1049
|
-
items: zod.z.object({
|
|
1050
|
-
$ref: zod.z.string().nullish(),
|
|
1051
|
-
type: zod.z.string().nullish()
|
|
1052
|
-
}).nullish(),
|
|
1053
|
-
properties: zod.z.union([zod.z.array(zod.z.string()).nullish(), zod.z.record(zod.z.object({ type: zod.z.string() })).nullish()]),
|
|
1054
|
-
description: zod.z.string().nullish(),
|
|
1055
|
-
additionalProperties: zod.z.object({
|
|
1056
|
-
type: zod.z.string().nullish()
|
|
1057
|
-
}).nullish()
|
|
1058
|
-
});
|
|
1059
|
-
const Definition = zod.z.object({
|
|
1060
|
-
required: zod.z.array(zod.z.string()).nullish(),
|
|
1061
|
-
properties: zod.z.record(zod.z.object({
|
|
1062
|
-
type: zod.z.string()
|
|
1063
|
-
})).nullish()
|
|
1064
|
-
});
|
|
1065
|
-
const Definitions = zod.z.record(Definition);
|
|
1066
|
-
const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
|
|
1067
|
-
const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
|
|
1068
|
-
const EndpointParameters = zod.z.object({
|
|
1069
|
-
type: EndpointParametersType.nullish(),
|
|
1070
|
-
description: zod.z.string().nullish(),
|
|
1071
|
-
name: zod.z.string(),
|
|
1072
|
-
in: EndpointParametersIn,
|
|
1073
|
-
required: zod.z.boolean().nullish(),
|
|
1074
|
-
schema: Schema.nullish(),
|
|
1075
|
-
default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
|
|
1076
|
-
enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
|
|
1077
|
-
items: zod.z.object({
|
|
1078
|
-
type: zod.z.string(),
|
|
1079
|
-
enum: zod.z.array(zod.z.any()).nullish()
|
|
1080
|
-
}).nullish()
|
|
1081
|
-
});
|
|
1082
|
-
const Endpoint = zod.z.object({
|
|
1083
|
-
description: zod.z.string().nullish(),
|
|
1084
|
-
consumes: zod.z.array(zod.z.string()).nullish(),
|
|
1085
|
-
produces: zod.z.array(zod.z.string()).nullish(),
|
|
1086
|
-
tags: zod.z.array(zod.z.string()).nullish(),
|
|
1087
|
-
summary: zod.z.string().nullish(),
|
|
1088
|
-
operationId: zod.z.string(),
|
|
1089
|
-
deprecated: zod.z.boolean().nullish(),
|
|
1090
|
-
responses: zod.z.record(zod.z.object({
|
|
1091
|
-
description: zod.z.string().nullish(),
|
|
1092
|
-
schema: Schema.nullish(),
|
|
1093
|
-
content: zod.z.object({
|
|
1094
|
-
"application/json": zod.z.object({
|
|
1095
|
-
schema: Schema.nullish()
|
|
1096
|
-
})
|
|
1097
|
-
}).nullish()
|
|
1098
|
-
})),
|
|
1099
|
-
parameters: zod.z.array(EndpointParameters).nullish(),
|
|
1100
|
-
requestBody: zod.z.object({
|
|
1101
|
-
required: zod.z.boolean().nullish(),
|
|
1102
|
-
content: zod.z.object({
|
|
1103
|
-
"application/json": zod.z.object({
|
|
1104
|
-
schema: Schema.nullish()
|
|
1105
|
-
}).nullish()
|
|
1106
|
-
}).nullish()
|
|
1107
|
-
}).nullish(),
|
|
1108
|
-
"x-security": zod.z.any().nullish()
|
|
1109
|
-
});
|
|
1110
|
-
const Operation = zod.z.object({
|
|
1111
|
-
get: Endpoint.nullish(),
|
|
1112
|
-
post: Endpoint.nullish(),
|
|
1113
|
-
patch: Endpoint.nullish(),
|
|
1114
|
-
delete: Endpoint.nullish(),
|
|
1115
|
-
put: Endpoint.nullish()
|
|
1116
|
-
});
|
|
1117
|
-
const Paths = zod.z.record(Operation);
|
|
1118
|
-
zod.z.object({
|
|
1119
|
-
paths: Paths,
|
|
1120
|
-
definitions: Definitions,
|
|
1121
|
-
basePath: zod.z.string(),
|
|
1122
|
-
info: zod.z.object({
|
|
1123
|
-
description: zod.z.string(),
|
|
1124
|
-
title: zod.z.string(),
|
|
1125
|
-
contact: zod.z.object({
|
|
1126
|
-
name: zod.z.string(),
|
|
1127
|
-
url: zod.z.string(),
|
|
1128
|
-
email: zod.z.string()
|
|
1129
|
-
}),
|
|
1130
|
-
version: zod.z.string()
|
|
1131
|
-
}),
|
|
1132
|
-
schemes: zod.z.array(zod.z.string()).nullish(),
|
|
1133
|
-
components: zod.z.object({
|
|
1134
|
-
schemas: Definitions
|
|
1135
|
-
}).nullish()
|
|
1136
|
-
});
|
|
1137
1060
|
|
|
1138
|
-
|
|
1061
|
+
// src/templates/template-query-method.ts
|
|
1062
|
+
var POST_FETCH_INCLUDES_PATH = ["/table-query/"];
|
|
1063
|
+
var templateQueryMethod = ({
|
|
1139
1064
|
classMethod,
|
|
1140
|
-
description,
|
|
1141
1065
|
httpMethod,
|
|
1142
|
-
path,
|
|
1066
|
+
path: path7,
|
|
1143
1067
|
pathParams,
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1068
|
+
responseClasses,
|
|
1069
|
+
methodParams,
|
|
1070
|
+
apiGenName,
|
|
1071
|
+
description,
|
|
1148
1072
|
deprecated
|
|
1149
1073
|
}) => {
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1074
|
+
const isPostFetch = httpMethod === "post" && (POST_FETCH_INCLUDES_PATH.some((p) => path7.includes(p)) || path7.endsWith("/list"));
|
|
1075
|
+
const isFetch = classMethod.startsWith("fetch");
|
|
1076
|
+
const isGet = httpMethod === "get" || isPostFetch || isFetch;
|
|
1077
|
+
const queryMethod = isGet ? "useQuery" : "useMutation";
|
|
1078
|
+
let mParams = "";
|
|
1079
|
+
let mParamsNoTypes = "";
|
|
1080
|
+
let newPath = `'${path7}'`;
|
|
1081
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path7);
|
|
1155
1082
|
for (const pathParam of sortedPathParams) {
|
|
1156
1083
|
const type = ParserUtils.parseType(pathParam);
|
|
1157
1084
|
if (pathParam.name !== "namespace") {
|
|
1158
|
-
|
|
1159
|
-
|
|
1085
|
+
mParams += pathParam.name + `:${type}, `;
|
|
1086
|
+
mParamsNoTypes += pathParam.name + ", ";
|
|
1160
1087
|
}
|
|
1161
1088
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1162
|
-
if (
|
|
1089
|
+
if (path7.match(`{${pathParam.name}}`)) {
|
|
1163
1090
|
if (type === "string") {
|
|
1164
1091
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1165
1092
|
} else {
|
|
@@ -1167,133 +1094,121 @@ const templateMethod = ({
|
|
|
1167
1094
|
}
|
|
1168
1095
|
}
|
|
1169
1096
|
}
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
const
|
|
1181
|
-
const isDelete = ["delete"].includes(httpMethod);
|
|
1182
|
-
let dataPayload = "{params}";
|
|
1183
|
-
const descriptionText = description ? `
|
|
1184
|
-
/**${deprecated ? "\n * @deprecated" : ""}
|
|
1185
|
-
* ${description.replace(/\n/g, "\n * ")}
|
|
1186
|
-
*/` : "";
|
|
1187
|
-
let formPayloadString = "";
|
|
1188
|
-
if (isFormUrlEncoded) {
|
|
1189
|
-
formPayloadString = ``;
|
|
1190
|
-
const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
|
|
1191
|
-
dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
|
|
1192
|
-
} else if (isPostPutPatch) {
|
|
1193
|
-
dataPayload = dataType ? `data, {params}` : "null, {params}";
|
|
1194
|
-
} else if (isDelete) {
|
|
1195
|
-
dataPayload = dataType ? `{data, params}` : "{params}";
|
|
1196
|
-
}
|
|
1197
|
-
const isFileUpload = methodParams.indexOf("data: {file") > -1;
|
|
1198
|
-
const resolvedResponseClass = responseClass || "unknown";
|
|
1199
|
-
const resolvedResponseClassValidated = responseClass || "z.unknown()";
|
|
1200
|
-
methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
|
|
1201
|
-
methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
|
|
1202
|
-
let methodImpl = "";
|
|
1203
|
-
const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
|
|
1204
|
-
const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
|
|
1205
|
-
const generateMethodName = () => `${classMethod}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
|
|
1206
|
-
const responseSyncType = "IResponse";
|
|
1207
|
-
methodImpl = `${descriptionText}
|
|
1208
|
-
${generateMethodName()} {
|
|
1209
|
-
${queryParamsDefault}
|
|
1210
|
-
const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
|
|
1211
|
-
const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
|
|
1097
|
+
const { responseType } = getResponseType({ responseClasses });
|
|
1098
|
+
let _methodName = convertMethodNameToHook({ classMethod, apiGenName, isGet });
|
|
1099
|
+
const _methodParams = methodParams && methodParams.length > 0 ? `& { ${methodParams} }` : "";
|
|
1100
|
+
const _methodParamsImpl = convertToMethodImplArgs(methodParams);
|
|
1101
|
+
const queryKey = createQueryKey(apiGenName, classMethod);
|
|
1102
|
+
const descriptionText = extractDescription(description, {
|
|
1103
|
+
isDeprecated: deprecated,
|
|
1104
|
+
responseClasses,
|
|
1105
|
+
other: [" ", "#### Default Query Options", "The default options include:", "```", "{", ` queryKey: [${queryKey}, input]`, "}", "```"]
|
|
1106
|
+
});
|
|
1107
|
+
const queryMethodImpl = `
|
|
1212
1108
|
|
|
1213
|
-
${
|
|
1109
|
+
${descriptionText}
|
|
1110
|
+
export const ${_methodName} = (
|
|
1111
|
+
sdk: AccelByteSDK,
|
|
1112
|
+
input: SdkSetConfigParam ${_methodParams},
|
|
1113
|
+
options?: Omit<UseQueryOptions<${responseType}, AxiosError<ApiError>>, 'queryKey'>,
|
|
1114
|
+
callback?: (data: AxiosResponse<${responseType}>) => void
|
|
1115
|
+
): UseQueryResult<${responseType}, AxiosError<ApiError>> => {
|
|
1116
|
+
|
|
1117
|
+
const queryFn = (
|
|
1118
|
+
sdk: AccelByteSDK,
|
|
1119
|
+
input: Parameters<typeof ${_methodName}>[1]
|
|
1120
|
+
) => async () => {
|
|
1121
|
+
const response =
|
|
1122
|
+
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1123
|
+
${classMethod}(${_methodParamsImpl}))
|
|
1124
|
+
callback && callback(response)
|
|
1125
|
+
return response.data
|
|
1214
1126
|
}
|
|
1127
|
+
|
|
1128
|
+
return ${queryMethod}<${responseType}, AxiosError<ApiError>>({
|
|
1129
|
+
queryKey: [${queryKey}, input],
|
|
1130
|
+
queryFn: queryFn(sdk, input),
|
|
1131
|
+
...options
|
|
1132
|
+
})
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1215
1135
|
`;
|
|
1216
|
-
|
|
1217
|
-
|
|
1136
|
+
const mutationMethodImpl = `
|
|
1137
|
+
|
|
1138
|
+
${descriptionText}
|
|
1139
|
+
export const ${_methodName} = (
|
|
1140
|
+
sdk: AccelByteSDK,
|
|
1141
|
+
options?: Omit<UseMutationOptions<${responseType}, AxiosError<ApiError>, SdkSetConfigParam ${_methodParams}>, 'mutationKey'>,
|
|
1142
|
+
callback?: (data: ${responseType}) => void
|
|
1143
|
+
): UseMutationResult<${responseType}, AxiosError<ApiError>, SdkSetConfigParam ${_methodParams}> => {
|
|
1144
|
+
|
|
1145
|
+
const mutationFn = async (input: SdkSetConfigParam ${_methodParams}) => {
|
|
1146
|
+
const response =
|
|
1147
|
+
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1148
|
+
${classMethod}(${_methodParamsImpl}))
|
|
1149
|
+
callback && callback(response.data)
|
|
1150
|
+
return response.data
|
|
1218
1151
|
}
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
}
|
|
1152
|
+
|
|
1153
|
+
return useMutation({
|
|
1154
|
+
mutationKey: [${queryKey}],
|
|
1155
|
+
mutationFn,
|
|
1156
|
+
...options
|
|
1157
|
+
})
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
`;
|
|
1161
|
+
return isGet ? queryMethodImpl : mutationMethodImpl;
|
|
1162
|
+
};
|
|
1163
|
+
function versionMutationSuffixMethodName(baseMethodName) {
|
|
1164
|
+
const parts = baseMethodName.split(/(_v\d+)$/);
|
|
1165
|
+
const name = parts[0];
|
|
1166
|
+
const versionSuffix = parts[1] || "";
|
|
1167
|
+
const res = `${name}Mutation${versionSuffix}`;
|
|
1225
1168
|
return res;
|
|
1169
|
+
}
|
|
1170
|
+
function createQueryKey(className, methodName) {
|
|
1171
|
+
const prefixRegex = /^(get|create|update|delete|patch|post|fetch)[_]?/i;
|
|
1172
|
+
const cleanedMethodName = methodName.replace(prefixRegex, "").trim();
|
|
1173
|
+
const finalMethodName = cleanedMethodName.charAt(0).toUpperCase() + cleanedMethodName.slice(1);
|
|
1174
|
+
return `Key_${className.replace("Api", "")}.${finalMethodName}`;
|
|
1175
|
+
}
|
|
1176
|
+
var prefixMappings = {
|
|
1177
|
+
get: "use",
|
|
1178
|
+
create: "useCreate",
|
|
1179
|
+
patch: "usePatch",
|
|
1180
|
+
update: "useUpdate",
|
|
1181
|
+
delete: "useDelete",
|
|
1182
|
+
post: "usePost",
|
|
1183
|
+
fetch: "useFetch"
|
|
1226
1184
|
};
|
|
1227
|
-
|
|
1228
|
-
const
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
path,
|
|
1233
|
-
pathParams,
|
|
1234
|
-
bodyParams,
|
|
1235
|
-
responseClass,
|
|
1236
|
-
classGenName,
|
|
1237
|
-
methodParams,
|
|
1238
|
-
methodParamsNoTypes,
|
|
1239
|
-
deprecated,
|
|
1240
|
-
xSecurity
|
|
1241
|
-
}) => {
|
|
1242
|
-
let newPath = `'${path}'`;
|
|
1243
|
-
let snippetMethod = "";
|
|
1244
|
-
for (const pathParam of pathParams) {
|
|
1245
|
-
const type = ParserUtils.parseType(pathParam);
|
|
1246
|
-
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1247
|
-
if (path.match(`{${pathParam.name}}`)) {
|
|
1248
|
-
if (type === "string") {
|
|
1249
|
-
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1250
|
-
} else {
|
|
1251
|
-
newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
|
|
1252
|
-
}
|
|
1185
|
+
function convertMethodNameToHook({ classMethod, apiGenName, isGet }) {
|
|
1186
|
+
for (const [originalPrefix] of Object.entries(prefixMappings)) {
|
|
1187
|
+
if (classMethod.startsWith(originalPrefix)) {
|
|
1188
|
+
const methodName = !isGet ? versionMutationSuffixMethodName(classMethod) : classMethod;
|
|
1189
|
+
return `use${apiGenName}_${capitalize(methodName)}`;
|
|
1253
1190
|
}
|
|
1254
1191
|
}
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
|
|
1192
|
+
return classMethod;
|
|
1193
|
+
}
|
|
1194
|
+
function convertToMethodImplArgs(methodArgs) {
|
|
1195
|
+
const properties = methodArgs.split(/,\s*(?![^{}]*\})/).map((prop) => prop.trim()).filter(Boolean);
|
|
1196
|
+
const formattedProperties = [];
|
|
1197
|
+
properties.forEach((prop) => {
|
|
1198
|
+
if (prop.includes(": {")) {
|
|
1199
|
+
const propertyName = prop.split(": {")[0].replace("?", "").trim();
|
|
1200
|
+
formattedProperties.push(`input.${propertyName}`);
|
|
1201
|
+
} else {
|
|
1202
|
+
const colonIndex = prop.indexOf(":");
|
|
1203
|
+
const propertyName = prop.substring(0, colonIndex).replace("?", "").trim();
|
|
1204
|
+
formattedProperties.push(`input.${propertyName}`);
|
|
1267
1205
|
}
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
/**${deprecated ? "\n * @deprecated" : ""}
|
|
1272
|
-
* ${description.replace(/\n/g, "\n * ")}
|
|
1273
|
-
*/` : "";
|
|
1274
|
-
const resolvedResponseClass = responseClass || "unknown";
|
|
1275
|
-
const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
|
|
1276
|
-
const methodImpl = `
|
|
1277
|
-
${descriptionText}
|
|
1278
|
-
async function ${classMethod}(${methodParams}): Promise<${responseType}> {
|
|
1279
|
-
const $ = new ${classGenName}(Network.create(requestConfig), namespace, useSchemaValidation)
|
|
1280
|
-
const resp = await $.${classMethod}(${methodParamsNoTypes})
|
|
1281
|
-
if (resp.error) throw resp.error
|
|
1282
|
-
return resp.response.data
|
|
1283
|
-
}
|
|
1284
|
-
`;
|
|
1285
|
-
const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
|
|
1286
|
-
snippetMethod += `${classMethod}(${methodParams})
|
|
1287
|
-
// return ${snippetPromiseString}`;
|
|
1288
|
-
return {
|
|
1289
|
-
generatedMethodString: methodImpl,
|
|
1290
|
-
snippetApiArgs,
|
|
1291
|
-
snippetMethod,
|
|
1292
|
-
snippetShell
|
|
1293
|
-
};
|
|
1294
|
-
};
|
|
1206
|
+
});
|
|
1207
|
+
return formattedProperties.join(", ");
|
|
1208
|
+
}
|
|
1295
1209
|
|
|
1296
|
-
|
|
1210
|
+
// src/templates/template-sdk-snippet.ts
|
|
1211
|
+
var templateSdkSnippet = ({
|
|
1297
1212
|
serviceNameTitle,
|
|
1298
1213
|
apiName,
|
|
1299
1214
|
snippetMethod,
|
|
@@ -1305,11 +1220,11 @@ const templateSdkSnippet = ({
|
|
|
1305
1220
|
normMethod = normalizeMethodSnippet(normMethod, "queryParams:");
|
|
1306
1221
|
normMethod = normalizeMethodSnippet(normMethod, "queryParams?:");
|
|
1307
1222
|
normMethod += "\n\n//" + methodArr[1];
|
|
1308
|
-
const sdkSnippet = `import {
|
|
1223
|
+
const sdkSnippet = `import { AccelByte } from '@accelbyte/sdk'
|
|
1309
1224
|
import { ${serviceNameTitle} } from '@accelbyte/sdk-${serviceNameTitle.toLowerCase()}'
|
|
1310
1225
|
|
|
1311
|
-
const sdk =
|
|
1312
|
-
|
|
1226
|
+
const sdk = AccelByte.SDK({
|
|
1227
|
+
coreConfig: {
|
|
1313
1228
|
baseURL: 'https://demo.accelbyte.io',
|
|
1314
1229
|
clientId: '77f88506b6174c3ea4d925f5b4096ce8',
|
|
1315
1230
|
namespace: 'accelbyte',
|
|
@@ -1321,7 +1236,7 @@ ${serviceNameTitle}.${apiName}(${snippetApiArgs.join(", ")})
|
|
|
1321
1236
|
.${normMethod}`;
|
|
1322
1237
|
return sdkSnippet;
|
|
1323
1238
|
};
|
|
1324
|
-
|
|
1239
|
+
var normalizeMethodSnippet = (methodInput, splitWord) => {
|
|
1325
1240
|
const split1 = methodInput.split(splitWord);
|
|
1326
1241
|
if (!split1[1]) {
|
|
1327
1242
|
return methodInput;
|
|
@@ -1339,327 +1254,486 @@ const normalizeMethodSnippet = (methodInput, splitWord) => {
|
|
|
1339
1254
|
return result;
|
|
1340
1255
|
};
|
|
1341
1256
|
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1257
|
+
// src/helpers/SwaggerReaderHelpers.ts
|
|
1258
|
+
var GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
|
|
1259
|
+
var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
1260
|
+
static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
|
|
1261
|
+
static parseAllEndpoints = async ({
|
|
1262
|
+
api,
|
|
1263
|
+
sdkName,
|
|
1264
|
+
serviceName
|
|
1265
|
+
}) => {
|
|
1266
|
+
const result = {
|
|
1267
|
+
admin: {
|
|
1268
|
+
arrayDefinitions: [],
|
|
1269
|
+
snippetMap: {},
|
|
1270
|
+
tagToClassImportsRecord: {},
|
|
1271
|
+
tagToEndpointClassesRecord: {},
|
|
1272
|
+
tagToSdkClientRecord: {},
|
|
1273
|
+
tagToSdkFunctionNamesRecord: {},
|
|
1274
|
+
tagToSdkImportsRecord: {},
|
|
1275
|
+
tagToEndpointQueryRecord: {},
|
|
1276
|
+
tagToSdkFunctionDescription: {}
|
|
1277
|
+
},
|
|
1278
|
+
public: {
|
|
1279
|
+
arrayDefinitions: [],
|
|
1280
|
+
snippetMap: {},
|
|
1281
|
+
tagToClassImportsRecord: {},
|
|
1282
|
+
tagToEndpointClassesRecord: {},
|
|
1283
|
+
tagToSdkClientRecord: {},
|
|
1284
|
+
tagToSdkFunctionNamesRecord: {},
|
|
1285
|
+
tagToSdkImportsRecord: {},
|
|
1286
|
+
tagToEndpointQueryRecord: {},
|
|
1287
|
+
tagToSdkFunctionDescription: {}
|
|
1288
|
+
}
|
|
1289
|
+
};
|
|
1290
|
+
const sortedPathsByLength = new Map(
|
|
1291
|
+
Object.entries(api.paths).sort((a, b) => {
|
|
1292
|
+
if (a[0].length === b[0].length) {
|
|
1293
|
+
return a[0].localeCompare(b[0]);
|
|
1294
|
+
} else {
|
|
1295
|
+
return a[0].length - b[0].length;
|
|
1296
|
+
}
|
|
1297
|
+
})
|
|
1298
|
+
);
|
|
1299
|
+
const sortedKeys = Array.from(sortedPathsByLength.keys());
|
|
1300
|
+
const servicePrefix = _SwaggerReaderHelpers.getServicePrefix(sortedKeys);
|
|
1301
|
+
const tagToClassMethodsMap = {
|
|
1302
|
+
admin: {},
|
|
1303
|
+
public: {}
|
|
1304
|
+
};
|
|
1305
|
+
for (const [path7, operation] of sortedPathsByLength) {
|
|
1306
|
+
if (path7.indexOf("/healthz") >= 0) {
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
const isAdminEndpoint = path7.indexOf("/admin/") > -1;
|
|
1310
|
+
const picked = isAdminEndpoint ? result.admin : result.public;
|
|
1311
|
+
const {
|
|
1312
|
+
arrayDefinitions,
|
|
1313
|
+
snippetMap,
|
|
1314
|
+
tagToClassImportsRecord,
|
|
1315
|
+
tagToEndpointClassesRecord,
|
|
1316
|
+
tagToSdkClientRecord,
|
|
1317
|
+
tagToSdkFunctionNamesRecord,
|
|
1318
|
+
tagToSdkImportsRecord,
|
|
1319
|
+
tagToEndpointQueryRecord,
|
|
1320
|
+
tagToSdkFunctionDescription
|
|
1321
|
+
} = picked;
|
|
1322
|
+
const tagToClassMethodsMapByType = isAdminEndpoint ? tagToClassMethodsMap.admin : tagToClassMethodsMap.public;
|
|
1323
|
+
const generatedMethods = {};
|
|
1324
|
+
const httpMethods = Object.keys(operation);
|
|
1325
|
+
for (const httpMethod of httpMethods) {
|
|
1326
|
+
const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
|
|
1327
|
+
console.error(JSON.stringify({ path: path7, httpMethod }, null, 2));
|
|
1328
|
+
throw error;
|
|
1329
|
+
});
|
|
1330
|
+
if (!endpoint.tags) continue;
|
|
1331
|
+
const [tag] = endpoint.tags;
|
|
1332
|
+
const pathWithBase = `${api.basePath ?? ""}${path7}`;
|
|
1333
|
+
const permissionType = getPermissionType(getPermission(endpoint));
|
|
1334
|
+
tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
|
|
1335
|
+
const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
|
|
1336
|
+
const classMethod = ParserUtils.generateNaturalLangMethod({
|
|
1337
|
+
servicePrefix,
|
|
1338
|
+
path: path7,
|
|
1339
|
+
httpMethod,
|
|
1340
|
+
isForm,
|
|
1341
|
+
existingMethods: tagToClassMethodsMapByType[tag],
|
|
1342
|
+
permissionType
|
|
1343
|
+
});
|
|
1344
|
+
tagToClassMethodsMapByType[tag][classMethod] = `${path7} ${httpMethod}`;
|
|
1345
|
+
generatedMethods[`${path7} ${httpMethod}`] = `${classMethod}`;
|
|
1346
|
+
if (!snippetMap[pathWithBase]) {
|
|
1347
|
+
snippetMap[pathWithBase] = {};
|
|
1348
|
+
}
|
|
1349
|
+
const description = endpoint.description?.replace(/\s+/g, " ") || "";
|
|
1350
|
+
const responseClasses = ParserUtils.get2xxResponses(endpoint.responses);
|
|
1351
|
+
const responseClass = responseClasses.length > 1 ? null : responseClasses?.[0];
|
|
1352
|
+
const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
|
|
1353
|
+
tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
|
|
1354
|
+
if (responseClass) {
|
|
1355
|
+
tagToClassImportsRecord[className][responseClass] = `import { ${responseClass} } from '../../generated-definitions/${responseClass}.js'`;
|
|
1356
|
+
}
|
|
1357
|
+
if (responseClass && responseClass.endsWith("Array")) {
|
|
1358
|
+
arrayDefinitions.push(responseClass);
|
|
1359
|
+
}
|
|
1360
|
+
const queryParams = ParserUtils.filterQueryParameters(endpoint.parameters);
|
|
1361
|
+
const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
|
|
1362
|
+
const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
|
|
1363
|
+
let bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
|
|
1364
|
+
const deprecated = !!endpoint.deprecated;
|
|
1365
|
+
if (endpoint.requestBody) {
|
|
1366
|
+
bodyParams = [
|
|
1367
|
+
{
|
|
1368
|
+
name: "body",
|
|
1369
|
+
in: "body",
|
|
1370
|
+
schema: endpoint.requestBody.content["application/json"]?.schema
|
|
1371
|
+
}
|
|
1372
|
+
];
|
|
1373
|
+
}
|
|
1374
|
+
const { methodImpl, methodParams, methodParamsNoTypes, importStatements } = templateMethod({
|
|
1375
|
+
classMethod,
|
|
1376
|
+
description,
|
|
1377
|
+
httpMethod,
|
|
1378
|
+
path: pathWithBase,
|
|
1379
|
+
pathParams,
|
|
1380
|
+
bodyParams,
|
|
1381
|
+
queryParams,
|
|
1382
|
+
isFormUrlEncoded,
|
|
1383
|
+
responseClasses,
|
|
1384
|
+
deprecated
|
|
1385
|
+
});
|
|
1386
|
+
tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
|
|
1387
|
+
const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
|
|
1388
|
+
const queryMethodImpl = templateQueryMethod({
|
|
1389
|
+
classMethod,
|
|
1390
|
+
httpMethod,
|
|
1391
|
+
path: pathWithBase,
|
|
1392
|
+
pathParams,
|
|
1393
|
+
responseClasses,
|
|
1394
|
+
methodParams,
|
|
1395
|
+
apiGenName,
|
|
1396
|
+
deprecated,
|
|
1397
|
+
description
|
|
1398
|
+
});
|
|
1399
|
+
tagToEndpointQueryRecord[tag] = (tagToEndpointQueryRecord[tag] || "") + queryMethodImpl;
|
|
1400
|
+
const fnDescription = extractDescription(description, { isDeprecated: deprecated, responseClasses });
|
|
1401
|
+
const tagFnDescriptions = tagToSdkFunctionDescription[tag];
|
|
1402
|
+
tagToSdkFunctionDescription[tag] = {
|
|
1403
|
+
...tagFnDescriptions,
|
|
1404
|
+
[classMethod]: fnDescription
|
|
1405
|
+
};
|
|
1406
|
+
const { generatedMethodString, snippetApiArgs, snippetMethod, snippetShell } = templateApiMethod({
|
|
1407
|
+
classMethod,
|
|
1408
|
+
httpMethod,
|
|
1409
|
+
path: pathWithBase,
|
|
1410
|
+
pathParams,
|
|
1411
|
+
bodyParams,
|
|
1412
|
+
responseClasses,
|
|
1413
|
+
classGenName,
|
|
1414
|
+
methodParams,
|
|
1415
|
+
methodParamsNoTypes,
|
|
1416
|
+
xSecurity: endpoint["x-security"]
|
|
1417
|
+
});
|
|
1418
|
+
tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
|
|
1419
|
+
tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + classMethod + ",";
|
|
1420
|
+
tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
|
|
1421
|
+
const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
|
|
1422
|
+
const resultSnippet = templateSdkSnippet({
|
|
1423
|
+
serviceNameTitle,
|
|
1424
|
+
apiName: apiGenName,
|
|
1425
|
+
snippetMethod,
|
|
1426
|
+
snippetApiArgs
|
|
1427
|
+
});
|
|
1428
|
+
const currentSnippetMap = {};
|
|
1429
|
+
snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
|
|
1430
|
+
currentSnippetMap.web = resultSnippet;
|
|
1431
|
+
const generatedDirName = isAdminEndpoint ? "generated-admin" : "generated-public";
|
|
1432
|
+
currentSnippetMap.webGit = GIT_URL + `/sdk-${sdkName}/src/${generatedDirName}/${apiGenName}.ts`;
|
|
1433
|
+
currentSnippetMap.shell = snippetShell;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
for (const key in result) {
|
|
1437
|
+
result[key].arrayDefinitions = Array.from(new Set(result[key].arrayDefinitions));
|
|
1438
|
+
}
|
|
1439
|
+
return result;
|
|
1440
|
+
};
|
|
1441
|
+
};
|
|
1442
|
+
|
|
1443
|
+
// src/templates/template-api-index.ts
|
|
1444
|
+
var templateApiIndex = (serviceNameTitle, apiList) => {
|
|
1445
|
+
let imports = "";
|
|
1446
|
+
let returnStatement = "";
|
|
1447
|
+
for (const cl of apiList) {
|
|
1448
|
+
const dir = cl.toLowerCase().includes("admin") && cl !== "AdminApi" ? "generated-admin" : "generated-public";
|
|
1449
|
+
imports += `
|
|
1450
|
+
import { ${cl} } from './${dir}/${cl}.js'`;
|
|
1451
|
+
returnStatement += `
|
|
1452
|
+
${cl}, `;
|
|
1453
|
+
}
|
|
1454
|
+
return `/**
|
|
1455
|
+
* AUTO GENERATED
|
|
1456
|
+
*/
|
|
1457
|
+
${imports}
|
|
1458
|
+
import { author, name, version } from '../package.json'
|
|
1459
|
+
|
|
1460
|
+
console.log(\`\${name}@\${version}\`)
|
|
1461
|
+
|
|
1462
|
+
const apis = {
|
|
1463
|
+
${returnStatement}
|
|
1464
|
+
version: () => console.log({
|
|
1465
|
+
version,
|
|
1466
|
+
name,
|
|
1467
|
+
author
|
|
1468
|
+
})
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
export const ${serviceNameTitle} = apis
|
|
1472
|
+
`;
|
|
1473
|
+
};
|
|
1474
|
+
|
|
1475
|
+
// src/templates/template-zod.ts
|
|
1476
|
+
var TemplateZod = class {
|
|
1477
|
+
duplicates;
|
|
1478
|
+
duplicateFound = false;
|
|
1479
|
+
//
|
|
1480
|
+
importClasses = /* @__PURE__ */ new Set();
|
|
1481
|
+
// --
|
|
1482
|
+
render = (fileName, definition, duplicates) => {
|
|
1483
|
+
this.duplicates = duplicates;
|
|
1484
|
+
const content = this.parseToZodSchema(definition, definition.required || []);
|
|
1485
|
+
const containsRecursiveType = this.importClasses.has(fileName);
|
|
1486
|
+
if (containsRecursiveType) {
|
|
1487
|
+
this.importClasses.delete(fileName);
|
|
1488
|
+
}
|
|
1489
|
+
let imports = "";
|
|
1490
|
+
for (const cl of Array.from(this.importClasses).sort()) {
|
|
1491
|
+
imports += `import { ${cl} } from './${cl}.js'
|
|
1492
|
+
`;
|
|
1493
|
+
}
|
|
1494
|
+
let exportedVariableString;
|
|
1495
|
+
let exportedTypeString;
|
|
1496
|
+
if (containsRecursiveType) {
|
|
1497
|
+
exportedVariableString = `
|
|
1498
|
+
export const ${fileName}: z.ZodType<${fileName}> = z.lazy(() =>
|
|
1499
|
+
${content.schemaString}
|
|
1500
|
+
)
|
|
1501
|
+
`;
|
|
1502
|
+
exportedTypeString = `
|
|
1503
|
+
export interface ${fileName} {
|
|
1504
|
+
${content.typeString}
|
|
1505
|
+
}
|
|
1506
|
+
`;
|
|
1507
|
+
} else {
|
|
1508
|
+
exportedVariableString = `export const ${fileName} = ${content.schemaString}`;
|
|
1509
|
+
exportedTypeString = `export interface ${fileName} extends z.TypeOf<typeof ${fileName}> {}`;
|
|
1510
|
+
}
|
|
1511
|
+
const template = `import { z } from 'zod'
|
|
1512
|
+
${imports}
|
|
1513
|
+
|
|
1514
|
+
${exportedVariableString}
|
|
1515
|
+
|
|
1516
|
+
${exportedTypeString}
|
|
1517
|
+
`;
|
|
1518
|
+
return { buffer: template, duplicateFound: this.duplicateFound };
|
|
1519
|
+
};
|
|
1520
|
+
// --
|
|
1521
|
+
parseToZodSchema = (definition, requiredAttrs) => {
|
|
1522
|
+
if (definition.additionalProperties) {
|
|
1523
|
+
return this.parseToZodAttribute("", definition, []);
|
|
1524
|
+
}
|
|
1525
|
+
let properties;
|
|
1526
|
+
if (definition.properties) {
|
|
1527
|
+
properties = Object.entries(definition.properties);
|
|
1528
|
+
} else if (definition.items?.properties) {
|
|
1529
|
+
properties = Object.entries(definition.items.properties);
|
|
1530
|
+
} else {
|
|
1531
|
+
return {
|
|
1532
|
+
schemaString: "z.any()",
|
|
1533
|
+
typeString: "any"
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
const schemaFields = [];
|
|
1537
|
+
const typeFields = [];
|
|
1538
|
+
for (const property of properties) {
|
|
1539
|
+
const [name, definition2] = property;
|
|
1540
|
+
const result = this.parseToZodAttribute(name, definition2, requiredAttrs);
|
|
1541
|
+
schemaFields.push(result.schemaString);
|
|
1542
|
+
typeFields.push(result.typeString);
|
|
1543
|
+
}
|
|
1544
|
+
if (definition?.type === "array") {
|
|
1545
|
+
return {
|
|
1546
|
+
schemaString: `z.array(z.object({${schemaFields.join(",")}}))`,
|
|
1547
|
+
typeString: typeFields.join(";")
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
return {
|
|
1551
|
+
schemaString: `z.object({${schemaFields.join(",")}})`,
|
|
1552
|
+
typeString: typeFields.join(";")
|
|
1553
|
+
};
|
|
1554
|
+
};
|
|
1555
|
+
// --
|
|
1556
|
+
parseToZodAttribute = (name, definition, requiredAttrs) => {
|
|
1557
|
+
const isRequired = requiredAttrs.includes(name) || name === "";
|
|
1558
|
+
const schemaRequired = isRequired ? "" : ".nullish()";
|
|
1559
|
+
const typeRequired = isRequired ? "" : "?";
|
|
1560
|
+
const typeNullishability = isRequired ? "" : " | null | undefined";
|
|
1561
|
+
const schemaAttribute = name ? `'${name}':` : "";
|
|
1562
|
+
const typeAttribute = name ? `'${name}'${typeRequired}:` : "";
|
|
1563
|
+
const type = definition?.type;
|
|
1564
|
+
if (definition.properties) {
|
|
1565
|
+
const result = this.parseToZodSchema(definition, requiredAttrs);
|
|
1566
|
+
return {
|
|
1567
|
+
schemaString: `${schemaAttribute} ${result.schemaString}${schemaRequired}`,
|
|
1568
|
+
typeString: `${typeAttribute} ${result.typeString}${typeNullishability}`
|
|
1569
|
+
};
|
|
1570
|
+
} else if (type) {
|
|
1571
|
+
if (type === "object" && definition.additionalProperties) {
|
|
1572
|
+
const zodAttribute = this.parseToZodAttribute("", definition.additionalProperties, [""]);
|
|
1573
|
+
return {
|
|
1574
|
+
schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
|
|
1575
|
+
typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
if (type === "object" && !definition.additionalProperties && !name) {
|
|
1579
|
+
return {
|
|
1580
|
+
schemaString: `z.any()`,
|
|
1581
|
+
typeString: "any"
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
if (type === "object" && !definition.additionalProperties) {
|
|
1585
|
+
return {
|
|
1586
|
+
schemaString: `${schemaAttribute} z.record(z.any())${schemaRequired}`,
|
|
1587
|
+
typeString: `${typeAttribute} Record<string, any>${typeNullishability}`
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
if (type === "integer" || type === "number") {
|
|
1591
|
+
const effectiveType = getZodNumberType(type);
|
|
1592
|
+
return {
|
|
1593
|
+
schemaString: `${schemaAttribute} z.${effectiveType.schemaString}()${schemaRequired}`,
|
|
1594
|
+
typeString: `${typeAttribute} ${effectiveType.typeString}${typeNullishability}`
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
if (type === "array") {
|
|
1598
|
+
const items = definition.items;
|
|
1599
|
+
const ref2 = items?.$ref;
|
|
1600
|
+
let model2;
|
|
1601
|
+
if (ref2) {
|
|
1602
|
+
const refType = ParserUtils.parseRefType(ref2);
|
|
1603
|
+
this.importClasses.add(refType);
|
|
1604
|
+
model2 = {
|
|
1605
|
+
schemaString: refType,
|
|
1606
|
+
typeString: refType
|
|
1607
|
+
};
|
|
1608
|
+
} else if (items) {
|
|
1609
|
+
if (items.type === "array") {
|
|
1610
|
+
const ref3 = items.items?.$ref;
|
|
1611
|
+
if (ref3) {
|
|
1612
|
+
const refType = ParserUtils.parseRefType(ref3);
|
|
1613
|
+
this.importClasses.add(refType);
|
|
1614
|
+
model2 = {
|
|
1615
|
+
schemaString: refType,
|
|
1616
|
+
typeString: refType
|
|
1617
|
+
};
|
|
1618
|
+
} else if (items.items) {
|
|
1619
|
+
model2 = this.parseEnumItems(items.items);
|
|
1620
|
+
}
|
|
1621
|
+
return {
|
|
1622
|
+
schemaString: `${schemaAttribute} z.array(z.array(${model2.schemaString}))${schemaRequired}`,
|
|
1623
|
+
typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
|
|
1624
|
+
};
|
|
1625
|
+
} else {
|
|
1626
|
+
model2 = this.parseEnumItems(items);
|
|
1627
|
+
}
|
|
1628
|
+
} else {
|
|
1629
|
+
return {
|
|
1630
|
+
schemaString: `${schemaAttribute} z.array(z.any())${schemaRequired}`,
|
|
1631
|
+
typeString: `${typeAttribute} any[]${typeNullishability}`
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
return {
|
|
1635
|
+
schemaString: `${schemaAttribute} z.array(${model2.schemaString})${schemaRequired}`,
|
|
1636
|
+
typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
if (type !== "object") {
|
|
1640
|
+
const result = extractEnumObject(type, isRequired, definition.enum);
|
|
1641
|
+
return {
|
|
1642
|
+
schemaString: `${schemaAttribute} ${result.schemaString}`,
|
|
1643
|
+
typeString: `${typeAttribute} ${result.typeString}`
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
const ref = definition.$ref;
|
|
1648
|
+
let model = `z.record(z.any())`;
|
|
1649
|
+
if (ref) {
|
|
1650
|
+
model = ParserUtils.parseRefType(ref);
|
|
1651
|
+
const fullModelName = ref.replace("#/definitions/", "");
|
|
1652
|
+
this.duplicateFound = this.duplicates.has(fullModelName);
|
|
1653
|
+
if (this.duplicateFound) {
|
|
1654
|
+
model = this.duplicates.get(fullModelName);
|
|
1655
|
+
}
|
|
1656
|
+
this.importClasses.add(model);
|
|
1657
|
+
model = `${model}`;
|
|
1658
|
+
}
|
|
1659
|
+
return {
|
|
1660
|
+
schemaString: `${schemaAttribute} ${model}${schemaRequired}`,
|
|
1661
|
+
typeString: `${typeAttribute} ${model}${typeNullishability}`
|
|
1662
|
+
};
|
|
1663
|
+
};
|
|
1664
|
+
parseEnumItems = (items) => {
|
|
1665
|
+
if (items.enum) {
|
|
1666
|
+
const enumStr = items.enum.map((e) => {
|
|
1667
|
+
return `"${e}"`;
|
|
1668
|
+
});
|
|
1669
|
+
return {
|
|
1670
|
+
schemaString: `z.enum([${enumStr}])`,
|
|
1671
|
+
typeString: `(${enumStr.join(" | ")})`
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
if (items.type === "object") {
|
|
1675
|
+
return this.parseToZodSchema(items, items.required);
|
|
1377
1676
|
}
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
callback?: (data: ${_responseType}) => void
|
|
1392
|
-
): UseQueryResult<${_responseType}, AxiosError<ApiError>> => {
|
|
1677
|
+
let effectiveType;
|
|
1678
|
+
if (items.type === "integer" || items.type === "number") {
|
|
1679
|
+
effectiveType = getZodNumberType(items.type);
|
|
1680
|
+
} else {
|
|
1681
|
+
effectiveType = { typeString: items.type, schemaString: items.type };
|
|
1682
|
+
}
|
|
1683
|
+
return {
|
|
1684
|
+
schemaString: `z.${effectiveType.schemaString}()`,
|
|
1685
|
+
typeString: effectiveType.typeString
|
|
1686
|
+
};
|
|
1687
|
+
};
|
|
1688
|
+
};
|
|
1689
|
+
var TemplateZodArray = class {
|
|
1393
1690
|
//
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
const data =
|
|
1399
|
-
(await ${apiGenName}(sdk, { namespace: input.namespace }).
|
|
1400
|
-
${classMethod}(${_methodParamsImpl}))
|
|
1401
|
-
callback && callback(data)
|
|
1402
|
-
return data
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
return ${queryMethod}<${_responseType}, AxiosError<ApiError>>({
|
|
1406
|
-
queryKey: [${createQueryKey(apiGenName, classMethod)}, input],
|
|
1407
|
-
queryFn: queryFn(sdk, input),
|
|
1408
|
-
...options
|
|
1409
|
-
})
|
|
1410
|
-
}
|
|
1691
|
+
render = (name) => {
|
|
1692
|
+
const cls = name.replace("Array", "");
|
|
1693
|
+
const template = `import { z } from 'zod'
|
|
1694
|
+
import { ${cls} } from './${cls}.js'
|
|
1411
1695
|
|
|
1412
|
-
|
|
1413
|
-
const mutationMethodImpl = `
|
|
1696
|
+
export const ${name} = z.array(${cls})
|
|
1414
1697
|
|
|
1415
|
-
export
|
|
1416
|
-
sdk: AccelbyteSDK,
|
|
1417
|
-
options?: Omit<UseMutationOptions<${_responseType}, AxiosError<ApiError>, ApiArgs ${_methodParams}>, 'mutationKey'>,
|
|
1418
|
-
callback?: (data: ${_responseType}) => void
|
|
1419
|
-
): UseMutationResult<${_responseType}, AxiosError<ApiError>, ApiArgs ${_methodParams}> => {
|
|
1420
|
-
//
|
|
1421
|
-
const mutationFn = async (input: ApiArgs ${_methodParams}) => {
|
|
1422
|
-
const data =
|
|
1423
|
-
(await ${apiGenName}(sdk, { namespace: input.namespace, config: input.config }).
|
|
1424
|
-
${classMethod}(${_methodParamsImpl}))
|
|
1425
|
-
callback && callback(data)
|
|
1426
|
-
return data
|
|
1427
|
-
}
|
|
1428
|
-
|
|
1429
|
-
return useMutation({
|
|
1430
|
-
mutationKey: [${createQueryKey(apiGenName, classMethod)}],
|
|
1431
|
-
mutationFn,
|
|
1432
|
-
...options
|
|
1433
|
-
})
|
|
1434
|
-
}
|
|
1435
|
-
|
|
1698
|
+
export interface ${name} extends z.TypeOf<typeof ${name}> {}
|
|
1436
1699
|
`;
|
|
1437
|
-
|
|
1700
|
+
return template;
|
|
1701
|
+
};
|
|
1438
1702
|
};
|
|
1439
|
-
|
|
1440
|
-
if (
|
|
1441
|
-
return
|
|
1703
|
+
var getZodNumberType = (type) => {
|
|
1704
|
+
if (type === "integer") {
|
|
1705
|
+
return {
|
|
1706
|
+
schemaString: "number().int",
|
|
1707
|
+
typeString: "number"
|
|
1708
|
+
};
|
|
1442
1709
|
}
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
}
|
|
1448
|
-
const prefixMappings = {
|
|
1449
|
-
get: "use",
|
|
1450
|
-
create: "useCreate",
|
|
1451
|
-
patch: "usePatch",
|
|
1452
|
-
update: "useUpdate",
|
|
1453
|
-
delete: "useDelete"
|
|
1710
|
+
return {
|
|
1711
|
+
schemaString: type,
|
|
1712
|
+
typeString: type
|
|
1713
|
+
};
|
|
1454
1714
|
};
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
return newMethodName + "Mutation";
|
|
1466
|
-
}
|
|
1467
|
-
}
|
|
1468
|
-
}
|
|
1469
|
-
return classMethod;
|
|
1470
|
-
}
|
|
1471
|
-
function convertToMethodImplArgs(methodArgs) {
|
|
1472
|
-
let properties = methodArgs.split(/,\s*(?![^{}]*\})/).map((prop) => prop.trim()).filter(Boolean);
|
|
1473
|
-
let formattedProperties = [];
|
|
1474
|
-
properties.forEach((prop) => {
|
|
1475
|
-
if (prop.includes(": {")) {
|
|
1476
|
-
const propertyName = prop.split(": {")[0].replace("?", "").trim();
|
|
1477
|
-
formattedProperties.push(`input.${propertyName}`);
|
|
1478
|
-
} else {
|
|
1479
|
-
const colonIndex = prop.indexOf(":");
|
|
1480
|
-
const propertyName = prop.substring(0, colonIndex).replace("?", "").trim();
|
|
1481
|
-
formattedProperties.push(`input.${propertyName}`);
|
|
1482
|
-
}
|
|
1483
|
-
});
|
|
1484
|
-
return formattedProperties.join(", ");
|
|
1485
|
-
}
|
|
1486
|
-
|
|
1487
|
-
const GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
|
|
1488
|
-
class SwaggerReaderHelpers {
|
|
1489
|
-
static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
|
|
1490
|
-
static parseAllEndpoints = async ({
|
|
1491
|
-
api,
|
|
1492
|
-
sdkName,
|
|
1493
|
-
serviceName
|
|
1494
|
-
}) => {
|
|
1495
|
-
const result = {
|
|
1496
|
-
admin: {
|
|
1497
|
-
arrayDefinitions: [],
|
|
1498
|
-
snippetMap: {},
|
|
1499
|
-
tagToClassImportsRecord: {},
|
|
1500
|
-
tagToEndpointClassesRecord: {},
|
|
1501
|
-
tagToSdkClientRecord: {},
|
|
1502
|
-
tagToSdkFunctionNamesRecord: {},
|
|
1503
|
-
tagToSdkImportsRecord: {},
|
|
1504
|
-
tagToEndpointQueryRecord: {}
|
|
1505
|
-
},
|
|
1506
|
-
public: {
|
|
1507
|
-
arrayDefinitions: [],
|
|
1508
|
-
snippetMap: {},
|
|
1509
|
-
tagToClassImportsRecord: {},
|
|
1510
|
-
tagToEndpointClassesRecord: {},
|
|
1511
|
-
tagToSdkClientRecord: {},
|
|
1512
|
-
tagToSdkFunctionNamesRecord: {},
|
|
1513
|
-
tagToSdkImportsRecord: {},
|
|
1514
|
-
tagToEndpointQueryRecord: {}
|
|
1515
|
-
}
|
|
1516
|
-
};
|
|
1517
|
-
const sortedPathsByLength = new Map(Object.entries(api.paths).sort((a, b) => {
|
|
1518
|
-
if (a[0].length === b[0].length) {
|
|
1519
|
-
return a[0].localeCompare(b[0]);
|
|
1520
|
-
} else {
|
|
1521
|
-
return a[0].length - b[0].length;
|
|
1522
|
-
}
|
|
1523
|
-
}));
|
|
1524
|
-
const sortedKeys = Array.from(sortedPathsByLength.keys());
|
|
1525
|
-
const servicePrefix = SwaggerReaderHelpers.getServicePrefix(sortedKeys);
|
|
1526
|
-
const tagToClassMethodsMap = {
|
|
1527
|
-
admin: {},
|
|
1528
|
-
public: {}
|
|
1715
|
+
var extractEnumObject = (type, isRequired, enumArr) => {
|
|
1716
|
+
const schemaRequired = isRequired ? "" : ".nullish()";
|
|
1717
|
+
const typeNullishability = isRequired ? "" : " | null | undefined";
|
|
1718
|
+
if (enumArr) {
|
|
1719
|
+
const enumStr = enumArr.map((e) => {
|
|
1720
|
+
return `"${e}"`;
|
|
1721
|
+
});
|
|
1722
|
+
return {
|
|
1723
|
+
schemaString: `z.enum([${enumStr}])${schemaRequired}`,
|
|
1724
|
+
typeString: `(${enumStr.join(" | ")}${typeNullishability})`
|
|
1529
1725
|
};
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
const isAdminEndpoint = path.indexOf("/admin/") > -1;
|
|
1535
|
-
const picked = isAdminEndpoint ? result.admin : result.public;
|
|
1536
|
-
const {
|
|
1537
|
-
arrayDefinitions,
|
|
1538
|
-
snippetMap,
|
|
1539
|
-
tagToClassImportsRecord,
|
|
1540
|
-
tagToEndpointClassesRecord,
|
|
1541
|
-
tagToSdkClientRecord,
|
|
1542
|
-
tagToSdkFunctionNamesRecord,
|
|
1543
|
-
tagToSdkImportsRecord,
|
|
1544
|
-
tagToEndpointQueryRecord
|
|
1545
|
-
} = picked;
|
|
1546
|
-
const tagToClassMethodsMapByType = isAdminEndpoint ? tagToClassMethodsMap.admin : tagToClassMethodsMap.public;
|
|
1547
|
-
const httpMethods = Object.keys(operation);
|
|
1548
|
-
for (const httpMethod of httpMethods) {
|
|
1549
|
-
const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
|
|
1550
|
-
console.error(JSON.stringify({ path, httpMethod }, null, 2));
|
|
1551
|
-
throw error;
|
|
1552
|
-
});
|
|
1553
|
-
if (!endpoint.tags)
|
|
1554
|
-
continue;
|
|
1555
|
-
const [tag] = endpoint.tags;
|
|
1556
|
-
const pathWithBase = `${api.basePath ?? ""}${path}`;
|
|
1557
|
-
tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
|
|
1558
|
-
const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
|
|
1559
|
-
const classMethod = ParserUtils.generateNaturalLangMethod({
|
|
1560
|
-
servicePrefix,
|
|
1561
|
-
path,
|
|
1562
|
-
httpMethod,
|
|
1563
|
-
isForm,
|
|
1564
|
-
existingMethods: tagToClassMethodsMapByType[tag]
|
|
1565
|
-
});
|
|
1566
|
-
tagToClassMethodsMapByType[tag][classMethod] = `${path} ${httpMethod}`;
|
|
1567
|
-
if (!snippetMap[pathWithBase]) {
|
|
1568
|
-
snippetMap[pathWithBase] = {};
|
|
1569
|
-
}
|
|
1570
|
-
const description = endpoint.description?.replace(/\s+/g, " ") || "";
|
|
1571
|
-
const responseClass = ParserUtils.get2xxResponse(endpoint.responses);
|
|
1572
|
-
const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
|
|
1573
|
-
tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
|
|
1574
|
-
if (responseClass) {
|
|
1575
|
-
const importTypeClass = ParserUtils.parseRefType(responseClass);
|
|
1576
|
-
tagToClassImportsRecord[className][importTypeClass] = `import { ${importTypeClass} } from '../../generated-definitions/${importTypeClass}.js'`;
|
|
1577
|
-
}
|
|
1578
|
-
if (responseClass && responseClass.endsWith("Array")) {
|
|
1579
|
-
arrayDefinitions.push(responseClass);
|
|
1580
|
-
}
|
|
1581
|
-
const queryParams = ParserUtils.filterQueryParameters(endpoint.parameters);
|
|
1582
|
-
const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
|
|
1583
|
-
const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
|
|
1584
|
-
let bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
|
|
1585
|
-
const deprecated = !!endpoint.deprecated;
|
|
1586
|
-
if (endpoint.requestBody) {
|
|
1587
|
-
bodyParams = [
|
|
1588
|
-
{
|
|
1589
|
-
name: "body",
|
|
1590
|
-
in: "body",
|
|
1591
|
-
schema: endpoint.requestBody.content["application/json"]?.schema
|
|
1592
|
-
}
|
|
1593
|
-
];
|
|
1594
|
-
}
|
|
1595
|
-
const { methodImpl, methodParams, methodParamsNoTypes, importStatements } = templateMethod({
|
|
1596
|
-
classMethod: ParserUtils.addDeprecatedSuffix(deprecated, classMethod),
|
|
1597
|
-
description,
|
|
1598
|
-
httpMethod,
|
|
1599
|
-
path: pathWithBase,
|
|
1600
|
-
pathParams,
|
|
1601
|
-
bodyParams,
|
|
1602
|
-
queryParams,
|
|
1603
|
-
isFormUrlEncoded,
|
|
1604
|
-
responseClass,
|
|
1605
|
-
deprecated
|
|
1606
|
-
});
|
|
1607
|
-
tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
|
|
1608
|
-
const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
|
|
1609
|
-
const queryMethodImpl = templateQueryMethod({
|
|
1610
|
-
classMethod: ParserUtils.addDeprecatedSuffix(deprecated, classMethod),
|
|
1611
|
-
httpMethod,
|
|
1612
|
-
path: pathWithBase,
|
|
1613
|
-
pathParams,
|
|
1614
|
-
responseClass,
|
|
1615
|
-
methodParams,
|
|
1616
|
-
apiGenName,
|
|
1617
|
-
isFormUrlEncoded,
|
|
1618
|
-
deprecated
|
|
1619
|
-
});
|
|
1620
|
-
tagToEndpointQueryRecord[tag] = (tagToEndpointQueryRecord[tag] || "") + queryMethodImpl;
|
|
1621
|
-
const { generatedMethodString, snippetApiArgs, snippetMethod, snippetShell } = templateApiMethod({
|
|
1622
|
-
classMethod: ParserUtils.addDeprecatedSuffix(deprecated, classMethod),
|
|
1623
|
-
description,
|
|
1624
|
-
httpMethod,
|
|
1625
|
-
path: pathWithBase,
|
|
1626
|
-
pathParams,
|
|
1627
|
-
bodyParams,
|
|
1628
|
-
responseClass,
|
|
1629
|
-
classGenName,
|
|
1630
|
-
methodParams,
|
|
1631
|
-
methodParamsNoTypes,
|
|
1632
|
-
deprecated,
|
|
1633
|
-
xSecurity: endpoint["x-security"]
|
|
1634
|
-
});
|
|
1635
|
-
tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
|
|
1636
|
-
tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + ParserUtils.addDeprecatedSuffix(deprecated, classMethod) + ",";
|
|
1637
|
-
tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
|
|
1638
|
-
const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
|
|
1639
|
-
const resultSnippet = templateSdkSnippet({
|
|
1640
|
-
serviceNameTitle,
|
|
1641
|
-
apiName: apiGenName,
|
|
1642
|
-
snippetMethod,
|
|
1643
|
-
snippetApiArgs
|
|
1644
|
-
});
|
|
1645
|
-
const currentSnippetMap = {};
|
|
1646
|
-
snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
|
|
1647
|
-
currentSnippetMap.web = resultSnippet;
|
|
1648
|
-
const generatedDirName = isAdminEndpoint ? "generated-admin" : "generated-public";
|
|
1649
|
-
currentSnippetMap.webGit = GIT_URL + `/sdk-${sdkName}/src/${generatedDirName}/${apiGenName}.ts`;
|
|
1650
|
-
currentSnippetMap.shell = snippetShell;
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
for (const key in result) {
|
|
1654
|
-
result[key].arrayDefinitions = Array.from(new Set(result[key].arrayDefinitions));
|
|
1655
|
-
}
|
|
1656
|
-
return result;
|
|
1726
|
+
}
|
|
1727
|
+
return {
|
|
1728
|
+
schemaString: `z.${type}()${schemaRequired}`,
|
|
1729
|
+
typeString: `${type}${typeNullishability}`
|
|
1657
1730
|
};
|
|
1658
|
-
}
|
|
1731
|
+
};
|
|
1659
1732
|
|
|
1660
|
-
|
|
1733
|
+
// src/CodeGenerator.ts
|
|
1734
|
+
var CodeGenerator = class _CodeGenerator {
|
|
1661
1735
|
static srcFolder = () => CliParser.getOutputPath();
|
|
1662
|
-
static getGeneratedFolder = (isAdmin) => isAdmin ? `${
|
|
1736
|
+
static getGeneratedFolder = (isAdmin) => isAdmin ? `${_CodeGenerator.srcFolder()}/generated-admin` : `${_CodeGenerator.srcFolder()}/generated-public`;
|
|
1663
1737
|
static getGeneratedSnippetsFolder = () => `${CliParser.getSnippetOutputPath()}/generated-snippets`;
|
|
1664
1738
|
static prepareDirs = (DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES) => {
|
|
1665
1739
|
ParserUtils.mkdirIfNotExist(DIST_DEFINITION_DIR);
|
|
@@ -1673,33 +1747,47 @@ class CodeGenerator {
|
|
|
1673
1747
|
const serviceName = nameArray[0];
|
|
1674
1748
|
const sdkName = nameArray[1];
|
|
1675
1749
|
const swaggerFile = nameArray[2];
|
|
1676
|
-
const parser = new
|
|
1750
|
+
const parser = new import_swagger_parser.default();
|
|
1677
1751
|
const swaggerFilePath = `${CliParser.getSwaggersOutputPath()}/${swaggerFile}`;
|
|
1678
1752
|
const api = await parser.parse(swaggerFilePath);
|
|
1679
1753
|
const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
|
|
1680
1754
|
const indexImportsSet = /* @__PURE__ */ new Set();
|
|
1755
|
+
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
1681
1756
|
const apiInfo = { ...api.info, "x-version": api["x-version"]?.version };
|
|
1682
1757
|
console.log("----------\nGenerating API:", { title: apiInfo.title, version: apiInfo.version });
|
|
1683
|
-
ParserUtils.
|
|
1684
|
-
ParserUtils.writeXVersion(CodeGenerator.srcFolder(), api["x-version"], api.info);
|
|
1758
|
+
ParserUtils.writeXVersion(_CodeGenerator.srcFolder(), api["x-version"], api.info);
|
|
1685
1759
|
const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
|
|
1686
1760
|
if (CliParser.getSnippetOutputPath()) {
|
|
1687
1761
|
try {
|
|
1688
|
-
ParserUtils.
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1762
|
+
ParserUtils.mkdirIfNotExist(_CodeGenerator.getGeneratedSnippetsFolder());
|
|
1763
|
+
ParserUtils.writeSnippetFile(
|
|
1764
|
+
_CodeGenerator.getGeneratedSnippetsFolder(),
|
|
1765
|
+
api.info.title,
|
|
1766
|
+
JSON.stringify(
|
|
1767
|
+
{
|
|
1768
|
+
...parsedInformation.public.snippetMap,
|
|
1769
|
+
...parsedInformation.admin.snippetMap
|
|
1770
|
+
},
|
|
1771
|
+
null,
|
|
1772
|
+
2
|
|
1773
|
+
)
|
|
1774
|
+
);
|
|
1692
1775
|
} catch (err) {
|
|
1693
|
-
console.
|
|
1776
|
+
console.error("Error generating snippets", err);
|
|
1694
1777
|
}
|
|
1695
1778
|
}
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
const
|
|
1701
|
-
|
|
1779
|
+
if (CliParser.isGenerateSnippetOnly()) {
|
|
1780
|
+
console.log("\nSuccessfully generate SDK snippets only\n----------\n\n");
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
const DIST_DIR = (isAdmin) => `${_CodeGenerator.getGeneratedFolder(isAdmin)}`;
|
|
1784
|
+
const DIST_DIR_ENDPOINTS = (isAdmin) => import_path3.default.join(DIST_DIR(isAdmin), "endpoints");
|
|
1785
|
+
const DIST_DIR_QUERIES = (isAdmin) => import_path3.default.join(DIST_DIR(isAdmin), "queries");
|
|
1786
|
+
const DIST_DEFINITION_DIR = import_path3.default.join(_CodeGenerator.srcFolder(), "generated-definitions");
|
|
1787
|
+
const targetSrcFolder = `${_CodeGenerator.srcFolder()}/`;
|
|
1788
|
+
_CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
|
|
1702
1789
|
const mainApiList = [];
|
|
1790
|
+
const generatedDefinitions = [];
|
|
1703
1791
|
const generatePublicOrAdmin = (isAdmin) => {
|
|
1704
1792
|
const parsedInformationByType = isAdmin ? parsedInformation.admin : parsedInformation.public;
|
|
1705
1793
|
const {
|
|
@@ -1709,7 +1797,8 @@ class CodeGenerator {
|
|
|
1709
1797
|
tagToSdkClientRecord,
|
|
1710
1798
|
tagToSdkFunctionNamesRecord,
|
|
1711
1799
|
tagToSdkImportsRecord,
|
|
1712
|
-
tagToEndpointQueryRecord
|
|
1800
|
+
tagToEndpointQueryRecord,
|
|
1801
|
+
tagToSdkFunctionDescription
|
|
1713
1802
|
} = parsedInformationByType;
|
|
1714
1803
|
const writeApiEndpointFiles = (isAdminEndpoint) => {
|
|
1715
1804
|
const apiList = [];
|
|
@@ -1722,16 +1811,36 @@ class CodeGenerator {
|
|
|
1722
1811
|
ParserUtils.writeClassFile(DIST_DIR_ENDPOINTS(isAdminEndpoint), classGenName, classBuffer, imports);
|
|
1723
1812
|
const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
|
|
1724
1813
|
const queryBuffer = tagToEndpointQueryRecord[tag];
|
|
1725
|
-
const queryFileName =
|
|
1814
|
+
const queryFileName = !CliParser.skipReactQuery() && ParserUtils.writeQueryFile(
|
|
1815
|
+
DIST_DIR_QUERIES(isAdminEndpoint),
|
|
1816
|
+
apiGenName,
|
|
1817
|
+
queryBuffer,
|
|
1818
|
+
apiImports,
|
|
1819
|
+
serviceNameTitle,
|
|
1820
|
+
tagToSdkFunctionNamesRecord[tag],
|
|
1821
|
+
imports,
|
|
1822
|
+
sdkName
|
|
1823
|
+
);
|
|
1726
1824
|
const apiBuffer = tagToSdkClientRecord[tag];
|
|
1727
|
-
ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports,
|
|
1825
|
+
ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionDescription[tag]);
|
|
1728
1826
|
apiList.push(apiGenName);
|
|
1729
|
-
indexImportsSet.add(
|
|
1730
|
-
|
|
1731
|
-
|
|
1827
|
+
indexImportsSet.add(
|
|
1828
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder)
|
|
1829
|
+
);
|
|
1830
|
+
indexImportsSet.add(
|
|
1831
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder)
|
|
1832
|
+
);
|
|
1833
|
+
queryFileName && queryImportsSet.add(
|
|
1834
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1835
|
+
import_path3.default.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`),
|
|
1836
|
+
targetSrcFolder
|
|
1837
|
+
)
|
|
1838
|
+
);
|
|
1732
1839
|
}
|
|
1733
1840
|
mainApiList.push(...apiList);
|
|
1734
|
-
indexImportsSet.add(
|
|
1841
|
+
indexImportsSet.add(
|
|
1842
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(_CodeGenerator.srcFolder(), serviceNameTitle), targetSrcFolder)
|
|
1843
|
+
);
|
|
1735
1844
|
};
|
|
1736
1845
|
const writeDefinitions = (api2) => {
|
|
1737
1846
|
const duplicates = /* @__PURE__ */ new Map();
|
|
@@ -1739,19 +1848,21 @@ class CodeGenerator {
|
|
|
1739
1848
|
for (const ref in definitions) {
|
|
1740
1849
|
const definition = definitions[ref];
|
|
1741
1850
|
const fileName = ParserUtils.parseRefType(ref);
|
|
1742
|
-
const fileExist =
|
|
1851
|
+
const fileExist = import_fs4.default.existsSync(import_path3.default.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
|
|
1743
1852
|
if (fileExist) {
|
|
1744
1853
|
const duplicateName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
|
|
1745
1854
|
duplicates.set(ref, duplicateName);
|
|
1746
1855
|
}
|
|
1747
1856
|
const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
|
|
1857
|
+
generatedDefinitions.push(fileName);
|
|
1748
1858
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
|
|
1749
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1859
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
|
|
1750
1860
|
}
|
|
1751
1861
|
for (const arrayClass of arrayDefinitions) {
|
|
1752
1862
|
const buffer = new TemplateZodArray().render(arrayClass);
|
|
1863
|
+
generatedDefinitions.push(arrayClass);
|
|
1753
1864
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
|
|
1754
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1865
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
|
|
1755
1866
|
}
|
|
1756
1867
|
};
|
|
1757
1868
|
writeApiEndpointFiles(isAdmin);
|
|
@@ -1759,45 +1870,48 @@ class CodeGenerator {
|
|
|
1759
1870
|
};
|
|
1760
1871
|
generatePublicOrAdmin(true);
|
|
1761
1872
|
generatePublicOrAdmin(false);
|
|
1762
|
-
const apiIndexBuff = templateApiIndex(
|
|
1763
|
-
ParserUtils.writeApiMainFile(
|
|
1873
|
+
const apiIndexBuff = templateApiIndex(serviceNameTitle, mainApiList);
|
|
1874
|
+
ParserUtils.writeApiMainFile(_CodeGenerator.srcFolder(), serviceNameTitle, apiIndexBuff);
|
|
1764
1875
|
console.log("\nCOMPLETED\n----------\n\n");
|
|
1765
|
-
return indexImportsSet;
|
|
1876
|
+
return { indexImports: indexImportsSet, queryImports: queryImportsSet };
|
|
1766
1877
|
};
|
|
1767
|
-
|
|
1878
|
+
// end of main
|
|
1879
|
+
};
|
|
1768
1880
|
|
|
1769
|
-
|
|
1881
|
+
// src/SwaggerDownloader.ts
|
|
1882
|
+
var https = __toESM(require("https"));
|
|
1883
|
+
var fs5 = __toESM(require("fs"));
|
|
1884
|
+
var path5 = __toESM(require("path"));
|
|
1885
|
+
var SwaggerDownloader = class _SwaggerDownloader {
|
|
1770
1886
|
static getDestFile = (targetFileName) => {
|
|
1771
1887
|
const destPath = CliParser.getResolvedSwaggersOutputPath();
|
|
1772
|
-
const destFile =
|
|
1773
|
-
if (
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
fs__namespace.mkdirSync(destPath);
|
|
1777
|
-
fs__namespace.writeFileSync(destFile, "");
|
|
1888
|
+
const destFile = path5.join(destPath, targetFileName);
|
|
1889
|
+
if (fs5.existsSync(destFile)) return destFile;
|
|
1890
|
+
if (!fs5.existsSync(destPath)) fs5.mkdirSync(destPath);
|
|
1891
|
+
fs5.writeFileSync(destFile, "");
|
|
1778
1892
|
return destFile;
|
|
1779
1893
|
};
|
|
1894
|
+
// session-api.json contains illegal URL encoded character that breaks the codegen
|
|
1895
|
+
// e.g. "$ref": "#/definitions/map%5Bstring%5Dinterface%20%7B%7D"
|
|
1780
1896
|
static postSanitizeDownloadedFile = (filePath) => {
|
|
1781
1897
|
const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
|
|
1782
|
-
|
|
1783
|
-
if (err)
|
|
1784
|
-
throw err;
|
|
1898
|
+
fs5.readFile(filePath, "utf8", (err, data) => {
|
|
1899
|
+
if (err) throw err;
|
|
1785
1900
|
let result = data;
|
|
1786
1901
|
searchStr.forEach((s) => {
|
|
1787
1902
|
result = result.replace(new RegExp(s, "g"), " ");
|
|
1788
1903
|
});
|
|
1789
|
-
|
|
1790
|
-
if (err2)
|
|
1791
|
-
throw err2;
|
|
1904
|
+
fs5.writeFile(filePath, result, "utf8", (err2) => {
|
|
1905
|
+
if (err2) throw err2;
|
|
1792
1906
|
console.log("File updated successfully.");
|
|
1793
1907
|
});
|
|
1794
1908
|
});
|
|
1795
1909
|
};
|
|
1796
1910
|
static downloadFile = async (targetFileName, url) => {
|
|
1797
|
-
const destFile =
|
|
1911
|
+
const destFile = _SwaggerDownloader.getDestFile(targetFileName);
|
|
1798
1912
|
let data = "";
|
|
1799
|
-
return new Promise((
|
|
1800
|
-
const request =
|
|
1913
|
+
return new Promise((resolve2) => {
|
|
1914
|
+
const request = https.get(url, function(response) {
|
|
1801
1915
|
response.on("data", (chunk) => {
|
|
1802
1916
|
data += chunk;
|
|
1803
1917
|
});
|
|
@@ -1805,11 +1919,11 @@ class SwaggerDownloader {
|
|
|
1805
1919
|
if (response.statusCode !== 200) {
|
|
1806
1920
|
console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
|
|
1807
1921
|
} else {
|
|
1808
|
-
|
|
1809
|
-
|
|
1922
|
+
fs5.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
|
|
1923
|
+
_SwaggerDownloader.postSanitizeDownloadedFile(destFile);
|
|
1810
1924
|
console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
|
|
1811
1925
|
}
|
|
1812
|
-
|
|
1926
|
+
resolve2(void 0);
|
|
1813
1927
|
});
|
|
1814
1928
|
});
|
|
1815
1929
|
request.on("error", (err) => {
|
|
@@ -1822,31 +1936,47 @@ class SwaggerDownloader {
|
|
|
1822
1936
|
for (const ref in swaggers) {
|
|
1823
1937
|
const targetFileName = swaggers[ref][2];
|
|
1824
1938
|
const url = swaggers[ref][3];
|
|
1825
|
-
await
|
|
1939
|
+
await _SwaggerDownloader.downloadFile(targetFileName, url);
|
|
1826
1940
|
}
|
|
1827
1941
|
};
|
|
1828
|
-
}
|
|
1942
|
+
};
|
|
1829
1943
|
|
|
1830
|
-
|
|
1944
|
+
// src/cli.ts
|
|
1945
|
+
var generateSdk = async () => {
|
|
1831
1946
|
const arrayOfSets = await Promise.all(CliParser.getConfigFile().map((config) => CodeGenerator.main(config)));
|
|
1947
|
+
if (CliParser.isGenerateSnippetOnly()) {
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1832
1950
|
const indexImportsSet = /* @__PURE__ */ new Set();
|
|
1951
|
+
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
1833
1952
|
const filenamesSet = /* @__PURE__ */ new Set();
|
|
1834
1953
|
for (const set of arrayOfSets) {
|
|
1835
|
-
set.forEach((value) => {
|
|
1836
|
-
const fileName =
|
|
1954
|
+
set.indexImports.forEach((value) => {
|
|
1955
|
+
const fileName = import_path4.default.basename(value);
|
|
1837
1956
|
if (!filenamesSet.has(fileName)) {
|
|
1838
1957
|
indexImportsSet.add(value);
|
|
1839
1958
|
filenamesSet.add(fileName);
|
|
1840
1959
|
}
|
|
1841
1960
|
});
|
|
1961
|
+
set.queryImports.forEach((value) => {
|
|
1962
|
+
const fileName = import_path4.default.basename(value);
|
|
1963
|
+
if (!filenamesSet.has(fileName)) {
|
|
1964
|
+
queryImportsSet.add(value);
|
|
1965
|
+
}
|
|
1966
|
+
});
|
|
1842
1967
|
}
|
|
1843
1968
|
const indexImportsArray = Array.from(indexImportsSet).sort();
|
|
1969
|
+
const queryImportsArray = Array.from(queryImportsSet).sort();
|
|
1844
1970
|
const filesToImport = indexImportsArray.map((fileToImport) => {
|
|
1845
1971
|
return `export * from '${fileToImport.replace("\\", "/")}.js'`;
|
|
1846
1972
|
});
|
|
1973
|
+
const queryFilesToImport = queryImportsArray.map((fileToImport) => {
|
|
1974
|
+
return `export * from '${fileToImport.replace("\\", "/")}.js'`;
|
|
1975
|
+
});
|
|
1847
1976
|
ParserUtils.writeAllImportsFile(CliParser.getOutputPath(), filesToImport.join("\n"));
|
|
1977
|
+
ParserUtils.writeAllQueryImportsFile(CliParser.getOutputPath(), queryFilesToImport.join("\n"));
|
|
1848
1978
|
};
|
|
1849
|
-
|
|
1979
|
+
import_yargs.default.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
1850
1980
|
CliParser.createInstance(yargs2);
|
|
1851
1981
|
SwaggerDownloader.main();
|
|
1852
1982
|
}).command("generate-code", "Generate code based on downloaded swagger files", async (yargs2) => {
|
|
@@ -1869,5 +1999,11 @@ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
|
1869
1999
|
}).option("output", {
|
|
1870
2000
|
description: "Output path for generated code. Required for generate-code",
|
|
1871
2001
|
type: "string"
|
|
2002
|
+
}).option("skipReactQuery", {
|
|
2003
|
+
description: "Skip generating react query",
|
|
2004
|
+
type: "boolean"
|
|
2005
|
+
}).option("snippetOnly", {
|
|
2006
|
+
description: "Only generate snippet",
|
|
2007
|
+
type: "boolean"
|
|
1872
2008
|
}).demandCommand(1).help().argv;
|
|
1873
|
-
//# sourceMappingURL=accelbyte-codegen.js.map
|
|
2009
|
+
//# sourceMappingURL=accelbyte-codegen.js.map
|