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