@accelbyte/codegen 4.1.5 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +112 -15
- package/dist/accelbyte-codegen.d.mts +31 -0
- package/dist/accelbyte-codegen.d.ts +31 -0
- package/dist/accelbyte-codegen.js +288 -157
- package/dist/accelbyte-codegen.js.map +1 -1
- package/dist/accelbyte-codegen.mjs +285 -157
- package/dist/accelbyte-codegen.mjs.map +1 -1
- package/package.json +6 -5
|
@@ -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.unstable_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,43 +303,45 @@ ${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
|
|
248
|
-
const interceptorsOverride = args?.axiosConfig?.interceptors
|
|
319
|
+
const interceptorsOverride = args?.axiosConfig?.interceptors
|
|
249
320
|
|
|
250
|
-
if (requestConfigOverrides || baseURLOverride || interceptorsOverride
|
|
321
|
+
if (requestConfigOverrides || baseURLOverride || interceptorsOverride) {
|
|
251
322
|
const requestConfig = ApiUtils.mergeAxiosConfigs(sdkAssembly.axiosInstance.defaults as AxiosRequestConfig, {
|
|
252
323
|
...(baseURLOverride ? { baseURL: baseURLOverride } : {}),
|
|
253
324
|
...requestConfigOverrides
|
|
254
325
|
})
|
|
255
326
|
axiosInstance = Network.create(requestConfig)
|
|
256
327
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
328
|
+
if (interceptorsOverride) {
|
|
329
|
+
for (const interceptor of interceptorsOverride) {
|
|
330
|
+
if (interceptor.type === 'request') {
|
|
331
|
+
axiosInstance.interceptors.request.use(interceptor.onRequest, interceptor.onError)
|
|
332
|
+
}
|
|
261
333
|
|
|
262
|
-
|
|
263
|
-
|
|
334
|
+
if (interceptor.type === 'response') {
|
|
335
|
+
axiosInstance.interceptors.response.use(interceptor.onSuccess, interceptor.onError)
|
|
336
|
+
}
|
|
264
337
|
}
|
|
338
|
+
} else {
|
|
339
|
+
axiosInstance.interceptors = sdkAssembly.axiosInstance.interceptors
|
|
265
340
|
}
|
|
266
341
|
}
|
|
267
342
|
|
|
268
343
|
${body}
|
|
269
|
-
|
|
344
|
+
|
|
270
345
|
return {
|
|
271
346
|
${returnsMethodsWithDescription}
|
|
272
347
|
}
|
|
@@ -277,7 +352,7 @@ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
|
277
352
|
// src/ParserQueryUtils.ts
|
|
278
353
|
var ParserQueryUtils = class {
|
|
279
354
|
/**
|
|
280
|
-
* convert csv 'aa,bb' into "aa='aa', bb='bb'"
|
|
355
|
+
* convert csv 'aa,bb' into "aa = 'Sdk.Class.aa', bb = 'Sdk.Class.bb'"
|
|
281
356
|
*/
|
|
282
357
|
static createQueryKeys(classNameWithoutApi, csvMethodNames, sdkName) {
|
|
283
358
|
const keys = csvMethodNames.split(",");
|
|
@@ -288,7 +363,7 @@ var ParserQueryUtils = class {
|
|
|
288
363
|
const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete|post|fetch)[_]?/, "");
|
|
289
364
|
if (!processedKeys.has(cleanedKey)) {
|
|
290
365
|
processedKeys.add(cleanedKey);
|
|
291
|
-
acc += `${cleanedKey}
|
|
366
|
+
acc += `${cleanedKey}: '${capitalize(sdkName)}.${classNameWithoutApi}.${cleanedKey}'`;
|
|
292
367
|
if (index < keys.length - 1) {
|
|
293
368
|
acc += ",\n";
|
|
294
369
|
}
|
|
@@ -302,42 +377,51 @@ var ParserQueryUtils = class {
|
|
|
302
377
|
|
|
303
378
|
// src/templates/template-query.ts
|
|
304
379
|
var generateImports2 = (body, className) => {
|
|
305
|
-
const
|
|
306
|
-
import {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
import { ${
|
|
310
|
-
|
|
311
|
-
|
|
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";
|
|
312
396
|
};
|
|
313
397
|
var templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports, sdkName) => {
|
|
314
398
|
const classNameWithoutApi = className.replace("Api", "");
|
|
315
399
|
const queryKeys = ParserQueryUtils.createQueryKeys(classNameWithoutApi, returnMethods, sdkName);
|
|
316
400
|
const generatedImports = generateImports2(body, className);
|
|
401
|
+
const queryKeyBlock = `export const Key_${classNameWithoutApi} = {
|
|
402
|
+
${queryKeys}
|
|
403
|
+
} as const`;
|
|
317
404
|
return `/**
|
|
318
405
|
* AUTO GENERATED
|
|
319
406
|
*/
|
|
320
|
-
/* eslint-disable camelcase */
|
|
321
407
|
${generatedImports}
|
|
322
408
|
${filterUsedImports(paramImports, body)}
|
|
323
409
|
|
|
324
|
-
|
|
325
|
-
${queryKeys}
|
|
326
|
-
}
|
|
410
|
+
${queryKeyBlock}
|
|
327
411
|
|
|
328
412
|
${body}
|
|
329
413
|
`;
|
|
330
414
|
};
|
|
331
415
|
function filterUsedImports(importArr, body) {
|
|
332
|
-
return importArr.filter((
|
|
333
|
-
const start =
|
|
334
|
-
const end =
|
|
416
|
+
return importArr.filter((path9) => {
|
|
417
|
+
const start = path9.indexOf("{") + 1;
|
|
418
|
+
const end = path9.indexOf("}");
|
|
335
419
|
if (start > 0 && end > start) {
|
|
336
|
-
const importName =
|
|
420
|
+
const importName = path9.slice(start, end).trim();
|
|
337
421
|
return body.includes(importName);
|
|
338
422
|
}
|
|
339
423
|
return false;
|
|
340
|
-
}).map((
|
|
424
|
+
}).map((path9) => path9).join("\n") + "\n";
|
|
341
425
|
}
|
|
342
426
|
|
|
343
427
|
// src/ParserUtils.ts
|
|
@@ -354,8 +438,8 @@ var REMOVED_KEYWORDS = [
|
|
|
354
438
|
"/{namespace}/"
|
|
355
439
|
];
|
|
356
440
|
var ParserUtils = class _ParserUtils {
|
|
357
|
-
static getVersionSuffixFromPath(
|
|
358
|
-
const version2_3_4_etc =
|
|
441
|
+
static getVersionSuffixFromPath(path9) {
|
|
442
|
+
const version2_3_4_etc = path9.match(/\/v([2-9]|[1-9]\d+)\/+/);
|
|
359
443
|
const methodSuffix = version2_3_4_etc ? `_v${version2_3_4_etc[1]}` : "";
|
|
360
444
|
return methodSuffix;
|
|
361
445
|
}
|
|
@@ -437,13 +521,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
437
521
|
};
|
|
438
522
|
static parseRefImport = (bodyParam) => {
|
|
439
523
|
const $ref = bodyParam?.schema?.$ref || bodyParam?.schema?.items?.$ref;
|
|
440
|
-
if (!$ref) {
|
|
524
|
+
if (!$ref || $ref.endsWith("__dictionary__")) {
|
|
441
525
|
return null;
|
|
442
526
|
}
|
|
443
527
|
const type = _ParserUtils.parseRefType($ref);
|
|
444
528
|
return `import { ${type} } from '../../generated-definitions/${type}.js'`;
|
|
445
529
|
};
|
|
446
530
|
static parseRefType = ($ref) => {
|
|
531
|
+
if ($ref.endsWith("__dictionary__")) return "__dictionary__";
|
|
447
532
|
let ref = $ref.replace(".", "/");
|
|
448
533
|
if (ref[ref.length - 1] === "." || ref[ref.length - 1] === "/") {
|
|
449
534
|
ref = ref.slice(0, -1);
|
|
@@ -550,14 +635,14 @@ var ParserUtils = class _ParserUtils {
|
|
|
550
635
|
* to this
|
|
551
636
|
* `createGenerateByRequestIdByUserId`
|
|
552
637
|
*/
|
|
553
|
-
static generateNaturalLangMethod = ({ servicePrefix, path:
|
|
554
|
-
let path_ =
|
|
638
|
+
static generateNaturalLangMethod = ({ servicePrefix, path: path9, httpMethod, isForm, existingMethods, permissionType }) => {
|
|
639
|
+
let path_ = path9;
|
|
555
640
|
path_ = path_.replace(`/${servicePrefix}/`, "/");
|
|
556
641
|
REMOVED_KEYWORDS.forEach((prefix) => {
|
|
557
642
|
path_ = path_.replace(prefix, "/");
|
|
558
643
|
});
|
|
559
644
|
path_ = path_.substring(1);
|
|
560
|
-
const isPlural = httpMethod === "get" && !(
|
|
645
|
+
const isPlural = httpMethod === "get" && !(path9.slice(-1) === "}");
|
|
561
646
|
if (!isPlural) {
|
|
562
647
|
path_ = _ParserUtils.replaceAll(path_, "ies/", "y/");
|
|
563
648
|
path_ = _ParserUtils.replaceAll(path_, "s/", "/");
|
|
@@ -600,9 +685,9 @@ var ParserUtils = class _ParserUtils {
|
|
|
600
685
|
const genPath = import_lodash.default.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
|
|
601
686
|
let generatedMethod = import_lodash.default.camelCase(mappedMethod(httpMethod, isForm, permissionType) + genPath);
|
|
602
687
|
generatedMethod = _ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
|
|
603
|
-
const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(
|
|
604
|
-
generatedMethod = resolveConflicts({ path:
|
|
605
|
-
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);
|
|
606
691
|
return generatedMethod;
|
|
607
692
|
};
|
|
608
693
|
static filterBodyParams(parameters) {
|
|
@@ -618,17 +703,17 @@ var ParserUtils = class _ParserUtils {
|
|
|
618
703
|
return parameters.filter((parameter) => parameter.in === "query");
|
|
619
704
|
}
|
|
620
705
|
static mkdirIfNotExist(dirToCreate) {
|
|
621
|
-
if (!
|
|
622
|
-
|
|
706
|
+
if (!import_fs4.default.existsSync(dirToCreate)) {
|
|
707
|
+
import_fs4.default.mkdirSync(dirToCreate, { recursive: true });
|
|
623
708
|
}
|
|
624
709
|
}
|
|
625
710
|
static writeClassFile(distDir, apiName, apiBuffer, imports) {
|
|
626
711
|
const fileContent = templateClass(apiName, apiBuffer, imports);
|
|
627
|
-
|
|
712
|
+
import_fs4.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
628
713
|
}
|
|
629
714
|
static writeAtomFile(distDir, apiName, fileContent) {
|
|
630
715
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
631
|
-
|
|
716
|
+
import_fs4.default.writeFileSync(`${distDir}/${apiName}.atom.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
632
717
|
}
|
|
633
718
|
static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName) {
|
|
634
719
|
if (apiBuffer.length < 1) {
|
|
@@ -637,20 +722,21 @@ var ParserUtils = class _ParserUtils {
|
|
|
637
722
|
const queryFileName = `${apiName.replace("Api", "")}.query`;
|
|
638
723
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
639
724
|
const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName);
|
|
640
|
-
|
|
725
|
+
import_fs4.default.writeFileSync(`${distDir}/${queryFileName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
641
726
|
return queryFileName;
|
|
642
727
|
}
|
|
643
728
|
static writeXVersion(distDir, xversionJson, apiInfo) {
|
|
729
|
+
import_fs4.default.mkdirSync(distDir, { recursive: true });
|
|
644
730
|
if (xversionJson) {
|
|
645
731
|
console.log("x-version:", xversionJson);
|
|
646
|
-
|
|
732
|
+
import_fs4.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
|
|
647
733
|
} else {
|
|
648
734
|
const customVersion = {
|
|
649
735
|
...apiInfo,
|
|
650
736
|
gitHash: apiInfo.version
|
|
651
737
|
};
|
|
652
738
|
console.error(`!!!! Missing x-version for ${distDir} ${customVersion}`);
|
|
653
|
-
|
|
739
|
+
import_fs4.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
|
|
654
740
|
}
|
|
655
741
|
}
|
|
656
742
|
static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethodsDescription) {
|
|
@@ -659,28 +745,28 @@ var ParserUtils = class _ParserUtils {
|
|
|
659
745
|
newImports.push(el.replace("../../generated-definitions", "../generated-definitions"));
|
|
660
746
|
});
|
|
661
747
|
const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethodsDescription);
|
|
662
|
-
|
|
748
|
+
import_fs4.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
663
749
|
}
|
|
664
750
|
static writeApiMainFile(distDir, serviceName, fileContent) {
|
|
665
|
-
|
|
751
|
+
import_fs4.default.writeFileSync(`${distDir}/${serviceName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
|
|
666
752
|
}
|
|
667
753
|
static writeSnippetFile(distDir, name, docBuffer) {
|
|
668
754
|
let snippetFileName = _ParserUtils.replaceAll(name, " ", "-").toLowerCase();
|
|
669
755
|
snippetFileName = snippetFileName.replace("justice-", "");
|
|
670
756
|
snippetFileName = "snippet-" + snippetFileName + ".json";
|
|
671
|
-
|
|
757
|
+
import_fs4.default.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
|
|
672
758
|
}
|
|
673
759
|
static writeDefinitionFile(distDir, name, buffer) {
|
|
674
760
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
675
|
-
|
|
761
|
+
import_fs4.default.writeFileSync(import_path3.default.join(distDir, `${name}.ts`), _ParserUtils.prependCopyrightHeader(buffer));
|
|
676
762
|
}
|
|
677
763
|
static writeAllImportsFile(distDir, buffer) {
|
|
678
764
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
679
|
-
|
|
765
|
+
import_fs4.default.writeFileSync(import_path3.default.join(distDir, "all-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
680
766
|
}
|
|
681
767
|
static writeAllQueryImportsFile(distDir, buffer) {
|
|
682
768
|
_ParserUtils.mkdirIfNotExist(distDir);
|
|
683
|
-
|
|
769
|
+
import_fs4.default.writeFileSync(import_path3.default.join(distDir, "all-query-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
|
|
684
770
|
}
|
|
685
771
|
static toCamelCase(str) {
|
|
686
772
|
return str.split("/").map(function(word, index) {
|
|
@@ -706,15 +792,15 @@ var ParserUtils = class _ParserUtils {
|
|
|
706
792
|
});
|
|
707
793
|
}
|
|
708
794
|
static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
|
|
709
|
-
if (!
|
|
710
|
-
|
|
795
|
+
if (!import_fs4.default.existsSync(swaggerPatchedDir)) {
|
|
796
|
+
import_fs4.default.mkdirSync(swaggerPatchedDir, { recursive: true });
|
|
711
797
|
}
|
|
712
|
-
if (!
|
|
713
|
-
|
|
798
|
+
if (!import_fs4.default.existsSync(possibleSwaggerPatchFilePath)) {
|
|
799
|
+
import_fs4.default.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
|
|
714
800
|
return;
|
|
715
801
|
}
|
|
716
|
-
const swaggerContent = JSON.parse(
|
|
717
|
-
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"));
|
|
718
804
|
for (const patchEntry of swaggerPatchFileContent) {
|
|
719
805
|
const segments = patchEntry.path.split("/").filter(Boolean);
|
|
720
806
|
let currentNode = swaggerContent;
|
|
@@ -742,7 +828,7 @@ var ParserUtils = class _ParserUtils {
|
|
|
742
828
|
}
|
|
743
829
|
}
|
|
744
830
|
const { newDocument } = (0, import_fast_json_patch.applyPatch)(swaggerContent, swaggerPatchFileContent);
|
|
745
|
-
|
|
831
|
+
import_fs4.default.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
|
|
746
832
|
}
|
|
747
833
|
static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
|
|
748
834
|
const replaced = srcFolder.replace(/\\/g, "/");
|
|
@@ -757,8 +843,8 @@ var ParserUtils = class _ParserUtils {
|
|
|
757
843
|
*/
|
|
758
844
|
${content}`;
|
|
759
845
|
};
|
|
760
|
-
static sortPathParamsByPath = (pathParams,
|
|
761
|
-
const params =
|
|
846
|
+
static sortPathParamsByPath = (pathParams, path9) => {
|
|
847
|
+
const params = path9.match(/{\w*}/g) || [];
|
|
762
848
|
const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
|
|
763
849
|
return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
|
|
764
850
|
};
|
|
@@ -782,30 +868,40 @@ var mappedMethod = (httpMethod, isForm, permissionType) => {
|
|
|
782
868
|
return "delete";
|
|
783
869
|
}
|
|
784
870
|
};
|
|
785
|
-
var resolveConflicts = ({ path:
|
|
871
|
+
var resolveConflicts = ({ path: path9, generatedMethod, testedGeneratedMethod, existingMethods }) => {
|
|
786
872
|
let _testedGenMethod = testedGeneratedMethod;
|
|
787
873
|
try {
|
|
788
|
-
testConflict(
|
|
874
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
789
875
|
} catch (e) {
|
|
790
|
-
if (
|
|
876
|
+
if (path9.indexOf("/namespaces/") >= 0) {
|
|
791
877
|
generatedMethod += "_ByNS";
|
|
792
878
|
_testedGenMethod += "_ByNS";
|
|
793
879
|
}
|
|
794
880
|
}
|
|
795
881
|
try {
|
|
796
|
-
testConflict(
|
|
882
|
+
testConflict(path9, _testedGenMethod, existingMethods);
|
|
797
883
|
} catch (e) {
|
|
798
|
-
if (
|
|
884
|
+
if (path9.indexOf("/admin/") >= 0) {
|
|
799
885
|
generatedMethod += "_admin";
|
|
800
886
|
_testedGenMethod += "_admin";
|
|
801
887
|
}
|
|
802
888
|
}
|
|
803
|
-
|
|
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);
|
|
804
900
|
return generatedMethod;
|
|
805
901
|
};
|
|
806
|
-
var testConflict = (
|
|
902
|
+
var testConflict = (path9, generatedMethod, existingMethods) => {
|
|
807
903
|
if (existingMethods[generatedMethod]) {
|
|
808
|
-
const conflictingMethod = { path:
|
|
904
|
+
const conflictingMethod = { path: path9, generatedMethod };
|
|
809
905
|
throw Error(
|
|
810
906
|
`Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
|
|
811
907
|
existingMethods: ${JSON.stringify(existingMethods, null, 2)}`
|
|
@@ -922,7 +1018,7 @@ var OpenApiSpec = import_zod2.z.object({
|
|
|
922
1018
|
var templateApiMethod = ({
|
|
923
1019
|
classMethod,
|
|
924
1020
|
httpMethod,
|
|
925
|
-
path:
|
|
1021
|
+
path: path9,
|
|
926
1022
|
pathParams,
|
|
927
1023
|
bodyParams,
|
|
928
1024
|
responseClasses,
|
|
@@ -931,12 +1027,12 @@ var templateApiMethod = ({
|
|
|
931
1027
|
methodParamsNoTypes,
|
|
932
1028
|
xSecurity
|
|
933
1029
|
}) => {
|
|
934
|
-
let newPath = `'${
|
|
1030
|
+
let newPath = `'${path9}'`;
|
|
935
1031
|
let snippetMethod = "";
|
|
936
1032
|
for (const pathParam of pathParams) {
|
|
937
1033
|
const type = ParserUtils.parseType(pathParam);
|
|
938
1034
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
939
|
-
if (
|
|
1035
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
940
1036
|
if (type === "string") {
|
|
941
1037
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
942
1038
|
} else {
|
|
@@ -944,9 +1040,9 @@ var templateApiMethod = ({
|
|
|
944
1040
|
}
|
|
945
1041
|
}
|
|
946
1042
|
}
|
|
947
|
-
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${
|
|
1043
|
+
const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path9}'`, "--header 'accept: application/json'"];
|
|
948
1044
|
const snippetApiArgs = [];
|
|
949
|
-
if (xSecurity !== void 0 ||
|
|
1045
|
+
if (xSecurity !== void 0 || path9.includes("/admin")) {
|
|
950
1046
|
snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
|
|
951
1047
|
snippetApiArgs.push("{ axiosConfig: { request: { headers: { Authorization: 'Bearer {access_token}' } } } }".trim());
|
|
952
1048
|
}
|
|
@@ -984,7 +1080,7 @@ var templateMethod = ({
|
|
|
984
1080
|
classMethod,
|
|
985
1081
|
description,
|
|
986
1082
|
httpMethod,
|
|
987
|
-
path:
|
|
1083
|
+
path: path9,
|
|
988
1084
|
pathParams,
|
|
989
1085
|
bodyParams,
|
|
990
1086
|
queryParams,
|
|
@@ -994,9 +1090,9 @@ var templateMethod = ({
|
|
|
994
1090
|
}) => {
|
|
995
1091
|
let methodParams = "";
|
|
996
1092
|
let methodParamsNoTypes = "";
|
|
997
|
-
let newPath = `'${
|
|
1093
|
+
let newPath = `'${path9}'`;
|
|
998
1094
|
let importStatements = [];
|
|
999
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1095
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
1000
1096
|
for (const pathParam of sortedPathParams) {
|
|
1001
1097
|
const type = ParserUtils.parseType(pathParam);
|
|
1002
1098
|
if (pathParam.name !== "namespace") {
|
|
@@ -1004,7 +1100,7 @@ var templateMethod = ({
|
|
|
1004
1100
|
methodParamsNoTypes += pathParam.name + ", ";
|
|
1005
1101
|
}
|
|
1006
1102
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1007
|
-
if (
|
|
1103
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
1008
1104
|
if (type === "string") {
|
|
1009
1105
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1010
1106
|
} else {
|
|
@@ -1015,6 +1111,7 @@ var templateMethod = ({
|
|
|
1015
1111
|
let dataType = null;
|
|
1016
1112
|
if (httpMethod !== "get") {
|
|
1017
1113
|
dataType = ParserUtils.parseBodyParamsType(bodyParams);
|
|
1114
|
+
if (dataType === "__dictionary__") dataType = "Record<string, any>";
|
|
1018
1115
|
importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
|
|
1019
1116
|
methodParams += dataType ? `data: ${dataType},` : "";
|
|
1020
1117
|
methodParamsNoTypes += dataType ? `data,` : "";
|
|
@@ -1038,7 +1135,7 @@ var templateMethod = ({
|
|
|
1038
1135
|
}
|
|
1039
1136
|
const isFileUpload = methodParams.indexOf("data: {file") > -1;
|
|
1040
1137
|
const { responseType, responseTypeInResponse } = getResponseType({ responseClasses });
|
|
1041
|
-
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()";
|
|
1042
1139
|
methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
|
|
1043
1140
|
methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
|
|
1044
1141
|
const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
|
|
@@ -1069,7 +1166,7 @@ var POST_FETCH_INCLUDES_PATH = ["/table-query/"];
|
|
|
1069
1166
|
var templateQueryMethod = ({
|
|
1070
1167
|
classMethod,
|
|
1071
1168
|
httpMethod,
|
|
1072
|
-
path:
|
|
1169
|
+
path: path9,
|
|
1073
1170
|
pathParams,
|
|
1074
1171
|
responseClasses,
|
|
1075
1172
|
methodParams,
|
|
@@ -1077,14 +1174,14 @@ var templateQueryMethod = ({
|
|
|
1077
1174
|
description,
|
|
1078
1175
|
deprecated
|
|
1079
1176
|
}) => {
|
|
1080
|
-
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"));
|
|
1081
1178
|
const isFetch = classMethod.startsWith("fetch");
|
|
1082
1179
|
const isGet = httpMethod === "get" || isPostFetch || isFetch;
|
|
1083
1180
|
const queryMethod = isGet ? "useQuery" : "useMutation";
|
|
1084
1181
|
let mParams = "";
|
|
1085
1182
|
let mParamsNoTypes = "";
|
|
1086
|
-
let newPath = `'${
|
|
1087
|
-
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams,
|
|
1183
|
+
let newPath = `'${path9}'`;
|
|
1184
|
+
const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path9);
|
|
1088
1185
|
for (const pathParam of sortedPathParams) {
|
|
1089
1186
|
const type = ParserUtils.parseType(pathParam);
|
|
1090
1187
|
if (pathParam.name !== "namespace") {
|
|
@@ -1092,7 +1189,7 @@ var templateQueryMethod = ({
|
|
|
1092
1189
|
mParamsNoTypes += pathParam.name + ", ";
|
|
1093
1190
|
}
|
|
1094
1191
|
const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
|
|
1095
|
-
if (
|
|
1192
|
+
if (path9.match(`{${pathParam.name}}`)) {
|
|
1096
1193
|
if (type === "string") {
|
|
1097
1194
|
newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
|
|
1098
1195
|
} else {
|
|
@@ -1127,7 +1224,7 @@ export const ${_methodName} = (
|
|
|
1127
1224
|
const response =
|
|
1128
1225
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1129
1226
|
${classMethod}(${_methodParamsImpl}))
|
|
1130
|
-
callback
|
|
1227
|
+
callback?.(response)
|
|
1131
1228
|
return response.data
|
|
1132
1229
|
}
|
|
1133
1230
|
|
|
@@ -1152,7 +1249,7 @@ export const ${_methodName} = (
|
|
|
1152
1249
|
const response =
|
|
1153
1250
|
(await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
|
|
1154
1251
|
${classMethod}(${_methodParamsImpl}))
|
|
1155
|
-
callback
|
|
1252
|
+
callback?.(response.data)
|
|
1156
1253
|
return response.data
|
|
1157
1254
|
}
|
|
1158
1255
|
|
|
@@ -1331,11 +1428,11 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1331
1428
|
admin: {},
|
|
1332
1429
|
public: {}
|
|
1333
1430
|
};
|
|
1334
|
-
for (const [
|
|
1335
|
-
if (
|
|
1431
|
+
for (const [path9, operation] of sortedPathsByLength) {
|
|
1432
|
+
if (path9.indexOf("/healthz") >= 0) {
|
|
1336
1433
|
continue;
|
|
1337
1434
|
}
|
|
1338
|
-
const isAdminEndpoint =
|
|
1435
|
+
const isAdminEndpoint = path9.indexOf("/admin/") > -1;
|
|
1339
1436
|
const picked = isAdminEndpoint ? result.admin : result.public;
|
|
1340
1437
|
const {
|
|
1341
1438
|
arrayDefinitions,
|
|
@@ -1353,25 +1450,27 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1353
1450
|
const httpMethods = Object.keys(operation);
|
|
1354
1451
|
for (const httpMethod of httpMethods) {
|
|
1355
1452
|
const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
|
|
1356
|
-
console.error(JSON.stringify({ path:
|
|
1453
|
+
console.error(JSON.stringify({ path: path9, httpMethod }, null, 2));
|
|
1357
1454
|
throw error;
|
|
1358
1455
|
});
|
|
1359
1456
|
if (!endpoint.tags) continue;
|
|
1360
1457
|
const [tag] = endpoint.tags;
|
|
1361
|
-
const
|
|
1458
|
+
const configBasePath = CodegenConfig.getBasePath();
|
|
1459
|
+
const effectiveBasePath = configBasePath !== void 0 ? configBasePath : api.basePath ?? "";
|
|
1460
|
+
const pathWithBase = `${effectiveBasePath}${path9}`;
|
|
1362
1461
|
const permissionType = getPermissionType(getPermission(endpoint));
|
|
1363
1462
|
tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
|
|
1364
1463
|
const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
|
|
1365
1464
|
const classMethod = ParserUtils.generateNaturalLangMethod({
|
|
1366
1465
|
servicePrefix,
|
|
1367
|
-
path:
|
|
1466
|
+
path: path9,
|
|
1368
1467
|
httpMethod,
|
|
1369
1468
|
isForm,
|
|
1370
1469
|
existingMethods: tagToClassMethodsMapByType[tag],
|
|
1371
1470
|
permissionType
|
|
1372
1471
|
});
|
|
1373
|
-
tagToClassMethodsMapByType[tag][classMethod] = `${
|
|
1374
|
-
generatedMethods[`${
|
|
1472
|
+
tagToClassMethodsMapByType[tag][classMethod] = `${path9} ${httpMethod}`;
|
|
1473
|
+
generatedMethods[`${path9} ${httpMethod}`] = `${classMethod}`;
|
|
1375
1474
|
if (!snippetMap[pathWithBase]) {
|
|
1376
1475
|
snippetMap[pathWithBase] = {};
|
|
1377
1476
|
}
|
|
@@ -1380,7 +1479,7 @@ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
|
|
|
1380
1479
|
const responseClass = responseClasses.length > 1 ? null : responseClasses?.[0];
|
|
1381
1480
|
const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
|
|
1382
1481
|
tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
|
|
1383
|
-
if (responseClass) {
|
|
1482
|
+
if (responseClass && responseClass !== "__dictionary__") {
|
|
1384
1483
|
tagToClassImportsRecord[className][responseClass] = `import { ${responseClass} } from '../../generated-definitions/${responseClass}.js'`;
|
|
1385
1484
|
}
|
|
1386
1485
|
if (responseClass && responseClass.endsWith("Array")) {
|
|
@@ -1526,6 +1625,20 @@ var TemplateZod = class {
|
|
|
1526
1625
|
// --
|
|
1527
1626
|
render = (fileName, definition, duplicates) => {
|
|
1528
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
|
+
}
|
|
1529
1642
|
const content = this.parseToZodSchema(definition, definition.required || []);
|
|
1530
1643
|
const containsRecursiveType = this.importClasses.has(fileName);
|
|
1531
1644
|
if (containsRecursiveType) {
|
|
@@ -1614,7 +1727,14 @@ ${exportedTypeString}
|
|
|
1614
1727
|
};
|
|
1615
1728
|
} else if (type) {
|
|
1616
1729
|
if (type === "object" && definition.additionalProperties) {
|
|
1617
|
-
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, [""]);
|
|
1618
1738
|
return {
|
|
1619
1739
|
schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
|
|
1620
1740
|
typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
|
|
@@ -1800,8 +1920,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1800
1920
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
1801
1921
|
const apiInfo = { ...api.info, "x-version": api["x-version"]?.version };
|
|
1802
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()}/`;
|
|
1803
1926
|
if (!CliParser.isGenerateSnippetOnly()) {
|
|
1804
|
-
ParserUtils.writeXVersion(
|
|
1927
|
+
ParserUtils.writeXVersion(srcFolder, api["x-version"], api.info);
|
|
1805
1928
|
}
|
|
1806
1929
|
const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
|
|
1807
1930
|
if (CliParser.getSnippetOutputPath()) {
|
|
@@ -1827,11 +1950,10 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1827
1950
|
console.log("\nSuccessfully generate SDK snippets only\n----------\n\n");
|
|
1828
1951
|
return;
|
|
1829
1952
|
}
|
|
1830
|
-
const DIST_DIR = (isAdmin) =>
|
|
1831
|
-
const DIST_DIR_ENDPOINTS = (isAdmin) =>
|
|
1832
|
-
const DIST_DIR_QUERIES = (isAdmin) =>
|
|
1833
|
-
const DIST_DEFINITION_DIR =
|
|
1834
|
-
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");
|
|
1835
1957
|
_CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
|
|
1836
1958
|
const mainApiList = [];
|
|
1837
1959
|
const generatedDefinitions = [];
|
|
@@ -1872,30 +1994,31 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1872
1994
|
ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionDescription[tag]);
|
|
1873
1995
|
apiList.push(apiGenName);
|
|
1874
1996
|
indexImportsSet.add(
|
|
1875
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1997
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder)
|
|
1876
1998
|
);
|
|
1877
1999
|
indexImportsSet.add(
|
|
1878
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2000
|
+
ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder)
|
|
1879
2001
|
);
|
|
1880
2002
|
queryFileName && queryImportsSet.add(
|
|
1881
2003
|
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1882
|
-
|
|
2004
|
+
import_path4.default.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`),
|
|
1883
2005
|
targetSrcFolder
|
|
1884
2006
|
)
|
|
1885
2007
|
);
|
|
1886
2008
|
}
|
|
1887
2009
|
mainApiList.push(...apiList);
|
|
1888
|
-
|
|
1889
|
-
ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
1890
|
-
|
|
2010
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
2011
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(srcFolder, serviceNameTitle), targetSrcFolder));
|
|
2012
|
+
}
|
|
1891
2013
|
};
|
|
1892
2014
|
const writeDefinitions = (api2) => {
|
|
1893
2015
|
const duplicates = /* @__PURE__ */ new Map();
|
|
1894
2016
|
const definitions = api2?.components?.schemas || api2.definitions;
|
|
1895
2017
|
for (const ref in definitions) {
|
|
2018
|
+
if (ref === "__dictionary__") continue;
|
|
1896
2019
|
const definition = definitions[ref];
|
|
1897
2020
|
const fileName = ParserUtils.parseRefType(ref);
|
|
1898
|
-
const fileExist =
|
|
2021
|
+
const fileExist = import_fs5.default.existsSync(import_path4.default.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
|
|
1899
2022
|
if (fileExist) {
|
|
1900
2023
|
const duplicateName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
|
|
1901
2024
|
duplicates.set(ref, duplicateName);
|
|
@@ -1903,13 +2026,13 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1903
2026
|
const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
|
|
1904
2027
|
generatedDefinitions.push(fileName);
|
|
1905
2028
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
|
|
1906
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2029
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
|
|
1907
2030
|
}
|
|
1908
2031
|
for (const arrayClass of arrayDefinitions) {
|
|
1909
2032
|
const buffer = new TemplateZodArray().render(arrayClass);
|
|
1910
2033
|
generatedDefinitions.push(arrayClass);
|
|
1911
2034
|
ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
|
|
1912
|
-
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(
|
|
2035
|
+
indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path4.default.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
|
|
1913
2036
|
}
|
|
1914
2037
|
};
|
|
1915
2038
|
writeApiEndpointFiles(isAdmin);
|
|
@@ -1917,9 +2040,11 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1917
2040
|
};
|
|
1918
2041
|
generatePublicOrAdmin(true);
|
|
1919
2042
|
generatePublicOrAdmin(false);
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
2043
|
+
if (CodegenConfig.shouldProduceIndexFiles()) {
|
|
2044
|
+
const isGenerateWebSocket = CliParser.isGenerateWebSocket();
|
|
2045
|
+
const apiIndexBuff = templateApiIndex(serviceNameTitle, mainApiList, isGenerateWebSocket);
|
|
2046
|
+
ParserUtils.writeApiMainFile(srcFolder, serviceNameTitle, apiIndexBuff);
|
|
2047
|
+
}
|
|
1923
2048
|
console.log("\nCOMPLETED\n----------\n\n");
|
|
1924
2049
|
return { indexImports: indexImportsSet, queryImports: queryImportsSet };
|
|
1925
2050
|
};
|
|
@@ -1927,29 +2052,30 @@ var CodeGenerator = class _CodeGenerator {
|
|
|
1927
2052
|
};
|
|
1928
2053
|
|
|
1929
2054
|
// src/SwaggerDownloader.ts
|
|
2055
|
+
var fs6 = __toESM(require("fs"));
|
|
1930
2056
|
var https = __toESM(require("https"));
|
|
1931
|
-
var
|
|
1932
|
-
var path5 = __toESM(require("path"));
|
|
2057
|
+
var path6 = __toESM(require("path"));
|
|
1933
2058
|
var SwaggerDownloader = class _SwaggerDownloader {
|
|
1934
2059
|
static getDestFile = (targetFileName) => {
|
|
1935
2060
|
const destPath = CliParser.getResolvedSwaggersOutputPath();
|
|
1936
|
-
const destFile =
|
|
1937
|
-
if (
|
|
1938
|
-
if (!
|
|
1939
|
-
|
|
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, "");
|
|
1940
2065
|
return destFile;
|
|
1941
2066
|
};
|
|
1942
2067
|
// session-api.json contains illegal URL encoded character that breaks the codegen
|
|
1943
2068
|
// e.g. "$ref": "#/definitions/map%5Bstring%5Dinterface%20%7B%7D"
|
|
1944
2069
|
static postSanitizeDownloadedFile = (filePath) => {
|
|
1945
2070
|
const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
|
|
1946
|
-
|
|
2071
|
+
fs6.readFile(filePath, "utf8", (err, data) => {
|
|
1947
2072
|
if (err) throw err;
|
|
1948
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__");
|
|
1949
2075
|
searchStr.forEach((s) => {
|
|
1950
2076
|
result = result.replace(new RegExp(s, "g"), " ");
|
|
1951
2077
|
});
|
|
1952
|
-
|
|
2078
|
+
fs6.writeFile(filePath, result, "utf8", (err2) => {
|
|
1953
2079
|
if (err2) throw err2;
|
|
1954
2080
|
console.log("File updated successfully.");
|
|
1955
2081
|
});
|
|
@@ -1967,7 +2093,7 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1967
2093
|
if (response.statusCode !== 200) {
|
|
1968
2094
|
console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
|
|
1969
2095
|
} else {
|
|
1970
|
-
|
|
2096
|
+
fs6.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
|
|
1971
2097
|
_SwaggerDownloader.postSanitizeDownloadedFile(destFile);
|
|
1972
2098
|
console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
|
|
1973
2099
|
}
|
|
@@ -1990,8 +2116,8 @@ var SwaggerDownloader = class _SwaggerDownloader {
|
|
|
1990
2116
|
};
|
|
1991
2117
|
|
|
1992
2118
|
// src/WebsocketGenerator.ts
|
|
1993
|
-
var
|
|
1994
|
-
var
|
|
2119
|
+
var import_fs6 = __toESM(require("fs"));
|
|
2120
|
+
var import_path5 = __toESM(require("path"));
|
|
1995
2121
|
|
|
1996
2122
|
// src/templates/template-ws-class.ts
|
|
1997
2123
|
var definitionToFunctionName = (type) => {
|
|
@@ -2006,7 +2132,7 @@ var renderSendFunction = (name, definition) => {
|
|
|
2006
2132
|
send({ type: '${name}', ...data })
|
|
2007
2133
|
}`;
|
|
2008
2134
|
};
|
|
2009
|
-
var templateWebsocketClass = (name,
|
|
2135
|
+
var templateWebsocketClass = (name, path9, definitions) => {
|
|
2010
2136
|
const requestDefinitions = Object.keys(definitions).filter((key) => {
|
|
2011
2137
|
const val = definitions[key];
|
|
2012
2138
|
return val["x-type"] == "request";
|
|
@@ -2065,7 +2191,7 @@ const messageSerializer = (data: Record<string, any>) => {
|
|
|
2065
2191
|
export function WebSocketClass(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
|
|
2066
2192
|
const sdkAssembly = sdk.assembly()
|
|
2067
2193
|
const baseURL = (args?.coreConfig?.baseURL ?? sdkAssembly.coreConfig.baseURL).replace('http', 'ws')
|
|
2068
|
-
const path = '${
|
|
2194
|
+
const path = '${path9}'
|
|
2069
2195
|
const url = baseURL + path
|
|
2070
2196
|
let ws: WebSocket | null = null
|
|
2071
2197
|
let isDisconnectManually = false
|
|
@@ -2314,9 +2440,9 @@ ${renderUnion(["response", "notification"], definitions)}
|
|
|
2314
2440
|
// src/WebsocketGenerator.ts
|
|
2315
2441
|
var WebsocketGenerator = class {
|
|
2316
2442
|
static srcFolder = () => CliParser.getOutputPath();
|
|
2317
|
-
static outputFolder = () =>
|
|
2443
|
+
static outputFolder = () => import_path5.default.join(this.srcFolder(), "generated-websocket");
|
|
2318
2444
|
static schemaContent = () => {
|
|
2319
|
-
const fileContent = JSON.parse(
|
|
2445
|
+
const fileContent = JSON.parse(import_fs6.default.readFileSync(CliParser.getWebSocketSchemaPath(), "utf8"));
|
|
2320
2446
|
return fileContent;
|
|
2321
2447
|
};
|
|
2322
2448
|
static prepareDirs = () => {
|
|
@@ -2326,11 +2452,11 @@ var WebsocketGenerator = class {
|
|
|
2326
2452
|
const { name, path: wsPath, definitions } = this.schemaContent();
|
|
2327
2453
|
const templateDefinitions = templateWebsocketDefinitions(definitions);
|
|
2328
2454
|
this.prepareDirs();
|
|
2329
|
-
const filePath =
|
|
2330
|
-
|
|
2455
|
+
const filePath = import_path5.default.join(this.outputFolder(), "WebSocketDefinitions.ts");
|
|
2456
|
+
import_fs6.default.writeFileSync(filePath, templateDefinitions, "utf8");
|
|
2331
2457
|
const templateClass2 = templateWebsocketClass(name, wsPath, definitions);
|
|
2332
|
-
const filePathClass =
|
|
2333
|
-
|
|
2458
|
+
const filePathClass = import_path5.default.join(this.outputFolder(), "WebSocketClass.ts");
|
|
2459
|
+
import_fs6.default.writeFileSync(filePathClass, templateClass2, "utf8");
|
|
2334
2460
|
};
|
|
2335
2461
|
};
|
|
2336
2462
|
|
|
@@ -2343,24 +2469,28 @@ var generateSdk = async () => {
|
|
|
2343
2469
|
if (CliParser.isGenerateWebSocket()) {
|
|
2344
2470
|
WebsocketGenerator.main();
|
|
2345
2471
|
}
|
|
2472
|
+
if (!CodegenConfig.shouldProduceIndexFiles()) {
|
|
2473
|
+
return;
|
|
2474
|
+
}
|
|
2346
2475
|
const indexImportsSet = /* @__PURE__ */ new Set();
|
|
2347
2476
|
const queryImportsSet = /* @__PURE__ */ new Set();
|
|
2348
2477
|
const filenamesSet = /* @__PURE__ */ new Set();
|
|
2349
2478
|
for (const set of arrayOfSets) {
|
|
2350
2479
|
set.indexImports.forEach((value) => {
|
|
2351
|
-
const fileName =
|
|
2480
|
+
const fileName = import_path6.default.basename(value);
|
|
2352
2481
|
if (!filenamesSet.has(fileName)) {
|
|
2353
2482
|
indexImportsSet.add(value);
|
|
2354
2483
|
filenamesSet.add(fileName);
|
|
2355
2484
|
}
|
|
2356
2485
|
});
|
|
2357
2486
|
set.queryImports.forEach((value) => {
|
|
2358
|
-
const fileName =
|
|
2487
|
+
const fileName = import_path6.default.basename(value);
|
|
2359
2488
|
if (!filenamesSet.has(fileName)) {
|
|
2360
2489
|
queryImportsSet.add(value);
|
|
2361
2490
|
}
|
|
2362
2491
|
});
|
|
2363
2492
|
}
|
|
2493
|
+
const outputPath = CliParser.getOutputPath();
|
|
2364
2494
|
const indexImportsArray = Array.from(indexImportsSet).sort();
|
|
2365
2495
|
const queryImportsArray = Array.from(queryImportsSet).sort();
|
|
2366
2496
|
const filesToImport = indexImportsArray.map((fileToImport) => {
|
|
@@ -2369,8 +2499,8 @@ var generateSdk = async () => {
|
|
|
2369
2499
|
const queryFilesToImport = queryImportsArray.map((fileToImport) => {
|
|
2370
2500
|
return `export * from '${fileToImport.replace("\\", "/")}.js'`;
|
|
2371
2501
|
});
|
|
2372
|
-
ParserUtils.writeAllImportsFile(
|
|
2373
|
-
ParserUtils.writeAllQueryImportsFile(
|
|
2502
|
+
ParserUtils.writeAllImportsFile(outputPath, filesToImport.join("\n"));
|
|
2503
|
+
ParserUtils.writeAllQueryImportsFile(outputPath, queryFilesToImport.join("\n"));
|
|
2374
2504
|
};
|
|
2375
2505
|
import_yargs.default.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
|
|
2376
2506
|
CliParser.createInstance(yargs2);
|
|
@@ -2386,6 +2516,7 @@ import_yargs.default.command("download-swaggers", "Download swaggers JSON files"
|
|
|
2386
2516
|
return true;
|
|
2387
2517
|
});
|
|
2388
2518
|
CliParser.createInstance(yargs2);
|
|
2519
|
+
await CodegenConfig.loadConfig(import_path6.default.dirname(import_path6.default.resolve(CliParser.getConfigPath())));
|
|
2389
2520
|
await generateSdk();
|
|
2390
2521
|
}).option("config", {
|
|
2391
2522
|
description: "Path to the config file with backend service URLs.",
|