@accelbyte/codegen 4.1.6 → 4.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +277 -150
- package/dist/accelbyte-codegen.js.map +1 -1
- package/dist/accelbyte-codegen.mjs +274 -150
- 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.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,18 +278,16 @@ ${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
|
|
@@ -237,7 +305,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
237
305
|
if (interceptor.type === 'request') {
|
|
238
306
|
axiosInstance.interceptors.request.use(interceptor.onRequest, interceptor.onError)
|
|
239
307
|
}
|
|
240
|
-
|
|
308
|
+
|
|
241
309
|
if (interceptor.type === 'response') {
|
|
242
310
|
axiosInstance.interceptors.response.use(interceptor.onSuccess, interceptor.onError)
|
|
243
311
|
}
|
|
@@ -248,7 +316,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
248
316
|
}
|
|
249
317
|
|
|
250
318
|
${body}
|
|
251
|
-
|
|
319
|
+
|
|
252
320
|
return {
|
|
253
321
|
${returnsMethodsWithDescription}
|
|
254
322
|
}
|
|
@@ -259,7 +327,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
259
327
|
// src/ParserQueryUtils.ts
|
|
260
328
|
var ParserQueryUtils = class {
|
|
261
329
|
/**
|
|
262
|
-
* convert csv 'aa,bb' into "aa='aa', bb='bb'"
|
|
330
|
+
* convert csv 'aa,bb' into "aa = 'Sdk.Class.aa', bb = 'Sdk.Class.bb'"
|
|
263
331
|
*/
|
|
264
332
|
static createQueryKeys(classNameWithoutApi, csvMethodNames, sdkName) {
|
|
265
333
|
const keys = csvMethodNames.split(",");
|
|
@@ -270,7 +338,7 @@ var ParserQueryUtils = class {
|
|
|
270
338
|
const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete|post|fetch)[_]?/, "");
|
|
271
339
|
if (!processedKeys.has(cleanedKey)) {
|
|
272
340
|
processedKeys.add(cleanedKey);
|
|
273
|
-
acc += `${cleanedKey}
|
|
341
|
+
acc += `${cleanedKey}: '${capitalize(sdkName)}.${classNameWithoutApi}.${cleanedKey}'`;
|
|
274
342
|
if (index < keys.length - 1) {
|
|
275
343
|
acc += ",\n";
|
|
276
344
|
}
|
|
@@ -284,42 +352,51 @@ var ParserQueryUtils = class {
|
|
|
284
352
|
|
|
285
353
|
// src/templates/template-query.ts
|
|
286
354
|
var generateImports2 = (body, className) => {
|
|
287
|
-
const
|
|
288
|
-
import {
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
import { ${
|
|
292
|
-
|
|
293
|
-
|
|
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";
|
|
294
371
|
};
|
|
295
372
|
var templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports, sdkName) => {
|
|
296
373
|
const classNameWithoutApi = className.replace("Api", "");
|
|
297
374
|
const queryKeys = ParserQueryUtils.createQueryKeys(classNameWithoutApi, returnMethods, sdkName);
|
|
298
375
|
const generatedImports = generateImports2(body, className);
|
|
376
|
+
const queryKeyBlock = `export const Key_${classNameWithoutApi} = {
|
|
377
|
+
${queryKeys}
|
|
378
|
+
} as const`;
|
|
299
379
|
return `/**
|
|
300
380
|
* AUTO GENERATED
|
|
301
381
|
*/
|
|
302
|
-
/* eslint-disable camelcase */
|
|
303
382
|
${generatedImports}
|
|
304
383
|
${filterUsedImports(paramImports, body)}
|
|
305
384
|
|
|
306
|
-
|
|
307
|
-
${queryKeys}
|
|
308
|
-
}
|
|
385
|
+
${queryKeyBlock}
|
|
309
386
|
|
|
310
387
|
${body}
|
|
311
388
|
`;
|
|
312
389
|
};
|
|
313
390
|
function filterUsedImports(importArr, body) {
|
|
314
|
-
return importArr.filter((
|
|
315
|
-
const start =
|
|
316
|
-
const end =
|
|
391
|
+
return importArr.filter((path9) => {
|
|
392
|
+
const start = path9.indexOf("{") + 1;
|
|
393
|
+
const end = path9.indexOf("}");
|
|
317
394
|
if (start > 0 && end > start) {
|
|
318
|
-
const importName =
|
|
395
|
+
const importName = path9.slice(start, end).trim();
|
|
319
396
|
return body.includes(importName);
|
|
320
397
|
}
|
|
321
398
|
return false;
|
|
322
|
-
}).map((
|
|
399
|
+
}).map((path9) => path9).join("\n") + "\n";
|
|
323
400
|
}
|
|
324
401
|
|
|
325
402
|
// src/ParserUtils.ts
|
|
@@ -336,8 +413,8 @@ var REMOVED_KEYWORDS = [
|
|
|
336
413
|
"/{namespace}/"
|
|
337
414
|
];
|
|
338
415
|
var ParserUtils = class _ParserUtils {
|
|
339
|
-
static getVersionSuffixFromPath(
|
|
340
|
-
const version2_3_4_etc =
|
|
416
|
+
static getVersionSuffixFromPath(path9) {
|
|
417
|
+
const version2_3_4_etc = path9.match(/\/v([2-9]|[1-9]\d+)\/+/);
|
|
341
418
|
const methodSuffix = version2_3_4_etc ? `_v${version2_3_4_etc[1]}` : "";
|
|
342
419
|
return methodSuffix;
|
|
343
420
|
}
|
|
@@ -419,13 +496,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
419
496
|
};
|
|
420
497
|
static parseRefImport = (bodyParam) => {
|
|
421
498
|
const $ref = bodyParam?.schema?.$ref || bodyParam?.schema?.items?.$ref;
|
|
422
|
-
if (!$ref) {
|
|
499
|
+
if (!$ref || $ref.endsWith("__dictionary__")) {
|
|
423
500
|
return null;
|
|
424
501
|
}
|
|
425
502
|
const type = _ParserUtils.parseRefType($ref);
|
|
426
503
|
return `import { ${type} } from '../../generated-definitions/${type}.js'`;
|
|
427
504
|
};
|
|
428
505
|
static parseRefType = ($ref) => {
|
|
506
|
+
if ($ref.endsWith("__dictionary__")) return "__dictionary__";
|
|
429
507
|
let ref = $ref.replace(".", "/");
|
|
430
508
|
if (ref[ref.length - 1] === "." || ref[ref.length - 1] === "/") {
|
|
431
509
|
ref = ref.slice(0, -1);
|
|
@@ -532,14 +610,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
532
610
|
* to this
|
|
533
611
|
* `createGenerateByRequestIdByUserId`
|
|
534
612
|
*/
|
|
535
|
-
static generateNaturalLangMethod = ({ servicePrefix, path:
|
|
536
|
-
let path_ =
|
|
613
|
+
static generateNaturalLangMethod = ({ servicePrefix, path: path9, httpMethod, isForm, existingMethods, permissionType }) => {
|
|
614
|
+
let path_ = path9;
|
|
537
615
|
path_ = path_.replace(`/${servicePrefix}/`, "/");
|
|
538
616
|
REMOVED_KEYWORDS.forEach((prefix) => {
|
|
539
617
|
path_ = path_.replace(prefix, "/");
|
|
540
618
|
});
|
|
541
619
|
path_ = path_.substring(1);
|
|
542
|
-
const isPlural = httpMethod === "get" && !(
|
|
620
|
+
const isPlural = httpMethod === "get" && !(path9.slice(-1) === "}");
|
|
543
621
|
if (!isPlural) {
|
|
544
622
|
path_ = _ParserUtils.replaceAll(path_, "ies/", "y/");
|
|
545
623
|
path_ = _ParserUtils.replaceAll(path_, "s/", "/");
|
|
@@ -582,9 +660,9 @@ var ParserUtils = class _ParserUtils {
|
|
|
582
660
|
const genPath = _.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
|
|
583
661
|
let generatedMethod = _.camelCase(mappedMethod(httpMethod, isForm, permissionType) + genPath);
|
|
584
662
|
generatedMethod = _ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
|
|
585
|
-
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(
|
|
586
|
-
generatedMethod = resolveConflicts({ path:
|
|
587
|
-
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);
|
|
588
666
|
return generatedMethod;
|
|
589
667
|
};
|
|
590
668
|
static filterBodyParams(parameters) {
|
|
@@ -600,17 +678,17 @@ var ParserUtils = class _ParserUtils {
|
|
|
600
678
|
return parameters.filter((parameter) => parameter.in === "query");
|
|
601
679
|
}
|
|
602
680
|
static mkdirIfNotExist(dirToCreate) {
|
|
603
|
-
if (!
|
|
604
|
-
|
|
681
|
+
if (!fs4.existsSync(dirToCreate)) {
|
|
682
|
+
fs4.mkdirSync(dirToCreate, { recursive: true });
|
|
605
683
|
}
|
|
606
684
|
}
|
|
607
685
|
static writeClassFile(distDir, apiName, apiBuffer, imports) {
|
|
608
686
|
const fileContent = templateClass(apiName, apiBuffer, imports);
|
|
609
|
-
|
|
687
|
+
fs4.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
610
688
|
}
|
|
611
689
|
static writeAtomFile(distDir, apiName, fileContent) {
|
|
612
690
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
613
|
-
|
|
691
|
+
fs4.writeFileSync(`${distDir}/${apiName}.atom.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
614
692
|
}
|
|
615
693
|
static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName) {
|
|
616
694
|
if (apiBuffer.length < 1) {
|
|
@@ -619,20 +697,21 @@ var ParserUtils = class _ParserUtils {
|
|
|
619
697
|
const queryFileName = `${apiName.replace("Api", "")}.query`;
|
|
620
698
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
621
699
|
const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName);
|
|
622
|
-
|
|
700
|
+
fs4.writeFileSync(`${distDir}/${queryFileName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
623
701
|
return queryFileName;
|
|
624
702
|
}
|
|
625
703
|
static writeXVersion(distDir, xversionJson, apiInfo) {
|
|
704
|
+
fs4.mkdirSync(distDir, { recursive: true });
|
|
626
705
|
if (xversionJson) {
|
|
627
706
|
console.log("x-version:", xversionJson);
|
|
628
|
-
|
|
707
|
+
fs4.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
|
|
629
708
|
} else {
|
|
630
709
|
const customVersion = {
|
|
631
710
|
...apiInfo,
|
|
632
711
|
gitHash: apiInfo.version
|
|
633
712
|
};
|
|
634
713
|
console.error(`!!!! Missing x-version for ${distDir} ${customVersion}`);
|
|
635
|
-
|
|
714
|
+
fs4.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
|
|
636
715
|
}
|
|
637
716
|
}
|
|
638
717
|
static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethodsDescription) {
|
|
@@ -641,28 +720,28 @@ var ParserUtils = class _ParserUtils {
|
|
|
641
720
|
newImports.push(el.replace("../../generated-definitions", "../generated-definitions"));
|
|
642
721
|
});
|
|
643
722
|
const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethodsDescription);
|
|
644
|
-
|
|
723
|
+
fs4.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
645
724
|
}
|
|
646
725
|
static writeApiMainFile(distDir, serviceName, fileContent) {
|
|
647
|
-
|
|
726
|
+
fs4.writeFileSync(`${distDir}/${serviceName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
648
727
|
}
|
|
649
728
|
static writeSnippetFile(distDir, name, docBuffer) {
|
|
650
729
|
let snippetFileName = _ParserUtils.replaceAll(name, " ", "-").toLowerCase();
|
|
651
730
|
snippetFileName = snippetFileName.replace("justice-", "");
|
|
652
731
|
snippetFileName = "snippet-" + snippetFileName + ".json";
|
|
653
|
-
|
|
732
|
+
fs4.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
|
|
654
733
|
}
|
|
655
734
|
static writeDefinitionFile(distDir, name, buffer) {
|
|
656
735
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
657
|
-
|
|
736
|
+
fs4.writeFileSync(path4.join(distDir, `${name}.ts`), _ParserUtils.prependCopyrightHeader(buffer));
|
|
658
737
|
}
|
|
659
738
|
static writeAllImportsFile(distDir, buffer) {
|
|
660
739
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
661
|
-
|
|
740
|
+
fs4.writeFileSync(path4.join(distDir, "all-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
662
741
|
}
|
|
663
742
|
static writeAllQueryImportsFile(distDir, buffer) {
|
|
664
743
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
665
|
-
|
|
744
|
+
fs4.writeFileSync(path4.join(distDir, "all-query-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
666
745
|
}
|
|
667
746
|
static toCamelCase(str) {
|
|
668
747
|
return str.split("/").map(function(word, index) {
|
|
@@ -688,15 +767,15 @@ var ParserUtils = class _ParserUtils {
|
|
|
688
767
|
});
|
|
689
768
|
}
|
|
690
769
|
static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
|
|
691
|
-
if (!
|
|
692
|
-
|
|
770
|
+
if (!fs4.existsSync(swaggerPatchedDir)) {
|
|
771
|
+
fs4.mkdirSync(swaggerPatchedDir, { recursive: true });
|
|
693
772
|
}
|
|
694
|
-
if (!
|
|
695
|
-
|
|
773
|
+
if (!fs4.existsSync(possibleSwaggerPatchFilePath)) {
|
|
774
|
+
fs4.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
|
|
696
775
|
return;
|
|
697
776
|
}
|
|
698
|
-
const swaggerContent = JSON.parse(
|
|
699
|
-
const swaggerPatchFileContent = JSON.parse(
|
|
777
|
+
const swaggerContent = JSON.parse(fs4.readFileSync(swaggerFilePath, "utf8"));
|
|
778
|
+
const swaggerPatchFileContent = JSON.parse(fs4.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
|
|
700
779
|
for (const patchEntry of swaggerPatchFileContent) {
|
|
701
780
|
const segments = patchEntry.path.split("/").filter(Boolean);
|
|
702
781
|
let currentNode = swaggerContent;
|
|
@@ -724,7 +803,7 @@ var ParserUtils = class _ParserUtils {
|
|
|
724
803
|
}
|
|
725
804
|
}
|
|
726
805
|
const { newDocument } = applyPatch(swaggerContent, swaggerPatchFileContent);
|
|
727
|
-
|
|
806
|
+
fs4.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
|
|
728
807
|
}
|
|
729
808
|
static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
|
|
730
809
|
const replaced = srcFolder.replace(/\\/g, "/");
|
|
@@ -739,8 +818,8 @@ var ParserUtils = class _ParserUtils {
|
|
|
739
818
|
*/
|
|
740
819
|
${content}`;
|
|
741
820
|
};
|
|
742
|
-
static sortPathParamsByPath = (pathParams,
|
|
743
|
-
const params =
|
|
821
|
+
static sortPathParamsByPath = (pathParams, path9) => {
|
|
822
|
+
const params = path9.match(/{\w*}/g) || [];
|
|
744
823
|
const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
|
|
745
824
|
return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
|
|
746
825
|
};
|
|
@@ -764,30 +843,40 @@ var mappedMethod = (httpMethod, isForm, permissionType) => {
|
|
|
764
843
|
return "delete";
|
|
765
844
|
}
|
|
766
845
|
};
|
|
767
|
-
var resolveConflicts = ({ path:
|
|
846
|
+
var resolveConflicts = ({ path: path9, generatedMethod, testedGeneratedMethod, existingMethods }) => {
|
|
768
847
|
let _testedGenMethod = testedGeneratedMethod;
|
|
769
848
|
try {
|
|
770
|
-
testConflict(
|
|
849
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
771
850
|
} catch (e) {
|
|
772
|
-
if (
|
|
851
|
+
if (path9.indexOf("/namespaces/") >= 0) {
|
|
773
852
|
generatedMethod += "_ByNS";
|
|
774
853
|
_testedGenMethod += "_ByNS";
|
|
775
854
|
}
|
|
776
855
|
}
|
|
777
856
|
try {
|
|
778
|
-
testConflict(
|
|
857
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
779
858
|
} catch (e) {
|
|
780
|
-
if (
|
|
859
|
+
if (path9.indexOf("/admin/") >= 0) {
|
|
781
860
|
generatedMethod += "_admin";
|
|
782
861
|
_testedGenMethod += "_admin";
|
|
783
862
|
}
|
|
784
863
|
}
|
|
785
|
-
|
|
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);
|
|
786
875
|
return generatedMethod;
|
|
787
876
|
};
|
|
788
|
-
var testConflict = (
|
|
877
|
+
var testConflict = (path9, generatedMethod, existingMethods) => {
|
|
789
878
|
if (existingMethods[generatedMethod]) {
|
|
790
|
-
const conflictingMethod = { path:
|
|
879
|
+
const conflictingMethod = { path: path9, generatedMethod };
|
|
791
880
|
throw Error(
|
|
792
881
|
`Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
|
|
793
882
|
existingMethods: ${JSON.stringify(existingMethods, null, 2)}`
|
|
@@ -904,7 +993,7 @@ var OpenApiSpec = z2.object({
|
|
|
904
993
|
var templateApiMethod = ({
|
|
905
994
|
classMethod,
|
|
906
995
|
httpMethod,
|
|
907
|
-
path:
|
|
996
|
+
path: path9,
|
|
908
997
|
pathParams,
|
|
909
998
|
bodyParams,
|
|
910
999
|
responseClasses,
|
|
@@ -913,12 +1002,12 @@ var templateApiMethod = ({
|
|
|
913
1002
|
methodParamsNoTypes,
|
|
914
1003
|
xSecurity
|
|
915
1004
|
}) => {
|
|
916
|
-
let newPath = `'${
|
|
1005
|
+
let newPath = `'${path9}'`;
|
|
917
1006
|
let snippetMethod = "";
|
|
918
1007
|
for (const pathParam of pathParams) {
|
|
919
1008
|
const type = ParserUtils.parseType(pathParam);
|
|
920
1009
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
921
|
-
if (
|
|
1010
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
922
1011
|
if (type === "string") {
|
|
923
1012
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
924
1013
|
} else {
|
|
@@ -926,9 +1015,9 @@ var templateApiMethod = ({
|
|
|
926
1015
|
}
|
|
927
1016
|
}
|
|
928
1017
|
}
|
|
929
|
-
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${
|
|
1018
|
+
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path9}'`, "--header 'accept: application/json'"];
|
|
930
1019
|
const snippetApiArgs = [];
|
|
931
|
-
if (xSecurity !== void 0 ||
|
|
1020
|
+
if (xSecurity !== void 0 || path9.includes("/admin")) {
|
|
932
1021
|
snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
|
|
933
1022
|
snippetApiArgs.push("{ axiosConfig: { request: { headers: { Authorization: 'Bearer {access_token}' } } } }".trim());
|
|
934
1023
|
}
|
|
@@ -966,7 +1055,7 @@ var templateMethod = ({
|
|
|
966
1055
|
classMethod,
|
|
967
1056
|
description,
|
|
968
1057
|
httpMethod,
|
|
969
|
-
path:
|
|
1058
|
+
path: path9,
|
|
970
1059
|
pathParams,
|
|
971
1060
|
bodyParams,
|
|
972
1061
|
queryParams,
|
|
@@ -976,9 +1065,9 @@ var templateMethod = ({
|
|
|
976
1065
|
}) => {
|
|
977
1066
|
let methodParams = "";
|
|
978
1067
|
let methodParamsNoTypes = "";
|
|
979
|
-
let newPath = `'${
|
|
1068
|
+
let newPath = `'${path9}'`;
|
|
980
1069
|
let importStatements = [];
|
|
981
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1070
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
982
1071
|
for (const pathParam of sortedPathParams) {
|
|
983
1072
|
const type = ParserUtils.parseType(pathParam);
|
|
984
1073
|
if (pathParam.name !== "namespace") {
|
|
@@ -986,7 +1075,7 @@ var templateMethod = ({
|
|
|
986
1075
|
methodParamsNoTypes += pathParam.name + ", ";
|
|
987
1076
|
}
|
|
988
1077
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
989
|
-
if (
|
|
1078
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
990
1079
|
if (type === "string") {
|
|
991
1080
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
992
1081
|
} else {
|
|
@@ -997,6 +1086,7 @@ var templateMethod = ({
|
|
|
997
1086
|
let dataType = null;
|
|
998
1087
|
if (httpMethod !== "get") {
|
|
999
1088
|
dataType = ParserUtils.parseBodyParamsType(bodyParams);
|
|
1089
|
+
if (dataType === "__dictionary__") dataType = "Record<string, any>";
|
|
1000
1090
|
importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
|
|
1001
1091
|
methodParams += dataType ? `data: ${dataType},` : "";
|
|
1002
1092
|
methodParamsNoTypes += dataType ? `data,` : "";
|
|
@@ -1020,7 +1110,7 @@ var templateMethod = ({
|
|
|
1020
1110
|
}
|
|
1021
1111
|
const isFileUpload = methodParams.indexOf("data: {file") > -1;
|
|
1022
1112
|
const { responseType, responseTypeInResponse } = getResponseType({ responseClasses });
|
|
1023
|
-
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()";
|
|
1024
1114
|
methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
|
|
1025
1115
|
methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
|
|
1026
1116
|
const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
|
|
@@ -1051,7 +1141,7 @@ var POST_FETCH_INCLUDES_PATH = ["/table-query/"];
|
|
|
1051
1141
|
var templateQueryMethod = ({
|
|
1052
1142
|
classMethod,
|
|
1053
1143
|
httpMethod,
|
|
1054
|
-
path:
|
|
1144
|
+
path: path9,
|
|
1055
1145
|
pathParams,
|
|
1056
1146
|
responseClasses,
|
|
1057
1147
|
methodParams,
|
|
@@ -1059,14 +1149,14 @@ var templateQueryMethod = ({
|
|
|
1059
1149
|
description,
|
|
1060
1150
|
deprecated
|
|
1061
1151
|
}) => {
|
|
1062
|
-
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"));
|
|
1063
1153
|
const isFetch = classMethod.startsWith("fetch");
|
|
1064
1154
|
const isGet = httpMethod === "get" || isPostFetch || isFetch;
|
|
1065
1155
|
const queryMethod = isGet ? "useQuery" : "useMutation";
|
|
1066
1156
|
let mParams = "";
|
|
1067
1157
|
let mParamsNoTypes = "";
|
|
1068
|
-
let newPath = `'${
|
|
1069
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1158
|
+
let newPath = `'${path9}'`;
|
|
1159
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
1070
1160
|
for (const pathParam of sortedPathParams) {
|
|
1071
1161
|
const type = ParserUtils.parseType(pathParam);
|
|
1072
1162
|
if (pathParam.name !== "namespace") {
|
|
@@ -1074,7 +1164,7 @@ var templateQueryMethod = ({
|
|
|
1074
1164
|
mParamsNoTypes += pathParam.name + ", ";
|
|
1075
1165
|
}
|
|
1076
1166
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1077
|
-
if (
|
|
1167
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
1078
1168
|
if (type === "string") {
|
|
1079
1169
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1080
1170
|
} else {
|
|
@@ -1109,7 +1199,7 @@ export const ${_methodName} = (
|
|
|
1109
1199
|
const response =
|
|
1110
1200
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1111
1201
|
${classMethod}(${_methodParamsImpl}))
|
|
1112
|
-
callback
|
|
1202
|
+
callback?.(response)
|
|
1113
1203
|
return response.data
|
|
1114
1204
|
}
|
|
1115
1205
|
|
|
@@ -1134,7 +1224,7 @@ export const ${_methodName} = (
|
|
|
1134
1224
|
const response =
|
|
1135
1225
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1136
1226
|
${classMethod}(${_methodParamsImpl}))
|
|
1137
|
-
callback
|
|
1227
|
+
callback?.(response.data)
|
|
1138
1228
|
return response.data
|
|
1139
1229
|
}
|
|
1140
1230
|
|
|
@@ -1313,11 +1403,11 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1313
1403
|
admin: {},
|
|
1314
1404
|
public: {}
|
|
1315
1405
|
};
|
|
1316
|
-
for (const [
|
|
1317
|
-
if (
|
|
1406
|
+
for (const [path9, operation] of sortedPathsByLength) {
|
|
1407
|
+
if (path9.indexOf("/healthz") >= 0) {
|
|
1318
1408
|
continue;
|
|
1319
1409
|
}
|
|
1320
|
-
const isAdminEndpoint =
|
|
1410
|
+
const isAdminEndpoint = path9.indexOf("/admin/") > -1;
|
|
1321
1411
|
const picked = isAdminEndpoint ? result.admin : result.public;
|
|
1322
1412
|
const {
|
|
1323
1413
|
arrayDefinitions,
|
|
@@ -1335,25 +1425,27 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1335
1425
|
const httpMethods = Object.keys(operation);
|
|
1336
1426
|
for (const httpMethod of httpMethods) {
|
|
1337
1427
|
const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
|
|
1338
|
-
console.error(JSON.stringify({ path:
|
|
1428
|
+
console.error(JSON.stringify({ path: path9, httpMethod }, null, 2));
|
|
1339
1429
|
throw error;
|
|
1340
1430
|
});
|
|
1341
1431
|
if (!endpoint.tags) continue;
|
|
1342
1432
|
const [tag] = endpoint.tags;
|
|
1343
|
-
const
|
|
1433
|
+
const configBasePath = CodegenConfig.getBasePath();
|
|
1434
|
+
const effectiveBasePath = configBasePath !== void 0 ? configBasePath : api.basePath ?? "";
|
|
1435
|
+
const pathWithBase = `${effectiveBasePath}${path9}`;
|
|
1344
1436
|
const permissionType = getPermissionType(getPermission(endpoint));
|
|
1345
1437
|
tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
|
|
1346
1438
|
const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
|
|
1347
1439
|
const classMethod = ParserUtils.generateNaturalLangMethod({
|
|
1348
1440
|
servicePrefix,
|
|
1349
|
-
path:
|
|
1441
|
+
path: path9,
|
|
1350
1442
|
httpMethod,
|
|
1351
1443
|
isForm,
|
|
1352
1444
|
existingMethods: tagToClassMethodsMapByType[tag],
|
|
1353
1445
|
permissionType
|
|
1354
1446
|
});
|
|
1355
|
-
tagToClassMethodsMapByType[tag][classMethod] = `${
|
|
1356
|
-
generatedMethods[`${
|
|
1447
|
+
tagToClassMethodsMapByType[tag][classMethod] = `${path9} ${httpMethod}`;
|
|
1448
|
+
generatedMethods[`${path9} ${httpMethod}`] = `${classMethod}`;
|
|
1357
1449
|
if (!snippetMap[pathWithBase]) {
|
|
1358
1450
|
snippetMap[pathWithBase] = {};
|
|
1359
1451
|
}
|
|
@@ -1362,7 +1454,7 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1362
1454
|
const responseClass = responseClasses.length > 1 ? null : responseClasses?.[0];
|
|
1363
1455
|
const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
|
|
1364
1456
|
tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
|
|
1365
|
-
if (responseClass) {
|
|
1457
|
+
if (responseClass && responseClass !== "__dictionary__") {
|
|
1366
1458
|
tagToClassImportsRecord[className][responseClass] = `import { ${responseClass} } from '../../generated-definitions/${responseClass}.js'`;
|
|
1367
1459
|
}
|
|
1368
1460
|
if (responseClass && responseClass.endsWith("Array")) {
|
|
@@ -1508,6 +1600,20 @@ var TemplateZod = class {
|
|
|
1508
1600
|
// --
|
|
1509
1601
|
render = (fileName, definition, duplicates) => {
|
|
1510
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
|
+
}
|
|
1511
1617
|
const content = this.parseToZodSchema(definition, definition.required || []);
|
|
1512
1618
|
const containsRecursiveType = this.importClasses.has(fileName);
|
|
1513
1619
|
if (containsRecursiveType) {
|
|
@@ -1596,7 +1702,14 @@ ${exportedTypeString}
|
|
|
1596
1702
|
};
|
|
1597
1703
|
} else if (type) {
|
|
1598
1704
|
if (type === "object" && definition.additionalProperties) {
|
|
1599
|
-
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, [""]);
|
|
1600
1713
|
return {
|
|
1601
1714
|
schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
|
|
1602
1715
|
typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
|
|
@@ -1782,8 +1895,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1782
1895
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
1783
1896
|
const apiInfo = { ...api.info, "x-version": api["x-version"]?.version };
|
|
1784
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()}/`;
|
|
1785
1901
|
if (!CliParser.isGenerateSnippetOnly()) {
|
|
1786
|
-
ParserUtils.writeXVersion(
|
|
1902
|
+
ParserUtils.writeXVersion(srcFolder, api["x-version"], api.info);
|
|
1787
1903
|
}
|
|
1788
1904
|
const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
|
|
1789
1905
|
if (CliParser.getSnippetOutputPath()) {
|
|
@@ -1809,11 +1925,10 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1809
1925
|
console.log("\nSuccessfully generate SDK snippets only\n----------\n\n");
|
|
1810
1926
|
return;
|
|
1811
1927
|
}
|
|
1812
|
-
const DIST_DIR = (isAdmin) =>
|
|
1813
|
-
const DIST_DIR_ENDPOINTS = (isAdmin) =>
|
|
1814
|
-
const DIST_DIR_QUERIES = (isAdmin) =>
|
|
1815
|
-
const DIST_DEFINITION_DIR =
|
|
1816
|
-
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");
|
|
1817
1932
|
_CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
|
|
1818
1933
|
const mainApiList = [];
|
|
1819
1934
|
const generatedDefinitions = [];
|
|
@@ -1854,30 +1969,31 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1854
1969
|
ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionDescription[tag]);
|
|
1855
1970
|
apiList.push(apiGenName);
|
|
1856
1971
|
indexImportsSet.add(
|
|
1857
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1972
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder)
|
|
1858
1973
|
);
|
|
1859
1974
|
indexImportsSet.add(
|
|
1860
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1975
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder)
|
|
1861
1976
|
);
|
|
1862
1977
|
queryFileName && queryImportsSet.add(
|
|
1863
1978
|
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1864
|
-
|
|
1979
|
+
path5.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`),
|
|
1865
1980
|
targetSrcFolder
|
|
1866
1981
|
)
|
|
1867
1982
|
);
|
|
1868
1983
|
}
|
|
1869
1984
|
mainApiList.push(...apiList);
|
|
1870
|
-
|
|
1871
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1872
|
-
|
|
1985
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
1986
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(srcFolder, serviceNameTitle), targetSrcFolder));
|
|
1987
|
+
}
|
|
1873
1988
|
};
|
|
1874
1989
|
const writeDefinitions = (api2) => {
|
|
1875
1990
|
const duplicates = /* @__PURE__ */ new Map();
|
|
1876
1991
|
const definitions = api2?.components?.schemas || api2.definitions;
|
|
1877
1992
|
for (const ref in definitions) {
|
|
1993
|
+
if (ref === "__dictionary__") continue;
|
|
1878
1994
|
const definition = definitions[ref];
|
|
1879
1995
|
const fileName = ParserUtils.parseRefType(ref);
|
|
1880
|
-
const fileExist =
|
|
1996
|
+
const fileExist = fs5.existsSync(path5.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
|
|
1881
1997
|
if (fileExist) {
|
|
1882
1998
|
const duplicateName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
|
|
1883
1999
|
duplicates.set(ref, duplicateName);
|
|
@@ -1885,13 +2001,13 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1885
2001
|
const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
|
|
1886
2002
|
generatedDefinitions.push(fileName);
|
|
1887
2003
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
|
|
1888
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2004
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
|
|
1889
2005
|
}
|
|
1890
2006
|
for (const arrayClass of arrayDefinitions) {
|
|
1891
2007
|
const buffer = new TemplateZodArray().render(arrayClass);
|
|
1892
2008
|
generatedDefinitions.push(arrayClass);
|
|
1893
2009
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
|
|
1894
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2010
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path5.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
|
|
1895
2011
|
}
|
|
1896
2012
|
};
|
|
1897
2013
|
writeApiEndpointFiles(isAdmin);
|
|
@@ -1899,9 +2015,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1899
2015
|
};
|
|
1900
2016
|
generatePublicOrAdmin(true);
|
|
1901
2017
|
generatePublicOrAdmin(false);
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
2018
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
2019
|
+
const isGenerateWebSocket = CliParser.isGenerateWebSocket();
|
|
2020
|
+
const apiIndexBuff = templateApiIndex(serviceNameTitle, mainApiList, isGenerateWebSocket);
|
|
2021
|
+
ParserUtils.writeApiMainFile(srcFolder, serviceNameTitle, apiIndexBuff);
|
|
2022
|
+
}
|
|
1905
2023
|
console.log("\nCOMPLETED\n----------\n\n");
|
|
1906
2024
|
return { indexImports: indexImportsSet, queryImports: queryImportsSet };
|
|
1907
2025
|
};
|
|
@@ -1909,29 +2027,30 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1909
2027
|
};
|
|
1910
2028
|
|
|
1911
2029
|
// src/SwaggerDownloader.ts
|
|
2030
|
+
import * as fs6 from "fs";
|
|
1912
2031
|
import * as https from "https";
|
|
1913
|
-
import * as
|
|
1914
|
-
import * as path5 from "path";
|
|
2032
|
+
import * as path6 from "path";
|
|
1915
2033
|
var SwaggerDownloader = class _SwaggerDownloader {
|
|
1916
2034
|
static getDestFile = (targetFileName) => {
|
|
1917
2035
|
const destPath = CliParser.getResolvedSwaggersOutputPath();
|
|
1918
|
-
const destFile =
|
|
1919
|
-
if (
|
|
1920
|
-
if (!
|
|
1921
|
-
|
|
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, "");
|
|
1922
2040
|
return destFile;
|
|
1923
2041
|
};
|
|
1924
2042
|
// session-api.json contains illegal URL encoded character that breaks the codegen
|
|
1925
2043
|
// e.g. "$ref": "#/definitions/map%5Bstring%5Dinterface%20%7B%7D"
|
|
1926
2044
|
static postSanitizeDownloadedFile = (filePath) => {
|
|
1927
2045
|
const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
|
|
1928
|
-
|
|
2046
|
+
fs6.readFile(filePath, "utf8", (err, data) => {
|
|
1929
2047
|
if (err) throw err;
|
|
1930
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__");
|
|
1931
2050
|
searchStr.forEach((s) => {
|
|
1932
2051
|
result = result.replace(new RegExp(s, "g"), " ");
|
|
1933
2052
|
});
|
|
1934
|
-
|
|
2053
|
+
fs6.writeFile(filePath, result, "utf8", (err2) => {
|
|
1935
2054
|
if (err2) throw err2;
|
|
1936
2055
|
console.log("File updated successfully.");
|
|
1937
2056
|
});
|
|
@@ -1949,7 +2068,7 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1949
2068
|
if (response.statusCode !== 200) {
|
|
1950
2069
|
console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
|
|
1951
2070
|
} else {
|
|
1952
|
-
|
|
2071
|
+
fs6.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
|
|
1953
2072
|
_SwaggerDownloader.postSanitizeDownloadedFile(destFile);
|
|
1954
2073
|
console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
|
|
1955
2074
|
}
|
|
@@ -1972,8 +2091,8 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1972
2091
|
};
|
|
1973
2092
|
|
|
1974
2093
|
// src/WebsocketGenerator.ts
|
|
1975
|
-
import
|
|
1976
|
-
import
|
|
2094
|
+
import fs7 from "fs";
|
|
2095
|
+
import path7 from "path";
|
|
1977
2096
|
|
|
1978
2097
|
// src/templates/template-ws-class.ts
|
|
1979
2098
|
var definitionToFunctionName = (type) => {
|
|
@@ -1988,7 +2107,7 @@ var renderSendFunction = (name, definition) => {
|
|
|
1988
2107
|
send({ type: '${name}', ...data })
|
|
1989
2108
|
}`;
|
|
1990
2109
|
};
|
|
1991
|
-
var templateWebsocketClass = (name,
|
|
2110
|
+
var templateWebsocketClass = (name, path9, definitions) => {
|
|
1992
2111
|
const requestDefinitions = Object.keys(definitions).filter((key) => {
|
|
1993
2112
|
const val = definitions[key];
|
|
1994
2113
|
return val["x-type"] == "request";
|
|
@@ -2047,7 +2166,7 @@ const messageSerializer = (data: Record<string, any>) => {
|
|
|
2047
2166
|
export function WebSocketClass(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
2048
2167
|
const sdkAssembly = sdk.assembly()
|
|
2049
2168
|
const baseURL = (args?.coreConfig?.baseURL ?? sdkAssembly.coreConfig.baseURL).replace('http', 'ws')
|
|
2050
|
-
const path = '${
|
|
2169
|
+
const path = '${path9}'
|
|
2051
2170
|
const url = baseURL + path
|
|
2052
2171
|
let ws: WebSocket | null = null
|
|
2053
2172
|
let isDisconnectManually = false
|
|
@@ -2296,9 +2415,9 @@ ${renderUnion(["response", "notification"], definitions)}
|
|
|
2296
2415
|
// src/WebsocketGenerator.ts
|
|
2297
2416
|
var WebsocketGenerator = class {
|
|
2298
2417
|
static srcFolder = () => CliParser.getOutputPath();
|
|
2299
|
-
static outputFolder = () =>
|
|
2418
|
+
static outputFolder = () => path7.join(this.srcFolder(), "generated-websocket");
|
|
2300
2419
|
static schemaContent = () => {
|
|
2301
|
-
const fileContent = JSON.parse(
|
|
2420
|
+
const fileContent = JSON.parse(fs7.readFileSync(CliParser.getWebSocketSchemaPath(), "utf8"));
|
|
2302
2421
|
return fileContent;
|
|
2303
2422
|
};
|
|
2304
2423
|
static prepareDirs = () => {
|
|
@@ -2308,11 +2427,11 @@ var WebsocketGenerator = class {
|
|
|
2308
2427
|
const { name, path: wsPath, definitions } = this.schemaContent();
|
|
2309
2428
|
const templateDefinitions = templateWebsocketDefinitions(definitions);
|
|
2310
2429
|
this.prepareDirs();
|
|
2311
|
-
const filePath =
|
|
2312
|
-
|
|
2430
|
+
const filePath = path7.join(this.outputFolder(), "WebSocketDefinitions.ts");
|
|
2431
|
+
fs7.writeFileSync(filePath, templateDefinitions, "utf8");
|
|
2313
2432
|
const templateClass2 = templateWebsocketClass(name, wsPath, definitions);
|
|
2314
|
-
const filePathClass =
|
|
2315
|
-
|
|
2433
|
+
const filePathClass = path7.join(this.outputFolder(), "WebSocketClass.ts");
|
|
2434
|
+
fs7.writeFileSync(filePathClass, templateClass2, "utf8");
|
|
2316
2435
|
};
|
|
2317
2436
|
};
|
|
2318
2437
|
|
|
@@ -2325,24 +2444,28 @@ var generateSdk = async () => {
|
|
|
2325
2444
|
if (CliParser.isGenerateWebSocket()) {
|
|
2326
2445
|
WebsocketGenerator.main();
|
|
2327
2446
|
}
|
|
2447
|
+
if (!CodegenConfig.shouldProduceIndexFiles()) {
|
|
2448
|
+
return;
|
|
2449
|
+
}
|
|
2328
2450
|
const indexImportsSet = /* @__PURE__ */ new Set();
|
|
2329
2451
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
2330
2452
|
const filenamesSet = /* @__PURE__ */ new Set();
|
|
2331
2453
|
for (const set of arrayOfSets) {
|
|
2332
2454
|
set.indexImports.forEach((value) => {
|
|
2333
|
-
const fileName =
|
|
2455
|
+
const fileName = path8.basename(value);
|
|
2334
2456
|
if (!filenamesSet.has(fileName)) {
|
|
2335
2457
|
indexImportsSet.add(value);
|
|
2336
2458
|
filenamesSet.add(fileName);
|
|
2337
2459
|
}
|
|
2338
2460
|
});
|
|
2339
2461
|
set.queryImports.forEach((value) => {
|
|
2340
|
-
const fileName =
|
|
2462
|
+
const fileName = path8.basename(value);
|
|
2341
2463
|
if (!filenamesSet.has(fileName)) {
|
|
2342
2464
|
queryImportsSet.add(value);
|
|
2343
2465
|
}
|
|
2344
2466
|
});
|
|
2345
2467
|
}
|
|
2468
|
+
const outputPath = CliParser.getOutputPath();
|
|
2346
2469
|
const indexImportsArray = Array.from(indexImportsSet).sort();
|
|
2347
2470
|
const queryImportsArray = Array.from(queryImportsSet).sort();
|
|
2348
2471
|
const filesToImport = indexImportsArray.map((fileToImport) => {
|
|
@@ -2351,8 +2474,8 @@ var generateSdk = async () => {
|
|
|
2351
2474
|
const queryFilesToImport = queryImportsArray.map((fileToImport) => {
|
|
2352
2475
|
return `export * from '${fileToImport.replace("\\", "/")}.js'`;
|
|
2353
2476
|
});
|
|
2354
|
-
ParserUtils.writeAllImportsFile(
|
|
2355
|
-
ParserUtils.writeAllQueryImportsFile(
|
|
2477
|
+
ParserUtils.writeAllImportsFile(outputPath, filesToImport.join("\n"));
|
|
2478
|
+
ParserUtils.writeAllQueryImportsFile(outputPath, queryFilesToImport.join("\n"));
|
|
2356
2479
|
};
|
|
2357
2480
|
yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
2358
2481
|
CliParser.createInstance(yargs2);
|
|
@@ -2368,6 +2491,7 @@ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
|
2368
2491
|
return true;
|
|
2369
2492
|
});
|
|
2370
2493
|
CliParser.createInstance(yargs2);
|
|
2494
|
+
await CodegenConfig.loadConfig(path8.dirname(path8.resolve(CliParser.getConfigPath())));
|
|
2371
2495
|
await generateSdk();
|
|
2372
2496
|
}).option("config", {
|
|
2373
2497
|
description: "Path to the config file with backend service URLs.",
|