@accelbyte/codegen 2.2.1 → 3.0.3

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/.eslintrc.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "plugins": ["unused-imports"],
3
+ "rules": {
4
+ "unused-imports/no-unused-imports": "error"
5
+ }
6
+ }
@@ -81,7 +81,7 @@ class CliParser {
81
81
  }
82
82
 
83
83
  const getImportableVarMap$1 = () => ({
84
- "@accelbyte/sdk": ["CodeGenUtil", "SdkCache", "IResponse", "IResponseWithSync", "Validate"],
84
+ "@accelbyte/sdk": ["CodeGenUtil", "IResponse", "Validate"],
85
85
  axios: ["AxiosRequestConfig", "AxiosResponse"],
86
86
  zod: ["z"]
87
87
  });
@@ -114,14 +114,14 @@ ${generateImports(body, importStatements, makeNewImportVarMap$1(), getImportable
114
114
 
115
115
  export class ${className} {
116
116
  // @ts-ignore
117
- constructor(private axiosInstance: AxiosInstance, private namespace: string, private cache = false, private isValidationEnabled = true) {}
117
+ constructor(private axiosInstance: AxiosInstance, private namespace: string, private isValidationEnabled = true) {}
118
118
  ${body}
119
119
  }
120
120
  `;
121
121
  };
122
122
 
123
123
  const getImportableVarMap = () => ({
124
- "@accelbyte/sdk": ["CodeGenUtil", "SdkCache", "IResponse", "IResponseWithSync", "Validate", "ApiArgs", "Network", "AccelbyteSDK"]
124
+ "@accelbyte/sdk": ["CodeGenUtil", "IResponse", "Validate", "ApiArgs", "Network", "AccelbyteSDK"]
125
125
  });
126
126
  const makeNewImportVarMap = () => ({
127
127
  "@accelbyte/sdk": ["AccelbyteSDK", "ApiArgs", "ApiUtils"]
@@ -137,7 +137,6 @@ export function ${className}(sdk: AccelbyteSDK, args?: ApiArgs) {
137
137
  const sdkAssembly = sdk.assembly()
138
138
 
139
139
  const namespace = args?.namespace ? args?.namespace : sdkAssembly.namespace
140
- const cache = args?.cache ? args?.cache : sdkAssembly.cache
141
140
  const requestConfig = ApiUtils.mergedConfigs(sdkAssembly.config, args)
142
141
  const isValidationEnabled = args?.isValidationEnabled !== false
143
142
  ${body}
@@ -941,7 +940,7 @@ const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
941
940
  let imports = "";
942
941
  let returnStatement = "";
943
942
  for (const cl of apiList) {
944
- const dir = cl.toLowerCase().includes("admin") ? "generated-admin" : "generated-public";
943
+ const dir = cl.toLowerCase().includes("admin") && cl !== "AdminApi" ? "generated-admin" : "generated-public";
945
944
  imports += `
946
945
  import { ${cl} } from './${dir}/${cl}.js'`;
947
946
  returnStatement += `
@@ -1021,7 +1020,8 @@ const Endpoint = zod.z.object({
1021
1020
  schema: Schema.nullish()
1022
1021
  })
1023
1022
  }).nullish()
1024
- }).nullish()
1023
+ }).nullish(),
1024
+ "x-security": zod.z.any().nullish()
1025
1025
  });
1026
1026
  const Operation = zod.z.object({
1027
1027
  get: Endpoint.nullish(),
@@ -1117,28 +1117,20 @@ const templateMethod = ({
1117
1117
  methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
1118
1118
  let methodImpl = "";
1119
1119
  const isCacheFetch = ["get"].includes(httpMethod) && resolvedResponseClass !== "unknown";
1120
- const cachedFetchMethod = classMethod;
1121
1120
  const deprecateTag = isCacheFetch ? `/**
1122
1121
  * @deprecated Use "${classMethod}()" instead.
1123
1122
  */` : "";
1124
1123
  const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
1125
- const methodName = httpMethod === "get" ? cachedFetchMethod : ["post", "put", "patch", "delete"].includes(httpMethod) ? classMethod : "";
1126
1124
  const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1127
- const generateMethodName = () => `${methodName}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
1128
- const responseSyncType = httpMethod === "get" ? "IResponseWithSync" : ["post", "put", "patch", "delete"].includes(httpMethod) ? "IResponse" : "";
1125
+ const generateMethodName = () => `${classMethod}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
1126
+ const responseSyncType = "IResponse";
1129
1127
  methodImpl = `${descriptionText}
1130
1128
  ${generateMethodName()} {
1131
1129
  ${queryParamsDefault}
1132
1130
  const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1133
1131
  const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
1134
1132
 
1135
- ${httpMethod === "get" ? ` const res = () => this.isValidationEnabled ? Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}') : Validate.unsafeResponse(() => resultPromise)
1136
-
1137
- if (!this.cache) {
1138
- return SdkCache.withoutCache(res)
1139
- }
1140
- const cacheKey = url + CodeGenUtil.hashCode(JSON.stringify({ params }))
1141
- return SdkCache.withCache(cacheKey, res)` : ""}${["post", "put", "patch", "delete"].includes(httpMethod) ? ` return this.isValidationEnabled ? Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}') : Validate.unsafeResponse(() => resultPromise)` : ""}
1133
+ ${` return this.isValidationEnabled ? Validate.responseType(() => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}') : Validate.unsafeResponse(() => resultPromise)`}
1142
1134
  }
1143
1135
  `;
1144
1136
  if (!isGuardInvoked) {
@@ -1171,17 +1163,13 @@ const templateApiMethod = ({
1171
1163
  classGenName,
1172
1164
  methodParams,
1173
1165
  methodParamsNoTypes,
1174
- deprecated
1166
+ deprecated,
1167
+ xSecurity
1175
1168
  }) => {
1176
- let methodSignature = "";
1177
1169
  let newPath = `'${path}'`;
1178
- let snippetSdk = "";
1179
- let snippetShell = "";
1170
+ let snippetMethod = "";
1180
1171
  for (const pathParam of pathParams) {
1181
1172
  const type = ParserUtils.parseType(pathParam);
1182
- if (pathParam.name !== "namespace") {
1183
- methodSignature += pathParam.name + `:${type}, `;
1184
- }
1185
1173
  const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1186
1174
  if (path.match(`{${pathParam.name}}`)) {
1187
1175
  if (type === "string") {
@@ -1191,16 +1179,21 @@ const templateApiMethod = ({
1191
1179
  }
1192
1180
  }
1193
1181
  }
1194
- snippetShell = `curl --location --request \\
1195
- ${httpMethod} '__DOMAIN__${path}' \\
1196
- --header 'accept: application/json'`;
1182
+ const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path}'`, "--header 'accept: application/json'"];
1183
+ const snippetApiArgs = [];
1184
+ if (xSecurity !== void 0 || path.includes("/admin")) {
1185
+ snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
1186
+ snippetApiArgs.push("{ config: { headers: { Authorization: 'Bearer {access_token}' } }}".trim());
1187
+ }
1197
1188
  if (httpMethod !== "get") {
1198
1189
  const curlParams = bodyParams?.map((ob) => {
1199
1190
  return ` "${ob.name}": ""`;
1200
1191
  });
1201
- snippetShell += ` \\
1202
- --data-raw '{ ${curlParams}}'`;
1192
+ if (curlParams.length > 0) {
1193
+ snippetShellArgs.push(`--data-raw '{ ${curlParams}}'`);
1194
+ }
1203
1195
  }
1196
+ const snippetShell = `curl ${snippetShellArgs.join(" \\\n ")}`;
1204
1197
  const descriptionText = description ? `
1205
1198
  /**${deprecated ? "\n * @deprecated" : ""}
1206
1199
  * ${description.replace(/\n/g, "\n * ")}
@@ -1210,20 +1203,31 @@ const templateApiMethod = ({
1210
1203
  const methodImpl = `
1211
1204
  ${descriptionText}
1212
1205
  async function ${classMethod}(${methodParams}): Promise<${responseType}> {
1213
- const $ = new ${classGenName}(Network.create(requestConfig), namespace, cache, isValidationEnabled)
1206
+ const $ = new ${classGenName}(Network.create(requestConfig), namespace, isValidationEnabled)
1214
1207
  const resp = await $.${classMethod}(${methodParamsNoTypes})
1215
1208
  if (resp.error) throw resp.error
1216
1209
  return resp.response.data
1217
1210
  }
1218
1211
  `;
1219
1212
  const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
1220
- snippetSdk += `${classMethod}(${methodParams})
1213
+ snippetMethod += `${classMethod}(${methodParams})
1221
1214
  // return ${snippetPromiseString}`;
1222
- return [methodImpl, snippetSdk, snippetShell];
1215
+ return {
1216
+ generatedMethodString: methodImpl,
1217
+ snippetApiArgs,
1218
+ snippetMethod,
1219
+ snippetShell
1220
+ };
1223
1221
  };
1224
1222
 
1225
- const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1226
- const methodArr = methodSnippet.split("//");
1223
+ const templateSdkSnippet = ({
1224
+ serviceNameTitle,
1225
+ apiName,
1226
+ snippetMethod,
1227
+ snippetApiArgs: snippetApiArgsParam
1228
+ }) => {
1229
+ const methodArr = snippetMethod.split("//");
1230
+ const snippetApiArgs = ["sdk", ...snippetApiArgsParam];
1227
1231
  let normMethod = normalizeMethodSnippet(methodArr[0].trim(), "data:");
1228
1232
  normMethod = normalizeMethodSnippet(normMethod, "queryParams:");
1229
1233
  normMethod = normalizeMethodSnippet(normMethod, "queryParams?:");
@@ -1232,14 +1236,16 @@ const templateSdkSnippet = (serviceNameTitle, apiName, methodSnippet) => {
1232
1236
  import { ${serviceNameTitle} } from '@accelbyte/sdk-${serviceNameTitle.toLowerCase()}'
1233
1237
 
1234
1238
  const sdk = Accelbyte.SDK({
1239
+ options: {
1235
1240
  baseURL: 'https://demo.accelbyte.io',
1236
1241
  clientId: '77f88506b6174c3ea4d925f5b4096ce8',
1237
1242
  namespace: 'accelbyte',
1238
1243
  redirectURI: 'http://localhost:3030'
1244
+ }
1239
1245
  })
1240
1246
 
1241
- ${serviceNameTitle}.${apiName}(sdk)
1242
- .${normMethod}`;
1247
+ ${serviceNameTitle}.${apiName}(${snippetApiArgs.join(", ")})
1248
+ .${normMethod}`;
1243
1249
  return sdkSnippet;
1244
1250
  };
1245
1251
  const normalizeMethodSnippet = (methodInput, splitWord) => {
@@ -1378,7 +1384,7 @@ class SwaggerReaderHelpers {
1378
1384
  deprecated
1379
1385
  });
1380
1386
  tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
1381
- const [generatedMethodString, snippetMethod, snippetShell] = templateApiMethod({
1387
+ const { generatedMethodString, snippetApiArgs, snippetMethod, snippetShell } = templateApiMethod({
1382
1388
  classMethod,
1383
1389
  description,
1384
1390
  httpMethod,
@@ -1389,14 +1395,15 @@ class SwaggerReaderHelpers {
1389
1395
  classGenName,
1390
1396
  methodParams,
1391
1397
  methodParamsNoTypes,
1392
- deprecated
1398
+ deprecated,
1399
+ xSecurity: endpoint["x-security"]
1393
1400
  });
1394
1401
  tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
1395
1402
  tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + classMethod + ",";
1396
1403
  tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
1397
1404
  const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1398
1405
  const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1399
- const resultSnippet = templateSdkSnippet(serviceNameTitle, apiGenName, snippetMethod);
1406
+ const resultSnippet = templateSdkSnippet({ serviceNameTitle, apiName: apiGenName, snippetMethod, snippetApiArgs });
1400
1407
  const currentSnippetMap = {};
1401
1408
  snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
1402
1409
  currentSnippetMap.web = resultSnippet;