@accelbyte/codegen 2.0.0-beta.4 → 2.0.0-beta.6

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.
@@ -238,14 +238,14 @@ class ParserUtils {
238
238
  static replaceAll = (string, search, replace) => {
239
239
  return string.split(search).join(replace);
240
240
  };
241
- static generateClassName = (tag) => {
241
+ static generateClassName = (tag, isAdmin) => {
242
242
  const className = _.upperFirst(_.camelCase(tag));
243
- const classGenName = CliParser.isAdmin() ? className + "Admin$" : className + "$";
243
+ const classGenName = isAdmin ? className + "Admin$" : className + "$";
244
244
  return { className, classGenName };
245
245
  };
246
- static generateApiName = (tag) => {
246
+ static generateApiName = (tag, isAdmin) => {
247
247
  const apiName = _.upperFirst(_.camelCase(tag));
248
- const apiGenName = CliParser.isAdmin() ? apiName + "AdminApi" : apiName + "Api";
248
+ const apiGenName = isAdmin ? apiName + "AdminApi" : apiName + "Api";
249
249
  return { apiName, apiGenName };
250
250
  };
251
251
  static parseQueryParamAttributeDefault = (definition) => {
@@ -685,205 +685,6 @@ const isSwaggerIntegerType = (type) => {
685
685
  return type === "integer" || type === "int";
686
686
  };
687
687
 
688
- const Schema = zod.z.object({
689
- $ref: zod.z.string().nullish(),
690
- type: zod.z.union([zod.z.literal("array"), zod.z.literal("object"), zod.z.literal("file"), zod.z.literal("string"), zod.z.literal("boolean"), zod.z.literal("integer")]).nullish(),
691
- items: zod.z.object({
692
- $ref: zod.z.string().nullish(),
693
- type: zod.z.string().nullish()
694
- }).nullish(),
695
- properties: zod.z.union([zod.z.array(zod.z.string()).nullish(), zod.z.record(zod.z.object({ type: zod.z.string() })).nullish()]),
696
- description: zod.z.string().nullish(),
697
- additionalProperties: zod.z.object({
698
- type: zod.z.string().nullish()
699
- }).nullish()
700
- });
701
- const Definition = zod.z.object({
702
- required: zod.z.array(zod.z.string()).nullish(),
703
- properties: zod.z.record(zod.z.object({
704
- type: zod.z.string()
705
- })).nullish()
706
- });
707
- const Definitions = zod.z.record(Definition);
708
- const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
709
- const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
710
- const EndpointParameters = zod.z.object({
711
- type: EndpointParametersType.nullish(),
712
- description: zod.z.string().nullish(),
713
- name: zod.z.string(),
714
- in: EndpointParametersIn,
715
- required: zod.z.boolean().nullish(),
716
- schema: Schema.nullish(),
717
- default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
718
- enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
719
- items: zod.z.object({
720
- type: zod.z.string(),
721
- enum: zod.z.array(zod.z.any()).nullish()
722
- }).nullish()
723
- });
724
- const Endpoint = zod.z.object({
725
- description: zod.z.string().nullish(),
726
- consumes: zod.z.array(zod.z.string()).nullish(),
727
- produces: zod.z.array(zod.z.string()).nullish(),
728
- tags: zod.z.array(zod.z.string()).nullish(),
729
- summary: zod.z.string().nullish(),
730
- operationId: zod.z.string(),
731
- deprecated: zod.z.boolean().nullish(),
732
- responses: zod.z.record(zod.z.object({
733
- description: zod.z.string().nullish(),
734
- schema: Schema.nullish(),
735
- content: zod.z.object({
736
- "application/json": zod.z.object({
737
- schema: Schema.nullish()
738
- })
739
- }).nullish()
740
- })),
741
- parameters: zod.z.array(EndpointParameters).nullish(),
742
- requestBody: zod.z.object({
743
- required: zod.z.boolean(),
744
- content: zod.z.object({
745
- "application/json": zod.z.object({
746
- schema: Schema.nullish()
747
- })
748
- }).nullish()
749
- }).nullish()
750
- });
751
- const Operation = zod.z.object({
752
- get: Endpoint.nullish(),
753
- post: Endpoint.nullish(),
754
- patch: Endpoint.nullish(),
755
- delete: Endpoint.nullish(),
756
- put: Endpoint.nullish()
757
- });
758
- const Paths = zod.z.record(Operation);
759
- zod.z.object({
760
- paths: Paths,
761
- definitions: Definitions,
762
- basePath: zod.z.string(),
763
- info: zod.z.object({
764
- description: zod.z.string(),
765
- title: zod.z.string(),
766
- contact: zod.z.object({
767
- name: zod.z.string(),
768
- url: zod.z.string(),
769
- email: zod.z.string()
770
- }),
771
- version: zod.z.string()
772
- }),
773
- schemes: zod.z.array(zod.z.string()).nullish(),
774
- components: zod.z.object({
775
- schemas: Definitions
776
- }).nullish()
777
- });
778
-
779
- const templateMethod = ({
780
- classMethod,
781
- description,
782
- httpMethod,
783
- path,
784
- pathParams,
785
- bodyParams,
786
- queryParams,
787
- isFormUrlEncoded,
788
- responseClass
789
- }) => {
790
- let methodParams = "";
791
- let methodParamsNoTypes = "";
792
- let newPath = `'${path}'`;
793
- let importStatements = [];
794
- const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
795
- for (const pathParam of sortedPathParams) {
796
- const type = ParserUtils.parseType(pathParam);
797
- if (pathParam.name !== "namespace") {
798
- methodParams += pathParam.name + `:${type}, `;
799
- methodParamsNoTypes += pathParam.name + ", ";
800
- }
801
- const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
802
- if (path.match(`{${pathParam.name}}`)) {
803
- if (type === "string") {
804
- newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
805
- } else {
806
- newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
807
- }
808
- }
809
- }
810
- let dataType = null;
811
- if (httpMethod !== "get") {
812
- dataType = ParserUtils.parseBodyParamsType(bodyParams);
813
- importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
814
- methodParams += dataType ? `data: ${dataType},` : "";
815
- methodParamsNoTypes += dataType ? `data,` : "";
816
- }
817
- const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
818
- const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
819
- const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
820
- const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
821
- const isDelete = ["delete"].includes(httpMethod);
822
- let dataPayload = "{params}";
823
- const descriptionText = description ? `
824
- /**
825
- * ${description.replace(/\n/g, "\n * ")}
826
- */` : "";
827
- let formPayloadString = "";
828
- if (isFormUrlEncoded) {
829
- formPayloadString = ``;
830
- const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
831
- dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
832
- } else if (isPostPutPatch) {
833
- dataPayload = dataType ? `data, {params}` : "null, {params}";
834
- } else if (isDelete) {
835
- dataPayload = dataType ? `{data, params}` : "{params}";
836
- }
837
- const isFileUpload = methodParams.indexOf("data: {file") > -1;
838
- const resolvedResponseClass = responseClass || "unknown";
839
- const resolvedResponseClassValidated = responseClass || "z.unknown()";
840
- methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
841
- methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
842
- let methodImpl = "";
843
- const isCacheFetch = ["get"].includes(httpMethod) && resolvedResponseClass !== "unknown";
844
- const cachedFetchMethod = classMethod;
845
- const deprecateTag = isCacheFetch ? `/**
846
- * @deprecated Use "${classMethod}()" instead.
847
- */` : "";
848
- const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
849
- const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
850
- const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
851
- const generateMethodName = () => `${methodName}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
852
- const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
853
- methodImpl = `${descriptionText}
854
- ${generateMethodName()} {
855
- ${queryParamsDefault}
856
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
857
- const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
858
-
859
- ${httpMethod === "get" ? ` const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')
860
-
861
- if (!this.cache) {
862
- return SdkCache.withoutCache(res)
863
- }
864
- const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
865
- return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? ` return Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')` : ""}
866
- }
867
- `;
868
- if (!isGuardInvoked) {
869
- methodImpl = `${descriptionText}
870
- ${deprecateTag}
871
- TODO_${classMethod}(${methodParams}): Promise<AxiosResponse<${resolvedResponseClass}>> {
872
- ${queryParamsDefault}
873
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
874
- return this.axiosInstance.${httpMethod}(url, ${dataPayload})
875
- }
876
- `;
877
- }
878
- const res = {
879
- methodImpl,
880
- methodParams,
881
- methodParamsNoTypes,
882
- importStatements
883
- };
884
- return res;
885
- };
886
-
887
688
  class TemplateZod {
888
689
  duplicates;
889
690
  duplicateFound = false;
@@ -1136,6 +937,227 @@ const extractEnumObject = (type, isRequired, enumArr) => {
1136
937
  };
1137
938
  };
1138
939
 
940
+ const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
941
+ let imports = "";
942
+ let returnStatement = "";
943
+ for (const cl of apiList) {
944
+ imports += `
945
+ import { ${cl} } from './${serviceName}/${cl}.js'`;
946
+ returnStatement += `
947
+ ${cl}, `;
948
+ }
949
+ return `/**
950
+ * AUTO GENERATED
951
+ */
952
+ ${imports}
953
+
954
+ const apis = {
955
+ ${returnStatement}
956
+ }
957
+
958
+ export const ${ParserUtils.convertDashesToTitleCase(serviceNameTitle)} = apis
959
+ `;
960
+ };
961
+
962
+ const Schema = zod.z.object({
963
+ $ref: zod.z.string().nullish(),
964
+ type: zod.z.union([zod.z.literal("array"), zod.z.literal("object"), zod.z.literal("file"), zod.z.literal("string"), zod.z.literal("boolean"), zod.z.literal("integer")]).nullish(),
965
+ items: zod.z.object({
966
+ $ref: zod.z.string().nullish(),
967
+ type: zod.z.string().nullish()
968
+ }).nullish(),
969
+ properties: zod.z.union([zod.z.array(zod.z.string()).nullish(), zod.z.record(zod.z.object({ type: zod.z.string() })).nullish()]),
970
+ description: zod.z.string().nullish(),
971
+ additionalProperties: zod.z.object({
972
+ type: zod.z.string().nullish()
973
+ }).nullish()
974
+ });
975
+ const Definition = zod.z.object({
976
+ required: zod.z.array(zod.z.string()).nullish(),
977
+ properties: zod.z.record(zod.z.object({
978
+ type: zod.z.string()
979
+ })).nullish()
980
+ });
981
+ const Definitions = zod.z.record(Definition);
982
+ const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
983
+ const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
984
+ const EndpointParameters = zod.z.object({
985
+ type: EndpointParametersType.nullish(),
986
+ description: zod.z.string().nullish(),
987
+ name: zod.z.string(),
988
+ in: EndpointParametersIn,
989
+ required: zod.z.boolean().nullish(),
990
+ schema: Schema.nullish(),
991
+ default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
992
+ enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
993
+ items: zod.z.object({
994
+ type: zod.z.string(),
995
+ enum: zod.z.array(zod.z.any()).nullish()
996
+ }).nullish()
997
+ });
998
+ const Endpoint = zod.z.object({
999
+ description: zod.z.string().nullish(),
1000
+ consumes: zod.z.array(zod.z.string()).nullish(),
1001
+ produces: zod.z.array(zod.z.string()).nullish(),
1002
+ tags: zod.z.array(zod.z.string()).nullish(),
1003
+ summary: zod.z.string().nullish(),
1004
+ operationId: zod.z.string(),
1005
+ deprecated: zod.z.boolean().nullish(),
1006
+ responses: zod.z.record(zod.z.object({
1007
+ description: zod.z.string().nullish(),
1008
+ schema: Schema.nullish(),
1009
+ content: zod.z.object({
1010
+ "application/json": zod.z.object({
1011
+ schema: Schema.nullish()
1012
+ })
1013
+ }).nullish()
1014
+ })),
1015
+ parameters: zod.z.array(EndpointParameters).nullish(),
1016
+ requestBody: zod.z.object({
1017
+ required: zod.z.boolean(),
1018
+ content: zod.z.object({
1019
+ "application/json": zod.z.object({
1020
+ schema: Schema.nullish()
1021
+ })
1022
+ }).nullish()
1023
+ }).nullish()
1024
+ });
1025
+ const Operation = zod.z.object({
1026
+ get: Endpoint.nullish(),
1027
+ post: Endpoint.nullish(),
1028
+ patch: Endpoint.nullish(),
1029
+ delete: Endpoint.nullish(),
1030
+ put: Endpoint.nullish()
1031
+ });
1032
+ const Paths = zod.z.record(Operation);
1033
+ zod.z.object({
1034
+ paths: Paths,
1035
+ definitions: Definitions,
1036
+ basePath: zod.z.string(),
1037
+ info: zod.z.object({
1038
+ description: zod.z.string(),
1039
+ title: zod.z.string(),
1040
+ contact: zod.z.object({
1041
+ name: zod.z.string(),
1042
+ url: zod.z.string(),
1043
+ email: zod.z.string()
1044
+ }),
1045
+ version: zod.z.string()
1046
+ }),
1047
+ schemes: zod.z.array(zod.z.string()).nullish(),
1048
+ components: zod.z.object({
1049
+ schemas: Definitions
1050
+ }).nullish()
1051
+ });
1052
+
1053
+ const templateMethod = ({
1054
+ classMethod,
1055
+ description,
1056
+ httpMethod,
1057
+ path,
1058
+ pathParams,
1059
+ bodyParams,
1060
+ queryParams,
1061
+ isFormUrlEncoded,
1062
+ responseClass
1063
+ }) => {
1064
+ let methodParams = "";
1065
+ let methodParamsNoTypes = "";
1066
+ let newPath = `'${path}'`;
1067
+ let importStatements = [];
1068
+ const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
1069
+ for (const pathParam of sortedPathParams) {
1070
+ const type = ParserUtils.parseType(pathParam);
1071
+ if (pathParam.name !== "namespace") {
1072
+ methodParams += pathParam.name + `:${type}, `;
1073
+ methodParamsNoTypes += pathParam.name + ", ";
1074
+ }
1075
+ const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1076
+ if (path.match(`{${pathParam.name}}`)) {
1077
+ if (type === "string") {
1078
+ newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
1079
+ } else {
1080
+ newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
1081
+ }
1082
+ }
1083
+ }
1084
+ let dataType = null;
1085
+ if (httpMethod !== "get") {
1086
+ dataType = ParserUtils.parseBodyParamsType(bodyParams);
1087
+ importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
1088
+ methodParams += dataType ? `data: ${dataType},` : "";
1089
+ methodParamsNoTypes += dataType ? `data,` : "";
1090
+ }
1091
+ const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
1092
+ const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
1093
+ const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
1094
+ const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
1095
+ const isDelete = ["delete"].includes(httpMethod);
1096
+ let dataPayload = "{params}";
1097
+ const descriptionText = description ? `
1098
+ /**
1099
+ * ${description.replace(/\n/g, "\n * ")}
1100
+ */` : "";
1101
+ let formPayloadString = "";
1102
+ if (isFormUrlEncoded) {
1103
+ formPayloadString = ``;
1104
+ const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
1105
+ dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
1106
+ } else if (isPostPutPatch) {
1107
+ dataPayload = dataType ? `data, {params}` : "null, {params}";
1108
+ } else if (isDelete) {
1109
+ dataPayload = dataType ? `{data, params}` : "{params}";
1110
+ }
1111
+ const isFileUpload = methodParams.indexOf("data: {file") > -1;
1112
+ const resolvedResponseClass = responseClass || "unknown";
1113
+ const resolvedResponseClassValidated = responseClass || "z.unknown()";
1114
+ methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
1115
+ methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
1116
+ let methodImpl = "";
1117
+ const isCacheFetch = ["get"].includes(httpMethod) && resolvedResponseClass !== "unknown";
1118
+ const cachedFetchMethod = classMethod;
1119
+ const deprecateTag = isCacheFetch ? `/**
1120
+ * @deprecated Use "${classMethod}()" instead.
1121
+ */` : "";
1122
+ const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
1123
+ const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
1124
+ const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1125
+ const generateMethodName = () => `${methodName}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
1126
+ const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
1127
+ methodImpl = `${descriptionText}
1128
+ ${generateMethodName()} {
1129
+ ${queryParamsDefault}
1130
+ const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1131
+ const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
1132
+
1133
+ ${httpMethod === "get" ? ` const res = () => Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')
1134
+
1135
+ if (!this.cache) {
1136
+ return SdkCache.withoutCache(res)
1137
+ }
1138
+ const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
1139
+ return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? ` return Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')` : ""}
1140
+ }
1141
+ `;
1142
+ if (!isGuardInvoked) {
1143
+ methodImpl = `${descriptionText}
1144
+ ${deprecateTag}
1145
+ TODO_${classMethod}(${methodParams}): Promise<AxiosResponse<${resolvedResponseClass}>> {
1146
+ ${queryParamsDefault}
1147
+ const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1148
+ return this.axiosInstance.${httpMethod}(url, ${dataPayload})
1149
+ }
1150
+ `;
1151
+ }
1152
+ const res = {
1153
+ methodImpl,
1154
+ methodParams,
1155
+ methodParamsNoTypes,
1156
+ importStatements
1157
+ };
1158
+ return res;
1159
+ };
1160
+
1139
1161
  const templateApiMethod = ({
1140
1162
  classMethod,
1141
1163
  description,
@@ -1197,28 +1219,6 @@ const templateApiMethod = ({
1197
1219
  return [methodImpl, snippetSdk, snippetShell];
1198
1220
  };
1199
1221
 
1200
- const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
1201
- let imports = "";
1202
- let returnStatement = "";
1203
- for (const cl of apiList) {
1204
- imports += `
1205
- import { ${cl} } from './${serviceName}/${cl}.js'`;
1206
- returnStatement += `
1207
- ${cl}, `;
1208
- }
1209
- return `/**
1210
- * AUTO GENERATED
1211
- */
1212
- ${imports}
1213
-
1214
- const apis = {
1215
- ${returnStatement}
1216
- }
1217
-
1218
- export const ${ParserUtils.convertDashesToTitleCase(serviceNameTitle)} = apis
1219
- `;
1220
- };
1221
-
1222
1222
  const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1223
1223
  const methodArr = methodSnippet.split("//");
1224
1224
  let normMethod = normalizeMethodSnippet(methodArr[0].trim(), "data:");
@@ -1258,21 +1258,33 @@ const normalizeMethodSnippet = (methodInput, splitWord) => {
1258
1258
  };
1259
1259
 
1260
1260
  const GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
1261
- class CodeGenerator {
1262
- static getPatchedDir = () => path.join(CliParser.getSwaggersOutputPath(), "patched");
1263
- static getGeneratedPublicFolder = () => `${CliParser.getOutputPath()}/generated-public`;
1264
- static getGeneratedAdminFolder = () => `${CliParser.getOutputPath()}/generated-admin`;
1265
- static getGeneratedSnippetsFolder = () => `${CliParser.getSnippetOutputPath()}/generated-snippets`;
1261
+ class SwaggerReaderHelpers {
1266
1262
  static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
1267
- static iterateApi = async (api, serviceName) => {
1268
- const apiBufferByTag = {};
1269
- const apiArgumentsByTag = {};
1270
- const classBufferByTag = {};
1271
- const dependenciesByTag = {};
1272
- const classImports = {};
1273
- let arrayDefinitions = [];
1274
- const snippetMap = {};
1275
- const mapClassMethods = {};
1263
+ static parseAllEndpoints = async ({
1264
+ api,
1265
+ sdkName,
1266
+ serviceName
1267
+ }) => {
1268
+ const result = {
1269
+ admin: {
1270
+ arrayDefinitions: [],
1271
+ snippetMap: {},
1272
+ tagToClassImportsRecord: {},
1273
+ tagToEndpointClassesRecord: {},
1274
+ tagToSdkClientRecord: {},
1275
+ tagToSdkFunctionNamesRecord: {},
1276
+ tagToSdkImportsRecord: {}
1277
+ },
1278
+ public: {
1279
+ arrayDefinitions: [],
1280
+ snippetMap: {},
1281
+ tagToClassImportsRecord: {},
1282
+ tagToEndpointClassesRecord: {},
1283
+ tagToSdkClientRecord: {},
1284
+ tagToSdkFunctionNamesRecord: {},
1285
+ tagToSdkImportsRecord: {}
1286
+ }
1287
+ };
1276
1288
  const sortedPathsByLength = new Map(Object.entries(api.paths).sort((a, b) => {
1277
1289
  if (a[0].length === b[0].length) {
1278
1290
  return a[0].localeCompare(b[0]);
@@ -1281,55 +1293,62 @@ class CodeGenerator {
1281
1293
  }
1282
1294
  }));
1283
1295
  const sortedKeys = Array.from(sortedPathsByLength.keys());
1284
- const servicePrefix = CodeGenerator.getServicePrefix(sortedKeys);
1285
- for (const [path2, operation] of sortedPathsByLength) {
1286
- const isAdminEndpoint = path2.indexOf("/admin/") > -1;
1287
- if (CliParser.isAdmin() && !isAdminEndpoint) {
1288
- continue;
1289
- } else if (!CliParser.isAdmin() && isAdminEndpoint) {
1290
- continue;
1291
- } else if (path2.indexOf("/healthz") >= 0) {
1296
+ const servicePrefix = SwaggerReaderHelpers.getServicePrefix(sortedKeys);
1297
+ const tagToClassMethodsMap = {
1298
+ admin: {},
1299
+ public: {}
1300
+ };
1301
+ for (const [path, operation] of sortedPathsByLength) {
1302
+ if (path.indexOf("/healthz") >= 0) {
1292
1303
  continue;
1293
1304
  }
1305
+ const isAdminEndpoint = path.indexOf("/admin/") > -1;
1306
+ const picked = isAdminEndpoint ? result.admin : result.public;
1307
+ const {
1308
+ arrayDefinitions,
1309
+ snippetMap,
1310
+ tagToClassImportsRecord,
1311
+ tagToEndpointClassesRecord,
1312
+ tagToSdkClientRecord,
1313
+ tagToSdkFunctionNamesRecord,
1314
+ tagToSdkImportsRecord
1315
+ } = picked;
1316
+ const tagToClassMethodsMapByType = isAdminEndpoint ? tagToClassMethodsMap.admin : tagToClassMethodsMap.public;
1294
1317
  const httpMethods = Object.keys(operation);
1295
1318
  for (const httpMethod of httpMethods) {
1296
1319
  const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
1297
- console.error(JSON.stringify({ path: path2, httpMethod }, null, 2));
1320
+ console.error(JSON.stringify({ path, httpMethod }, null, 2));
1298
1321
  throw error;
1299
1322
  });
1300
- if (!endpoint.tags) {
1301
- continue;
1302
- }
1303
- if (endpoint.deprecated) {
1323
+ if (!endpoint.tags || endpoint.deprecated)
1304
1324
  continue;
1305
- }
1306
1325
  const [tag] = endpoint.tags;
1307
- mapClassMethods[tag] = mapClassMethods[tag] ? mapClassMethods[tag] : {};
1326
+ const pathWithBase = `${api.basePath ?? ""}${path}`;
1327
+ tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
1308
1328
  const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
1309
1329
  const classMethod = ParserUtils.generateNaturalLangMethod({
1310
1330
  servicePrefix,
1311
- path: path2,
1331
+ path,
1312
1332
  httpMethod,
1313
1333
  isForm,
1314
- existingMethods: mapClassMethods[tag]
1334
+ existingMethods: tagToClassMethodsMapByType[tag]
1315
1335
  });
1316
- mapClassMethods[tag][classMethod] = `${path2} ${httpMethod}`;
1317
- snippetMap[path2] = snippetMap[path2] ? snippetMap[path2] : {};
1318
- let description = endpoint.description;
1319
- description = description || "";
1320
- description = description.replace(/\s+/g, " ");
1336
+ tagToClassMethodsMapByType[tag][classMethod] = `${path} ${httpMethod}`;
1337
+ if (!snippetMap[pathWithBase]) {
1338
+ snippetMap[pathWithBase] = {};
1339
+ }
1340
+ const description = endpoint.description?.replace(/\s+/g, " ") || "";
1321
1341
  const responseClass = ParserUtils.get2xxResponse(endpoint.responses);
1322
- const { className, classGenName } = ParserUtils.generateClassName(tag);
1323
- classImports[className] = classImports[className] ? classImports[className] : {};
1342
+ const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
1343
+ tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
1324
1344
  if (responseClass) {
1325
1345
  const importTypeClass = ParserUtils.parseRefType(responseClass);
1326
- classImports[className][importTypeClass] = `import { ${importTypeClass} } from '../definitions/${importTypeClass}.js'`;
1346
+ tagToClassImportsRecord[className][importTypeClass] = `import { ${importTypeClass} } from '../definitions/${importTypeClass}.js'`;
1327
1347
  }
1328
1348
  if (responseClass && responseClass.endsWith("Array")) {
1329
1349
  arrayDefinitions.push(responseClass);
1330
1350
  }
1331
1351
  const queryParams = ParserUtils.filterQueryParameters(endpoint.parameters);
1332
- const pathWithBase = `${api.basePath ?? ""}${path2}`;
1333
1352
  const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
1334
1353
  const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
1335
1354
  let bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
@@ -1353,8 +1372,8 @@ class CodeGenerator {
1353
1372
  isFormUrlEncoded,
1354
1373
  responseClass
1355
1374
  });
1356
- classBufferByTag[tag] = (classBufferByTag[tag] || "") + methodImpl;
1357
- const [generatedMethodString1, snippetMethod, snippetShell] = templateApiMethod({
1375
+ tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
1376
+ const [generatedMethodString, snippetMethod, snippetShell] = templateApiMethod({
1358
1377
  classMethod,
1359
1378
  description,
1360
1379
  httpMethod,
@@ -1366,32 +1385,37 @@ class CodeGenerator {
1366
1385
  methodParams,
1367
1386
  methodParamsNoTypes
1368
1387
  });
1369
- apiBufferByTag[tag] = (apiBufferByTag[tag] || "") + generatedMethodString1;
1370
- apiArgumentsByTag[tag] = (apiArgumentsByTag[tag] || "") + classMethod + ",";
1371
- dependenciesByTag[tag] = dependenciesByTag[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...dependenciesByTag[tag]])] : [...new Set(importStatements)];
1388
+ tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
1389
+ tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + classMethod + ",";
1390
+ tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
1372
1391
  const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1373
- const { apiGenName } = ParserUtils.generateApiName(tag);
1392
+ const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1374
1393
  const resultSnippet = templateSdkSnippet(serviceNameTitle, apiGenName, snippetMethod);
1375
- snippetMap[path2][httpMethod] = {
1376
- web: resultSnippet,
1377
- webGit: GIT_URL + `/sdk-${serviceName}/src/generated-public/${serviceName}/${apiGenName}.ts`,
1378
- shell: snippetShell
1379
- };
1394
+ const currentSnippetMap = {};
1395
+ snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
1396
+ if (!isAdminEndpoint) {
1397
+ currentSnippetMap.web = !isAdminEndpoint ? resultSnippet : "";
1398
+ currentSnippetMap.webGit = !isAdminEndpoint ? GIT_URL + `/sdk-${sdkName}/src/generated-public/${serviceName}/${apiGenName}.ts` : "";
1399
+ }
1400
+ currentSnippetMap.shell = snippetShell;
1380
1401
  }
1381
1402
  }
1382
- arrayDefinitions = [...new Set(arrayDefinitions)];
1383
- return {
1384
- apiArgumentsByTag,
1385
- apiBufferByTag,
1386
- classBufferByTag,
1387
- dependenciesByTag,
1388
- classImports,
1389
- arrayDefinitions,
1390
- snippetMap
1391
- };
1403
+ for (const key in result) {
1404
+ result[key].arrayDefinitions = Array.from(new Set(result[key].arrayDefinitions));
1405
+ }
1406
+ return result;
1392
1407
  };
1408
+ }
1409
+
1410
+ class CodeGenerator {
1411
+ static getPatchedDir = () => path.join(CliParser.getSwaggersOutputPath(), "patched");
1412
+ static getGeneratedPublicFolder = () => `${CliParser.getOutputPath()}/generated-public`;
1413
+ static getGeneratedAdminFolder = () => `${CliParser.getOutputPath()}/generated-admin`;
1414
+ static getGeneratedSnippetsFolder = () => `${CliParser.getSnippetOutputPath()}/generated-snippets`;
1415
+ static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
1393
1416
  static main = async (nameArray) => {
1394
1417
  const serviceName = nameArray[0];
1418
+ const sdkName = nameArray[1];
1395
1419
  const swaggerFile = nameArray[2];
1396
1420
  const parser = new SwaggerParser();
1397
1421
  const generatedFolder = CliParser.isAdmin() ? CodeGenerator.getGeneratedAdminFolder() : CodeGenerator.getGeneratedPublicFolder();
@@ -1407,26 +1431,38 @@ class CodeGenerator {
1407
1431
  ParserUtils.mkdirIfNotExist(DIST_DEFINITION_DIR);
1408
1432
  ParserUtils.mkdirIfNotExist(DIST_ENDPOINTS_DIR);
1409
1433
  ParserUtils.syncPackageVersion(apiInfo, CliParser.skipVersionSync(), process.env.PRERELEASE_ID);
1410
- const { apiArgumentsByTag, apiBufferByTag, classBufferByTag, dependenciesByTag, classImports, arrayDefinitions, snippetMap } = await CodeGenerator.iterateApi(api, serviceName);
1434
+ const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
1435
+ const parsedInformationByType = CliParser.isAdmin() ? parsedInformation.admin : parsedInformation.public;
1436
+ const {
1437
+ arrayDefinitions,
1438
+ tagToClassImportsRecord,
1439
+ tagToEndpointClassesRecord,
1440
+ tagToSdkClientRecord,
1441
+ tagToSdkFunctionNamesRecord,
1442
+ tagToSdkImportsRecord
1443
+ } = parsedInformationByType;
1411
1444
  if (CliParser.getSnippetOutputPath()) {
1412
1445
  try {
1413
- ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify(snippetMap, null, 2));
1446
+ ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify({
1447
+ ...parsedInformation.public.snippetMap,
1448
+ ...parsedInformation.admin.snippetMap
1449
+ }, null, 2));
1414
1450
  } catch (err) {
1415
1451
  console.log("Generating snippets", err);
1416
1452
  }
1417
1453
  }
1418
1454
  const targetSrcFolder = `${CliParser.getOutputPath()}/`;
1419
1455
  const apiList = [];
1420
- for (const tag in classBufferByTag) {
1421
- const { className, classGenName } = ParserUtils.generateClassName(tag);
1422
- const classBuffer = classBufferByTag[tag];
1423
- const imports = [.../* @__PURE__ */ new Set([...dependenciesByTag[tag], ...Object.values(classImports[className])])];
1424
- const apiImports = [.../* @__PURE__ */ new Set([...dependenciesByTag[tag], ...Object.values(classImports[className])])];
1456
+ for (const tag in tagToEndpointClassesRecord) {
1457
+ const { className, classGenName } = ParserUtils.generateClassName(tag, CliParser.isAdmin());
1458
+ const classBuffer = tagToEndpointClassesRecord[tag];
1459
+ const imports = [.../* @__PURE__ */ new Set([...tagToSdkImportsRecord[tag], ...Object.values(tagToClassImportsRecord[className])])];
1460
+ const apiImports = [.../* @__PURE__ */ new Set([...tagToSdkImportsRecord[tag], ...Object.values(tagToClassImportsRecord[className])])];
1425
1461
  apiImports.push(`import { ${classGenName} } from './endpoints/${classGenName}.js'`);
1426
1462
  ParserUtils.writeClassFile(DIST_ENDPOINTS_DIR, classGenName, classBuffer, imports);
1427
- const apiBuffer = apiBufferByTag[tag];
1428
- const { apiGenName } = ParserUtils.generateApiName(tag);
1429
- ParserUtils.writeApiFile(DIST_DIR, apiGenName, apiBuffer, apiImports, apiArgumentsByTag[tag]);
1463
+ const apiBuffer = tagToSdkClientRecord[tag];
1464
+ const { apiGenName } = ParserUtils.generateApiName(tag, CliParser.isAdmin());
1465
+ ParserUtils.writeApiFile(DIST_DIR, apiGenName, apiBuffer, apiImports, tagToSdkFunctionNamesRecord[tag]);
1430
1466
  apiList.push(apiGenName);
1431
1467
  indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_ENDPOINTS_DIR, `${classGenName}`), targetSrcFolder));
1432
1468
  indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DIR, `${apiGenName}`), targetSrcFolder));