@accelbyte/codegen 4.1.5 → 4.2.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/README.md +112 -15
- package/dist/accelbyte-codegen.d.mts +31 -0
- package/dist/accelbyte-codegen.d.ts +31 -0
- package/dist/accelbyte-codegen.js +288 -157
- package/dist/accelbyte-codegen.js.map +1 -1
- package/dist/accelbyte-codegen.mjs +285 -157
- package/dist/accelbyte-codegen.mjs.map +1 -1
- package/package.json +6 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
|
-
import
|
|
4
|
+
import path8 from "path";
|
|
5
5
|
import yargs from "yargs";
|
|
6
6
|
|
|
7
7
|
// src/CliParser.ts
|
|
@@ -65,18 +65,55 @@ var CliParser = class _CliParser {
|
|
|
65
65
|
|
|
66
66
|
// src/CodeGenerator.ts
|
|
67
67
|
import SwaggerParser from "@apidevtools/swagger-parser";
|
|
68
|
-
import
|
|
69
|
-
import
|
|
68
|
+
import fs5 from "fs";
|
|
69
|
+
import path5 from "path";
|
|
70
|
+
|
|
71
|
+
// src/CodegenConfig.ts
|
|
72
|
+
import fs2 from "fs";
|
|
73
|
+
import path2 from "path";
|
|
74
|
+
import { pathToFileURL } from "url";
|
|
75
|
+
var CodegenConfig = class _CodegenConfig {
|
|
76
|
+
static config = {};
|
|
77
|
+
static async loadConfig(configDir) {
|
|
78
|
+
const configPath = path2.join(configDir, "abcodegen.config.ts");
|
|
79
|
+
if (!fs2.existsSync(configPath)) {
|
|
80
|
+
_CodegenConfig.config = {};
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const loaded = await import(pathToFileURL(configPath).href);
|
|
84
|
+
_CodegenConfig.config = loaded.default ?? loaded ?? {};
|
|
85
|
+
}
|
|
86
|
+
static shouldProduceIndexFiles() {
|
|
87
|
+
return _CodegenConfig.config.shouldProduceIndexFiles ?? true;
|
|
88
|
+
}
|
|
89
|
+
static getBasePath() {
|
|
90
|
+
return _CodegenConfig.config.basePath;
|
|
91
|
+
}
|
|
92
|
+
static getOverrideAsAny() {
|
|
93
|
+
return _CodegenConfig.config.overrideAsAny;
|
|
94
|
+
}
|
|
95
|
+
static splitOutputByServiceName() {
|
|
96
|
+
return _CodegenConfig.config.unstable_splitOutputByServiceName ?? false;
|
|
97
|
+
}
|
|
98
|
+
/** Reset to defaults — used for testing */
|
|
99
|
+
static reset() {
|
|
100
|
+
_CodegenConfig.config = {};
|
|
101
|
+
}
|
|
102
|
+
/** Set config directly — used for testing */
|
|
103
|
+
static setConfig(config) {
|
|
104
|
+
_CodegenConfig.config = config;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
70
107
|
|
|
71
108
|
// src/ParserUtils.ts
|
|
72
109
|
import { applyPatch } from "fast-json-patch";
|
|
73
|
-
import
|
|
110
|
+
import fs4 from "fs";
|
|
74
111
|
import _ from "lodash";
|
|
75
|
-
import
|
|
112
|
+
import path4 from "path";
|
|
76
113
|
|
|
77
114
|
// src/helpers/utils.ts
|
|
78
|
-
import
|
|
79
|
-
import
|
|
115
|
+
import fs3 from "fs";
|
|
116
|
+
import path3 from "path";
|
|
80
117
|
var capitalize = (string) => {
|
|
81
118
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
82
119
|
};
|
|
@@ -138,7 +175,8 @@ var getResponseType = ({
|
|
|
138
175
|
defaultType = "unknown"
|
|
139
176
|
}) => {
|
|
140
177
|
const responseClass = responseClasses.length === 1 ? responseClasses?.[0] : "unknown";
|
|
141
|
-
const
|
|
178
|
+
const rawResponseType = responseClass !== "unknown" ? responseClasses?.[0] : defaultType;
|
|
179
|
+
const responseType = rawResponseType === "__dictionary__" ? "Record<string, any>" : rawResponseType;
|
|
142
180
|
return {
|
|
143
181
|
responseType,
|
|
144
182
|
responseTypeInAxiosResponse: `Promise<AxiosResponse<${responseType}>>`,
|
|
@@ -153,10 +191,10 @@ var getImportableVarMap = () => ({
|
|
|
153
191
|
zod: ["z"]
|
|
154
192
|
});
|
|
155
193
|
var makeNewImportVarMap = () => ({
|
|
156
|
-
axios: ["AxiosInstance", "AxiosRequestConfig"]
|
|
157
|
-
"@accelbyte/sdk": ["SDKRequestConfig"]
|
|
194
|
+
axios: ["AxiosInstance", "AxiosRequestConfig"]
|
|
158
195
|
});
|
|
159
|
-
var
|
|
196
|
+
var CLASS_TYPE_ONLY_VARS = /* @__PURE__ */ new Set(["AxiosInstance", "AxiosRequestConfig", "AxiosResponse", "SdkSetConfigParam", "Response"]);
|
|
197
|
+
var generateImports = (body, importStatements, makeNewImportVarMap3, getImportableVarMap3, typeOnlyVars = /* @__PURE__ */ new Set()) => {
|
|
160
198
|
const usedImportVarMap = makeNewImportVarMap3;
|
|
161
199
|
const importableVarMap = getImportableVarMap3;
|
|
162
200
|
for (const [moduleSource, importableVars] of Object.entries(importableVarMap)) {
|
|
@@ -167,22 +205,45 @@ var generateImports = (body, importStatements, makeNewImportVarMap3, getImportab
|
|
|
167
205
|
}
|
|
168
206
|
}
|
|
169
207
|
}
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
208
|
+
const importLines = [];
|
|
209
|
+
for (const moduleSource of Object.keys(usedImportVarMap).sort()) {
|
|
210
|
+
const allVars = usedImportVarMap[moduleSource];
|
|
211
|
+
const valueVars = allVars.filter((v) => !typeOnlyVars.has(v)).sort();
|
|
212
|
+
const typeVars = allVars.filter((v) => typeOnlyVars.has(v)).sort();
|
|
213
|
+
if (valueVars.length > 0) {
|
|
214
|
+
importLines.push(`import { ${valueVars.join(", ")} } from '${moduleSource}'`);
|
|
215
|
+
}
|
|
216
|
+
if (typeVars.length > 0) {
|
|
217
|
+
importLines.push(`import type { ${typeVars.join(", ")} } from '${moduleSource}'`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const generatedImports = importLines.join("\n");
|
|
173
221
|
return `${generatedImports}
|
|
174
222
|
${importStatements.sort().join("\n")}`;
|
|
175
223
|
};
|
|
176
224
|
var templateClass = (className, body, importStatements) => {
|
|
225
|
+
const attributes = {
|
|
226
|
+
definitions: ["private axiosInstance: AxiosInstance", "private namespace: string", "private useSchemaValidation: boolean"],
|
|
227
|
+
assignments: ["this.axiosInstance = axiosInstance", "this.namespace = namespace", "this.useSchemaValidation = useSchemaValidation"]
|
|
228
|
+
};
|
|
229
|
+
let namespaceConstructor = "namespace";
|
|
230
|
+
if (!body.includes(".replace('{namespace}', this.namespace)")) {
|
|
231
|
+
namespaceConstructor = "_namespace";
|
|
232
|
+
attributes.definitions.splice(1, 1);
|
|
233
|
+
attributes.assignments.splice(1, 1);
|
|
234
|
+
}
|
|
177
235
|
return `/**
|
|
178
236
|
* AUTO GENERATED
|
|
179
237
|
*/
|
|
180
|
-
${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
|
|
238
|
+
${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap(), CLASS_TYPE_ONLY_VARS)}
|
|
181
239
|
|
|
182
240
|
export class ${className} {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
constructor(
|
|
241
|
+
${attributes.definitions.join("\n")}
|
|
242
|
+
|
|
243
|
+
constructor(axiosInstance: AxiosInstance, ${namespaceConstructor}: string, useSchemaValidation = true) {
|
|
244
|
+
${attributes.assignments.join("\n")}
|
|
245
|
+
}
|
|
246
|
+
|
|
186
247
|
${body}
|
|
187
248
|
}
|
|
188
249
|
`;
|
|
@@ -197,6 +258,15 @@ var makeNewImportVarMap2 = () => ({
|
|
|
197
258
|
"@accelbyte/sdk": ["AccelByteSDK", "SdkSetConfigParam", "ApiUtils", "Network"],
|
|
198
259
|
axios: ["AxiosRequestConfig", "AxiosResponse"]
|
|
199
260
|
});
|
|
261
|
+
var API_TYPE_ONLY_VARS = /* @__PURE__ */ new Set([
|
|
262
|
+
"AxiosRequestConfig",
|
|
263
|
+
"AxiosResponse",
|
|
264
|
+
"AxiosDefaults",
|
|
265
|
+
"HeadersDefaults",
|
|
266
|
+
"AccelByteSDK",
|
|
267
|
+
"SdkSetConfigParam",
|
|
268
|
+
"Response"
|
|
269
|
+
]);
|
|
200
270
|
var templateApiClass = (className, body, importStatements, returnMethods) => {
|
|
201
271
|
const returnsMethodsWithDescription = Object.keys(returnMethods).reduce((acc, key) => {
|
|
202
272
|
acc += `
|
|
@@ -208,43 +278,45 @@ ${key},`;
|
|
|
208
278
|
return `/**
|
|
209
279
|
* AUTO GENERATED
|
|
210
280
|
*/
|
|
211
|
-
|
|
212
|
-
// @ts-ignore -> ts-expect-error TS6133
|
|
213
|
-
${generateImports(body, importStatements, makeNewImportVarMap2(), getImportableVarMap2())}
|
|
281
|
+
${generateImports(body, importStatements, makeNewImportVarMap2(), getImportableVarMap2(), API_TYPE_ONLY_VARS)}
|
|
214
282
|
${`import { ${$className} } from './endpoints/${$className}.js'
|
|
215
283
|
`}
|
|
216
284
|
|
|
217
285
|
export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
218
286
|
const sdkAssembly = sdk.assembly()
|
|
219
|
-
|
|
287
|
+
|
|
220
288
|
const namespace = args?.coreConfig?.namespace ?? sdkAssembly.coreConfig.namespace
|
|
221
289
|
const useSchemaValidation = args?.coreConfig?.useSchemaValidation ?? sdkAssembly.coreConfig.useSchemaValidation
|
|
222
|
-
|
|
290
|
+
|
|
223
291
|
let axiosInstance = sdkAssembly.axiosInstance
|
|
224
292
|
const requestConfigOverrides = args?.axiosConfig?.request
|
|
225
293
|
const baseURLOverride = args?.coreConfig?.baseURL
|
|
226
|
-
const interceptorsOverride = args?.axiosConfig?.interceptors
|
|
294
|
+
const interceptorsOverride = args?.axiosConfig?.interceptors
|
|
227
295
|
|
|
228
|
-
if (requestConfigOverrides || baseURLOverride || interceptorsOverride
|
|
296
|
+
if (requestConfigOverrides || baseURLOverride || interceptorsOverride) {
|
|
229
297
|
const requestConfig = ApiUtils.mergeAxiosConfigs(sdkAssembly.axiosInstance.defaults as AxiosRequestConfig, {
|
|
230
298
|
...(baseURLOverride ? { baseURL: baseURLOverride } : {}),
|
|
231
299
|
...requestConfigOverrides
|
|
232
300
|
})
|
|
233
301
|
axiosInstance = Network.create(requestConfig)
|
|
234
302
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
303
|
+
if (interceptorsOverride) {
|
|
304
|
+
for (const interceptor of interceptorsOverride) {
|
|
305
|
+
if (interceptor.type === 'request') {
|
|
306
|
+
axiosInstance.interceptors.request.use(interceptor.onRequest, interceptor.onError)
|
|
307
|
+
}
|
|
239
308
|
|
|
240
|
-
|
|
241
|
-
|
|
309
|
+
if (interceptor.type === 'response') {
|
|
310
|
+
axiosInstance.interceptors.response.use(interceptor.onSuccess, interceptor.onError)
|
|
311
|
+
}
|
|
242
312
|
}
|
|
313
|
+
} else {
|
|
314
|
+
axiosInstance.interceptors = sdkAssembly.axiosInstance.interceptors
|
|
243
315
|
}
|
|
244
316
|
}
|
|
245
317
|
|
|
246
318
|
${body}
|
|
247
|
-
|
|
319
|
+
|
|
248
320
|
return {
|
|
249
321
|
${returnsMethodsWithDescription}
|
|
250
322
|
}
|
|
@@ -255,7 +327,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
255
327
|
// src/ParserQueryUtils.ts
|
|
256
328
|
var ParserQueryUtils = class {
|
|
257
329
|
/**
|
|
258
|
-
* convert csv 'aa,bb' into "aa='aa', bb='bb'"
|
|
330
|
+
* convert csv 'aa,bb' into "aa = 'Sdk.Class.aa', bb = 'Sdk.Class.bb'"
|
|
259
331
|
*/
|
|
260
332
|
static createQueryKeys(classNameWithoutApi, csvMethodNames, sdkName) {
|
|
261
333
|
const keys = csvMethodNames.split(",");
|
|
@@ -266,7 +338,7 @@ var ParserQueryUtils = class {
|
|
|
266
338
|
const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete|post|fetch)[_]?/, "");
|
|
267
339
|
if (!processedKeys.has(cleanedKey)) {
|
|
268
340
|
processedKeys.add(cleanedKey);
|
|
269
|
-
acc += `${cleanedKey}
|
|
341
|
+
acc += `${cleanedKey}: '${capitalize(sdkName)}.${classNameWithoutApi}.${cleanedKey}'`;
|
|
270
342
|
if (index < keys.length - 1) {
|
|
271
343
|
acc += ",\n";
|
|
272
344
|
}
|
|
@@ -280,42 +352,51 @@ var ParserQueryUtils = class {
|
|
|
280
352
|
|
|
281
353
|
// src/templates/template-query.ts
|
|
282
354
|
var generateImports2 = (body, className) => {
|
|
283
|
-
const
|
|
284
|
-
import {
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
import { ${
|
|
288
|
-
|
|
289
|
-
|
|
355
|
+
const lines = [];
|
|
356
|
+
lines.push("import type { AccelByteSDK, ApiError, SdkSetConfigParam } from '@accelbyte/sdk'");
|
|
357
|
+
const axiosTypes = ["AxiosError", "AxiosResponse"].filter((t) => body.includes(t));
|
|
358
|
+
if (axiosTypes.length) {
|
|
359
|
+
lines.push(`import type { ${axiosTypes.join(", ")} } from 'axios'`);
|
|
360
|
+
}
|
|
361
|
+
const rqValues = ["useMutation", "useQuery"].filter((t) => body.includes(t));
|
|
362
|
+
if (rqValues.length) {
|
|
363
|
+
lines.push(`import { ${rqValues.join(", ")} } from '@tanstack/react-query'`);
|
|
364
|
+
}
|
|
365
|
+
const rqTypes = ["UseMutationOptions", "UseMutationResult", "UseQueryOptions", "UseQueryResult"].filter((t) => body.includes(t));
|
|
366
|
+
if (rqTypes.length) {
|
|
367
|
+
lines.push(`import type { ${rqTypes.join(", ")} } from '@tanstack/react-query'`);
|
|
368
|
+
}
|
|
369
|
+
lines.push(`import { ${className} } from "../${className}.js"`);
|
|
370
|
+
return lines.join("\n") + "\n";
|
|
290
371
|
};
|
|
291
372
|
var templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports, sdkName) => {
|
|
292
373
|
const classNameWithoutApi = className.replace("Api", "");
|
|
293
374
|
const queryKeys = ParserQueryUtils.createQueryKeys(classNameWithoutApi, returnMethods, sdkName);
|
|
294
375
|
const generatedImports = generateImports2(body, className);
|
|
376
|
+
const queryKeyBlock = `export const Key_${classNameWithoutApi} = {
|
|
377
|
+
${queryKeys}
|
|
378
|
+
} as const`;
|
|
295
379
|
return `/**
|
|
296
380
|
* AUTO GENERATED
|
|
297
381
|
*/
|
|
298
|
-
/* eslint-disable camelcase */
|
|
299
382
|
${generatedImports}
|
|
300
383
|
${filterUsedImports(paramImports, body)}
|
|
301
384
|
|
|
302
|
-
|
|
303
|
-
${queryKeys}
|
|
304
|
-
}
|
|
385
|
+
${queryKeyBlock}
|
|
305
386
|
|
|
306
387
|
${body}
|
|
307
388
|
`;
|
|
308
389
|
};
|
|
309
390
|
function filterUsedImports(importArr, body) {
|
|
310
|
-
return importArr.filter((
|
|
311
|
-
const start =
|
|
312
|
-
const end =
|
|
391
|
+
return importArr.filter((path9) => {
|
|
392
|
+
const start = path9.indexOf("{") + 1;
|
|
393
|
+
const end = path9.indexOf("}");
|
|
313
394
|
if (start > 0 && end > start) {
|
|
314
|
-
const importName =
|
|
395
|
+
const importName = path9.slice(start, end).trim();
|
|
315
396
|
return body.includes(importName);
|
|
316
397
|
}
|
|
317
398
|
return false;
|
|
318
|
-
}).map((
|
|
399
|
+
}).map((path9) => path9).join("\n") + "\n";
|
|
319
400
|
}
|
|
320
401
|
|
|
321
402
|
// src/ParserUtils.ts
|
|
@@ -332,8 +413,8 @@ var REMOVED_KEYWORDS = [
|
|
|
332
413
|
"/{namespace}/"
|
|
333
414
|
];
|
|
334
415
|
var ParserUtils = class _ParserUtils {
|
|
335
|
-
static getVersionSuffixFromPath(
|
|
336
|
-
const version2_3_4_etc =
|
|
416
|
+
static getVersionSuffixFromPath(path9) {
|
|
417
|
+
const version2_3_4_etc = path9.match(/\/v([2-9]|[1-9]\d+)\/+/);
|
|
337
418
|
const methodSuffix = version2_3_4_etc ? `_v${version2_3_4_etc[1]}` : "";
|
|
338
419
|
return methodSuffix;
|
|
339
420
|
}
|
|
@@ -415,13 +496,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
415
496
|
};
|
|
416
497
|
static parseRefImport = (bodyParam) => {
|
|
417
498
|
const $ref = bodyParam?.schema?.$ref || bodyParam?.schema?.items?.$ref;
|
|
418
|
-
if (!$ref) {
|
|
499
|
+
if (!$ref || $ref.endsWith("__dictionary__")) {
|
|
419
500
|
return null;
|
|
420
501
|
}
|
|
421
502
|
const type = _ParserUtils.parseRefType($ref);
|
|
422
503
|
return `import { ${type} } from '../../generated-definitions/${type}.js'`;
|
|
423
504
|
};
|
|
424
505
|
static parseRefType = ($ref) => {
|
|
506
|
+
if ($ref.endsWith("__dictionary__")) return "__dictionary__";
|
|
425
507
|
let ref = $ref.replace(".", "/");
|
|
426
508
|
if (ref[ref.length - 1] === "." || ref[ref.length - 1] === "/") {
|
|
427
509
|
ref = ref.slice(0, -1);
|
|
@@ -528,14 +610,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
528
610
|
* to this
|
|
529
611
|
* `createGenerateByRequestIdByUserId`
|
|
530
612
|
*/
|
|
531
|
-
static generateNaturalLangMethod = ({ servicePrefix, path:
|
|
532
|
-
let path_ =
|
|
613
|
+
static generateNaturalLangMethod = ({ servicePrefix, path: path9, httpMethod, isForm, existingMethods, permissionType }) => {
|
|
614
|
+
let path_ = path9;
|
|
533
615
|
path_ = path_.replace(`/${servicePrefix}/`, "/");
|
|
534
616
|
REMOVED_KEYWORDS.forEach((prefix) => {
|
|
535
617
|
path_ = path_.replace(prefix, "/");
|
|
536
618
|
});
|
|
537
619
|
path_ = path_.substring(1);
|
|
538
|
-
const isPlural = httpMethod === "get" && !(
|
|
620
|
+
const isPlural = httpMethod === "get" && !(path9.slice(-1) === "}");
|
|
539
621
|
if (!isPlural) {
|
|
540
622
|
path_ = _ParserUtils.replaceAll(path_, "ies/", "y/");
|
|
541
623
|
path_ = _ParserUtils.replaceAll(path_, "s/", "/");
|
|
@@ -578,9 +660,9 @@ var ParserUtils = class _ParserUtils {
|
|
|
578
660
|
const genPath = _.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
|
|
579
661
|
let generatedMethod = _.camelCase(mappedMethod(httpMethod, isForm, permissionType) + genPath);
|
|
580
662
|
generatedMethod = _ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
|
|
581
|
-
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(
|
|
582
|
-
generatedMethod = resolveConflicts({ path:
|
|
583
|
-
generatedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(
|
|
663
|
+
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path9);
|
|
664
|
+
generatedMethod = resolveConflicts({ path: path9, generatedMethod, testedGeneratedMethod, existingMethods });
|
|
665
|
+
generatedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path9);
|
|
584
666
|
return generatedMethod;
|
|
585
667
|
};
|
|
586
668
|
static filterBodyParams(parameters) {
|
|
@@ -596,17 +678,17 @@ var ParserUtils = class _ParserUtils {
|
|
|
596
678
|
return parameters.filter((parameter) => parameter.in === "query");
|
|
597
679
|
}
|
|
598
680
|
static mkdirIfNotExist(dirToCreate) {
|
|
599
|
-
if (!
|
|
600
|
-
|
|
681
|
+
if (!fs4.existsSync(dirToCreate)) {
|
|
682
|
+
fs4.mkdirSync(dirToCreate, { recursive: true });
|
|
601
683
|
}
|
|
602
684
|
}
|
|
603
685
|
static writeClassFile(distDir, apiName, apiBuffer, imports) {
|
|
604
686
|
const fileContent = templateClass(apiName, apiBuffer, imports);
|
|
605
|
-
|
|
687
|
+
fs4.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
606
688
|
}
|
|
607
689
|
static writeAtomFile(distDir, apiName, fileContent) {
|
|
608
690
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
609
|
-
|
|
691
|
+
fs4.writeFileSync(`${distDir}/${apiName}.atom.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
610
692
|
}
|
|
611
693
|
static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName) {
|
|
612
694
|
if (apiBuffer.length < 1) {
|
|
@@ -615,20 +697,21 @@ var ParserUtils = class _ParserUtils {
|
|
|
615
697
|
const queryFileName = `${apiName.replace("Api", "")}.query`;
|
|
616
698
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
617
699
|
const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName);
|
|
618
|
-
|
|
700
|
+
fs4.writeFileSync(`${distDir}/${queryFileName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
619
701
|
return queryFileName;
|
|
620
702
|
}
|
|
621
703
|
static writeXVersion(distDir, xversionJson, apiInfo) {
|
|
704
|
+
fs4.mkdirSync(distDir, { recursive: true });
|
|
622
705
|
if (xversionJson) {
|
|
623
706
|
console.log("x-version:", xversionJson);
|
|
624
|
-
|
|
707
|
+
fs4.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
|
|
625
708
|
} else {
|
|
626
709
|
const customVersion = {
|
|
627
710
|
...apiInfo,
|
|
628
711
|
gitHash: apiInfo.version
|
|
629
712
|
};
|
|
630
713
|
console.error(`!!!! Missing x-version for ${distDir} ${customVersion}`);
|
|
631
|
-
|
|
714
|
+
fs4.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
|
|
632
715
|
}
|
|
633
716
|
}
|
|
634
717
|
static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethodsDescription) {
|
|
@@ -637,28 +720,28 @@ var ParserUtils = class _ParserUtils {
|
|
|
637
720
|
newImports.push(el.replace("../../generated-definitions", "../generated-definitions"));
|
|
638
721
|
});
|
|
639
722
|
const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethodsDescription);
|
|
640
|
-
|
|
723
|
+
fs4.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
641
724
|
}
|
|
642
725
|
static writeApiMainFile(distDir, serviceName, fileContent) {
|
|
643
|
-
|
|
726
|
+
fs4.writeFileSync(`${distDir}/${serviceName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
644
727
|
}
|
|
645
728
|
static writeSnippetFile(distDir, name, docBuffer) {
|
|
646
729
|
let snippetFileName = _ParserUtils.replaceAll(name, " ", "-").toLowerCase();
|
|
647
730
|
snippetFileName = snippetFileName.replace("justice-", "");
|
|
648
731
|
snippetFileName = "snippet-" + snippetFileName + ".json";
|
|
649
|
-
|
|
732
|
+
fs4.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
|
|
650
733
|
}
|
|
651
734
|
static writeDefinitionFile(distDir, name, buffer) {
|
|
652
735
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
653
|
-
|
|
736
|
+
fs4.writeFileSync(path4.join(distDir, `${name}.ts`), _ParserUtils.prependCopyrightHeader(buffer));
|
|
654
737
|
}
|
|
655
738
|
static writeAllImportsFile(distDir, buffer) {
|
|
656
739
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
657
|
-
|
|
740
|
+
fs4.writeFileSync(path4.join(distDir, "all-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
658
741
|
}
|
|
659
742
|
static writeAllQueryImportsFile(distDir, buffer) {
|
|
660
743
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
661
|
-
|
|
744
|
+
fs4.writeFileSync(path4.join(distDir, "all-query-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
662
745
|
}
|
|
663
746
|
static toCamelCase(str) {
|
|
664
747
|
return str.split("/").map(function(word, index) {
|
|
@@ -684,15 +767,15 @@ var ParserUtils = class _ParserUtils {
|
|
|
684
767
|
});
|
|
685
768
|
}
|
|
686
769
|
static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
|
|
687
|
-
if (!
|
|
688
|
-
|
|
770
|
+
if (!fs4.existsSync(swaggerPatchedDir)) {
|
|
771
|
+
fs4.mkdirSync(swaggerPatchedDir, { recursive: true });
|
|
689
772
|
}
|
|
690
|
-
if (!
|
|
691
|
-
|
|
773
|
+
if (!fs4.existsSync(possibleSwaggerPatchFilePath)) {
|
|
774
|
+
fs4.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
|
|
692
775
|
return;
|
|
693
776
|
}
|
|
694
|
-
const swaggerContent = JSON.parse(
|
|
695
|
-
const swaggerPatchFileContent = JSON.parse(
|
|
777
|
+
const swaggerContent = JSON.parse(fs4.readFileSync(swaggerFilePath, "utf8"));
|
|
778
|
+
const swaggerPatchFileContent = JSON.parse(fs4.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
|
|
696
779
|
for (const patchEntry of swaggerPatchFileContent) {
|
|
697
780
|
const segments = patchEntry.path.split("/").filter(Boolean);
|
|
698
781
|
let currentNode = swaggerContent;
|
|
@@ -720,7 +803,7 @@ var ParserUtils = class _ParserUtils {
|
|
|
720
803
|
}
|
|
721
804
|
}
|
|
722
805
|
const { newDocument } = applyPatch(swaggerContent, swaggerPatchFileContent);
|
|
723
|
-
|
|
806
|
+
fs4.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
|
|
724
807
|
}
|
|
725
808
|
static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
|
|
726
809
|
const replaced = srcFolder.replace(/\\/g, "/");
|
|
@@ -735,8 +818,8 @@ var ParserUtils = class _ParserUtils {
|
|
|
735
818
|
*/
|
|
736
819
|
${content}`;
|
|
737
820
|
};
|
|
738
|
-
static sortPathParamsByPath = (pathParams,
|
|
739
|
-
const params =
|
|
821
|
+
static sortPathParamsByPath = (pathParams, path9) => {
|
|
822
|
+
const params = path9.match(/{\w*}/g) || [];
|
|
740
823
|
const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
|
|
741
824
|
return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
|
|
742
825
|
};
|
|
@@ -760,30 +843,40 @@ var mappedMethod = (httpMethod, isForm, permissionType) => {
|
|
|
760
843
|
return "delete";
|
|
761
844
|
}
|
|
762
845
|
};
|
|
763
|
-
var resolveConflicts = ({ path:
|
|
846
|
+
var resolveConflicts = ({ path: path9, generatedMethod, testedGeneratedMethod, existingMethods }) => {
|
|
764
847
|
let _testedGenMethod = testedGeneratedMethod;
|
|
765
848
|
try {
|
|
766
|
-
testConflict(
|
|
849
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
767
850
|
} catch (e) {
|
|
768
|
-
if (
|
|
851
|
+
if (path9.indexOf("/namespaces/") >= 0) {
|
|
769
852
|
generatedMethod += "_ByNS";
|
|
770
853
|
_testedGenMethod += "_ByNS";
|
|
771
854
|
}
|
|
772
855
|
}
|
|
773
856
|
try {
|
|
774
|
-
testConflict(
|
|
857
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
775
858
|
} catch (e) {
|
|
776
|
-
if (
|
|
859
|
+
if (path9.indexOf("/admin/") >= 0) {
|
|
777
860
|
generatedMethod += "_admin";
|
|
778
861
|
_testedGenMethod += "_admin";
|
|
779
862
|
}
|
|
780
863
|
}
|
|
781
|
-
|
|
864
|
+
try {
|
|
865
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
866
|
+
} catch (e) {
|
|
867
|
+
const parentSegmentMatch = path9.match(/\/([^/{}]+)\/{[^}]+}\/[^/]*$/);
|
|
868
|
+
if (parentSegmentMatch) {
|
|
869
|
+
const suffix = "_By" + _.upperFirst(_.camelCase(parentSegmentMatch[1]));
|
|
870
|
+
generatedMethod += suffix;
|
|
871
|
+
_testedGenMethod += suffix;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
782
875
|
return generatedMethod;
|
|
783
876
|
};
|
|
784
|
-
var testConflict = (
|
|
877
|
+
var testConflict = (path9, generatedMethod, existingMethods) => {
|
|
785
878
|
if (existingMethods[generatedMethod]) {
|
|
786
|
-
const conflictingMethod = { path:
|
|
879
|
+
const conflictingMethod = { path: path9, generatedMethod };
|
|
787
880
|
throw Error(
|
|
788
881
|
`Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
|
|
789
882
|
existingMethods: ${JSON.stringify(existingMethods, null, 2)}`
|
|
@@ -900,7 +993,7 @@ var OpenApiSpec = z2.object({
|
|
|
900
993
|
var templateApiMethod = ({
|
|
901
994
|
classMethod,
|
|
902
995
|
httpMethod,
|
|
903
|
-
path:
|
|
996
|
+
path: path9,
|
|
904
997
|
pathParams,
|
|
905
998
|
bodyParams,
|
|
906
999
|
responseClasses,
|
|
@@ -909,12 +1002,12 @@ var templateApiMethod = ({
|
|
|
909
1002
|
methodParamsNoTypes,
|
|
910
1003
|
xSecurity
|
|
911
1004
|
}) => {
|
|
912
|
-
let newPath = `'${
|
|
1005
|
+
let newPath = `'${path9}'`;
|
|
913
1006
|
let snippetMethod = "";
|
|
914
1007
|
for (const pathParam of pathParams) {
|
|
915
1008
|
const type = ParserUtils.parseType(pathParam);
|
|
916
1009
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
917
|
-
if (
|
|
1010
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
918
1011
|
if (type === "string") {
|
|
919
1012
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
920
1013
|
} else {
|
|
@@ -922,9 +1015,9 @@ var templateApiMethod = ({
|
|
|
922
1015
|
}
|
|
923
1016
|
}
|
|
924
1017
|
}
|
|
925
|
-
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${
|
|
1018
|
+
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path9}'`, "--header 'accept: application/json'"];
|
|
926
1019
|
const snippetApiArgs = [];
|
|
927
|
-
if (xSecurity !== void 0 ||
|
|
1020
|
+
if (xSecurity !== void 0 || path9.includes("/admin")) {
|
|
928
1021
|
snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
|
|
929
1022
|
snippetApiArgs.push("{ axiosConfig: { request: { headers: { Authorization: 'Bearer {access_token}' } } } }".trim());
|
|
930
1023
|
}
|
|
@@ -962,7 +1055,7 @@ var templateMethod = ({
|
|
|
962
1055
|
classMethod,
|
|
963
1056
|
description,
|
|
964
1057
|
httpMethod,
|
|
965
|
-
path:
|
|
1058
|
+
path: path9,
|
|
966
1059
|
pathParams,
|
|
967
1060
|
bodyParams,
|
|
968
1061
|
queryParams,
|
|
@@ -972,9 +1065,9 @@ var templateMethod = ({
|
|
|
972
1065
|
}) => {
|
|
973
1066
|
let methodParams = "";
|
|
974
1067
|
let methodParamsNoTypes = "";
|
|
975
|
-
let newPath = `'${
|
|
1068
|
+
let newPath = `'${path9}'`;
|
|
976
1069
|
let importStatements = [];
|
|
977
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1070
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
978
1071
|
for (const pathParam of sortedPathParams) {
|
|
979
1072
|
const type = ParserUtils.parseType(pathParam);
|
|
980
1073
|
if (pathParam.name !== "namespace") {
|
|
@@ -982,7 +1075,7 @@ var templateMethod = ({
|
|
|
982
1075
|
methodParamsNoTypes += pathParam.name + ", ";
|
|
983
1076
|
}
|
|
984
1077
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
985
|
-
if (
|
|
1078
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
986
1079
|
if (type === "string") {
|
|
987
1080
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
988
1081
|
} else {
|
|
@@ -993,6 +1086,7 @@ var templateMethod = ({
|
|
|
993
1086
|
let dataType = null;
|
|
994
1087
|
if (httpMethod !== "get") {
|
|
995
1088
|
dataType = ParserUtils.parseBodyParamsType(bodyParams);
|
|
1089
|
+
if (dataType === "__dictionary__") dataType = "Record<string, any>";
|
|
996
1090
|
importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
|
|
997
1091
|
methodParams += dataType ? `data: ${dataType},` : "";
|
|
998
1092
|
methodParamsNoTypes += dataType ? `data,` : "";
|
|
@@ -1016,7 +1110,7 @@ var templateMethod = ({
|
|
|
1016
1110
|
}
|
|
1017
1111
|
const isFileUpload = methodParams.indexOf("data: {file") > -1;
|
|
1018
1112
|
const { responseType, responseTypeInResponse } = getResponseType({ responseClasses });
|
|
1019
|
-
const resolvedResponseClassValidated = responseType !== "unknown" ? `${responseType}` : "z.unknown()";
|
|
1113
|
+
const resolvedResponseClassValidated = responseClasses.length === 1 && responseClasses[0] === "__dictionary__" ? "z.record(z.string(), z.any())" : responseType !== "unknown" ? `${responseType}` : "z.unknown()";
|
|
1020
1114
|
methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
|
|
1021
1115
|
methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
|
|
1022
1116
|
const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
|
|
@@ -1047,7 +1141,7 @@ var POST_FETCH_INCLUDES_PATH = ["/table-query/"];
|
|
|
1047
1141
|
var templateQueryMethod = ({
|
|
1048
1142
|
classMethod,
|
|
1049
1143
|
httpMethod,
|
|
1050
|
-
path:
|
|
1144
|
+
path: path9,
|
|
1051
1145
|
pathParams,
|
|
1052
1146
|
responseClasses,
|
|
1053
1147
|
methodParams,
|
|
@@ -1055,14 +1149,14 @@ var templateQueryMethod = ({
|
|
|
1055
1149
|
description,
|
|
1056
1150
|
deprecated
|
|
1057
1151
|
}) => {
|
|
1058
|
-
const isPostFetch = httpMethod === "post" && (POST_FETCH_INCLUDES_PATH.some((p) =>
|
|
1152
|
+
const isPostFetch = httpMethod === "post" && (POST_FETCH_INCLUDES_PATH.some((p) => path9.includes(p)) || path9.endsWith("/list"));
|
|
1059
1153
|
const isFetch = classMethod.startsWith("fetch");
|
|
1060
1154
|
const isGet = httpMethod === "get" || isPostFetch || isFetch;
|
|
1061
1155
|
const queryMethod = isGet ? "useQuery" : "useMutation";
|
|
1062
1156
|
let mParams = "";
|
|
1063
1157
|
let mParamsNoTypes = "";
|
|
1064
|
-
let newPath = `'${
|
|
1065
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1158
|
+
let newPath = `'${path9}'`;
|
|
1159
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
1066
1160
|
for (const pathParam of sortedPathParams) {
|
|
1067
1161
|
const type = ParserUtils.parseType(pathParam);
|
|
1068
1162
|
if (pathParam.name !== "namespace") {
|
|
@@ -1070,7 +1164,7 @@ var templateQueryMethod = ({
|
|
|
1070
1164
|
mParamsNoTypes += pathParam.name + ", ";
|
|
1071
1165
|
}
|
|
1072
1166
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1073
|
-
if (
|
|
1167
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
1074
1168
|
if (type === "string") {
|
|
1075
1169
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1076
1170
|
} else {
|
|
@@ -1105,7 +1199,7 @@ export const ${_methodName} = (
|
|
|
1105
1199
|
const response =
|
|
1106
1200
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1107
1201
|
${classMethod}(${_methodParamsImpl}))
|
|
1108
|
-
callback
|
|
1202
|
+
callback?.(response)
|
|
1109
1203
|
return response.data
|
|
1110
1204
|
}
|
|
1111
1205
|
|
|
@@ -1130,7 +1224,7 @@ export const ${_methodName} = (
|
|
|
1130
1224
|
const response =
|
|
1131
1225
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1132
1226
|
${classMethod}(${_methodParamsImpl}))
|
|
1133
|
-
callback
|
|
1227
|
+
callback?.(response.data)
|
|
1134
1228
|
return response.data
|
|
1135
1229
|
}
|
|
1136
1230
|
|
|
@@ -1309,11 +1403,11 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1309
1403
|
admin: {},
|
|
1310
1404
|
public: {}
|
|
1311
1405
|
};
|
|
1312
|
-
for (const [
|
|
1313
|
-
if (
|
|
1406
|
+
for (const [path9, operation] of sortedPathsByLength) {
|
|
1407
|
+
if (path9.indexOf("/healthz") >= 0) {
|
|
1314
1408
|
continue;
|
|
1315
1409
|
}
|
|
1316
|
-
const isAdminEndpoint =
|
|
1410
|
+
const isAdminEndpoint = path9.indexOf("/admin/") > -1;
|
|
1317
1411
|
const picked = isAdminEndpoint ? result.admin : result.public;
|
|
1318
1412
|
const {
|
|
1319
1413
|
arrayDefinitions,
|
|
@@ -1331,25 +1425,27 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1331
1425
|
const httpMethods = Object.keys(operation);
|
|
1332
1426
|
for (const httpMethod of httpMethods) {
|
|
1333
1427
|
const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
|
|
1334
|
-
console.error(JSON.stringify({ path:
|
|
1428
|
+
console.error(JSON.stringify({ path: path9, httpMethod }, null, 2));
|
|
1335
1429
|
throw error;
|
|
1336
1430
|
});
|
|
1337
1431
|
if (!endpoint.tags) continue;
|
|
1338
1432
|
const [tag] = endpoint.tags;
|
|
1339
|
-
const
|
|
1433
|
+
const configBasePath = CodegenConfig.getBasePath();
|
|
1434
|
+
const effectiveBasePath = configBasePath !== void 0 ? configBasePath : api.basePath ?? "";
|
|
1435
|
+
const pathWithBase = `${effectiveBasePath}${path9}`;
|
|
1340
1436
|
const permissionType = getPermissionType(getPermission(endpoint));
|
|
1341
1437
|
tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
|
|
1342
1438
|
const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
|
|
1343
1439
|
const classMethod = ParserUtils.generateNaturalLangMethod({
|
|
1344
1440
|
servicePrefix,
|
|
1345
|
-
path:
|
|
1441
|
+
path: path9,
|
|
1346
1442
|
httpMethod,
|
|
1347
1443
|
isForm,
|
|
1348
1444
|
existingMethods: tagToClassMethodsMapByType[tag],
|
|
1349
1445
|
permissionType
|
|
1350
1446
|
});
|
|
1351
|
-
tagToClassMethodsMapByType[tag][classMethod] = `${
|
|
1352
|
-
generatedMethods[`${
|
|
1447
|
+
tagToClassMethodsMapByType[tag][classMethod] = `${path9} ${httpMethod}`;
|
|
1448
|
+
generatedMethods[`${path9} ${httpMethod}`] = `${classMethod}`;
|
|
1353
1449
|
if (!snippetMap[pathWithBase]) {
|
|
1354
1450
|
snippetMap[pathWithBase] = {};
|
|
1355
1451
|
}
|
|
@@ -1358,7 +1454,7 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1358
1454
|
const responseClass = responseClasses.length > 1 ? null : responseClasses?.[0];
|
|
1359
1455
|
const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
|
|
1360
1456
|
tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
|
|
1361
|
-
if (responseClass) {
|
|
1457
|
+
if (responseClass && responseClass !== "__dictionary__") {
|
|
1362
1458
|
tagToClassImportsRecord[className][responseClass] = `import { ${responseClass} } from '../../generated-definitions/${responseClass}.js'`;
|
|
1363
1459
|
}
|
|
1364
1460
|
if (responseClass && responseClass.endsWith("Array")) {
|
|
@@ -1504,6 +1600,20 @@ var TemplateZod = class {
|
|
|
1504
1600
|
// --
|
|
1505
1601
|
render = (fileName, definition, duplicates) => {
|
|
1506
1602
|
this.duplicates = duplicates;
|
|
1603
|
+
const overrideAsAny = CodegenConfig.getOverrideAsAny();
|
|
1604
|
+
const override = overrideAsAny?.[fileName];
|
|
1605
|
+
if (override !== void 0) {
|
|
1606
|
+
const shouldOverride = typeof override === "function" ? override(definition) : override;
|
|
1607
|
+
if (shouldOverride) {
|
|
1608
|
+
const template2 = `import { z } from 'zod'
|
|
1609
|
+
|
|
1610
|
+
export const ${fileName} = z.any()
|
|
1611
|
+
|
|
1612
|
+
export interface ${fileName} extends z.TypeOf<typeof ${fileName}> {}
|
|
1613
|
+
`;
|
|
1614
|
+
return { buffer: template2, duplicateFound: false };
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1507
1617
|
const content = this.parseToZodSchema(definition, definition.required || []);
|
|
1508
1618
|
const containsRecursiveType = this.importClasses.has(fileName);
|
|
1509
1619
|
if (containsRecursiveType) {
|
|
@@ -1592,7 +1702,14 @@ ${exportedTypeString}
|
|
|
1592
1702
|
};
|
|
1593
1703
|
} else if (type) {
|
|
1594
1704
|
if (type === "object" && definition.additionalProperties) {
|
|
1595
|
-
const
|
|
1705
|
+
const additionalProps = definition.additionalProperties;
|
|
1706
|
+
if (Object.keys(additionalProps).length === 0) {
|
|
1707
|
+
return {
|
|
1708
|
+
schemaString: `${schemaAttribute} z.record(z.any())${schemaRequired}`,
|
|
1709
|
+
typeString: `${typeAttribute} Record<string, any>${typeNullishability}`
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
const zodAttribute = this.parseToZodAttribute("", additionalProps, [""]);
|
|
1596
1713
|
return {
|
|
1597
1714
|
schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
|
|
1598
1715
|
typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
|
|
@@ -1778,8 +1895,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1778
1895
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
1779
1896
|
const apiInfo = { ...api.info, "x-version": api["x-version"]?.version };
|
|
1780
1897
|
console.log("----------\nGenerating API:", { title: apiInfo.title, version: apiInfo.version });
|
|
1898
|
+
const isSplitByService = CodegenConfig.splitOutputByServiceName();
|
|
1899
|
+
const srcFolder = isSplitByService ? path5.join(CliParser.getOutputPath(), serviceName) : CliParser.getOutputPath();
|
|
1900
|
+
const targetSrcFolder = `${CliParser.getOutputPath()}/`;
|
|
1781
1901
|
if (!CliParser.isGenerateSnippetOnly()) {
|
|
1782
|
-
ParserUtils.writeXVersion(
|
|
1902
|
+
ParserUtils.writeXVersion(srcFolder, api["x-version"], api.info);
|
|
1783
1903
|
}
|
|
1784
1904
|
const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
|
|
1785
1905
|
if (CliParser.getSnippetOutputPath()) {
|
|
@@ -1805,11 +1925,10 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1805
1925
|
console.log("\nSuccessfully generate SDK snippets only\n----------\n\n");
|
|
1806
1926
|
return;
|
|
1807
1927
|
}
|
|
1808
|
-
const DIST_DIR = (isAdmin) =>
|
|
1809
|
-
const DIST_DIR_ENDPOINTS = (isAdmin) =>
|
|
1810
|
-
const DIST_DIR_QUERIES = (isAdmin) =>
|
|
1811
|
-
const DIST_DEFINITION_DIR =
|
|
1812
|
-
const targetSrcFolder = `${_CodeGenerator.srcFolder()}/`;
|
|
1928
|
+
const DIST_DIR = (isAdmin) => path5.join(srcFolder, isAdmin ? "generated-admin" : "generated-public");
|
|
1929
|
+
const DIST_DIR_ENDPOINTS = (isAdmin) => path5.join(DIST_DIR(isAdmin), "endpoints");
|
|
1930
|
+
const DIST_DIR_QUERIES = (isAdmin) => path5.join(DIST_DIR(isAdmin), "queries");
|
|
1931
|
+
const DIST_DEFINITION_DIR = path5.join(srcFolder, "generated-definitions");
|
|
1813
1932
|
_CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
|
|
1814
1933
|
const mainApiList = [];
|
|
1815
1934
|
const generatedDefinitions = [];
|
|
@@ -1850,30 +1969,31 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1850
1969
|
ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionDescription[tag]);
|
|
1851
1970
|
apiList.push(apiGenName);
|
|
1852
1971
|
indexImportsSet.add(
|
|
1853
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1972
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder)
|
|
1854
1973
|
);
|
|
1855
1974
|
indexImportsSet.add(
|
|
1856
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1975
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder)
|
|
1857
1976
|
);
|
|
1858
1977
|
queryFileName && queryImportsSet.add(
|
|
1859
1978
|
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1860
|
-
|
|
1979
|
+
path5.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`),
|
|
1861
1980
|
targetSrcFolder
|
|
1862
1981
|
)
|
|
1863
1982
|
);
|
|
1864
1983
|
}
|
|
1865
1984
|
mainApiList.push(...apiList);
|
|
1866
|
-
|
|
1867
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1868
|
-
|
|
1985
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
1986
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(srcFolder, serviceNameTitle), targetSrcFolder));
|
|
1987
|
+
}
|
|
1869
1988
|
};
|
|
1870
1989
|
const writeDefinitions = (api2) => {
|
|
1871
1990
|
const duplicates = /* @__PURE__ */ new Map();
|
|
1872
1991
|
const definitions = api2?.components?.schemas || api2.definitions;
|
|
1873
1992
|
for (const ref in definitions) {
|
|
1993
|
+
if (ref === "__dictionary__") continue;
|
|
1874
1994
|
const definition = definitions[ref];
|
|
1875
1995
|
const fileName = ParserUtils.parseRefType(ref);
|
|
1876
|
-
const fileExist =
|
|
1996
|
+
const fileExist = fs5.existsSync(path5.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
|
|
1877
1997
|
if (fileExist) {
|
|
1878
1998
|
const duplicateName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
|
|
1879
1999
|
duplicates.set(ref, duplicateName);
|
|
@@ -1881,13 +2001,13 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1881
2001
|
const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
|
|
1882
2002
|
generatedDefinitions.push(fileName);
|
|
1883
2003
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
|
|
1884
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2004
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
|
|
1885
2005
|
}
|
|
1886
2006
|
for (const arrayClass of arrayDefinitions) {
|
|
1887
2007
|
const buffer = new TemplateZodArray().render(arrayClass);
|
|
1888
2008
|
generatedDefinitions.push(arrayClass);
|
|
1889
2009
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
|
|
1890
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2010
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
|
|
1891
2011
|
}
|
|
1892
2012
|
};
|
|
1893
2013
|
writeApiEndpointFiles(isAdmin);
|
|
@@ -1895,9 +2015,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1895
2015
|
};
|
|
1896
2016
|
generatePublicOrAdmin(true);
|
|
1897
2017
|
generatePublicOrAdmin(false);
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
2018
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
2019
|
+
const isGenerateWebSocket = CliParser.isGenerateWebSocket();
|
|
2020
|
+
const apiIndexBuff = templateApiIndex(serviceNameTitle, mainApiList, isGenerateWebSocket);
|
|
2021
|
+
ParserUtils.writeApiMainFile(srcFolder, serviceNameTitle, apiIndexBuff);
|
|
2022
|
+
}
|
|
1901
2023
|
console.log("\nCOMPLETED\n----------\n\n");
|
|
1902
2024
|
return { indexImports: indexImportsSet, queryImports: queryImportsSet };
|
|
1903
2025
|
};
|
|
@@ -1905,29 +2027,30 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1905
2027
|
};
|
|
1906
2028
|
|
|
1907
2029
|
// src/SwaggerDownloader.ts
|
|
2030
|
+
import * as fs6 from "fs";
|
|
1908
2031
|
import * as https from "https";
|
|
1909
|
-
import * as
|
|
1910
|
-
import * as path5 from "path";
|
|
2032
|
+
import * as path6 from "path";
|
|
1911
2033
|
var SwaggerDownloader = class _SwaggerDownloader {
|
|
1912
2034
|
static getDestFile = (targetFileName) => {
|
|
1913
2035
|
const destPath = CliParser.getResolvedSwaggersOutputPath();
|
|
1914
|
-
const destFile =
|
|
1915
|
-
if (
|
|
1916
|
-
if (!
|
|
1917
|
-
|
|
2036
|
+
const destFile = path6.join(destPath, targetFileName);
|
|
2037
|
+
if (fs6.existsSync(destFile)) return destFile;
|
|
2038
|
+
if (!fs6.existsSync(destPath)) fs6.mkdirSync(destPath);
|
|
2039
|
+
fs6.writeFileSync(destFile, "");
|
|
1918
2040
|
return destFile;
|
|
1919
2041
|
};
|
|
1920
2042
|
// session-api.json contains illegal URL encoded character that breaks the codegen
|
|
1921
2043
|
// e.g. "$ref": "#/definitions/map%5Bstring%5Dinterface%20%7B%7D"
|
|
1922
2044
|
static postSanitizeDownloadedFile = (filePath) => {
|
|
1923
2045
|
const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
|
|
1924
|
-
|
|
2046
|
+
fs6.readFile(filePath, "utf8", (err, data) => {
|
|
1925
2047
|
if (err) throw err;
|
|
1926
2048
|
let result = data;
|
|
2049
|
+
result = result.replace(new RegExp("map%5Bstring%5Dinterface%20%7B%7D", "g"), "__dictionary__").replace(new RegExp("map\\[string\\]interface \\{\\}", "g"), "__dictionary__").replace(new RegExp("map\\[string\\]any", "g"), "__dictionary__");
|
|
1927
2050
|
searchStr.forEach((s) => {
|
|
1928
2051
|
result = result.replace(new RegExp(s, "g"), " ");
|
|
1929
2052
|
});
|
|
1930
|
-
|
|
2053
|
+
fs6.writeFile(filePath, result, "utf8", (err2) => {
|
|
1931
2054
|
if (err2) throw err2;
|
|
1932
2055
|
console.log("File updated successfully.");
|
|
1933
2056
|
});
|
|
@@ -1945,7 +2068,7 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1945
2068
|
if (response.statusCode !== 200) {
|
|
1946
2069
|
console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
|
|
1947
2070
|
} else {
|
|
1948
|
-
|
|
2071
|
+
fs6.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
|
|
1949
2072
|
_SwaggerDownloader.postSanitizeDownloadedFile(destFile);
|
|
1950
2073
|
console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
|
|
1951
2074
|
}
|
|
@@ -1968,8 +2091,8 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1968
2091
|
};
|
|
1969
2092
|
|
|
1970
2093
|
// src/WebsocketGenerator.ts
|
|
1971
|
-
import
|
|
1972
|
-
import
|
|
2094
|
+
import fs7 from "fs";
|
|
2095
|
+
import path7 from "path";
|
|
1973
2096
|
|
|
1974
2097
|
// src/templates/template-ws-class.ts
|
|
1975
2098
|
var definitionToFunctionName = (type) => {
|
|
@@ -1984,7 +2107,7 @@ var renderSendFunction = (name, definition) => {
|
|
|
1984
2107
|
send({ type: '${name}', ...data })
|
|
1985
2108
|
}`;
|
|
1986
2109
|
};
|
|
1987
|
-
var templateWebsocketClass = (name,
|
|
2110
|
+
var templateWebsocketClass = (name, path9, definitions) => {
|
|
1988
2111
|
const requestDefinitions = Object.keys(definitions).filter((key) => {
|
|
1989
2112
|
const val = definitions[key];
|
|
1990
2113
|
return val["x-type"] == "request";
|
|
@@ -2043,7 +2166,7 @@ const messageSerializer = (data: Record<string, any>) => {
|
|
|
2043
2166
|
export function WebSocketClass(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
2044
2167
|
const sdkAssembly = sdk.assembly()
|
|
2045
2168
|
const baseURL = (args?.coreConfig?.baseURL ?? sdkAssembly.coreConfig.baseURL).replace('http', 'ws')
|
|
2046
|
-
const path = '${
|
|
2169
|
+
const path = '${path9}'
|
|
2047
2170
|
const url = baseURL + path
|
|
2048
2171
|
let ws: WebSocket | null = null
|
|
2049
2172
|
let isDisconnectManually = false
|
|
@@ -2292,9 +2415,9 @@ ${renderUnion(["response", "notification"], definitions)}
|
|
|
2292
2415
|
// src/WebsocketGenerator.ts
|
|
2293
2416
|
var WebsocketGenerator = class {
|
|
2294
2417
|
static srcFolder = () => CliParser.getOutputPath();
|
|
2295
|
-
static outputFolder = () =>
|
|
2418
|
+
static outputFolder = () => path7.join(this.srcFolder(), "generated-websocket");
|
|
2296
2419
|
static schemaContent = () => {
|
|
2297
|
-
const fileContent = JSON.parse(
|
|
2420
|
+
const fileContent = JSON.parse(fs7.readFileSync(CliParser.getWebSocketSchemaPath(), "utf8"));
|
|
2298
2421
|
return fileContent;
|
|
2299
2422
|
};
|
|
2300
2423
|
static prepareDirs = () => {
|
|
@@ -2304,11 +2427,11 @@ var WebsocketGenerator = class {
|
|
|
2304
2427
|
const { name, path: wsPath, definitions } = this.schemaContent();
|
|
2305
2428
|
const templateDefinitions = templateWebsocketDefinitions(definitions);
|
|
2306
2429
|
this.prepareDirs();
|
|
2307
|
-
const filePath =
|
|
2308
|
-
|
|
2430
|
+
const filePath = path7.join(this.outputFolder(), "WebSocketDefinitions.ts");
|
|
2431
|
+
fs7.writeFileSync(filePath, templateDefinitions, "utf8");
|
|
2309
2432
|
const templateClass2 = templateWebsocketClass(name, wsPath, definitions);
|
|
2310
|
-
const filePathClass =
|
|
2311
|
-
|
|
2433
|
+
const filePathClass = path7.join(this.outputFolder(), "WebSocketClass.ts");
|
|
2434
|
+
fs7.writeFileSync(filePathClass, templateClass2, "utf8");
|
|
2312
2435
|
};
|
|
2313
2436
|
};
|
|
2314
2437
|
|
|
@@ -2321,24 +2444,28 @@ var generateSdk = async () => {
|
|
|
2321
2444
|
if (CliParser.isGenerateWebSocket()) {
|
|
2322
2445
|
WebsocketGenerator.main();
|
|
2323
2446
|
}
|
|
2447
|
+
if (!CodegenConfig.shouldProduceIndexFiles()) {
|
|
2448
|
+
return;
|
|
2449
|
+
}
|
|
2324
2450
|
const indexImportsSet = /* @__PURE__ */ new Set();
|
|
2325
2451
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
2326
2452
|
const filenamesSet = /* @__PURE__ */ new Set();
|
|
2327
2453
|
for (const set of arrayOfSets) {
|
|
2328
2454
|
set.indexImports.forEach((value) => {
|
|
2329
|
-
const fileName =
|
|
2455
|
+
const fileName = path8.basename(value);
|
|
2330
2456
|
if (!filenamesSet.has(fileName)) {
|
|
2331
2457
|
indexImportsSet.add(value);
|
|
2332
2458
|
filenamesSet.add(fileName);
|
|
2333
2459
|
}
|
|
2334
2460
|
});
|
|
2335
2461
|
set.queryImports.forEach((value) => {
|
|
2336
|
-
const fileName =
|
|
2462
|
+
const fileName = path8.basename(value);
|
|
2337
2463
|
if (!filenamesSet.has(fileName)) {
|
|
2338
2464
|
queryImportsSet.add(value);
|
|
2339
2465
|
}
|
|
2340
2466
|
});
|
|
2341
2467
|
}
|
|
2468
|
+
const outputPath = CliParser.getOutputPath();
|
|
2342
2469
|
const indexImportsArray = Array.from(indexImportsSet).sort();
|
|
2343
2470
|
const queryImportsArray = Array.from(queryImportsSet).sort();
|
|
2344
2471
|
const filesToImport = indexImportsArray.map((fileToImport) => {
|
|
@@ -2347,8 +2474,8 @@ var generateSdk = async () => {
|
|
|
2347
2474
|
const queryFilesToImport = queryImportsArray.map((fileToImport) => {
|
|
2348
2475
|
return `export * from '${fileToImport.replace("\\", "/")}.js'`;
|
|
2349
2476
|
});
|
|
2350
|
-
ParserUtils.writeAllImportsFile(
|
|
2351
|
-
ParserUtils.writeAllQueryImportsFile(
|
|
2477
|
+
ParserUtils.writeAllImportsFile(outputPath, filesToImport.join("\n"));
|
|
2478
|
+
ParserUtils.writeAllQueryImportsFile(outputPath, queryFilesToImport.join("\n"));
|
|
2352
2479
|
};
|
|
2353
2480
|
yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
2354
2481
|
CliParser.createInstance(yargs2);
|
|
@@ -2364,6 +2491,7 @@ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
|
2364
2491
|
return true;
|
|
2365
2492
|
});
|
|
2366
2493
|
CliParser.createInstance(yargs2);
|
|
2494
|
+
await CodegenConfig.loadConfig(path8.dirname(path8.resolve(CliParser.getConfigPath())));
|
|
2367
2495
|
await generateSdk();
|
|
2368
2496
|
}).option("config", {
|
|
2369
2497
|
description: "Path to the config file with backend service URLs.",
|