@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
|
@@ -21,9 +21,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
21
21
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
22
22
|
mod
|
|
23
23
|
));
|
|
24
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
24
25
|
|
|
25
26
|
// src/cli.ts
|
|
26
|
-
var
|
|
27
|
+
var cli_exports = {};
|
|
28
|
+
module.exports = __toCommonJS(cli_exports);
|
|
29
|
+
var import_path6 = __toESM(require("path"));
|
|
27
30
|
var import_yargs = __toESM(require("yargs"));
|
|
28
31
|
|
|
29
32
|
// src/CliParser.ts
|
|
@@ -87,18 +90,55 @@ var CliParser = class _CliParser {
|
|
|
87
90
|
|
|
88
91
|
// src/CodeGenerator.ts
|
|
89
92
|
var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser"));
|
|
90
|
-
var
|
|
91
|
-
var
|
|
93
|
+
var import_fs5 = __toESM(require("fs"));
|
|
94
|
+
var import_path4 = __toESM(require("path"));
|
|
95
|
+
|
|
96
|
+
// src/CodegenConfig.ts
|
|
97
|
+
var import_fs2 = __toESM(require("fs"));
|
|
98
|
+
var import_path = __toESM(require("path"));
|
|
99
|
+
var import_url = require("url");
|
|
100
|
+
var CodegenConfig = class _CodegenConfig {
|
|
101
|
+
static config = {};
|
|
102
|
+
static async loadConfig(configDir) {
|
|
103
|
+
const configPath = import_path.default.join(configDir, "abcodegen.config.ts");
|
|
104
|
+
if (!import_fs2.default.existsSync(configPath)) {
|
|
105
|
+
_CodegenConfig.config = {};
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const loaded = await import((0, import_url.pathToFileURL)(configPath).href);
|
|
109
|
+
_CodegenConfig.config = loaded.default ?? loaded ?? {};
|
|
110
|
+
}
|
|
111
|
+
static shouldProduceIndexFiles() {
|
|
112
|
+
return _CodegenConfig.config.shouldProduceIndexFiles ?? true;
|
|
113
|
+
}
|
|
114
|
+
static getBasePath() {
|
|
115
|
+
return _CodegenConfig.config.basePath;
|
|
116
|
+
}
|
|
117
|
+
static getOverrideAsAny() {
|
|
118
|
+
return _CodegenConfig.config.overrideAsAny;
|
|
119
|
+
}
|
|
120
|
+
static splitOutputByServiceName() {
|
|
121
|
+
return _CodegenConfig.config.splitOutputByServiceName ?? false;
|
|
122
|
+
}
|
|
123
|
+
/** Reset to defaults — used for testing */
|
|
124
|
+
static reset() {
|
|
125
|
+
_CodegenConfig.config = {};
|
|
126
|
+
}
|
|
127
|
+
/** Set config directly — used for testing */
|
|
128
|
+
static setConfig(config) {
|
|
129
|
+
_CodegenConfig.config = config;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
92
132
|
|
|
93
133
|
// src/ParserUtils.ts
|
|
94
134
|
var import_fast_json_patch = require("fast-json-patch");
|
|
95
|
-
var
|
|
135
|
+
var import_fs4 = __toESM(require("fs"));
|
|
96
136
|
var import_lodash = __toESM(require("lodash"));
|
|
97
|
-
var
|
|
137
|
+
var import_path3 = __toESM(require("path"));
|
|
98
138
|
|
|
99
139
|
// src/helpers/utils.ts
|
|
100
|
-
var
|
|
101
|
-
var
|
|
140
|
+
var import_fs3 = __toESM(require("fs"));
|
|
141
|
+
var import_path2 = __toESM(require("path"));
|
|
102
142
|
var capitalize = (string) => {
|
|
103
143
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
104
144
|
};
|
|
@@ -160,7 +200,8 @@ var getResponseType = ({
|
|
|
160
200
|
defaultType = "unknown"
|
|
161
201
|
}) => {
|
|
162
202
|
const responseClass = responseClasses.length === 1 ? responseClasses?.[0] : "unknown";
|
|
163
|
-
const
|
|
203
|
+
const rawResponseType = responseClass !== "unknown" ? responseClasses?.[0] : defaultType;
|
|
204
|
+
const responseType = rawResponseType === "__dictionary__" ? "Record<string, any>" : rawResponseType;
|
|
164
205
|
return {
|
|
165
206
|
responseType,
|
|
166
207
|
responseTypeInAxiosResponse: `Promise<AxiosResponse<${responseType}>>`,
|
|
@@ -175,10 +216,10 @@ var getImportableVarMap = () => ({
|
|
|
175
216
|
zod: ["z"]
|
|
176
217
|
});
|
|
177
218
|
var makeNewImportVarMap = () => ({
|
|
178
|
-
axios: ["AxiosInstance", "AxiosRequestConfig"]
|
|
179
|
-
"@accelbyte/sdk": ["SDKRequestConfig"]
|
|
219
|
+
axios: ["AxiosInstance", "AxiosRequestConfig"]
|
|
180
220
|
});
|
|
181
|
-
var
|
|
221
|
+
var CLASS_TYPE_ONLY_VARS = /* @__PURE__ */ new Set(["AxiosInstance", "AxiosRequestConfig", "AxiosResponse", "SdkSetConfigParam", "Response"]);
|
|
222
|
+
var generateImports = (body, importStatements, makeNewImportVarMap3, getImportableVarMap3, typeOnlyVars = /* @__PURE__ */ new Set()) => {
|
|
182
223
|
const usedImportVarMap = makeNewImportVarMap3;
|
|
183
224
|
const importableVarMap = getImportableVarMap3;
|
|
184
225
|
for (const [moduleSource, importableVars] of Object.entries(importableVarMap)) {
|
|
@@ -189,22 +230,45 @@ var generateImports = (body, importStatements, makeNewImportVarMap3, getImportab
|
|
|
189
230
|
}
|
|
190
231
|
}
|
|
191
232
|
}
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
233
|
+
const importLines = [];
|
|
234
|
+
for (const moduleSource of Object.keys(usedImportVarMap).sort()) {
|
|
235
|
+
const allVars = usedImportVarMap[moduleSource];
|
|
236
|
+
const valueVars = allVars.filter((v) => !typeOnlyVars.has(v)).sort();
|
|
237
|
+
const typeVars = allVars.filter((v) => typeOnlyVars.has(v)).sort();
|
|
238
|
+
if (valueVars.length > 0) {
|
|
239
|
+
importLines.push(`import { ${valueVars.join(", ")} } from '${moduleSource}'`);
|
|
240
|
+
}
|
|
241
|
+
if (typeVars.length > 0) {
|
|
242
|
+
importLines.push(`import type { ${typeVars.join(", ")} } from '${moduleSource}'`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const generatedImports = importLines.join("\n");
|
|
195
246
|
return `${generatedImports}
|
|
196
247
|
${importStatements.sort().join("\n")}`;
|
|
197
248
|
};
|
|
198
249
|
var templateClass = (className, body, importStatements) => {
|
|
250
|
+
const attributes = {
|
|
251
|
+
definitions: ["private axiosInstance: AxiosInstance", "private namespace: string", "private useSchemaValidation: boolean"],
|
|
252
|
+
assignments: ["this.axiosInstance = axiosInstance", "this.namespace = namespace", "this.useSchemaValidation = useSchemaValidation"]
|
|
253
|
+
};
|
|
254
|
+
let namespaceConstructor = "namespace";
|
|
255
|
+
if (!body.includes(".replace('{namespace}', this.namespace)")) {
|
|
256
|
+
namespaceConstructor = "_namespace";
|
|
257
|
+
attributes.definitions.splice(1, 1);
|
|
258
|
+
attributes.assignments.splice(1, 1);
|
|
259
|
+
}
|
|
199
260
|
return `/**
|
|
200
261
|
* AUTO GENERATED
|
|
201
262
|
*/
|
|
202
|
-
${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
|
|
263
|
+
${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap(), CLASS_TYPE_ONLY_VARS)}
|
|
203
264
|
|
|
204
265
|
export class ${className} {
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
constructor(
|
|
266
|
+
${attributes.definitions.join("\n")}
|
|
267
|
+
|
|
268
|
+
constructor(axiosInstance: AxiosInstance, ${namespaceConstructor}: string, useSchemaValidation = true) {
|
|
269
|
+
${attributes.assignments.join("\n")}
|
|
270
|
+
}
|
|
271
|
+
|
|
208
272
|
${body}
|
|
209
273
|
}
|
|
210
274
|
`;
|
|
@@ -219,6 +283,15 @@ var makeNewImportVarMap2 = () => ({
|
|
|
219
283
|
"@accelbyte/sdk": ["AccelByteSDK", "SdkSetConfigParam", "ApiUtils", "Network"],
|
|
220
284
|
axios: ["AxiosRequestConfig", "AxiosResponse"]
|
|
221
285
|
});
|
|
286
|
+
var API_TYPE_ONLY_VARS = /* @__PURE__ */ new Set([
|
|
287
|
+
"AxiosRequestConfig",
|
|
288
|
+
"AxiosResponse",
|
|
289
|
+
"AxiosDefaults",
|
|
290
|
+
"HeadersDefaults",
|
|
291
|
+
"AccelByteSDK",
|
|
292
|
+
"SdkSetConfigParam",
|
|
293
|
+
"Response"
|
|
294
|
+
]);
|
|
222
295
|
var templateApiClass = (className, body, importStatements, returnMethods) => {
|
|
223
296
|
const returnsMethodsWithDescription = Object.keys(returnMethods).reduce((acc, key) => {
|
|
224
297
|
acc += `
|
|
@@ -230,18 +303,16 @@ ${key},`;
|
|
|
230
303
|
return `/**
|
|
231
304
|
* AUTO GENERATED
|
|
232
305
|
*/
|
|
233
|
-
|
|
234
|
-
// @ts-ignore -> ts-expect-error TS6133
|
|
235
|
-
${generateImports(body, importStatements, makeNewImportVarMap2(), getImportableVarMap2())}
|
|
306
|
+
${generateImports(body, importStatements, makeNewImportVarMap2(), getImportableVarMap2(), API_TYPE_ONLY_VARS)}
|
|
236
307
|
${`import { ${$className} } from './endpoints/${$className}.js'
|
|
237
308
|
`}
|
|
238
309
|
|
|
239
310
|
export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
240
311
|
const sdkAssembly = sdk.assembly()
|
|
241
|
-
|
|
312
|
+
|
|
242
313
|
const namespace = args?.coreConfig?.namespace ?? sdkAssembly.coreConfig.namespace
|
|
243
314
|
const useSchemaValidation = args?.coreConfig?.useSchemaValidation ?? sdkAssembly.coreConfig.useSchemaValidation
|
|
244
|
-
|
|
315
|
+
|
|
245
316
|
let axiosInstance = sdkAssembly.axiosInstance
|
|
246
317
|
const requestConfigOverrides = args?.axiosConfig?.request
|
|
247
318
|
const baseURLOverride = args?.coreConfig?.baseURL
|
|
@@ -259,7 +330,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
259
330
|
if (interceptor.type === 'request') {
|
|
260
331
|
axiosInstance.interceptors.request.use(interceptor.onRequest, interceptor.onError)
|
|
261
332
|
}
|
|
262
|
-
|
|
333
|
+
|
|
263
334
|
if (interceptor.type === 'response') {
|
|
264
335
|
axiosInstance.interceptors.response.use(interceptor.onSuccess, interceptor.onError)
|
|
265
336
|
}
|
|
@@ -270,7 +341,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
270
341
|
}
|
|
271
342
|
|
|
272
343
|
${body}
|
|
273
|
-
|
|
344
|
+
|
|
274
345
|
return {
|
|
275
346
|
${returnsMethodsWithDescription}
|
|
276
347
|
}
|
|
@@ -281,7 +352,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
281
352
|
// src/ParserQueryUtils.ts
|
|
282
353
|
var ParserQueryUtils = class {
|
|
283
354
|
/**
|
|
284
|
-
* convert csv 'aa,bb' into "aa='aa', bb='bb'"
|
|
355
|
+
* convert csv 'aa,bb' into "aa = 'Sdk.Class.aa', bb = 'Sdk.Class.bb'"
|
|
285
356
|
*/
|
|
286
357
|
static createQueryKeys(classNameWithoutApi, csvMethodNames, sdkName) {
|
|
287
358
|
const keys = csvMethodNames.split(",");
|
|
@@ -292,7 +363,7 @@ var ParserQueryUtils = class {
|
|
|
292
363
|
const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete|post|fetch)[_]?/, "");
|
|
293
364
|
if (!processedKeys.has(cleanedKey)) {
|
|
294
365
|
processedKeys.add(cleanedKey);
|
|
295
|
-
acc += `${cleanedKey}
|
|
366
|
+
acc += `${cleanedKey}: '${capitalize(sdkName)}.${classNameWithoutApi}.${cleanedKey}'`;
|
|
296
367
|
if (index < keys.length - 1) {
|
|
297
368
|
acc += ",\n";
|
|
298
369
|
}
|
|
@@ -306,42 +377,51 @@ var ParserQueryUtils = class {
|
|
|
306
377
|
|
|
307
378
|
// src/templates/template-query.ts
|
|
308
379
|
var generateImports2 = (body, className) => {
|
|
309
|
-
const
|
|
310
|
-
import {
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
import { ${
|
|
314
|
-
|
|
315
|
-
|
|
380
|
+
const lines = [];
|
|
381
|
+
lines.push("import type { AccelByteSDK, ApiError, SdkSetConfigParam } from '@accelbyte/sdk'");
|
|
382
|
+
const axiosTypes = ["AxiosError", "AxiosResponse"].filter((t) => body.includes(t));
|
|
383
|
+
if (axiosTypes.length) {
|
|
384
|
+
lines.push(`import type { ${axiosTypes.join(", ")} } from 'axios'`);
|
|
385
|
+
}
|
|
386
|
+
const rqValues = ["useMutation", "useQuery"].filter((t) => body.includes(t));
|
|
387
|
+
if (rqValues.length) {
|
|
388
|
+
lines.push(`import { ${rqValues.join(", ")} } from '@tanstack/react-query'`);
|
|
389
|
+
}
|
|
390
|
+
const rqTypes = ["UseMutationOptions", "UseMutationResult", "UseQueryOptions", "UseQueryResult"].filter((t) => body.includes(t));
|
|
391
|
+
if (rqTypes.length) {
|
|
392
|
+
lines.push(`import type { ${rqTypes.join(", ")} } from '@tanstack/react-query'`);
|
|
393
|
+
}
|
|
394
|
+
lines.push(`import { ${className} } from "../${className}.js"`);
|
|
395
|
+
return lines.join("\n") + "\n";
|
|
316
396
|
};
|
|
317
397
|
var templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports, sdkName) => {
|
|
318
398
|
const classNameWithoutApi = className.replace("Api", "");
|
|
319
399
|
const queryKeys = ParserQueryUtils.createQueryKeys(classNameWithoutApi, returnMethods, sdkName);
|
|
320
400
|
const generatedImports = generateImports2(body, className);
|
|
401
|
+
const queryKeyBlock = `export const Key_${classNameWithoutApi} = {
|
|
402
|
+
${queryKeys}
|
|
403
|
+
} as const`;
|
|
321
404
|
return `/**
|
|
322
405
|
* AUTO GENERATED
|
|
323
406
|
*/
|
|
324
|
-
/* eslint-disable camelcase */
|
|
325
407
|
${generatedImports}
|
|
326
408
|
${filterUsedImports(paramImports, body)}
|
|
327
409
|
|
|
328
|
-
|
|
329
|
-
${queryKeys}
|
|
330
|
-
}
|
|
410
|
+
${queryKeyBlock}
|
|
331
411
|
|
|
332
412
|
${body}
|
|
333
413
|
`;
|
|
334
414
|
};
|
|
335
415
|
function filterUsedImports(importArr, body) {
|
|
336
|
-
return importArr.filter((
|
|
337
|
-
const start =
|
|
338
|
-
const end =
|
|
416
|
+
return importArr.filter((path9) => {
|
|
417
|
+
const start = path9.indexOf("{") + 1;
|
|
418
|
+
const end = path9.indexOf("}");
|
|
339
419
|
if (start > 0 && end > start) {
|
|
340
|
-
const importName =
|
|
420
|
+
const importName = path9.slice(start, end).trim();
|
|
341
421
|
return body.includes(importName);
|
|
342
422
|
}
|
|
343
423
|
return false;
|
|
344
|
-
}).map((
|
|
424
|
+
}).map((path9) => path9).join("\n") + "\n";
|
|
345
425
|
}
|
|
346
426
|
|
|
347
427
|
// src/ParserUtils.ts
|
|
@@ -358,8 +438,8 @@ var REMOVED_KEYWORDS = [
|
|
|
358
438
|
"/{namespace}/"
|
|
359
439
|
];
|
|
360
440
|
var ParserUtils = class _ParserUtils {
|
|
361
|
-
static getVersionSuffixFromPath(
|
|
362
|
-
const version2_3_4_etc =
|
|
441
|
+
static getVersionSuffixFromPath(path9) {
|
|
442
|
+
const version2_3_4_etc = path9.match(/\/v([2-9]|[1-9]\d+)\/+/);
|
|
363
443
|
const methodSuffix = version2_3_4_etc ? `_v${version2_3_4_etc[1]}` : "";
|
|
364
444
|
return methodSuffix;
|
|
365
445
|
}
|
|
@@ -441,13 +521,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
441
521
|
};
|
|
442
522
|
static parseRefImport = (bodyParam) => {
|
|
443
523
|
const $ref = bodyParam?.schema?.$ref || bodyParam?.schema?.items?.$ref;
|
|
444
|
-
if (!$ref) {
|
|
524
|
+
if (!$ref || $ref.endsWith("__dictionary__")) {
|
|
445
525
|
return null;
|
|
446
526
|
}
|
|
447
527
|
const type = _ParserUtils.parseRefType($ref);
|
|
448
528
|
return `import { ${type} } from '../../generated-definitions/${type}.js'`;
|
|
449
529
|
};
|
|
450
530
|
static parseRefType = ($ref) => {
|
|
531
|
+
if ($ref.endsWith("__dictionary__")) return "__dictionary__";
|
|
451
532
|
let ref = $ref.replace(".", "/");
|
|
452
533
|
if (ref[ref.length - 1] === "." || ref[ref.length - 1] === "/") {
|
|
453
534
|
ref = ref.slice(0, -1);
|
|
@@ -554,14 +635,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
554
635
|
* to this
|
|
555
636
|
* `createGenerateByRequestIdByUserId`
|
|
556
637
|
*/
|
|
557
|
-
static generateNaturalLangMethod = ({ servicePrefix, path:
|
|
558
|
-
let path_ =
|
|
638
|
+
static generateNaturalLangMethod = ({ servicePrefix, path: path9, httpMethod, isForm, existingMethods, permissionType }) => {
|
|
639
|
+
let path_ = path9;
|
|
559
640
|
path_ = path_.replace(`/${servicePrefix}/`, "/");
|
|
560
641
|
REMOVED_KEYWORDS.forEach((prefix) => {
|
|
561
642
|
path_ = path_.replace(prefix, "/");
|
|
562
643
|
});
|
|
563
644
|
path_ = path_.substring(1);
|
|
564
|
-
const isPlural = httpMethod === "get" && !(
|
|
645
|
+
const isPlural = httpMethod === "get" && !(path9.slice(-1) === "}");
|
|
565
646
|
if (!isPlural) {
|
|
566
647
|
path_ = _ParserUtils.replaceAll(path_, "ies/", "y/");
|
|
567
648
|
path_ = _ParserUtils.replaceAll(path_, "s/", "/");
|
|
@@ -604,9 +685,9 @@ var ParserUtils = class _ParserUtils {
|
|
|
604
685
|
const genPath = import_lodash.default.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
|
|
605
686
|
let generatedMethod = import_lodash.default.camelCase(mappedMethod(httpMethod, isForm, permissionType) + genPath);
|
|
606
687
|
generatedMethod = _ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
|
|
607
|
-
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(
|
|
608
|
-
generatedMethod = resolveConflicts({ path:
|
|
609
|
-
generatedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(
|
|
688
|
+
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path9);
|
|
689
|
+
generatedMethod = resolveConflicts({ path: path9, generatedMethod, testedGeneratedMethod, existingMethods });
|
|
690
|
+
generatedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path9);
|
|
610
691
|
return generatedMethod;
|
|
611
692
|
};
|
|
612
693
|
static filterBodyParams(parameters) {
|
|
@@ -622,17 +703,17 @@ var ParserUtils = class _ParserUtils {
|
|
|
622
703
|
return parameters.filter((parameter) => parameter.in === "query");
|
|
623
704
|
}
|
|
624
705
|
static mkdirIfNotExist(dirToCreate) {
|
|
625
|
-
if (!
|
|
626
|
-
|
|
706
|
+
if (!import_fs4.default.existsSync(dirToCreate)) {
|
|
707
|
+
import_fs4.default.mkdirSync(dirToCreate, { recursive: true });
|
|
627
708
|
}
|
|
628
709
|
}
|
|
629
710
|
static writeClassFile(distDir, apiName, apiBuffer, imports) {
|
|
630
711
|
const fileContent = templateClass(apiName, apiBuffer, imports);
|
|
631
|
-
|
|
712
|
+
import_fs4.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
632
713
|
}
|
|
633
714
|
static writeAtomFile(distDir, apiName, fileContent) {
|
|
634
715
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
635
|
-
|
|
716
|
+
import_fs4.default.writeFileSync(`${distDir}/${apiName}.atom.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
636
717
|
}
|
|
637
718
|
static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName) {
|
|
638
719
|
if (apiBuffer.length < 1) {
|
|
@@ -641,20 +722,21 @@ var ParserUtils = class _ParserUtils {
|
|
|
641
722
|
const queryFileName = `${apiName.replace("Api", "")}.query`;
|
|
642
723
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
643
724
|
const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName);
|
|
644
|
-
|
|
725
|
+
import_fs4.default.writeFileSync(`${distDir}/${queryFileName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
645
726
|
return queryFileName;
|
|
646
727
|
}
|
|
647
728
|
static writeXVersion(distDir, xversionJson, apiInfo) {
|
|
729
|
+
import_fs4.default.mkdirSync(distDir, { recursive: true });
|
|
648
730
|
if (xversionJson) {
|
|
649
731
|
console.log("x-version:", xversionJson);
|
|
650
|
-
|
|
732
|
+
import_fs4.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
|
|
651
733
|
} else {
|
|
652
734
|
const customVersion = {
|
|
653
735
|
...apiInfo,
|
|
654
736
|
gitHash: apiInfo.version
|
|
655
737
|
};
|
|
656
738
|
console.error(`!!!! Missing x-version for ${distDir} ${customVersion}`);
|
|
657
|
-
|
|
739
|
+
import_fs4.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
|
|
658
740
|
}
|
|
659
741
|
}
|
|
660
742
|
static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethodsDescription) {
|
|
@@ -663,28 +745,28 @@ var ParserUtils = class _ParserUtils {
|
|
|
663
745
|
newImports.push(el.replace("../../generated-definitions", "../generated-definitions"));
|
|
664
746
|
});
|
|
665
747
|
const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethodsDescription);
|
|
666
|
-
|
|
748
|
+
import_fs4.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
667
749
|
}
|
|
668
750
|
static writeApiMainFile(distDir, serviceName, fileContent) {
|
|
669
|
-
|
|
751
|
+
import_fs4.default.writeFileSync(`${distDir}/${serviceName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
670
752
|
}
|
|
671
753
|
static writeSnippetFile(distDir, name, docBuffer) {
|
|
672
754
|
let snippetFileName = _ParserUtils.replaceAll(name, " ", "-").toLowerCase();
|
|
673
755
|
snippetFileName = snippetFileName.replace("justice-", "");
|
|
674
756
|
snippetFileName = "snippet-" + snippetFileName + ".json";
|
|
675
|
-
|
|
757
|
+
import_fs4.default.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
|
|
676
758
|
}
|
|
677
759
|
static writeDefinitionFile(distDir, name, buffer) {
|
|
678
760
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
679
|
-
|
|
761
|
+
import_fs4.default.writeFileSync(import_path3.default.join(distDir, `${name}.ts`), _ParserUtils.prependCopyrightHeader(buffer));
|
|
680
762
|
}
|
|
681
763
|
static writeAllImportsFile(distDir, buffer) {
|
|
682
764
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
683
|
-
|
|
765
|
+
import_fs4.default.writeFileSync(import_path3.default.join(distDir, "all-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
684
766
|
}
|
|
685
767
|
static writeAllQueryImportsFile(distDir, buffer) {
|
|
686
768
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
687
|
-
|
|
769
|
+
import_fs4.default.writeFileSync(import_path3.default.join(distDir, "all-query-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
688
770
|
}
|
|
689
771
|
static toCamelCase(str) {
|
|
690
772
|
return str.split("/").map(function(word, index) {
|
|
@@ -710,15 +792,15 @@ var ParserUtils = class _ParserUtils {
|
|
|
710
792
|
});
|
|
711
793
|
}
|
|
712
794
|
static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
|
|
713
|
-
if (!
|
|
714
|
-
|
|
795
|
+
if (!import_fs4.default.existsSync(swaggerPatchedDir)) {
|
|
796
|
+
import_fs4.default.mkdirSync(swaggerPatchedDir, { recursive: true });
|
|
715
797
|
}
|
|
716
|
-
if (!
|
|
717
|
-
|
|
798
|
+
if (!import_fs4.default.existsSync(possibleSwaggerPatchFilePath)) {
|
|
799
|
+
import_fs4.default.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
|
|
718
800
|
return;
|
|
719
801
|
}
|
|
720
|
-
const swaggerContent = JSON.parse(
|
|
721
|
-
const swaggerPatchFileContent = JSON.parse(
|
|
802
|
+
const swaggerContent = JSON.parse(import_fs4.default.readFileSync(swaggerFilePath, "utf8"));
|
|
803
|
+
const swaggerPatchFileContent = JSON.parse(import_fs4.default.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
|
|
722
804
|
for (const patchEntry of swaggerPatchFileContent) {
|
|
723
805
|
const segments = patchEntry.path.split("/").filter(Boolean);
|
|
724
806
|
let currentNode = swaggerContent;
|
|
@@ -746,7 +828,7 @@ var ParserUtils = class _ParserUtils {
|
|
|
746
828
|
}
|
|
747
829
|
}
|
|
748
830
|
const { newDocument } = (0, import_fast_json_patch.applyPatch)(swaggerContent, swaggerPatchFileContent);
|
|
749
|
-
|
|
831
|
+
import_fs4.default.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
|
|
750
832
|
}
|
|
751
833
|
static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
|
|
752
834
|
const replaced = srcFolder.replace(/\\/g, "/");
|
|
@@ -761,8 +843,8 @@ var ParserUtils = class _ParserUtils {
|
|
|
761
843
|
*/
|
|
762
844
|
${content}`;
|
|
763
845
|
};
|
|
764
|
-
static sortPathParamsByPath = (pathParams,
|
|
765
|
-
const params =
|
|
846
|
+
static sortPathParamsByPath = (pathParams, path9) => {
|
|
847
|
+
const params = path9.match(/{\w*}/g) || [];
|
|
766
848
|
const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
|
|
767
849
|
return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
|
|
768
850
|
};
|
|
@@ -786,30 +868,40 @@ var mappedMethod = (httpMethod, isForm, permissionType) => {
|
|
|
786
868
|
return "delete";
|
|
787
869
|
}
|
|
788
870
|
};
|
|
789
|
-
var resolveConflicts = ({ path:
|
|
871
|
+
var resolveConflicts = ({ path: path9, generatedMethod, testedGeneratedMethod, existingMethods }) => {
|
|
790
872
|
let _testedGenMethod = testedGeneratedMethod;
|
|
791
873
|
try {
|
|
792
|
-
testConflict(
|
|
874
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
793
875
|
} catch (e) {
|
|
794
|
-
if (
|
|
876
|
+
if (path9.indexOf("/namespaces/") >= 0) {
|
|
795
877
|
generatedMethod += "_ByNS";
|
|
796
878
|
_testedGenMethod += "_ByNS";
|
|
797
879
|
}
|
|
798
880
|
}
|
|
799
881
|
try {
|
|
800
|
-
testConflict(
|
|
882
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
801
883
|
} catch (e) {
|
|
802
|
-
if (
|
|
884
|
+
if (path9.indexOf("/admin/") >= 0) {
|
|
803
885
|
generatedMethod += "_admin";
|
|
804
886
|
_testedGenMethod += "_admin";
|
|
805
887
|
}
|
|
806
888
|
}
|
|
807
|
-
|
|
889
|
+
try {
|
|
890
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
891
|
+
} catch (e) {
|
|
892
|
+
const parentSegmentMatch = path9.match(/\/([^/{}]+)\/{[^}]+}\/[^/]*$/);
|
|
893
|
+
if (parentSegmentMatch) {
|
|
894
|
+
const suffix = "_By" + import_lodash.default.upperFirst(import_lodash.default.camelCase(parentSegmentMatch[1]));
|
|
895
|
+
generatedMethod += suffix;
|
|
896
|
+
_testedGenMethod += suffix;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
808
900
|
return generatedMethod;
|
|
809
901
|
};
|
|
810
|
-
var testConflict = (
|
|
902
|
+
var testConflict = (path9, generatedMethod, existingMethods) => {
|
|
811
903
|
if (existingMethods[generatedMethod]) {
|
|
812
|
-
const conflictingMethod = { path:
|
|
904
|
+
const conflictingMethod = { path: path9, generatedMethod };
|
|
813
905
|
throw Error(
|
|
814
906
|
`Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
|
|
815
907
|
existingMethods: ${JSON.stringify(existingMethods, null, 2)}`
|
|
@@ -926,7 +1018,7 @@ var OpenApiSpec = import_zod2.z.object({
|
|
|
926
1018
|
var templateApiMethod = ({
|
|
927
1019
|
classMethod,
|
|
928
1020
|
httpMethod,
|
|
929
|
-
path:
|
|
1021
|
+
path: path9,
|
|
930
1022
|
pathParams,
|
|
931
1023
|
bodyParams,
|
|
932
1024
|
responseClasses,
|
|
@@ -935,12 +1027,12 @@ var templateApiMethod = ({
|
|
|
935
1027
|
methodParamsNoTypes,
|
|
936
1028
|
xSecurity
|
|
937
1029
|
}) => {
|
|
938
|
-
let newPath = `'${
|
|
1030
|
+
let newPath = `'${path9}'`;
|
|
939
1031
|
let snippetMethod = "";
|
|
940
1032
|
for (const pathParam of pathParams) {
|
|
941
1033
|
const type = ParserUtils.parseType(pathParam);
|
|
942
1034
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
943
|
-
if (
|
|
1035
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
944
1036
|
if (type === "string") {
|
|
945
1037
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
946
1038
|
} else {
|
|
@@ -948,9 +1040,9 @@ var templateApiMethod = ({
|
|
|
948
1040
|
}
|
|
949
1041
|
}
|
|
950
1042
|
}
|
|
951
|
-
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${
|
|
1043
|
+
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path9}'`, "--header 'accept: application/json'"];
|
|
952
1044
|
const snippetApiArgs = [];
|
|
953
|
-
if (xSecurity !== void 0 ||
|
|
1045
|
+
if (xSecurity !== void 0 || path9.includes("/admin")) {
|
|
954
1046
|
snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
|
|
955
1047
|
snippetApiArgs.push("{ axiosConfig: { request: { headers: { Authorization: 'Bearer {access_token}' } } } }".trim());
|
|
956
1048
|
}
|
|
@@ -988,7 +1080,7 @@ var templateMethod = ({
|
|
|
988
1080
|
classMethod,
|
|
989
1081
|
description,
|
|
990
1082
|
httpMethod,
|
|
991
|
-
path:
|
|
1083
|
+
path: path9,
|
|
992
1084
|
pathParams,
|
|
993
1085
|
bodyParams,
|
|
994
1086
|
queryParams,
|
|
@@ -998,9 +1090,9 @@ var templateMethod = ({
|
|
|
998
1090
|
}) => {
|
|
999
1091
|
let methodParams = "";
|
|
1000
1092
|
let methodParamsNoTypes = "";
|
|
1001
|
-
let newPath = `'${
|
|
1093
|
+
let newPath = `'${path9}'`;
|
|
1002
1094
|
let importStatements = [];
|
|
1003
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1095
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
1004
1096
|
for (const pathParam of sortedPathParams) {
|
|
1005
1097
|
const type = ParserUtils.parseType(pathParam);
|
|
1006
1098
|
if (pathParam.name !== "namespace") {
|
|
@@ -1008,7 +1100,7 @@ var templateMethod = ({
|
|
|
1008
1100
|
methodParamsNoTypes += pathParam.name + ", ";
|
|
1009
1101
|
}
|
|
1010
1102
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1011
|
-
if (
|
|
1103
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
1012
1104
|
if (type === "string") {
|
|
1013
1105
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1014
1106
|
} else {
|
|
@@ -1019,6 +1111,7 @@ var templateMethod = ({
|
|
|
1019
1111
|
let dataType = null;
|
|
1020
1112
|
if (httpMethod !== "get") {
|
|
1021
1113
|
dataType = ParserUtils.parseBodyParamsType(bodyParams);
|
|
1114
|
+
if (dataType === "__dictionary__") dataType = "Record<string, any>";
|
|
1022
1115
|
importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
|
|
1023
1116
|
methodParams += dataType ? `data: ${dataType},` : "";
|
|
1024
1117
|
methodParamsNoTypes += dataType ? `data,` : "";
|
|
@@ -1042,7 +1135,7 @@ var templateMethod = ({
|
|
|
1042
1135
|
}
|
|
1043
1136
|
const isFileUpload = methodParams.indexOf("data: {file") > -1;
|
|
1044
1137
|
const { responseType, responseTypeInResponse } = getResponseType({ responseClasses });
|
|
1045
|
-
const resolvedResponseClassValidated = responseType !== "unknown" ? `${responseType}` : "z.unknown()";
|
|
1138
|
+
const resolvedResponseClassValidated = responseClasses.length === 1 && responseClasses[0] === "__dictionary__" ? "z.record(z.string(), z.any())" : responseType !== "unknown" ? `${responseType}` : "z.unknown()";
|
|
1046
1139
|
methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
|
|
1047
1140
|
methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
|
|
1048
1141
|
const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
|
|
@@ -1073,7 +1166,7 @@ var POST_FETCH_INCLUDES_PATH = ["/table-query/"];
|
|
|
1073
1166
|
var templateQueryMethod = ({
|
|
1074
1167
|
classMethod,
|
|
1075
1168
|
httpMethod,
|
|
1076
|
-
path:
|
|
1169
|
+
path: path9,
|
|
1077
1170
|
pathParams,
|
|
1078
1171
|
responseClasses,
|
|
1079
1172
|
methodParams,
|
|
@@ -1081,14 +1174,14 @@ var templateQueryMethod = ({
|
|
|
1081
1174
|
description,
|
|
1082
1175
|
deprecated
|
|
1083
1176
|
}) => {
|
|
1084
|
-
const isPostFetch = httpMethod === "post" && (POST_FETCH_INCLUDES_PATH.some((p) =>
|
|
1177
|
+
const isPostFetch = httpMethod === "post" && (POST_FETCH_INCLUDES_PATH.some((p) => path9.includes(p)) || path9.endsWith("/list"));
|
|
1085
1178
|
const isFetch = classMethod.startsWith("fetch");
|
|
1086
1179
|
const isGet = httpMethod === "get" || isPostFetch || isFetch;
|
|
1087
1180
|
const queryMethod = isGet ? "useQuery" : "useMutation";
|
|
1088
1181
|
let mParams = "";
|
|
1089
1182
|
let mParamsNoTypes = "";
|
|
1090
|
-
let newPath = `'${
|
|
1091
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1183
|
+
let newPath = `'${path9}'`;
|
|
1184
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
1092
1185
|
for (const pathParam of sortedPathParams) {
|
|
1093
1186
|
const type = ParserUtils.parseType(pathParam);
|
|
1094
1187
|
if (pathParam.name !== "namespace") {
|
|
@@ -1096,7 +1189,7 @@ var templateQueryMethod = ({
|
|
|
1096
1189
|
mParamsNoTypes += pathParam.name + ", ";
|
|
1097
1190
|
}
|
|
1098
1191
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1099
|
-
if (
|
|
1192
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
1100
1193
|
if (type === "string") {
|
|
1101
1194
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1102
1195
|
} else {
|
|
@@ -1131,7 +1224,7 @@ export const ${_methodName} = (
|
|
|
1131
1224
|
const response =
|
|
1132
1225
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1133
1226
|
${classMethod}(${_methodParamsImpl}))
|
|
1134
|
-
callback
|
|
1227
|
+
callback?.(response)
|
|
1135
1228
|
return response.data
|
|
1136
1229
|
}
|
|
1137
1230
|
|
|
@@ -1156,7 +1249,7 @@ export const ${_methodName} = (
|
|
|
1156
1249
|
const response =
|
|
1157
1250
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1158
1251
|
${classMethod}(${_methodParamsImpl}))
|
|
1159
|
-
callback
|
|
1252
|
+
callback?.(response.data)
|
|
1160
1253
|
return response.data
|
|
1161
1254
|
}
|
|
1162
1255
|
|
|
@@ -1335,11 +1428,11 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1335
1428
|
admin: {},
|
|
1336
1429
|
public: {}
|
|
1337
1430
|
};
|
|
1338
|
-
for (const [
|
|
1339
|
-
if (
|
|
1431
|
+
for (const [path9, operation] of sortedPathsByLength) {
|
|
1432
|
+
if (path9.indexOf("/healthz") >= 0) {
|
|
1340
1433
|
continue;
|
|
1341
1434
|
}
|
|
1342
|
-
const isAdminEndpoint =
|
|
1435
|
+
const isAdminEndpoint = path9.indexOf("/admin/") > -1;
|
|
1343
1436
|
const picked = isAdminEndpoint ? result.admin : result.public;
|
|
1344
1437
|
const {
|
|
1345
1438
|
arrayDefinitions,
|
|
@@ -1357,25 +1450,27 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1357
1450
|
const httpMethods = Object.keys(operation);
|
|
1358
1451
|
for (const httpMethod of httpMethods) {
|
|
1359
1452
|
const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
|
|
1360
|
-
console.error(JSON.stringify({ path:
|
|
1453
|
+
console.error(JSON.stringify({ path: path9, httpMethod }, null, 2));
|
|
1361
1454
|
throw error;
|
|
1362
1455
|
});
|
|
1363
1456
|
if (!endpoint.tags) continue;
|
|
1364
1457
|
const [tag] = endpoint.tags;
|
|
1365
|
-
const
|
|
1458
|
+
const configBasePath = CodegenConfig.getBasePath();
|
|
1459
|
+
const effectiveBasePath = configBasePath !== void 0 ? configBasePath : api.basePath ?? "";
|
|
1460
|
+
const pathWithBase = `${effectiveBasePath}${path9}`;
|
|
1366
1461
|
const permissionType = getPermissionType(getPermission(endpoint));
|
|
1367
1462
|
tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
|
|
1368
1463
|
const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
|
|
1369
1464
|
const classMethod = ParserUtils.generateNaturalLangMethod({
|
|
1370
1465
|
servicePrefix,
|
|
1371
|
-
path:
|
|
1466
|
+
path: path9,
|
|
1372
1467
|
httpMethod,
|
|
1373
1468
|
isForm,
|
|
1374
1469
|
existingMethods: tagToClassMethodsMapByType[tag],
|
|
1375
1470
|
permissionType
|
|
1376
1471
|
});
|
|
1377
|
-
tagToClassMethodsMapByType[tag][classMethod] = `${
|
|
1378
|
-
generatedMethods[`${
|
|
1472
|
+
tagToClassMethodsMapByType[tag][classMethod] = `${path9} ${httpMethod}`;
|
|
1473
|
+
generatedMethods[`${path9} ${httpMethod}`] = `${classMethod}`;
|
|
1379
1474
|
if (!snippetMap[pathWithBase]) {
|
|
1380
1475
|
snippetMap[pathWithBase] = {};
|
|
1381
1476
|
}
|
|
@@ -1384,7 +1479,7 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1384
1479
|
const responseClass = responseClasses.length > 1 ? null : responseClasses?.[0];
|
|
1385
1480
|
const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
|
|
1386
1481
|
tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
|
|
1387
|
-
if (responseClass) {
|
|
1482
|
+
if (responseClass && responseClass !== "__dictionary__") {
|
|
1388
1483
|
tagToClassImportsRecord[className][responseClass] = `import { ${responseClass} } from '../../generated-definitions/${responseClass}.js'`;
|
|
1389
1484
|
}
|
|
1390
1485
|
if (responseClass && responseClass.endsWith("Array")) {
|
|
@@ -1530,6 +1625,20 @@ var TemplateZod = class {
|
|
|
1530
1625
|
// --
|
|
1531
1626
|
render = (fileName, definition, duplicates) => {
|
|
1532
1627
|
this.duplicates = duplicates;
|
|
1628
|
+
const overrideAsAny = CodegenConfig.getOverrideAsAny();
|
|
1629
|
+
const override = overrideAsAny?.[fileName];
|
|
1630
|
+
if (override !== void 0) {
|
|
1631
|
+
const shouldOverride = typeof override === "function" ? override(definition) : override;
|
|
1632
|
+
if (shouldOverride) {
|
|
1633
|
+
const template2 = `import { z } from 'zod'
|
|
1634
|
+
|
|
1635
|
+
export const ${fileName} = z.any()
|
|
1636
|
+
|
|
1637
|
+
export interface ${fileName} extends z.TypeOf<typeof ${fileName}> {}
|
|
1638
|
+
`;
|
|
1639
|
+
return { buffer: template2, duplicateFound: false };
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1533
1642
|
const content = this.parseToZodSchema(definition, definition.required || []);
|
|
1534
1643
|
const containsRecursiveType = this.importClasses.has(fileName);
|
|
1535
1644
|
if (containsRecursiveType) {
|
|
@@ -1618,7 +1727,14 @@ ${exportedTypeString}
|
|
|
1618
1727
|
};
|
|
1619
1728
|
} else if (type) {
|
|
1620
1729
|
if (type === "object" && definition.additionalProperties) {
|
|
1621
|
-
const
|
|
1730
|
+
const additionalProps = definition.additionalProperties;
|
|
1731
|
+
if (Object.keys(additionalProps).length === 0) {
|
|
1732
|
+
return {
|
|
1733
|
+
schemaString: `${schemaAttribute} z.record(z.any())${schemaRequired}`,
|
|
1734
|
+
typeString: `${typeAttribute} Record<string, any>${typeNullishability}`
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
const zodAttribute = this.parseToZodAttribute("", additionalProps, [""]);
|
|
1622
1738
|
return {
|
|
1623
1739
|
schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
|
|
1624
1740
|
typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
|
|
@@ -1804,8 +1920,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1804
1920
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
1805
1921
|
const apiInfo = { ...api.info, "x-version": api["x-version"]?.version };
|
|
1806
1922
|
console.log("----------\nGenerating API:", { title: apiInfo.title, version: apiInfo.version });
|
|
1923
|
+
const isSplitByService = CodegenConfig.splitOutputByServiceName();
|
|
1924
|
+
const srcFolder = isSplitByService ? import_path4.default.join(CliParser.getOutputPath(), serviceName) : CliParser.getOutputPath();
|
|
1925
|
+
const targetSrcFolder = `${CliParser.getOutputPath()}/`;
|
|
1807
1926
|
if (!CliParser.isGenerateSnippetOnly()) {
|
|
1808
|
-
ParserUtils.writeXVersion(
|
|
1927
|
+
ParserUtils.writeXVersion(srcFolder, api["x-version"], api.info);
|
|
1809
1928
|
}
|
|
1810
1929
|
const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
|
|
1811
1930
|
if (CliParser.getSnippetOutputPath()) {
|
|
@@ -1831,11 +1950,10 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1831
1950
|
console.log("\nSuccessfully generate SDK snippets only\n----------\n\n");
|
|
1832
1951
|
return;
|
|
1833
1952
|
}
|
|
1834
|
-
const DIST_DIR = (isAdmin) =>
|
|
1835
|
-
const DIST_DIR_ENDPOINTS = (isAdmin) =>
|
|
1836
|
-
const DIST_DIR_QUERIES = (isAdmin) =>
|
|
1837
|
-
const DIST_DEFINITION_DIR =
|
|
1838
|
-
const targetSrcFolder = `${_CodeGenerator.srcFolder()}/`;
|
|
1953
|
+
const DIST_DIR = (isAdmin) => import_path4.default.join(srcFolder, isAdmin ? "generated-admin" : "generated-public");
|
|
1954
|
+
const DIST_DIR_ENDPOINTS = (isAdmin) => import_path4.default.join(DIST_DIR(isAdmin), "endpoints");
|
|
1955
|
+
const DIST_DIR_QUERIES = (isAdmin) => import_path4.default.join(DIST_DIR(isAdmin), "queries");
|
|
1956
|
+
const DIST_DEFINITION_DIR = import_path4.default.join(srcFolder, "generated-definitions");
|
|
1839
1957
|
_CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
|
|
1840
1958
|
const mainApiList = [];
|
|
1841
1959
|
const generatedDefinitions = [];
|
|
@@ -1876,30 +1994,31 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1876
1994
|
ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionDescription[tag]);
|
|
1877
1995
|
apiList.push(apiGenName);
|
|
1878
1996
|
indexImportsSet.add(
|
|
1879
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1997
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder)
|
|
1880
1998
|
);
|
|
1881
1999
|
indexImportsSet.add(
|
|
1882
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2000
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder)
|
|
1883
2001
|
);
|
|
1884
2002
|
queryFileName && queryImportsSet.add(
|
|
1885
2003
|
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1886
|
-
|
|
2004
|
+
import_path4.default.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`),
|
|
1887
2005
|
targetSrcFolder
|
|
1888
2006
|
)
|
|
1889
2007
|
);
|
|
1890
2008
|
}
|
|
1891
2009
|
mainApiList.push(...apiList);
|
|
1892
|
-
|
|
1893
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1894
|
-
|
|
2010
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
2011
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(srcFolder, serviceNameTitle), targetSrcFolder));
|
|
2012
|
+
}
|
|
1895
2013
|
};
|
|
1896
2014
|
const writeDefinitions = (api2) => {
|
|
1897
2015
|
const duplicates = /* @__PURE__ */ new Map();
|
|
1898
2016
|
const definitions = api2?.components?.schemas || api2.definitions;
|
|
1899
2017
|
for (const ref in definitions) {
|
|
2018
|
+
if (ref === "__dictionary__") continue;
|
|
1900
2019
|
const definition = definitions[ref];
|
|
1901
2020
|
const fileName = ParserUtils.parseRefType(ref);
|
|
1902
|
-
const fileExist =
|
|
2021
|
+
const fileExist = import_fs5.default.existsSync(import_path4.default.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
|
|
1903
2022
|
if (fileExist) {
|
|
1904
2023
|
const duplicateName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
|
|
1905
2024
|
duplicates.set(ref, duplicateName);
|
|
@@ -1907,13 +2026,13 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1907
2026
|
const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
|
|
1908
2027
|
generatedDefinitions.push(fileName);
|
|
1909
2028
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
|
|
1910
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2029
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
|
|
1911
2030
|
}
|
|
1912
2031
|
for (const arrayClass of arrayDefinitions) {
|
|
1913
2032
|
const buffer = new TemplateZodArray().render(arrayClass);
|
|
1914
2033
|
generatedDefinitions.push(arrayClass);
|
|
1915
2034
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
|
|
1916
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2035
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
|
|
1917
2036
|
}
|
|
1918
2037
|
};
|
|
1919
2038
|
writeApiEndpointFiles(isAdmin);
|
|
@@ -1921,9 +2040,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1921
2040
|
};
|
|
1922
2041
|
generatePublicOrAdmin(true);
|
|
1923
2042
|
generatePublicOrAdmin(false);
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
2043
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
2044
|
+
const isGenerateWebSocket = CliParser.isGenerateWebSocket();
|
|
2045
|
+
const apiIndexBuff = templateApiIndex(serviceNameTitle, mainApiList, isGenerateWebSocket);
|
|
2046
|
+
ParserUtils.writeApiMainFile(srcFolder, serviceNameTitle, apiIndexBuff);
|
|
2047
|
+
}
|
|
1927
2048
|
console.log("\nCOMPLETED\n----------\n\n");
|
|
1928
2049
|
return { indexImports: indexImportsSet, queryImports: queryImportsSet };
|
|
1929
2050
|
};
|
|
@@ -1931,29 +2052,30 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1931
2052
|
};
|
|
1932
2053
|
|
|
1933
2054
|
// src/SwaggerDownloader.ts
|
|
2055
|
+
var fs6 = __toESM(require("fs"));
|
|
1934
2056
|
var https = __toESM(require("https"));
|
|
1935
|
-
var
|
|
1936
|
-
var path5 = __toESM(require("path"));
|
|
2057
|
+
var path6 = __toESM(require("path"));
|
|
1937
2058
|
var SwaggerDownloader = class _SwaggerDownloader {
|
|
1938
2059
|
static getDestFile = (targetFileName) => {
|
|
1939
2060
|
const destPath = CliParser.getResolvedSwaggersOutputPath();
|
|
1940
|
-
const destFile =
|
|
1941
|
-
if (
|
|
1942
|
-
if (!
|
|
1943
|
-
|
|
2061
|
+
const destFile = path6.join(destPath, targetFileName);
|
|
2062
|
+
if (fs6.existsSync(destFile)) return destFile;
|
|
2063
|
+
if (!fs6.existsSync(destPath)) fs6.mkdirSync(destPath);
|
|
2064
|
+
fs6.writeFileSync(destFile, "");
|
|
1944
2065
|
return destFile;
|
|
1945
2066
|
};
|
|
1946
2067
|
// session-api.json contains illegal URL encoded character that breaks the codegen
|
|
1947
2068
|
// e.g. "$ref": "#/definitions/map%5Bstring%5Dinterface%20%7B%7D"
|
|
1948
2069
|
static postSanitizeDownloadedFile = (filePath) => {
|
|
1949
2070
|
const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
|
|
1950
|
-
|
|
2071
|
+
fs6.readFile(filePath, "utf8", (err, data) => {
|
|
1951
2072
|
if (err) throw err;
|
|
1952
2073
|
let result = data;
|
|
2074
|
+
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__");
|
|
1953
2075
|
searchStr.forEach((s) => {
|
|
1954
2076
|
result = result.replace(new RegExp(s, "g"), " ");
|
|
1955
2077
|
});
|
|
1956
|
-
|
|
2078
|
+
fs6.writeFile(filePath, result, "utf8", (err2) => {
|
|
1957
2079
|
if (err2) throw err2;
|
|
1958
2080
|
console.log("File updated successfully.");
|
|
1959
2081
|
});
|
|
@@ -1971,7 +2093,7 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1971
2093
|
if (response.statusCode !== 200) {
|
|
1972
2094
|
console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
|
|
1973
2095
|
} else {
|
|
1974
|
-
|
|
2096
|
+
fs6.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
|
|
1975
2097
|
_SwaggerDownloader.postSanitizeDownloadedFile(destFile);
|
|
1976
2098
|
console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
|
|
1977
2099
|
}
|
|
@@ -1994,8 +2116,8 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1994
2116
|
};
|
|
1995
2117
|
|
|
1996
2118
|
// src/WebsocketGenerator.ts
|
|
1997
|
-
var
|
|
1998
|
-
var
|
|
2119
|
+
var import_fs6 = __toESM(require("fs"));
|
|
2120
|
+
var import_path5 = __toESM(require("path"));
|
|
1999
2121
|
|
|
2000
2122
|
// src/templates/template-ws-class.ts
|
|
2001
2123
|
var definitionToFunctionName = (type) => {
|
|
@@ -2010,7 +2132,7 @@ var renderSendFunction = (name, definition) => {
|
|
|
2010
2132
|
send({ type: '${name}', ...data })
|
|
2011
2133
|
}`;
|
|
2012
2134
|
};
|
|
2013
|
-
var templateWebsocketClass = (name,
|
|
2135
|
+
var templateWebsocketClass = (name, path9, definitions) => {
|
|
2014
2136
|
const requestDefinitions = Object.keys(definitions).filter((key) => {
|
|
2015
2137
|
const val = definitions[key];
|
|
2016
2138
|
return val["x-type"] == "request";
|
|
@@ -2069,7 +2191,7 @@ const messageSerializer = (data: Record<string, any>) => {
|
|
|
2069
2191
|
export function WebSocketClass(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
2070
2192
|
const sdkAssembly = sdk.assembly()
|
|
2071
2193
|
const baseURL = (args?.coreConfig?.baseURL ?? sdkAssembly.coreConfig.baseURL).replace('http', 'ws')
|
|
2072
|
-
const path = '${
|
|
2194
|
+
const path = '${path9}'
|
|
2073
2195
|
const url = baseURL + path
|
|
2074
2196
|
let ws: WebSocket | null = null
|
|
2075
2197
|
let isDisconnectManually = false
|
|
@@ -2318,9 +2440,9 @@ ${renderUnion(["response", "notification"], definitions)}
|
|
|
2318
2440
|
// src/WebsocketGenerator.ts
|
|
2319
2441
|
var WebsocketGenerator = class {
|
|
2320
2442
|
static srcFolder = () => CliParser.getOutputPath();
|
|
2321
|
-
static outputFolder = () =>
|
|
2443
|
+
static outputFolder = () => import_path5.default.join(this.srcFolder(), "generated-websocket");
|
|
2322
2444
|
static schemaContent = () => {
|
|
2323
|
-
const fileContent = JSON.parse(
|
|
2445
|
+
const fileContent = JSON.parse(import_fs6.default.readFileSync(CliParser.getWebSocketSchemaPath(), "utf8"));
|
|
2324
2446
|
return fileContent;
|
|
2325
2447
|
};
|
|
2326
2448
|
static prepareDirs = () => {
|
|
@@ -2330,11 +2452,11 @@ var WebsocketGenerator = class {
|
|
|
2330
2452
|
const { name, path: wsPath, definitions } = this.schemaContent();
|
|
2331
2453
|
const templateDefinitions = templateWebsocketDefinitions(definitions);
|
|
2332
2454
|
this.prepareDirs();
|
|
2333
|
-
const filePath =
|
|
2334
|
-
|
|
2455
|
+
const filePath = import_path5.default.join(this.outputFolder(), "WebSocketDefinitions.ts");
|
|
2456
|
+
import_fs6.default.writeFileSync(filePath, templateDefinitions, "utf8");
|
|
2335
2457
|
const templateClass2 = templateWebsocketClass(name, wsPath, definitions);
|
|
2336
|
-
const filePathClass =
|
|
2337
|
-
|
|
2458
|
+
const filePathClass = import_path5.default.join(this.outputFolder(), "WebSocketClass.ts");
|
|
2459
|
+
import_fs6.default.writeFileSync(filePathClass, templateClass2, "utf8");
|
|
2338
2460
|
};
|
|
2339
2461
|
};
|
|
2340
2462
|
|
|
@@ -2347,24 +2469,28 @@ var generateSdk = async () => {
|
|
|
2347
2469
|
if (CliParser.isGenerateWebSocket()) {
|
|
2348
2470
|
WebsocketGenerator.main();
|
|
2349
2471
|
}
|
|
2472
|
+
if (!CodegenConfig.shouldProduceIndexFiles()) {
|
|
2473
|
+
return;
|
|
2474
|
+
}
|
|
2350
2475
|
const indexImportsSet = /* @__PURE__ */ new Set();
|
|
2351
2476
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
2352
2477
|
const filenamesSet = /* @__PURE__ */ new Set();
|
|
2353
2478
|
for (const set of arrayOfSets) {
|
|
2354
2479
|
set.indexImports.forEach((value) => {
|
|
2355
|
-
const fileName =
|
|
2480
|
+
const fileName = import_path6.default.basename(value);
|
|
2356
2481
|
if (!filenamesSet.has(fileName)) {
|
|
2357
2482
|
indexImportsSet.add(value);
|
|
2358
2483
|
filenamesSet.add(fileName);
|
|
2359
2484
|
}
|
|
2360
2485
|
});
|
|
2361
2486
|
set.queryImports.forEach((value) => {
|
|
2362
|
-
const fileName =
|
|
2487
|
+
const fileName = import_path6.default.basename(value);
|
|
2363
2488
|
if (!filenamesSet.has(fileName)) {
|
|
2364
2489
|
queryImportsSet.add(value);
|
|
2365
2490
|
}
|
|
2366
2491
|
});
|
|
2367
2492
|
}
|
|
2493
|
+
const outputPath = CliParser.getOutputPath();
|
|
2368
2494
|
const indexImportsArray = Array.from(indexImportsSet).sort();
|
|
2369
2495
|
const queryImportsArray = Array.from(queryImportsSet).sort();
|
|
2370
2496
|
const filesToImport = indexImportsArray.map((fileToImport) => {
|
|
@@ -2373,8 +2499,8 @@ var generateSdk = async () => {
|
|
|
2373
2499
|
const queryFilesToImport = queryImportsArray.map((fileToImport) => {
|
|
2374
2500
|
return `export * from '${fileToImport.replace("\\", "/")}.js'`;
|
|
2375
2501
|
});
|
|
2376
|
-
ParserUtils.writeAllImportsFile(
|
|
2377
|
-
ParserUtils.writeAllQueryImportsFile(
|
|
2502
|
+
ParserUtils.writeAllImportsFile(outputPath, filesToImport.join("\n"));
|
|
2503
|
+
ParserUtils.writeAllQueryImportsFile(outputPath, queryFilesToImport.join("\n"));
|
|
2378
2504
|
};
|
|
2379
2505
|
import_yargs.default.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
2380
2506
|
CliParser.createInstance(yargs2);
|
|
@@ -2390,6 +2516,7 @@ import_yargs.default.command("download-swaggers", "Download swaggers JSON files"
|
|
|
2390
2516
|
return true;
|
|
2391
2517
|
});
|
|
2392
2518
|
CliParser.createInstance(yargs2);
|
|
2519
|
+
await CodegenConfig.loadConfig(import_path6.default.dirname(import_path6.default.resolve(CliParser.getConfigPath())));
|
|
2393
2520
|
await generateSdk();
|
|
2394
2521
|
}).option("config", {
|
|
2395
2522
|
description: "Path to the config file with backend service URLs.",
|