@accelbyte/codegen 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,97 +1,180 @@
1
1
  #!/usr/bin/env node
2
-
3
- 'use strict';
4
-
5
- var yargs = require('yargs');
6
- var zod = require('zod');
7
- var fs = require('fs');
8
- var path = require('path');
9
- var SwaggerParser = require('@apidevtools/swagger-parser');
10
- var fastJsonPatch = require('fast-json-patch');
11
- var _ = require('lodash');
12
- var semver = require('semver');
13
- var https = require('https');
14
-
15
- function _interopNamespaceDefault(e) {
16
- var n = Object.create(null);
17
- if (e) {
18
- Object.keys(e).forEach(function (k) {
19
- if (k !== 'default') {
20
- var d = Object.getOwnPropertyDescriptor(e, k);
21
- Object.defineProperty(n, k, d.get ? d : {
22
- enumerable: true,
23
- get: function () { return e[k]; }
24
- });
25
- }
26
- });
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
13
  }
28
- n.default = e;
29
- return Object.freeze(n);
30
- }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
31
24
 
32
- var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
33
- var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
34
- var https__namespace = /*#__PURE__*/_interopNamespaceDefault(https);
25
+ // src/cli.ts
26
+ var import_yargs = __toESM(require("yargs"));
27
+ var import_path4 = __toESM(require("path"));
35
28
 
36
- const SwaggersConfig = zod.z.array(zod.z.array(zod.z.string()));
37
- class CliParser {
29
+ // src/CliParser.ts
30
+ var import_fs = __toESM(require("fs"));
31
+ var path = __toESM(require("path"));
32
+ var import_zod = require("zod");
33
+ var SwaggersConfig = import_zod.z.array(import_zod.z.array(import_zod.z.string()));
34
+ var CliParser = class _CliParser {
38
35
  static _instance;
39
36
  argv;
40
- constructor(yargs) {
41
- this.argv = yargs.parse();
37
+ constructor(yargs2) {
38
+ this.argv = yargs2.parse();
42
39
  }
43
- static createInstance = (yargs) => {
44
- CliParser._instance = new CliParser(yargs);
45
- return CliParser._instance;
40
+ static createInstance = (yargs2) => {
41
+ _CliParser._instance = new _CliParser(yargs2);
42
+ return _CliParser._instance;
46
43
  };
47
- static instance = (yargs) => {
48
- if (!CliParser._instance && yargs) {
49
- return CliParser.createInstance(yargs);
44
+ static instance = (yargs2) => {
45
+ if (!_CliParser._instance && yargs2) {
46
+ return _CliParser.createInstance(yargs2);
50
47
  }
51
- return CliParser._instance;
48
+ return _CliParser._instance;
52
49
  };
53
50
  static getConfigPath = () => {
54
- return CliParser.instance().argv.config;
51
+ return _CliParser.instance().argv.config;
55
52
  };
56
53
  static getConfigFile = () => {
57
- const configPath = CliParser.getConfigPath();
58
- if (!configPath)
59
- throw new Error("Missing config file");
60
- const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
54
+ const configPath = _CliParser.getConfigPath();
55
+ if (!configPath) throw new Error("Missing config file");
56
+ const config = JSON.parse(import_fs.default.readFileSync(configPath, "utf8"));
61
57
  if (!SwaggersConfig.safeParse(config).success) {
62
58
  throw new Error("Wrong config file format");
63
59
  }
64
60
  return config;
65
61
  };
66
62
  static getOutputPath = () => {
67
- return CliParser.instance().argv.output;
63
+ return _CliParser.instance().argv.output;
68
64
  };
69
65
  static getSwaggersOutputPath = () => {
70
- return CliParser.instance().argv.swaggersOutput;
66
+ return _CliParser.instance().argv.swaggersOutput;
71
67
  };
72
68
  static getResolvedSwaggersOutputPath = () => {
73
- return path__namespace.resolve(CliParser.getSwaggersOutputPath());
69
+ return path.resolve(_CliParser.getSwaggersOutputPath());
74
70
  };
75
71
  static getSnippetOutputPath = () => {
76
- return CliParser.instance().argv.snippetOutput;
72
+ return _CliParser.instance().argv.snippetOutput;
77
73
  };
78
- static skipVersionSync = () => {
79
- return CliParser.instance().argv.skipVersionSync;
74
+ static skipReactQuery = () => {
75
+ return _CliParser.instance().argv.skipReactQuery;
80
76
  };
77
+ static isGenerateSnippetOnly = () => {
78
+ return _CliParser.instance().argv.snippetOnly;
79
+ };
80
+ };
81
+
82
+ // src/CodeGenerator.ts
83
+ var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser"));
84
+ var import_fs4 = __toESM(require("fs"));
85
+ var import_path3 = __toESM(require("path"));
86
+
87
+ // src/ParserUtils.ts
88
+ var import_fast_json_patch = require("fast-json-patch");
89
+ var import_fs3 = __toESM(require("fs"));
90
+ var import_lodash = __toESM(require("lodash"));
91
+ var import_path2 = __toESM(require("path"));
92
+
93
+ // src/helpers/utils.ts
94
+ var import_fs2 = __toESM(require("fs"));
95
+ var import_path = __toESM(require("path"));
96
+ var capitalize = (string) => {
97
+ return string.charAt(0).toUpperCase() + string.slice(1);
98
+ };
99
+ function isObject(o) {
100
+ return o instanceof Object && o.constructor === Object;
81
101
  }
102
+ var getPermission = (endpoint) => {
103
+ const xSecurity = endpoint["x-security"];
104
+ let xSecurityPerm = void 0;
105
+ if (Array.isArray(xSecurity)) {
106
+ for (const obj of xSecurity) {
107
+ if (obj?.userPermissions) {
108
+ xSecurityPerm = obj.userPermissions;
109
+ }
110
+ if (obj?.groupPermissions) {
111
+ xSecurityPerm = obj.groupPermissions;
112
+ }
113
+ }
114
+ } else if (isObject(xSecurity)) {
115
+ xSecurityPerm = xSecurity?.userPermission;
116
+ }
117
+ return xSecurityPerm;
118
+ };
119
+ var PermissionRegex = /\[(\w+)\]/;
120
+ var getPermissionType = (permission) => {
121
+ if (!permission) return null;
122
+ if (Array.isArray(permission)) {
123
+ const perm = permission?.[0];
124
+ if (!perm) return null;
125
+ const [_3, type2] = perm?.match(PermissionRegex);
126
+ return type2 || null;
127
+ }
128
+ const [_2, type] = permission?.match(PermissionRegex);
129
+ return type || null;
130
+ };
131
+ var removeAdminPrefix = (name) => name.startsWith("Admin") && name !== "Admin" ? name.replace(/^Admin/, "") : name;
132
+ var escapeComment = (string) => string.replace(/\*\//g, "*\\/").replace(/\n/g, "\n * ");
133
+ var generateJsDoc = ({ indentation = 4, lines }) => {
134
+ const indent = " ".repeat(indentation);
135
+ const formattedLines = lines.filter(Boolean).map((line) => `${indent} * ${line}`).join("\n");
136
+ return `${indent}/**
137
+ ${formattedLines}
138
+ ${indent} */`;
139
+ };
140
+ var extractDescription = (description, options) => {
141
+ const { indentation = 2, responseClasses, other, isDeprecated } = options;
142
+ return description ? generateJsDoc({
143
+ lines: [
144
+ isDeprecated ? "@deprecated" : "",
145
+ escapeComment(description),
146
+ ...responseClasses.length > 1 ? [" ", "#### Response type:", ...responseClasses.map((val) => `- \`${val}\``)] : "",
147
+ ...options?.other ? other : ""
148
+ ],
149
+ indentation
150
+ }) : "";
151
+ };
152
+ var getResponseType = ({
153
+ responseClasses,
154
+ defaultType = "unknown"
155
+ }) => {
156
+ const responseClass = responseClasses.length === 1 ? responseClasses?.[0] : "unknown";
157
+ const responseType = responseClass !== "unknown" ? responseClasses?.[0] : defaultType;
158
+ return {
159
+ responseType,
160
+ responseTypeInAxiosResponse: `Promise<AxiosResponse<${responseType}>>`,
161
+ responseTypeInResponse: `Promise<Response<${responseType}>>`
162
+ };
163
+ };
82
164
 
83
- const getImportableVarMap$1 = () => ({
84
- "@accelbyte/sdk": ["CodeGenUtil", "IResponse", "Validate"],
85
- axios: ["AxiosRequestConfig", "AxiosResponse"],
165
+ // src/templates/template-class.ts
166
+ var getImportableVarMap = () => ({
167
+ "@accelbyte/sdk": ["CodeGenUtil", "Response", "Validate", "SdkSetConfigParam"],
168
+ axios: ["AxiosResponse"],
86
169
  zod: ["z"]
87
170
  });
88
- const makeNewImportVarMap$1 = () => ({
89
- axios: ["AxiosInstance"],
171
+ var makeNewImportVarMap = () => ({
172
+ axios: ["AxiosInstance", "AxiosRequestConfig"],
90
173
  "@accelbyte/sdk": ["SDKRequestConfig"]
91
174
  });
92
- const generateImports$1 = (body, importStatements, makeNewImportVarMap2, getImportableVarMap2) => {
93
- const usedImportVarMap = makeNewImportVarMap2;
94
- const importableVarMap = getImportableVarMap2;
175
+ var generateImports = (body, importStatements, makeNewImportVarMap3, getImportableVarMap3) => {
176
+ const usedImportVarMap = makeNewImportVarMap3;
177
+ const importableVarMap = getImportableVarMap3;
95
178
  for (const [moduleSource, importableVars] of Object.entries(importableVarMap)) {
96
179
  for (const importableVar of importableVars) {
97
180
  const importVarRegex = new RegExp(`(?<![\\d\\w_])${importableVar}(?![\\d\\w_])`);
@@ -106,33 +189,125 @@ const generateImports$1 = (body, importStatements, makeNewImportVarMap2, getImpo
106
189
  return `${generatedImports}
107
190
  ${importStatements.sort().join("\n")}`;
108
191
  };
109
- const templateClass = (className, body, importStatements) => {
192
+ var templateClass = (className, body, importStatements) => {
110
193
  return `/**
111
194
  * AUTO GENERATED
112
195
  */
113
- ${generateImports$1(body, importStatements, makeNewImportVarMap$1(), getImportableVarMap$1())}
196
+ ${generateImports(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
114
197
 
115
198
  export class ${className} {
116
199
  // @ts-ignore
200
+ // prettier-ignore
117
201
  constructor(private axiosInstance: AxiosInstance, private namespace: string, private useSchemaValidation = true) {}
118
202
  ${body}
119
203
  }
120
204
  `;
121
205
  };
122
206
 
123
- const generateImports = (body, className) => {
124
- const generatedImports = `import { AccelbyteSDK, ApiArgs, ApiError } from '@accelbyte/sdk'
125
- import { AxiosError } from 'axios'
207
+ // src/templates/template-api-class.ts
208
+ var getImportableVarMap2 = () => ({
209
+ "@accelbyte/sdk": ["CodeGenUtil", "Response", "Validate", "SdkSetConfigParam", "Network", "AccelByteSDK"],
210
+ axios: ["AxiosDefaults", "HeadersDefaults"]
211
+ });
212
+ var makeNewImportVarMap2 = () => ({
213
+ "@accelbyte/sdk": ["AccelByteSDK", "SdkSetConfigParam", "ApiUtils", "Network"],
214
+ axios: ["AxiosRequestConfig", "AxiosResponse"]
215
+ });
216
+ var templateApiClass = (className, body, importStatements, returnMethods) => {
217
+ const returnsMethodsWithDescription = Object.keys(returnMethods).reduce((acc, key) => {
218
+ acc += `
219
+ ${returnMethods[key]}
220
+ ${key},`;
221
+ return acc;
222
+ }, "");
223
+ const $className = className.replace(/Api$/, "$");
224
+ return `/**
225
+ * AUTO GENERATED
226
+ */
227
+ /* eslint-disable camelcase */
228
+ // @ts-ignore -> ts-expect-error TS6133
229
+ ${generateImports(body, importStatements, makeNewImportVarMap2(), getImportableVarMap2())}
230
+ ${`import { ${$className} } from './endpoints/${$className}.js'
231
+ `}
232
+
233
+ export function ${className}(sdk: AccelByteSDK, args?: SdkSetConfigParam) {
234
+ const sdkAssembly = sdk.assembly()
235
+
236
+ const namespace = args?.coreConfig?.namespace ?? sdkAssembly.coreConfig.namespace
237
+ const useSchemaValidation = args?.coreConfig?.useSchemaValidation ?? sdkAssembly.coreConfig.useSchemaValidation
238
+
239
+ let axiosInstance = sdkAssembly.axiosInstance
240
+ const requestConfigOverrides = args?.axiosConfig?.request
241
+ const baseURLOverride = args?.coreConfig?.baseURL
242
+ const interceptorsOverride = args?.axiosConfig?.interceptors ?? []
243
+
244
+ if (requestConfigOverrides || baseURLOverride || interceptorsOverride.length > 0) {
245
+ const requestConfig = ApiUtils.mergeAxiosConfigs(sdkAssembly.axiosInstance.defaults as AxiosRequestConfig, {
246
+ ...(baseURLOverride ? { baseURL: baseURLOverride } : {}),
247
+ ...requestConfigOverrides
248
+ })
249
+ axiosInstance = Network.create(requestConfig)
250
+
251
+ for (const interceptor of interceptorsOverride) {
252
+ if (interceptor.type === 'request') {
253
+ axiosInstance.interceptors.request.use(interceptor.onRequest, interceptor.onError)
254
+ }
255
+
256
+ if (interceptor.type === 'response') {
257
+ axiosInstance.interceptors.response.use(interceptor.onSuccess, interceptor.onError)
258
+ }
259
+ }
260
+ }
261
+
262
+ ${body}
263
+
264
+ return {
265
+ ${returnsMethodsWithDescription}
266
+ }
267
+ }
268
+ `;
269
+ };
270
+
271
+ // src/ParserQueryUtils.ts
272
+ var ParserQueryUtils = class {
273
+ /**
274
+ * convert csv 'aa,bb' into "aa='aa', bb='bb'"
275
+ */
276
+ static createQueryKeys(classNameWithoutApi, csvMethodNames, sdkName) {
277
+ const keys = csvMethodNames.split(",");
278
+ const processedKeys = /* @__PURE__ */ new Set();
279
+ const enumString = keys.reduce((acc, key, index) => {
280
+ const trimmedKey = key.trim();
281
+ if (trimmedKey) {
282
+ const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete|post|fetch)[_]?/, "");
283
+ if (!processedKeys.has(cleanedKey)) {
284
+ processedKeys.add(cleanedKey);
285
+ acc += `${cleanedKey} = '${capitalize(sdkName)}.${classNameWithoutApi}.${cleanedKey}'`;
286
+ if (index < keys.length - 1) {
287
+ acc += ",\n";
288
+ }
289
+ }
290
+ }
291
+ return acc;
292
+ }, "");
293
+ return enumString;
294
+ }
295
+ };
296
+
297
+ // src/templates/template-query.ts
298
+ var generateImports2 = (body, className) => {
299
+ const generatedImports = `import { AccelByteSDK, SdkSetConfigParam, ApiError } from '@accelbyte/sdk'
300
+ import { AxiosError, AxiosResponse } from 'axios'
126
301
  // @ts-ignore
127
302
  import { useQuery, UseQueryOptions, UseQueryResult, useMutation, UseMutationOptions, UseMutationResult } from '@tanstack/react-query'
128
303
  import { ${className} } from "../${className}.js"
129
304
  `;
130
305
  return generatedImports;
131
306
  };
132
- const templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports) => {
307
+ var templateQuery = (className, body, importStatements, serviceNameTitle, returnMethods, paramImports, sdkName) => {
133
308
  const classNameWithoutApi = className.replace("Api", "");
134
- const queryKeys = ParserUtils.createQueryKeys(classNameWithoutApi, returnMethods);
135
- const generatedImports = generateImports(body, className);
309
+ const queryKeys = ParserQueryUtils.createQueryKeys(classNameWithoutApi, returnMethods, sdkName);
310
+ const generatedImports = generateImports2(body, className);
136
311
  return `/**
137
312
  * AUTO GENERATED
138
313
  */
@@ -148,117 +323,19 @@ export enum Key_${classNameWithoutApi} {
148
323
  `;
149
324
  };
150
325
  function filterUsedImports(importArr, body) {
151
- return importArr.filter((path) => {
152
- const start = path.indexOf("{") + 1;
153
- const end = path.indexOf("}");
326
+ return importArr.filter((path7) => {
327
+ const start = path7.indexOf("{") + 1;
328
+ const end = path7.indexOf("}");
154
329
  if (start > 0 && end > start) {
155
- const importName = path.slice(start, end).trim();
330
+ const importName = path7.slice(start, end).trim();
156
331
  return body.includes(importName);
157
332
  }
158
333
  return false;
159
- }).map((path) => path).join("\n") + "\n";
160
- }
161
-
162
- const getImportableVarMap = () => ({
163
- "@accelbyte/sdk": ["CodeGenUtil", "IResponse", "Validate", "ApiArgs", "Network", "AccelbyteSDK"]
164
- });
165
- const makeNewImportVarMap = () => ({
166
- "@accelbyte/sdk": ["AccelbyteSDK", "ApiArgs", "ApiUtils"]
167
- });
168
- const templateApiClass = (className, body, importStatements, returnMethods) => {
169
- const $className = className.replace("Api", "$");
170
- return `/**
171
- * AUTO GENERATED
172
- */
173
- /* eslint-disable camelcase */
174
- // @ts-ignore -> ts-expect-error TS6133
175
- ${generateImports$1(body, importStatements, makeNewImportVarMap(), getImportableVarMap())}
176
- ${`import { ${$className} } from './endpoints/${$className}.js'
177
- `}
178
-
179
- export function ${className}(sdk: AccelbyteSDK, args?: ApiArgs) {
180
- const sdkAssembly = sdk.assembly()
181
-
182
- const namespace = args?.namespace ? args?.namespace : sdkAssembly.namespace
183
- const requestConfig = ApiUtils.mergedConfigs(sdkAssembly.config, args)
184
- const useSchemaValidation = sdkAssembly.useSchemaValidation
185
- ${body}
186
-
187
- return {
188
- ${returnMethods}
189
- }
190
- }
191
- `;
192
- };
193
-
194
- const VersionBumpType = zod.z.enum(["CUTOFF", "RELEASE", "HOTFIX", "BREAKING"]);
195
- class VersionHelpers {
196
- static getNextVersion = ({
197
- serviceVersion,
198
- versionBumpType,
199
- sdkVersion,
200
- nextPrereleaseId
201
- }) => {
202
- if (versionBumpType !== void 0) {
203
- const parsed = VersionBumpType.safeParse(versionBumpType);
204
- if (!parsed.success) {
205
- throw new Error(`Invalid process.env.VERSION_BUMP_TYPE: ${versionBumpType}`);
206
- }
207
- if ((parsed.data === "HOTFIX" || parsed.data === "RELEASE") && nextPrereleaseId) {
208
- throw new Error(`process.env.PRERELEASE_ID should be empty when process.env.VERSION_BUMP_TYPE is "HOTFIX" or "PRELEASE".`);
209
- }
210
- }
211
- const serviceSemvers = semver.parse(serviceVersion);
212
- const sdkSemvers = semver.parse(sdkVersion);
213
- if (serviceSemvers === null) {
214
- throw new Error(`Invalid service version: ${serviceVersion}`);
215
- }
216
- if (sdkSemvers === null) {
217
- throw new Error(`Invalid sdk version: ${sdkVersion}`);
218
- }
219
- const { major: currentMajor, minor: currentMinor, patch: currentPatch, prerelease: currentPrerelease } = sdkSemvers;
220
- let nextMajor = currentMajor;
221
- let nextMinor = currentMinor;
222
- let nextPatch = currentPatch;
223
- switch (versionBumpType) {
224
- case VersionBumpType.Enum.BREAKING: {
225
- nextMajor++;
226
- nextMinor = 0;
227
- nextPatch = 0;
228
- break;
229
- }
230
- case VersionBumpType.Enum.CUTOFF: {
231
- nextMinor++;
232
- nextPatch = 0;
233
- break;
234
- }
235
- case VersionBumpType.Enum.RELEASE:
236
- break;
237
- case VersionBumpType.Enum.HOTFIX: {
238
- nextPatch++;
239
- break;
240
- }
241
- }
242
- let nextVersion = [
243
- nextMajor,
244
- nextMinor,
245
- nextPatch
246
- ].join(".");
247
- if (nextPrereleaseId) {
248
- if (nextMinor !== currentMinor) {
249
- nextVersion += `-${nextPrereleaseId}.0`;
250
- } else {
251
- if (currentPrerelease.length)
252
- nextVersion += `-${currentPrerelease.join(".")}`;
253
- nextVersion = semver.inc(nextVersion, "prerelease", void 0, nextPrereleaseId);
254
- }
255
- }
256
- return nextVersion;
257
- };
334
+ }).map((path7) => path7).join("\n") + "\n";
258
335
  }
259
336
 
260
- const UNDEFINED_SWAGGER_SEMVER = "0.0.0";
261
- const REMOVED_KEYWORDS = [
337
+ // src/ParserUtils.ts
338
+ var REMOVED_KEYWORDS = [
262
339
  "/admin/",
263
340
  "/public/",
264
341
  "/v1/",
@@ -270,52 +347,34 @@ const REMOVED_KEYWORDS = [
270
347
  "/namespaces/",
271
348
  "/{namespace}/"
272
349
  ];
273
- class ParserUtils {
274
- static createQueryKeys(classNameWithoutApi, csvMethodNames) {
275
- const keys = csvMethodNames.split(",");
276
- const processedKeys = /* @__PURE__ */ new Set();
277
- const enumString = keys.reduce((acc, key, index) => {
278
- const trimmedKey = key.trim();
279
- const isDeprecated = key.indexOf("_DEPRECATED") > 0;
280
- if (trimmedKey && !isDeprecated) {
281
- const cleanedKey = trimmedKey.replace(/^(get|update|create|patch|delete)[_]?/, "");
282
- if (!processedKeys.has(cleanedKey)) {
283
- processedKeys.add(cleanedKey);
284
- acc += `${cleanedKey} = '${classNameWithoutApi}.${cleanedKey}'`;
285
- if (index < keys.length - 1) {
286
- acc += ",\n";
287
- }
288
- }
289
- }
290
- return acc;
291
- }, "");
292
- return enumString;
293
- }
294
- static addDeprecatedSuffix(isDeprecated, methodName) {
295
- if (isDeprecated) {
296
- return methodName + "_DEPRECATED";
297
- } else {
298
- return methodName;
299
- }
350
+ var ParserUtils = class _ParserUtils {
351
+ static getVersionSuffixFromPath(path7) {
352
+ const version2_3_4_etc = path7.match(/\/v([2-9]|[1-9]\d+)\/+/);
353
+ const methodSuffix = version2_3_4_etc ? `_v${version2_3_4_etc[1]}` : "";
354
+ return methodSuffix;
300
355
  }
301
356
  static replaceAll = (text, search, replace) => {
302
357
  return text.split(search).join(replace);
303
358
  };
304
359
  static generateClassName = (tag, isAdmin) => {
305
- const className = _.upperFirst(_.camelCase(tag));
306
- const classGenName = isAdmin ? className + "Admin$" : className + "$";
307
- return { className, classGenName };
360
+ const className = import_lodash.default.upperFirst(import_lodash.default.camelCase(tag));
361
+ const formattedApiName = removeAdminPrefix(className);
362
+ const classGenName = isAdmin ? formattedApiName + "Admin$" : formattedApiName + "$";
363
+ return { className: formattedApiName, classGenName };
308
364
  };
309
365
  static generateApiName = (tag, isAdmin) => {
310
- const apiName = _.upperFirst(_.camelCase(tag));
311
- const apiGenName = isAdmin ? apiName + "AdminApi" : apiName + "Api";
366
+ const apiName = import_lodash.default.upperFirst(import_lodash.default.camelCase(tag));
367
+ const formattedApiName = removeAdminPrefix(apiName);
368
+ const apiGenName = isAdmin ? formattedApiName + "AdminApi" : formattedApiName + "Api";
312
369
  return { apiName, apiGenName };
313
370
  };
314
371
  static parseQueryParamAttributeDefault = (definition) => {
315
372
  const attrName = definition.name.slice(definition.name.lastIndexOf(".") + 1);
316
373
  let defaultValue = definition.default;
317
374
  if (definition.type === "array" && Array.isArray(definition.default)) {
318
- const mappedDefaultValue = definition.default.map((defaultValue2) => typeof defaultValue2 === "string" ? `'${defaultValue2}'` : defaultValue2);
375
+ const mappedDefaultValue = definition.default.map(
376
+ (defaultValue2) => typeof defaultValue2 === "string" ? `'${defaultValue2}'` : defaultValue2
377
+ );
319
378
  defaultValue = `[${mappedDefaultValue.join(", ")}]`;
320
379
  }
321
380
  if (definition.type === "string") {
@@ -324,24 +383,21 @@ class ParserUtils {
324
383
  return `${attrName}: ${defaultValue}`;
325
384
  };
326
385
  static parseType = (pathParam) => {
327
- if (isSwaggerIntegerType(pathParam.type || pathParam?.schema?.type))
328
- return "number";
386
+ if (isSwaggerIntegerType(pathParam.type || pathParam?.schema?.type)) return "number";
329
387
  if (pathParam.type === "array") {
330
- if (isSwaggerIntegerType(pathParam.items.type))
331
- return "number[]";
388
+ if (isSwaggerIntegerType(pathParam.items.type)) return "number[]";
332
389
  return `${pathParam.items.type ?? "any"}[]`;
333
390
  }
334
391
  if (pathParam?.schema?.type === "array") {
335
- if (isSwaggerIntegerType(pathParam.schema.items.type))
336
- return "number[]";
392
+ if (isSwaggerIntegerType(pathParam.schema.items.type)) return "number[]";
337
393
  return `${pathParam.schema.items.type ?? "any"}[]`;
338
394
  }
339
- if (pathParam?.schema?.type)
340
- return pathParam.schema.type;
395
+ if (pathParam?.schema?.type) return pathParam.schema.type;
341
396
  return pathParam.type;
342
397
  };
343
398
  static parseQueryParamsType = (queryParams) => {
344
- return queryParams.map((queryParam) => ParserUtils.parseAttributeType(queryParam)).join(", ");
399
+ const result = queryParams.map((queryParam) => _ParserUtils.parseAttributeType(queryParam)).join(", ");
400
+ return result;
345
401
  };
346
402
  static isAnyQueryParamRequired = (queryParams) => {
347
403
  return queryParams.some((queryParam) => queryParam.required);
@@ -356,11 +412,11 @@ class ParserUtils {
356
412
  return result;
357
413
  };
358
414
  static parseQueryParamsDefault = (queryParams) => {
359
- const result = queryParams.filter((queryParam) => !!queryParam.default && !queryParam.required).map(ParserUtils.parseQueryParamAttributeDefault).join(",");
415
+ const result = queryParams.filter((queryParam) => !!queryParam.default && !queryParam.required).map(_ParserUtils.parseQueryParamAttributeDefault).join(",");
360
416
  return result ? `${result},` : "";
361
417
  };
362
418
  static parseBodyParamsImports = (bodyParams) => {
363
- return bodyParams.map((bodyParams2) => ParserUtils.parseRefImport(bodyParams2)).filter(Boolean);
419
+ return bodyParams.map((bodyParams2) => _ParserUtils.parseRefImport(bodyParams2)).filter(Boolean);
364
420
  };
365
421
  static parseImportDir = ($ref) => {
366
422
  let ref = $ref.replace(".", "/");
@@ -378,7 +434,7 @@ class ParserUtils {
378
434
  if (!$ref) {
379
435
  return null;
380
436
  }
381
- const type = ParserUtils.parseRefType($ref);
437
+ const type = _ParserUtils.parseRefType($ref);
382
438
  return `import { ${type} } from '../../generated-definitions/${type}.js'`;
383
439
  };
384
440
  static parseRefType = ($ref) => {
@@ -387,7 +443,7 @@ class ParserUtils {
387
443
  ref = ref.slice(0, -1);
388
444
  }
389
445
  const val = ref.slice(ref.lastIndexOf("/") + 1);
390
- return _.upperFirst(_.camelCase(val)).replace(/( \w)/g, (group) => group.replace(" ", "").toUpperCase());
446
+ return import_lodash.default.upperFirst(import_lodash.default.camelCase(val)).replace(/( \w)/g, (group) => group.replace(" ", "").toUpperCase());
391
447
  };
392
448
  static parseAttributeType = (definition) => {
393
449
  const required = definition.required ? "" : "?";
@@ -396,10 +452,13 @@ class ParserUtils {
396
452
  const enums = definition.enum.map((enm) => definition.type === "string" ? `'${enm}'` : enm).join(" | ");
397
453
  return `${attrName}${required}: ${enums}`;
398
454
  }
399
- if (definition.type && ParserUtils.parseType(definition) === "number") {
455
+ if (definition.type && _ParserUtils.parseType(definition) === "number") {
400
456
  return `${attrName}${required}: number`;
401
457
  }
402
- if (definition?.schema?.type && ParserUtils.parseType(definition) === "number") {
458
+ if (definition.type && _ParserUtils.parseType(definition) === "number[]") {
459
+ return `${attrName}${required}: number[]`;
460
+ }
461
+ if (definition?.schema?.type && _ParserUtils.parseType(definition) === "number") {
403
462
  return `${attrName}${required}: number`;
404
463
  }
405
464
  if (definition.type && definition.type === "array") {
@@ -424,47 +483,44 @@ class ParserUtils {
424
483
  };
425
484
  static parseBodyParamsType = (bodyParams) => {
426
485
  const [bodyParam] = bodyParams;
427
- if (!bodyParam)
428
- return null;
486
+ if (!bodyParam) return null;
429
487
  if (bodyParams.length > 0 && bodyParam?.name !== "body" && !bodyParam?.schema) {
430
- let retBodyParams = `{${bodyParams.map((bodyParam2) => ParserUtils.parseAttributeType(bodyParam2)).join(",")}}`;
488
+ let retBodyParams = `{${bodyParams.map((bodyParam2) => _ParserUtils.parseAttributeType(bodyParam2)).join(",")}}`;
431
489
  retBodyParams = retBodyParams.replace("file?: file", "file?: File");
432
490
  return retBodyParams;
433
491
  }
434
492
  if (bodyParam?.schema?.type === "array" && !bodyParam?.schema?.items?.$ref) {
435
- if (isSwaggerIntegerType(bodyParam.schema.items.type))
436
- return "number[]";
493
+ if (isSwaggerIntegerType(bodyParam.schema.items.type)) return "number[]";
437
494
  return `${bodyParam.schema.items.type ?? "any"}[]`;
438
495
  }
439
496
  if (bodyParam?.schema?.type === "array" && bodyParam?.schema?.items?.$ref) {
440
- return `${ParserUtils.parseRefType(bodyParam.schema.items.$ref)}[]`;
497
+ return `${_ParserUtils.parseRefType(bodyParam.schema.items.$ref)}[]`;
441
498
  }
442
499
  if (bodyParam?.schema?.$ref) {
443
- return ParserUtils.parseRefType(bodyParam.schema.$ref);
500
+ return _ParserUtils.parseRefType(bodyParam.schema.$ref);
444
501
  }
445
502
  if (bodyParam?.schema?.additionalProperties?.type === "object") {
446
503
  return "any";
447
504
  }
448
505
  return null;
449
506
  };
450
- static get2xxResponse(methodEntity) {
507
+ static get2xxResponses(methodEntity) {
451
508
  const keys = Object.keys(methodEntity);
452
- let responseClass = null;
453
- keys.forEach((key) => {
454
- if (String(key).startsWith("2")) {
455
- const sch = methodEntity[key].schema;
456
- const schV3 = methodEntity[key].content && methodEntity[key].content["application/json"].schema;
457
- if (sch?.$ref) {
458
- responseClass = ParserUtils.parseRefType(sch.$ref);
459
- } else if (sch?.type === "array" && sch.items?.$ref) {
460
- responseClass = ParserUtils.parseRefType(sch.items.$ref);
461
- responseClass = `${responseClass}Array`;
462
- } else if (schV3?.$ref) {
463
- responseClass = ParserUtils.parseRefType(schV3.$ref);
464
- } else ;
509
+ const responseClasses = [];
510
+ const statusCodes = keys.filter((key) => String(key).startsWith("2"));
511
+ statusCodes.forEach((key) => {
512
+ const sch = methodEntity[key].schema;
513
+ const schV3 = methodEntity[key].content && methodEntity[key].content["application/json"].schema;
514
+ if (sch?.$ref) {
515
+ responseClasses.push(_ParserUtils.parseRefType(sch.$ref));
516
+ } else if (sch?.type === "array" && sch.items?.$ref) {
517
+ responseClasses.push(`${_ParserUtils.parseRefType(sch.items.$ref)}Array`);
518
+ } else if (schV3?.$ref) {
519
+ responseClasses.push(_ParserUtils.parseRefType(schV3.$ref));
520
+ } else {
465
521
  }
466
522
  });
467
- return responseClass;
523
+ return responseClasses;
468
524
  }
469
525
  static isFormUrlEncoded(httpMethod, contentTypes) {
470
526
  if (!contentTypes || contentTypes.length < 1) {
@@ -481,17 +537,24 @@ class ParserUtils {
481
537
  }
482
538
  return parameters.filter((parameter) => parameter.in === "path");
483
539
  }
484
- static generateNaturalLangMethod = ({ servicePrefix, path: path2, httpMethod, isForm, existingMethods }) => {
485
- let path_ = path2;
540
+ /**
541
+ * This method converts this
542
+ * POST `/gdpr/public/namespaces/{namespace}/users/{userId}/requests/{requestDate}/generate`
543
+ *
544
+ * to this
545
+ * `createGenerateByRequestIdByUserId`
546
+ */
547
+ static generateNaturalLangMethod = ({ servicePrefix, path: path7, httpMethod, isForm, existingMethods, permissionType }) => {
548
+ let path_ = path7;
486
549
  path_ = path_.replace(`/${servicePrefix}/`, "/");
487
550
  REMOVED_KEYWORDS.forEach((prefix) => {
488
551
  path_ = path_.replace(prefix, "/");
489
552
  });
490
553
  path_ = path_.substring(1);
491
- const isPlural = httpMethod === "get" && !(path2.slice(-1) === "}");
554
+ const isPlural = httpMethod === "get" && !(path7.slice(-1) === "}");
492
555
  if (!isPlural) {
493
- path_ = ParserUtils.replaceAll(path_, "ies/", "y/");
494
- path_ = ParserUtils.replaceAll(path_, "s/", "/");
556
+ path_ = _ParserUtils.replaceAll(path_, "ies/", "y/");
557
+ path_ = _ParserUtils.replaceAll(path_, "s/", "/");
495
558
  if (path_.indexOf("status") < 0) {
496
559
  path_ = path_.replace(/ies$/, "y");
497
560
  path_ = path_.replace(/s$/, "");
@@ -518,7 +581,7 @@ class ParserUtils {
518
581
  foundParam = true;
519
582
  let param = item.replace("{", "");
520
583
  param = param.replace("}", "");
521
- param = "Byword" + _.upperFirst(param);
584
+ param = "Byword" + import_lodash.default.upperFirst(param);
522
585
  listByParams.push(param);
523
586
  } else if (!foundParam) {
524
587
  if (lastWords.indexOf(item) === -1) {
@@ -528,10 +591,12 @@ class ParserUtils {
528
591
  foundParam = false;
529
592
  }
530
593
  });
531
- const genPath = _.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
532
- let generatedMethod = _.camelCase(mappedMethod(httpMethod, isForm) + genPath);
533
- generatedMethod = ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
534
- generatedMethod = resolveConflicts(path2, generatedMethod, existingMethods);
594
+ const genPath = import_lodash.default.upperFirst(lastWords) + "/" + listBeforeLastWords.join("/") + listByParams.reverse().join("/");
595
+ let generatedMethod = import_lodash.default.camelCase(mappedMethod(httpMethod, isForm, permissionType) + genPath);
596
+ generatedMethod = _ParserUtils.replaceAll(generatedMethod, "Byword", "_By");
597
+ const testedGeneratedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path7);
598
+ generatedMethod = resolveConflicts({ path: path7, generatedMethod, testedGeneratedMethod, existingMethods });
599
+ generatedMethod = generatedMethod + _ParserUtils.getVersionSuffixFromPath(path7);
535
600
  return generatedMethod;
536
601
  };
537
602
  static filterBodyParams(parameters) {
@@ -547,90 +612,76 @@ class ParserUtils {
547
612
  return parameters.filter((parameter) => parameter.in === "query");
548
613
  }
549
614
  static mkdirIfNotExist(dirToCreate) {
550
- if (!fs.existsSync(dirToCreate)) {
551
- fs.mkdirSync(dirToCreate, { recursive: true });
615
+ if (!import_fs3.default.existsSync(dirToCreate)) {
616
+ import_fs3.default.mkdirSync(dirToCreate, { recursive: true });
552
617
  }
553
618
  }
554
619
  static writeClassFile(distDir, apiName, apiBuffer, imports) {
555
620
  const fileContent = templateClass(apiName, apiBuffer, imports);
556
- fs.writeFileSync(`${distDir}/${apiName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
621
+ import_fs3.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
557
622
  }
558
623
  static writeAtomFile(distDir, apiName, fileContent) {
559
- ParserUtils.mkdirIfNotExist(distDir);
560
- fs.writeFileSync(`${distDir}/${apiName}.atom.ts`, ParserUtils.prependCopyrightHeader(fileContent));
624
+ _ParserUtils.mkdirIfNotExist(distDir);
625
+ import_fs3.default.writeFileSync(`${distDir}/${apiName}.atom.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
561
626
  }
562
- static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports) {
627
+ static writeQueryFile(distDir, apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName) {
563
628
  if (apiBuffer.length < 1) {
564
629
  return null;
565
630
  }
566
631
  const queryFileName = `${apiName.replace("Api", "")}.query`;
567
- ParserUtils.mkdirIfNotExist(distDir);
568
- const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports);
569
- fs.writeFileSync(`${distDir}/${queryFileName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
632
+ _ParserUtils.mkdirIfNotExist(distDir);
633
+ const fileContent = templateQuery(apiName, apiBuffer, imports, serviceNameTitle, returnMethods, paramImports, sdkName);
634
+ import_fs3.default.writeFileSync(`${distDir}/${queryFileName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
570
635
  return queryFileName;
571
636
  }
572
637
  static writeXVersion(distDir, xversionJson, apiInfo) {
573
638
  if (xversionJson) {
574
639
  console.log("x-version:", xversionJson);
575
- fs.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
640
+ import_fs3.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
576
641
  } else {
577
642
  const customVersion = {
578
643
  ...apiInfo,
579
644
  gitHash: apiInfo.version
580
645
  };
581
- console.error("!!!! Missing x-version for ", distDir, customVersion);
582
- fs.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
646
+ console.error(`!!!! Missing x-version for ${distDir} ${customVersion}`);
647
+ import_fs3.default.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
583
648
  }
584
649
  }
585
- static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethods) {
650
+ static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethodsDescription) {
586
651
  const newImports = [];
587
- imports.forEach((el, index) => {
652
+ imports.forEach((el) => {
588
653
  newImports.push(el.replace("../../generated-definitions", "../generated-definitions"));
589
654
  });
590
- const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethods);
591
- fs.writeFileSync(`${distDir}/${apiName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
655
+ const fileContent = templateApiClass(apiName, apiBuffer, newImports, returnMethodsDescription);
656
+ import_fs3.default.writeFileSync(`${distDir}/${apiName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
592
657
  }
593
658
  static writeApiMainFile(distDir, serviceName, fileContent) {
594
- fs.writeFileSync(`${distDir}/${serviceName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
659
+ import_fs3.default.writeFileSync(`${distDir}/${serviceName}.ts`, _ParserUtils.prependCopyrightHeader(fileContent));
595
660
  }
596
661
  static writeSnippetFile(distDir, name, docBuffer) {
597
- let snippetFileName = ParserUtils.replaceAll(name, " ", "-").toLowerCase();
662
+ let snippetFileName = _ParserUtils.replaceAll(name, " ", "-").toLowerCase();
598
663
  snippetFileName = snippetFileName.replace("justice-", "");
599
664
  snippetFileName = "snippet-" + snippetFileName + ".json";
600
- fs.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
665
+ import_fs3.default.writeFileSync(`${distDir}/${snippetFileName}`, docBuffer);
601
666
  }
602
667
  static writeDefinitionFile(distDir, name, buffer) {
603
- ParserUtils.mkdirIfNotExist(distDir);
604
- fs.writeFileSync(path.join(distDir, `${name}.ts`), ParserUtils.prependCopyrightHeader(buffer));
668
+ _ParserUtils.mkdirIfNotExist(distDir);
669
+ import_fs3.default.writeFileSync(import_path2.default.join(distDir, `${name}.ts`), _ParserUtils.prependCopyrightHeader(buffer));
605
670
  }
606
671
  static writeAllImportsFile(distDir, buffer) {
607
- ParserUtils.mkdirIfNotExist(distDir);
608
- fs.writeFileSync(path.join(distDir, "all-imports.ts"), ParserUtils.prependCopyrightHeader(buffer));
672
+ _ParserUtils.mkdirIfNotExist(distDir);
673
+ import_fs3.default.writeFileSync(import_path2.default.join(distDir, "all-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
609
674
  }
610
- static syncPackageVersion(apiInfo, skipVersionSync, prereleaseId) {
611
- if (skipVersionSync)
612
- return;
613
- const currDir = process.cwd();
614
- const { packageJSON, pathToPackageJSON } = ParserUtils.getPackageJSONInfo(currDir);
615
- const nextSemver = VersionHelpers.getNextVersion({
616
- serviceVersion: apiInfo["x-version"] || apiInfo.version || UNDEFINED_SWAGGER_SEMVER,
617
- versionBumpType: process.env.VERSION_BUMP_TYPE,
618
- sdkVersion: packageJSON.version,
619
- nextPrereleaseId: prereleaseId
620
- });
621
- packageJSON.version = nextSemver;
622
- fs.writeFileSync(pathToPackageJSON, JSON.stringify(packageJSON, null, 2));
623
- }
624
- static getPackageJSONInfo(dir) {
625
- const pathToPackageJSON = path.join(dir, "./package.json");
626
- return { packageJSON: JSON.parse(fs.readFileSync(pathToPackageJSON, "utf-8")), pathToPackageJSON };
675
+ static writeAllQueryImportsFile(distDir, buffer) {
676
+ _ParserUtils.mkdirIfNotExist(distDir);
677
+ import_fs3.default.writeFileSync(import_path2.default.join(distDir, "all-query-imports.ts"), _ParserUtils.prependCopyrightHeader(buffer));
627
678
  }
628
679
  static toCamelCase(str) {
629
680
  return str.split("/").map(function(word, index) {
630
681
  if (index === 0) {
631
682
  return word.toLowerCase();
632
683
  }
633
- return ParserUtils.toCamelCaseWord(word);
684
+ return _ParserUtils.toCamelCaseWord(word);
634
685
  }).join("");
635
686
  }
636
687
  static toCamelCaseWord(word) {
@@ -649,15 +700,15 @@ class ParserUtils {
649
700
  });
650
701
  }
651
702
  static applyPatchIfExists(swaggerFilePath, possibleSwaggerPatchFilePath, swaggerPatchedFilePath, swaggerPatchedDir) {
652
- if (!fs.existsSync(swaggerPatchedDir)) {
653
- fs.mkdirSync(swaggerPatchedDir, { recursive: true });
703
+ if (!import_fs3.default.existsSync(swaggerPatchedDir)) {
704
+ import_fs3.default.mkdirSync(swaggerPatchedDir, { recursive: true });
654
705
  }
655
- if (!fs.existsSync(possibleSwaggerPatchFilePath)) {
656
- fs.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
706
+ if (!import_fs3.default.existsSync(possibleSwaggerPatchFilePath)) {
707
+ import_fs3.default.copyFileSync(swaggerFilePath, swaggerPatchedFilePath);
657
708
  return;
658
709
  }
659
- const swaggerContent = JSON.parse(fs.readFileSync(swaggerFilePath, "utf8"));
660
- const swaggerPatchFileContent = JSON.parse(fs.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
710
+ const swaggerContent = JSON.parse(import_fs3.default.readFileSync(swaggerFilePath, "utf8"));
711
+ const swaggerPatchFileContent = JSON.parse(import_fs3.default.readFileSync(possibleSwaggerPatchFilePath, "utf8"));
661
712
  for (const patchEntry of swaggerPatchFileContent) {
662
713
  const segments = patchEntry.path.split("/").filter(Boolean);
663
714
  let currentNode = swaggerContent;
@@ -667,29 +718,32 @@ class ParserUtils {
667
718
  aggregatedPath += `/${segment}`;
668
719
  const effectiveSegment = segment.replace(/(~1)/g, "/").replace(/(~0)/g, "~");
669
720
  if (!currentNode[effectiveSegment]) {
670
- if (i + 1 === segments.length && patchEntry.op === "add") ; else {
671
- throw new Error([
672
- `JSON patch error: operation "${patchEntry.op}" on path "${aggregatedPath}" fails because the path doesn't exist in ${swaggerFilePath}. This may be caused by:
721
+ if (i + 1 === segments.length && patchEntry.op === "add") {
722
+ } else {
723
+ throw new Error(
724
+ [
725
+ `JSON patch error: operation "${patchEntry.op}" on path "${aggregatedPath}" fails because the path doesn't exist in ${swaggerFilePath}. This may be caused by:
673
726
  `,
674
- "1. The related service has patched the service, so patch is no longer needed.",
675
- "2. There is a breaking change on the service that causes the path to change.\n",
676
- `In any case, revisit this file: "${possibleSwaggerPatchFilePath}", then try again.
727
+ "1. The related service has patched the service, so patch is no longer needed.",
728
+ "2. There is a breaking change on the service that causes the path to change.\n",
729
+ `In any case, revisit this file: "${possibleSwaggerPatchFilePath}", then try again.
677
730
  `
678
- ].join("\n"));
731
+ ].join("\n")
732
+ );
679
733
  }
680
734
  }
681
735
  currentNode = currentNode[effectiveSegment];
682
736
  }
683
737
  }
684
- const { newDocument } = fastJsonPatch.applyPatch(swaggerContent, swaggerPatchFileContent);
685
- fs.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
738
+ const { newDocument } = (0, import_fast_json_patch.applyPatch)(swaggerContent, swaggerPatchFileContent);
739
+ import_fs3.default.writeFileSync(swaggerPatchedFilePath, JSON.stringify(newDocument, null, 2));
686
740
  }
687
741
  static getRelativePathToWebSdkSrcFolder(srcFolder, targetSrcFolder) {
688
742
  const replaced = srcFolder.replace(/\\/g, "/");
689
743
  return replaced.replace(/\\/g, "/").replace(targetSrcFolder, "./");
690
744
  }
691
745
  static prependCopyrightHeader = (content) => {
692
- const currentYear = new Date().getFullYear();
746
+ const currentYear = (/* @__PURE__ */ new Date()).getFullYear();
693
747
  return `/*
694
748
  * Copyright (c) 2022${currentYear > 2022 ? `-${currentYear}` : ""} AccelByte Inc. All Rights Reserved
695
749
  * This is licensed software from AccelByte Inc, for limitations
@@ -697,17 +751,21 @@ class ParserUtils {
697
751
  */
698
752
  ${content}`;
699
753
  };
700
- static sortPathParamsByPath = (pathParams, path2) => {
701
- const params = path2.match(/{\w*}/g) || [];
754
+ static sortPathParamsByPath = (pathParams, path7) => {
755
+ const params = path7.match(/{\w*}/g) || [];
702
756
  const cleanParams = params.map((param) => param.replace("{", "").replace("}", ""));
703
757
  return pathParams.sort((a, b) => cleanParams.indexOf(a.name) - cleanParams.indexOf(b.name));
704
758
  };
705
- }
706
- const mappedMethod = (httpMethod, isForm) => {
759
+ };
760
+ var mappedMethod = (httpMethod, isForm, permissionType) => {
707
761
  if (httpMethod === "get") {
708
762
  return "get";
709
763
  } else if (httpMethod === "post" && isForm) {
710
764
  return "post";
765
+ } else if (httpMethod === "post" && permissionType === "READ") {
766
+ return "fetch";
767
+ } else if (httpMethod === "post" && permissionType === "UPDATE") {
768
+ return "update";
711
769
  } else if (httpMethod === "post") {
712
770
  return "create";
713
771
  } else if (httpMethod === "put") {
@@ -718,448 +776,317 @@ const mappedMethod = (httpMethod, isForm) => {
718
776
  return "delete";
719
777
  }
720
778
  };
721
- const resolveConflicts = (path2, generatedMethod, existingMethods) => {
779
+ var resolveConflicts = ({ path: path7, generatedMethod, testedGeneratedMethod, existingMethods }) => {
780
+ let _testedGenMethod = testedGeneratedMethod;
722
781
  try {
723
- testConflict(path2, generatedMethod, existingMethods);
782
+ testConflict(path7, _testedGenMethod, existingMethods);
724
783
  } catch (e) {
725
- if (path2.indexOf("/namespaces/") >= 0) {
784
+ if (path7.indexOf("/namespaces/") >= 0) {
726
785
  generatedMethod += "_ByNS";
786
+ _testedGenMethod += "_ByNS";
727
787
  }
728
788
  }
729
789
  try {
730
- testConflict(path2, generatedMethod, existingMethods);
731
- } catch (e) {
732
- if (path2.indexOf("/v4/") >= 0) {
733
- generatedMethod += "_v4";
734
- }
735
- }
736
- try {
737
- testConflict(path2, generatedMethod, existingMethods);
738
- } catch (e) {
739
- if (path2.indexOf("/v3/") >= 0) {
740
- generatedMethod += "_v3";
741
- }
742
- }
743
- try {
744
- testConflict(path2, generatedMethod, existingMethods);
745
- } catch (e) {
746
- if (path2.indexOf("/v2/") >= 0) {
747
- generatedMethod += "_v2";
748
- }
749
- }
750
- try {
751
- testConflict(path2, generatedMethod, existingMethods);
790
+ testConflict(path7, _testedGenMethod, existingMethods);
752
791
  } catch (e) {
753
- if (path2.indexOf("/admin/") >= 0) {
792
+ if (path7.indexOf("/admin/") >= 0) {
754
793
  generatedMethod += "_admin";
794
+ _testedGenMethod += "_admin";
755
795
  }
756
796
  }
757
- testConflict(path2, generatedMethod, existingMethods);
797
+ testConflict(path7, _testedGenMethod, existingMethods);
758
798
  return generatedMethod;
759
799
  };
760
- const testConflict = (path2, generatedMethod, existingMethods) => {
800
+ var testConflict = (path7, generatedMethod, existingMethods) => {
761
801
  if (existingMethods[generatedMethod]) {
762
- const conflictingMethod = { path: path2, generatedMethod };
763
- throw Error(`Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
764
- existingMethods: ${JSON.stringify(existingMethods, null, 2)}`);
802
+ const conflictingMethod = { path: path7, generatedMethod };
803
+ throw Error(
804
+ `Duplicate method conflict in ${JSON.stringify(conflictingMethod)},
805
+ existingMethods: ${JSON.stringify(existingMethods, null, 2)}`
806
+ );
765
807
  }
766
808
  };
767
- const isSwaggerIntegerType = (type) => {
809
+ var isSwaggerIntegerType = (type) => {
768
810
  return type === "integer" || type === "int";
769
811
  };
770
812
 
771
- class TemplateZod {
772
- duplicates;
773
- duplicateFound = false;
774
- importClasses = /* @__PURE__ */ new Set();
775
- render = (fileName, definition, duplicates) => {
776
- this.duplicates = duplicates;
777
- const content = this.parseToZodSchema(definition, definition.required || []);
778
- const containsRecursiveType = this.importClasses.has(fileName);
779
- if (containsRecursiveType) {
780
- this.importClasses.delete(fileName);
781
- }
782
- let imports = "";
783
- for (const cl of Array.from(this.importClasses).sort()) {
784
- imports += `import { ${cl} } from './${cl}.js'
785
- `;
813
+ // src/Swagger.ts
814
+ var import_zod2 = require("zod");
815
+ var Schema = import_zod2.z.object({
816
+ $ref: import_zod2.z.string().nullish(),
817
+ type: import_zod2.z.union([import_zod2.z.literal("array"), import_zod2.z.literal("object"), import_zod2.z.literal("file"), import_zod2.z.literal("string"), import_zod2.z.literal("boolean"), import_zod2.z.literal("integer")]).nullish(),
818
+ items: import_zod2.z.object({
819
+ $ref: import_zod2.z.string().nullish(),
820
+ type: import_zod2.z.string().nullish()
821
+ }).nullish(),
822
+ properties: import_zod2.z.union([import_zod2.z.array(import_zod2.z.string()).nullish(), import_zod2.z.record(import_zod2.z.object({ type: import_zod2.z.string() })).nullish()]),
823
+ description: import_zod2.z.string().nullish(),
824
+ additionalProperties: import_zod2.z.object({
825
+ type: import_zod2.z.string().nullish()
826
+ }).nullish()
827
+ });
828
+ var Definition = import_zod2.z.object({
829
+ required: import_zod2.z.array(import_zod2.z.string()).nullish(),
830
+ properties: import_zod2.z.record(
831
+ import_zod2.z.object({
832
+ type: import_zod2.z.string()
833
+ })
834
+ ).nullish()
835
+ });
836
+ var Definitions = import_zod2.z.record(Definition);
837
+ var EndpointParametersType = import_zod2.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
838
+ var EndpointParametersIn = import_zod2.z.enum(["body", "formData", "header", "path", "query"]);
839
+ var EndpointParameters = import_zod2.z.object({
840
+ type: EndpointParametersType.nullish(),
841
+ description: import_zod2.z.string().nullish(),
842
+ name: import_zod2.z.string(),
843
+ in: EndpointParametersIn,
844
+ required: import_zod2.z.boolean().nullish(),
845
+ schema: Schema.nullish(),
846
+ default: import_zod2.z.union([import_zod2.z.boolean(), import_zod2.z.string(), import_zod2.z.number(), import_zod2.z.array(import_zod2.z.any())]).nullish(),
847
+ enum: import_zod2.z.array(import_zod2.z.union([import_zod2.z.boolean(), import_zod2.z.string(), import_zod2.z.number()])).nullish(),
848
+ items: import_zod2.z.object({
849
+ type: import_zod2.z.string(),
850
+ enum: import_zod2.z.array(import_zod2.z.any()).nullish()
851
+ }).nullish()
852
+ });
853
+ var Endpoint = import_zod2.z.object({
854
+ description: import_zod2.z.string().nullish(),
855
+ consumes: import_zod2.z.array(import_zod2.z.string()).nullish(),
856
+ produces: import_zod2.z.array(import_zod2.z.string()).nullish(),
857
+ tags: import_zod2.z.array(import_zod2.z.string()).nullish(),
858
+ summary: import_zod2.z.string().nullish(),
859
+ operationId: import_zod2.z.string(),
860
+ deprecated: import_zod2.z.boolean().nullish(),
861
+ responses: import_zod2.z.record(
862
+ import_zod2.z.object({
863
+ description: import_zod2.z.string().nullish(),
864
+ schema: Schema.nullish(),
865
+ content: import_zod2.z.object({
866
+ "application/json": import_zod2.z.object({
867
+ schema: Schema.nullish()
868
+ })
869
+ }).nullish()
870
+ })
871
+ ),
872
+ parameters: import_zod2.z.array(EndpointParameters).nullish(),
873
+ requestBody: import_zod2.z.object({
874
+ required: import_zod2.z.boolean().nullish(),
875
+ content: import_zod2.z.object({
876
+ "application/json": import_zod2.z.object({
877
+ schema: Schema.nullish()
878
+ }).nullish()
879
+ }).nullish()
880
+ }).nullish(),
881
+ // The proper type is z.array(z.record(z.array(z.string()))).nullish() but somehow there are endpoints with
882
+ // an object type instead of an array type, so, yeah.
883
+ //
884
+ // Services with this error: sdk-iam, sdk-ugc.
885
+ "x-security": import_zod2.z.any().nullish()
886
+ });
887
+ var Operation2 = import_zod2.z.object({
888
+ get: Endpoint.nullish(),
889
+ post: Endpoint.nullish(),
890
+ patch: Endpoint.nullish(),
891
+ delete: Endpoint.nullish(),
892
+ put: Endpoint.nullish()
893
+ });
894
+ var Paths = import_zod2.z.record(Operation2);
895
+ var OpenApiSpec = import_zod2.z.object({
896
+ paths: Paths,
897
+ definitions: Definitions,
898
+ basePath: import_zod2.z.string(),
899
+ info: import_zod2.z.object({
900
+ description: import_zod2.z.string(),
901
+ title: import_zod2.z.string(),
902
+ contact: import_zod2.z.object({
903
+ name: import_zod2.z.string(),
904
+ url: import_zod2.z.string(),
905
+ email: import_zod2.z.string()
906
+ }),
907
+ version: import_zod2.z.string()
908
+ }),
909
+ schemes: import_zod2.z.array(import_zod2.z.string()).nullish(),
910
+ components: import_zod2.z.object({
911
+ schemas: Definitions
912
+ }).nullish()
913
+ });
914
+
915
+ // src/templates/template-api-method.ts
916
+ var templateApiMethod = ({
917
+ classMethod,
918
+ httpMethod,
919
+ path: path7,
920
+ pathParams,
921
+ bodyParams,
922
+ responseClasses,
923
+ classGenName,
924
+ methodParams,
925
+ methodParamsNoTypes,
926
+ xSecurity
927
+ }) => {
928
+ let newPath = `'${path7}'`;
929
+ let snippetMethod = "";
930
+ for (const pathParam of pathParams) {
931
+ const type = ParserUtils.parseType(pathParam);
932
+ const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
933
+ if (path7.match(`{${pathParam.name}}`)) {
934
+ if (type === "string") {
935
+ newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
936
+ } else {
937
+ newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
938
+ }
786
939
  }
787
- let exportedVariableString;
788
- let exportedTypeString;
789
- if (containsRecursiveType) {
790
- exportedVariableString = `
791
- export const ${fileName}: z.ZodType<${fileName}> = z.lazy(() =>
792
- ${content.schemaString}
793
- )
794
- `;
795
- exportedTypeString = `
796
- export interface ${fileName} {
797
- ${content.typeString}
798
- }
799
- `;
800
- } else {
801
- exportedVariableString = `export const ${fileName} = ${content.schemaString}`;
802
- exportedTypeString = `export interface ${fileName} extends z.TypeOf<typeof ${fileName}> {}`;
940
+ }
941
+ const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path7}'`, "--header 'accept: application/json'"];
942
+ const snippetApiArgs = [];
943
+ if (xSecurity !== void 0 || path7.includes("/admin")) {
944
+ snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
945
+ snippetApiArgs.push("{ axiosConfig: { request: { headers: { Authorization: 'Bearer {access_token}' } } } }".trim());
946
+ }
947
+ if (httpMethod !== "get") {
948
+ const curlParams = bodyParams?.map((ob) => {
949
+ return ` "${ob.name}": ""`;
950
+ });
951
+ if (curlParams.length > 0) {
952
+ snippetShellArgs.push(`--data-raw '{ ${curlParams}}'`);
803
953
  }
804
- const template = `import { z } from 'zod'
805
- ${imports}
806
-
807
- ${exportedVariableString}
808
-
809
- ${exportedTypeString}
954
+ }
955
+ const snippetShell = `curl ${snippetShellArgs.join(" \\\n ")}`;
956
+ const { responseType, responseTypeInAxiosResponse } = getResponseType({ responseClasses });
957
+ const methodImpl = `
958
+ async function ${classMethod}(${methodParams}): ${responseTypeInAxiosResponse} {
959
+ const $ = new ${classGenName}(axiosInstance, namespace, useSchemaValidation)
960
+ const resp = await $.${classMethod}(${methodParamsNoTypes})
961
+ if (resp.error) throw resp.error
962
+ return resp.response
963
+ }
810
964
  `;
811
- return { buffer: template, duplicateFound: this.duplicateFound };
965
+ const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
966
+ snippetMethod += `${classMethod}(${methodParams})
967
+ // return ${snippetPromiseString}`;
968
+ return {
969
+ generatedMethodString: methodImpl,
970
+ snippetApiArgs,
971
+ snippetMethod,
972
+ snippetShell
812
973
  };
813
- parseToZodSchema = (definition, requiredAttrs) => {
814
- if (definition.additionalProperties) {
815
- return this.parseToZodAttribute("", definition, []);
816
- }
817
- let properties;
818
- if (definition.properties) {
819
- properties = Object.entries(definition.properties);
820
- } else if (definition.items?.properties) {
821
- properties = Object.entries(definition.items.properties);
822
- } else {
823
- return {
824
- schemaString: "z.any()",
825
- typeString: "any"
826
- };
827
- }
828
- const schemaFields = [];
829
- const typeFields = [];
830
- for (const property of properties) {
831
- const [name, definition2] = property;
832
- const result = this.parseToZodAttribute(name, definition2, requiredAttrs);
833
- schemaFields.push(result.schemaString);
834
- typeFields.push(result.typeString);
835
- }
836
- if (definition?.type === "array") {
837
- return {
838
- schemaString: `z.array(z.object({${schemaFields.join(",")}}))`,
839
- typeString: typeFields.join(";")
840
- };
841
- }
842
- return {
843
- schemaString: `z.object({${schemaFields.join(",")}})`,
844
- typeString: typeFields.join(";")
845
- };
846
- };
847
- parseToZodAttribute = (name, definition, requiredAttrs) => {
848
- const isRequired = requiredAttrs.includes(name) || name === "";
849
- const schemaRequired = isRequired ? "" : ".nullish()";
850
- const typeRequired = isRequired ? "" : "?";
851
- const typeNullishability = isRequired ? "" : " | null | undefined";
852
- const schemaAttribute = name ? `'${name}':` : "";
853
- const typeAttribute = name ? `'${name}'${typeRequired}:` : "";
854
- const type = definition?.type;
855
- if (definition.properties) {
856
- const result = this.parseToZodSchema(definition, requiredAttrs);
857
- return {
858
- schemaString: `${schemaAttribute} ${result.schemaString}${schemaRequired}`,
859
- typeString: `${typeAttribute} ${result.typeString}${typeNullishability}`
860
- };
861
- } else if (type) {
862
- if (type === "object" && definition.additionalProperties) {
863
- const zodAttribute = this.parseToZodAttribute("", definition.additionalProperties, [""]);
864
- return {
865
- schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
866
- typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
867
- };
868
- }
869
- if (type === "object" && !definition.additionalProperties && !name) {
870
- return {
871
- schemaString: `z.any()`,
872
- typeString: "any"
873
- };
874
- }
875
- if (type === "object" && !definition.additionalProperties) {
876
- return {
877
- schemaString: `${schemaAttribute} z.record(z.any())${schemaRequired}`,
878
- typeString: `${typeAttribute} Record<string, any>${typeNullishability}`
879
- };
880
- }
881
- if (type === "integer" || type === "number") {
882
- const effectiveType = getZodNumberType(type);
883
- return {
884
- schemaString: `${schemaAttribute} z.${effectiveType.schemaString}()${schemaRequired}`,
885
- typeString: `${typeAttribute} ${effectiveType.typeString}${typeNullishability}`
886
- };
887
- }
888
- if (type === "array") {
889
- const items = definition.items;
890
- const ref2 = items?.$ref;
891
- let model2;
892
- if (ref2) {
893
- const refType = ParserUtils.parseRefType(ref2);
894
- this.importClasses.add(refType);
895
- model2 = {
896
- schemaString: refType,
897
- typeString: refType
898
- };
899
- } else if (items) {
900
- if (items.type === "array") {
901
- const ref3 = items.items?.$ref;
902
- if (ref3) {
903
- const refType = ParserUtils.parseRefType(ref3);
904
- this.importClasses.add(refType);
905
- model2 = {
906
- schemaString: refType,
907
- typeString: refType
908
- };
909
- } else if (items.items) {
910
- model2 = this.parseEnumItems(items.items);
911
- }
912
- return {
913
- schemaString: `${schemaAttribute} z.array(z.array(${model2.schemaString}))${schemaRequired}`,
914
- typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
915
- };
916
- } else {
917
- model2 = this.parseEnumItems(items);
918
- }
919
- } else {
920
- return {
921
- schemaString: `${schemaAttribute} z.array(z.any())${schemaRequired}`,
922
- typeString: `${typeAttribute} any[]${typeNullishability}`
923
- };
924
- }
925
- return {
926
- schemaString: `${schemaAttribute} z.array(${model2.schemaString})${schemaRequired}`,
927
- typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
928
- };
929
- }
930
- if (type !== "object") {
931
- const result = extractEnumObject(type, isRequired, definition.enum);
932
- return {
933
- schemaString: `${schemaAttribute} ${result.schemaString}`,
934
- typeString: `${typeAttribute} ${result.typeString}`
935
- };
936
- }
974
+ };
975
+
976
+ // src/templates/template-method.ts
977
+ var templateMethod = ({
978
+ classMethod,
979
+ description,
980
+ httpMethod,
981
+ path: path7,
982
+ pathParams,
983
+ bodyParams,
984
+ queryParams,
985
+ isFormUrlEncoded,
986
+ responseClasses,
987
+ deprecated
988
+ }) => {
989
+ let methodParams = "";
990
+ let methodParamsNoTypes = "";
991
+ let newPath = `'${path7}'`;
992
+ let importStatements = [];
993
+ const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path7);
994
+ for (const pathParam of sortedPathParams) {
995
+ const type = ParserUtils.parseType(pathParam);
996
+ if (pathParam.name !== "namespace") {
997
+ methodParams += pathParam.name + `:${type}, `;
998
+ methodParamsNoTypes += pathParam.name + ", ";
937
999
  }
938
- const ref = definition.$ref;
939
- let model = `z.record(z.any())`;
940
- if (ref) {
941
- model = ParserUtils.parseRefType(ref);
942
- const fullModelName = ref.replace("#/definitions/", "");
943
- this.duplicateFound = this.duplicates.has(fullModelName);
944
- if (this.duplicateFound) {
945
- model = this.duplicates.get(fullModelName);
1000
+ const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1001
+ if (path7.match(`{${pathParam.name}}`)) {
1002
+ if (type === "string") {
1003
+ newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
1004
+ } else {
1005
+ newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
946
1006
  }
947
- this.importClasses.add(model);
948
- model = `${model}`;
949
- }
950
- return {
951
- schemaString: `${schemaAttribute} ${model}${schemaRequired}`,
952
- typeString: `${typeAttribute} ${model}${typeNullishability}`
953
- };
954
- };
955
- parseEnumItems = (items) => {
956
- if (items.enum) {
957
- const enumStr = items.enum.map((e) => {
958
- return `"${e}"`;
959
- });
960
- return {
961
- schemaString: `z.enum([${enumStr}])`,
962
- typeString: `(${enumStr.join(" | ")})`
963
- };
964
- }
965
- if (items.type === "object") {
966
- return this.parseToZodSchema(items, items.required);
967
1007
  }
968
- let effectiveType;
969
- if (items.type === "integer" || items.type === "number") {
970
- effectiveType = getZodNumberType(items.type);
971
- } else {
972
- effectiveType = { typeString: items.type, schemaString: items.type };
973
- }
974
- return {
975
- schemaString: `z.${effectiveType.schemaString}()`,
976
- typeString: effectiveType.typeString
977
- };
978
- };
979
- }
980
- class TemplateZodArray {
981
- render = (name) => {
982
- const cls = name.replace("Array", "");
983
- const template = `import { z } from 'zod'
984
- import { ${cls} } from './${cls}.js'
985
-
986
- export const ${name} = z.array(${cls})
1008
+ }
1009
+ let dataType = null;
1010
+ if (httpMethod !== "get") {
1011
+ dataType = ParserUtils.parseBodyParamsType(bodyParams);
1012
+ importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
1013
+ methodParams += dataType ? `data: ${dataType},` : "";
1014
+ methodParamsNoTypes += dataType ? `data,` : "";
1015
+ }
1016
+ const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
1017
+ const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
1018
+ const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as AxiosRequestConfig` : "const params = {} as AxiosRequestConfig";
1019
+ const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
1020
+ const isDelete = ["delete"].includes(httpMethod);
1021
+ let dataPayload = "{params}";
1022
+ const descriptionText = extractDescription(description, { isDeprecated: deprecated, responseClasses });
1023
+ let formPayloadString = "";
1024
+ if (isFormUrlEncoded) {
1025
+ formPayloadString = ``;
1026
+ const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
1027
+ dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
1028
+ } else if (isPostPutPatch) {
1029
+ dataPayload = dataType ? `data, {params}` : "null, {params}";
1030
+ } else if (isDelete) {
1031
+ dataPayload = dataType ? `{data, params}` : "{params}";
1032
+ }
1033
+ const isFileUpload = methodParams.indexOf("data: {file") > -1;
1034
+ const { responseType, responseTypeInResponse } = getResponseType({ responseClasses });
1035
+ const resolvedResponseClassValidated = responseType !== "unknown" ? `${responseType}` : "z.unknown()";
1036
+ methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
1037
+ methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
1038
+ const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
1039
+ const generatedMethodName = `${classMethod}(${methodParams}): ${responseTypeInResponse}`;
1040
+ let methodImpl = `${descriptionText}
1041
+ ${generatedMethodName} {
1042
+ ${queryParamsDefault}
1043
+ const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1044
+ const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
987
1045
 
988
- export interface ${name} extends z.TypeOf<typeof ${name}> {}
1046
+ ${` return Validate.validateOrReturnResponse(this.useSchemaValidation, () => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')`}
1047
+ }
989
1048
  `;
990
- return template;
991
- };
992
- }
993
- const getZodNumberType = (type) => {
994
- if (type === "integer") {
995
- return {
996
- schemaString: "number().int",
997
- typeString: "number"
998
- };
1049
+ if (!isGuardInvoked) {
1050
+ methodImpl = ``;
999
1051
  }
1000
- return {
1001
- schemaString: type,
1002
- typeString: type
1052
+ const res = {
1053
+ methodImpl,
1054
+ methodParams,
1055
+ methodParamsNoTypes,
1056
+ importStatements
1003
1057
  };
1058
+ return res;
1004
1059
  };
1005
- const extractEnumObject = (type, isRequired, enumArr) => {
1006
- const schemaRequired = isRequired ? "" : ".nullish()";
1007
- const typeNullishability = isRequired ? "" : " | null | undefined";
1008
- if (enumArr) {
1009
- const enumStr = enumArr.map((e) => {
1010
- return `"${e}"`;
1011
- });
1012
- return {
1013
- schemaString: `z.enum([${enumStr}])${schemaRequired}`,
1014
- typeString: `(${enumStr.join(" | ")}${typeNullishability})`
1015
- };
1016
- }
1017
- return {
1018
- schemaString: `z.${type}()${schemaRequired}`,
1019
- typeString: `${type}${typeNullishability}`
1020
- };
1021
- };
1022
-
1023
- const templateApiIndex = (serviceName, serviceNameTitle, apiList) => {
1024
- let imports = "";
1025
- let returnStatement = "";
1026
- for (const cl of apiList) {
1027
- const dir = cl.toLowerCase().includes("admin") && cl !== "AdminApi" ? "generated-admin" : "generated-public";
1028
- imports += `
1029
- import { ${cl} } from './${dir}/${cl}.js'`;
1030
- returnStatement += `
1031
- ${cl}, `;
1032
- }
1033
- return `/**
1034
- * AUTO GENERATED
1035
- */
1036
- ${imports}
1037
-
1038
- const apis = {
1039
- ${returnStatement}
1040
- }
1041
-
1042
- export const ${serviceNameTitle} = apis
1043
- `;
1044
- };
1045
-
1046
- const Schema = zod.z.object({
1047
- $ref: zod.z.string().nullish(),
1048
- 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(),
1049
- items: zod.z.object({
1050
- $ref: zod.z.string().nullish(),
1051
- type: zod.z.string().nullish()
1052
- }).nullish(),
1053
- properties: zod.z.union([zod.z.array(zod.z.string()).nullish(), zod.z.record(zod.z.object({ type: zod.z.string() })).nullish()]),
1054
- description: zod.z.string().nullish(),
1055
- additionalProperties: zod.z.object({
1056
- type: zod.z.string().nullish()
1057
- }).nullish()
1058
- });
1059
- const Definition = zod.z.object({
1060
- required: zod.z.array(zod.z.string()).nullish(),
1061
- properties: zod.z.record(zod.z.object({
1062
- type: zod.z.string()
1063
- })).nullish()
1064
- });
1065
- const Definitions = zod.z.record(Definition);
1066
- const EndpointParametersType = zod.z.enum(["apiKey", "boolean", "int", "integer", "number", "string", "array", "file"]);
1067
- const EndpointParametersIn = zod.z.enum(["body", "formData", "header", "path", "query"]);
1068
- const EndpointParameters = zod.z.object({
1069
- type: EndpointParametersType.nullish(),
1070
- description: zod.z.string().nullish(),
1071
- name: zod.z.string(),
1072
- in: EndpointParametersIn,
1073
- required: zod.z.boolean().nullish(),
1074
- schema: Schema.nullish(),
1075
- default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
1076
- enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
1077
- items: zod.z.object({
1078
- type: zod.z.string(),
1079
- enum: zod.z.array(zod.z.any()).nullish()
1080
- }).nullish()
1081
- });
1082
- const Endpoint = zod.z.object({
1083
- description: zod.z.string().nullish(),
1084
- consumes: zod.z.array(zod.z.string()).nullish(),
1085
- produces: zod.z.array(zod.z.string()).nullish(),
1086
- tags: zod.z.array(zod.z.string()).nullish(),
1087
- summary: zod.z.string().nullish(),
1088
- operationId: zod.z.string(),
1089
- deprecated: zod.z.boolean().nullish(),
1090
- responses: zod.z.record(zod.z.object({
1091
- description: zod.z.string().nullish(),
1092
- schema: Schema.nullish(),
1093
- content: zod.z.object({
1094
- "application/json": zod.z.object({
1095
- schema: Schema.nullish()
1096
- })
1097
- }).nullish()
1098
- })),
1099
- parameters: zod.z.array(EndpointParameters).nullish(),
1100
- requestBody: zod.z.object({
1101
- required: zod.z.boolean().nullish(),
1102
- content: zod.z.object({
1103
- "application/json": zod.z.object({
1104
- schema: Schema.nullish()
1105
- }).nullish()
1106
- }).nullish()
1107
- }).nullish(),
1108
- "x-security": zod.z.any().nullish()
1109
- });
1110
- const Operation = zod.z.object({
1111
- get: Endpoint.nullish(),
1112
- post: Endpoint.nullish(),
1113
- patch: Endpoint.nullish(),
1114
- delete: Endpoint.nullish(),
1115
- put: Endpoint.nullish()
1116
- });
1117
- const Paths = zod.z.record(Operation);
1118
- zod.z.object({
1119
- paths: Paths,
1120
- definitions: Definitions,
1121
- basePath: zod.z.string(),
1122
- info: zod.z.object({
1123
- description: zod.z.string(),
1124
- title: zod.z.string(),
1125
- contact: zod.z.object({
1126
- name: zod.z.string(),
1127
- url: zod.z.string(),
1128
- email: zod.z.string()
1129
- }),
1130
- version: zod.z.string()
1131
- }),
1132
- schemes: zod.z.array(zod.z.string()).nullish(),
1133
- components: zod.z.object({
1134
- schemas: Definitions
1135
- }).nullish()
1136
- });
1137
1060
 
1138
- const templateMethod = ({
1061
+ // src/templates/template-query-method.ts
1062
+ var POST_FETCH_INCLUDES_PATH = ["/table-query/"];
1063
+ var templateQueryMethod = ({
1139
1064
  classMethod,
1140
- description,
1141
1065
  httpMethod,
1142
- path,
1066
+ path: path7,
1143
1067
  pathParams,
1144
- bodyParams,
1145
- queryParams,
1146
- isFormUrlEncoded,
1147
- responseClass,
1068
+ responseClasses,
1069
+ methodParams,
1070
+ apiGenName,
1071
+ description,
1148
1072
  deprecated
1149
1073
  }) => {
1150
- let methodParams = "";
1151
- let methodParamsNoTypes = "";
1152
- let newPath = `'${path}'`;
1153
- let importStatements = [];
1154
- const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
1074
+ const isPostFetch = httpMethod === "post" && (POST_FETCH_INCLUDES_PATH.some((p) => path7.includes(p)) || path7.endsWith("/list"));
1075
+ const isFetch = classMethod.startsWith("fetch");
1076
+ const isGet = httpMethod === "get" || isPostFetch || isFetch;
1077
+ const queryMethod = isGet ? "useQuery" : "useMutation";
1078
+ let mParams = "";
1079
+ let mParamsNoTypes = "";
1080
+ let newPath = `'${path7}'`;
1081
+ const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path7);
1155
1082
  for (const pathParam of sortedPathParams) {
1156
1083
  const type = ParserUtils.parseType(pathParam);
1157
1084
  if (pathParam.name !== "namespace") {
1158
- methodParams += pathParam.name + `:${type}, `;
1159
- methodParamsNoTypes += pathParam.name + ", ";
1085
+ mParams += pathParam.name + `:${type}, `;
1086
+ mParamsNoTypes += pathParam.name + ", ";
1160
1087
  }
1161
1088
  const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1162
- if (path.match(`{${pathParam.name}}`)) {
1089
+ if (path7.match(`{${pathParam.name}}`)) {
1163
1090
  if (type === "string") {
1164
1091
  newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
1165
1092
  } else {
@@ -1167,133 +1094,121 @@ const templateMethod = ({
1167
1094
  }
1168
1095
  }
1169
1096
  }
1170
- let dataType = null;
1171
- if (httpMethod !== "get") {
1172
- dataType = ParserUtils.parseBodyParamsType(bodyParams);
1173
- importStatements = ParserUtils.parseBodyParamsImports(bodyParams);
1174
- methodParams += dataType ? `data: ${dataType},` : "";
1175
- methodParamsNoTypes += dataType ? `data,` : "";
1176
- }
1177
- const isAnyRequired = ParserUtils.isAnyQueryParamRequired(queryParams);
1178
- const queryParamsType = queryParams.length ? `queryParams${isAnyRequired ? "" : "?"}: {${ParserUtils.parseQueryParamsType(queryParams)}}` : "";
1179
- const queryParamsDefault = queryParams.length ? `const params = {${ParserUtils.parseQueryParamsDefault(queryParams)} ...queryParams} as SDKRequestConfig` : "const params = {} as SDKRequestConfig";
1180
- const isPostPutPatch = ["post", "put", "patch"].includes(httpMethod);
1181
- const isDelete = ["delete"].includes(httpMethod);
1182
- let dataPayload = "{params}";
1183
- const descriptionText = description ? `
1184
- /**${deprecated ? "\n * @deprecated" : ""}
1185
- * ${description.replace(/\n/g, "\n * ")}
1186
- */` : "";
1187
- let formPayloadString = "";
1188
- if (isFormUrlEncoded) {
1189
- formPayloadString = ``;
1190
- const params = "{ ...params, headers: { ...params.headers, 'content-type': 'application/x-www-form-urlencoded' } }";
1191
- dataPayload = dataType ? `CodeGenUtil.getFormUrlEncodedData(data), ${params}` : `null, ${params}`;
1192
- } else if (isPostPutPatch) {
1193
- dataPayload = dataType ? `data, {params}` : "null, {params}";
1194
- } else if (isDelete) {
1195
- dataPayload = dataType ? `{data, params}` : "{params}";
1196
- }
1197
- const isFileUpload = methodParams.indexOf("data: {file") > -1;
1198
- const resolvedResponseClass = responseClass || "unknown";
1199
- const resolvedResponseClassValidated = responseClass || "z.unknown()";
1200
- methodParams = (queryParamsType ? `${methodParams} ${queryParamsType}` : methodParams).replace(/,\s*$/, "");
1201
- methodParamsNoTypes = queryParamsType ? `${methodParamsNoTypes} queryParams` : methodParamsNoTypes;
1202
- let methodImpl = "";
1203
- const isGuardInvoked = ["get", "post", "put", "patch", "delete"].includes(httpMethod);
1204
- const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1205
- const generateMethodName = () => `${classMethod}(${methodParams}): Promise<${responseSyncType}<${responseType}>>`;
1206
- const responseSyncType = "IResponse";
1207
- methodImpl = `${descriptionText}
1208
- ${generateMethodName()} {
1209
- ${queryParamsDefault}
1210
- const url = ${newPath} ${formPayloadString} ${isFileUpload ? "\n// TODO file upload not implemented" : ""}
1211
- const resultPromise = this.axiosInstance.${httpMethod}(url, ${dataPayload})
1097
+ const { responseType } = getResponseType({ responseClasses });
1098
+ let _methodName = convertMethodNameToHook({ classMethod, apiGenName, isGet });
1099
+ const _methodParams = methodParams && methodParams.length > 0 ? `& { ${methodParams} }` : "";
1100
+ const _methodParamsImpl = convertToMethodImplArgs(methodParams);
1101
+ const queryKey = createQueryKey(apiGenName, classMethod);
1102
+ const descriptionText = extractDescription(description, {
1103
+ isDeprecated: deprecated,
1104
+ responseClasses,
1105
+ other: [" ", "#### Default Query Options", "The default options include:", "```", "{", ` queryKey: [${queryKey}, input]`, "}", "```"]
1106
+ });
1107
+ const queryMethodImpl = `
1212
1108
 
1213
- ${` return Validate.validateOrReturnResponse(this.useSchemaValidation, () => resultPromise, ${resolvedResponseClassValidated}, '${resolvedResponseClassValidated}')`}
1109
+ ${descriptionText}
1110
+ export const ${_methodName} = (
1111
+ sdk: AccelByteSDK,
1112
+ input: SdkSetConfigParam ${_methodParams},
1113
+ options?: Omit<UseQueryOptions<${responseType}, AxiosError<ApiError>>, 'queryKey'>,
1114
+ callback?: (data: AxiosResponse<${responseType}>) => void
1115
+ ): UseQueryResult<${responseType}, AxiosError<ApiError>> => {
1116
+
1117
+ const queryFn = (
1118
+ sdk: AccelByteSDK,
1119
+ input: Parameters<typeof ${_methodName}>[1]
1120
+ ) => async () => {
1121
+ const response =
1122
+ (await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
1123
+ ${classMethod}(${_methodParamsImpl}))
1124
+ callback && callback(response)
1125
+ return response.data
1214
1126
  }
1127
+
1128
+ return ${queryMethod}<${responseType}, AxiosError<ApiError>>({
1129
+ queryKey: [${queryKey}, input],
1130
+ queryFn: queryFn(sdk, input),
1131
+ ...options
1132
+ })
1133
+ }
1134
+
1215
1135
  `;
1216
- if (!isGuardInvoked) {
1217
- methodImpl = ``;
1136
+ const mutationMethodImpl = `
1137
+
1138
+ ${descriptionText}
1139
+ export const ${_methodName} = (
1140
+ sdk: AccelByteSDK,
1141
+ options?: Omit<UseMutationOptions<${responseType}, AxiosError<ApiError>, SdkSetConfigParam ${_methodParams}>, 'mutationKey'>,
1142
+ callback?: (data: ${responseType}) => void
1143
+ ): UseMutationResult<${responseType}, AxiosError<ApiError>, SdkSetConfigParam ${_methodParams}> => {
1144
+
1145
+ const mutationFn = async (input: SdkSetConfigParam ${_methodParams}) => {
1146
+ const response =
1147
+ (await ${apiGenName}(sdk, { coreConfig: input.coreConfig, axiosConfig: input.axiosConfig }).
1148
+ ${classMethod}(${_methodParamsImpl}))
1149
+ callback && callback(response.data)
1150
+ return response.data
1218
1151
  }
1219
- const res = {
1220
- methodImpl,
1221
- methodParams,
1222
- methodParamsNoTypes,
1223
- importStatements
1224
- };
1152
+
1153
+ return useMutation({
1154
+ mutationKey: [${queryKey}],
1155
+ mutationFn,
1156
+ ...options
1157
+ })
1158
+ }
1159
+
1160
+ `;
1161
+ return isGet ? queryMethodImpl : mutationMethodImpl;
1162
+ };
1163
+ function versionMutationSuffixMethodName(baseMethodName) {
1164
+ const parts = baseMethodName.split(/(_v\d+)$/);
1165
+ const name = parts[0];
1166
+ const versionSuffix = parts[1] || "";
1167
+ const res = `${name}Mutation${versionSuffix}`;
1225
1168
  return res;
1169
+ }
1170
+ function createQueryKey(className, methodName) {
1171
+ const prefixRegex = /^(get|create|update|delete|patch|post|fetch)[_]?/i;
1172
+ const cleanedMethodName = methodName.replace(prefixRegex, "").trim();
1173
+ const finalMethodName = cleanedMethodName.charAt(0).toUpperCase() + cleanedMethodName.slice(1);
1174
+ return `Key_${className.replace("Api", "")}.${finalMethodName}`;
1175
+ }
1176
+ var prefixMappings = {
1177
+ get: "use",
1178
+ create: "useCreate",
1179
+ patch: "usePatch",
1180
+ update: "useUpdate",
1181
+ delete: "useDelete",
1182
+ post: "usePost",
1183
+ fetch: "useFetch"
1226
1184
  };
1227
-
1228
- const templateApiMethod = ({
1229
- classMethod,
1230
- description,
1231
- httpMethod,
1232
- path,
1233
- pathParams,
1234
- bodyParams,
1235
- responseClass,
1236
- classGenName,
1237
- methodParams,
1238
- methodParamsNoTypes,
1239
- deprecated,
1240
- xSecurity
1241
- }) => {
1242
- let newPath = `'${path}'`;
1243
- let snippetMethod = "";
1244
- for (const pathParam of pathParams) {
1245
- const type = ParserUtils.parseType(pathParam);
1246
- const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1247
- if (path.match(`{${pathParam.name}}`)) {
1248
- if (type === "string") {
1249
- newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
1250
- } else {
1251
- newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
1252
- }
1185
+ function convertMethodNameToHook({ classMethod, apiGenName, isGet }) {
1186
+ for (const [originalPrefix] of Object.entries(prefixMappings)) {
1187
+ if (classMethod.startsWith(originalPrefix)) {
1188
+ const methodName = !isGet ? versionMutationSuffixMethodName(classMethod) : classMethod;
1189
+ return `use${apiGenName}_${capitalize(methodName)}`;
1253
1190
  }
1254
1191
  }
1255
- const snippetShellArgs = ["--location --request", `${httpMethod} '__DOMAIN__${path}'`, "--header 'accept: application/json'"];
1256
- const snippetApiArgs = [];
1257
- if (xSecurity !== void 0 || path.includes("/admin")) {
1258
- snippetShellArgs.push("--header 'Authorization: Bearer {access_token}'");
1259
- snippetApiArgs.push("{ config: { headers: { Authorization: 'Bearer {access_token}' } }}".trim());
1260
- }
1261
- if (httpMethod !== "get") {
1262
- const curlParams = bodyParams?.map((ob) => {
1263
- return ` "${ob.name}": ""`;
1264
- });
1265
- if (curlParams.length > 0) {
1266
- snippetShellArgs.push(`--data-raw '{ ${curlParams}}'`);
1192
+ return classMethod;
1193
+ }
1194
+ function convertToMethodImplArgs(methodArgs) {
1195
+ const properties = methodArgs.split(/,\s*(?![^{}]*\})/).map((prop) => prop.trim()).filter(Boolean);
1196
+ const formattedProperties = [];
1197
+ properties.forEach((prop) => {
1198
+ if (prop.includes(": {")) {
1199
+ const propertyName = prop.split(": {")[0].replace("?", "").trim();
1200
+ formattedProperties.push(`input.${propertyName}`);
1201
+ } else {
1202
+ const colonIndex = prop.indexOf(":");
1203
+ const propertyName = prop.substring(0, colonIndex).replace("?", "").trim();
1204
+ formattedProperties.push(`input.${propertyName}`);
1267
1205
  }
1268
- }
1269
- const snippetShell = `curl ${snippetShellArgs.join(" \\\n ")}`;
1270
- const descriptionText = description ? `
1271
- /**${deprecated ? "\n * @deprecated" : ""}
1272
- * ${description.replace(/\n/g, "\n * ")}
1273
- */` : "";
1274
- const resolvedResponseClass = responseClass || "unknown";
1275
- const responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1276
- const methodImpl = `
1277
- ${descriptionText}
1278
- async function ${classMethod}(${methodParams}): Promise<${responseType}> {
1279
- const $ = new ${classGenName}(Network.create(requestConfig), namespace, useSchemaValidation)
1280
- const resp = await $.${classMethod}(${methodParamsNoTypes})
1281
- if (resp.error) throw resp.error
1282
- return resp.response.data
1283
- }
1284
- `;
1285
- const snippetPromiseString = responseType !== "unknown" ? `Promise<${responseType}>` : "Promise";
1286
- snippetMethod += `${classMethod}(${methodParams})
1287
- // return ${snippetPromiseString}`;
1288
- return {
1289
- generatedMethodString: methodImpl,
1290
- snippetApiArgs,
1291
- snippetMethod,
1292
- snippetShell
1293
- };
1294
- };
1206
+ });
1207
+ return formattedProperties.join(", ");
1208
+ }
1295
1209
 
1296
- const templateSdkSnippet = ({
1210
+ // src/templates/template-sdk-snippet.ts
1211
+ var templateSdkSnippet = ({
1297
1212
  serviceNameTitle,
1298
1213
  apiName,
1299
1214
  snippetMethod,
@@ -1305,11 +1220,11 @@ const templateSdkSnippet = ({
1305
1220
  normMethod = normalizeMethodSnippet(normMethod, "queryParams:");
1306
1221
  normMethod = normalizeMethodSnippet(normMethod, "queryParams?:");
1307
1222
  normMethod += "\n\n//" + methodArr[1];
1308
- const sdkSnippet = `import { Accelbyte } from '@accelbyte/sdk'
1223
+ const sdkSnippet = `import { AccelByte } from '@accelbyte/sdk'
1309
1224
  import { ${serviceNameTitle} } from '@accelbyte/sdk-${serviceNameTitle.toLowerCase()}'
1310
1225
 
1311
- const sdk = Accelbyte.SDK({
1312
- options: {
1226
+ const sdk = AccelByte.SDK({
1227
+ coreConfig: {
1313
1228
  baseURL: 'https://demo.accelbyte.io',
1314
1229
  clientId: '77f88506b6174c3ea4d925f5b4096ce8',
1315
1230
  namespace: 'accelbyte',
@@ -1321,7 +1236,7 @@ ${serviceNameTitle}.${apiName}(${snippetApiArgs.join(", ")})
1321
1236
  .${normMethod}`;
1322
1237
  return sdkSnippet;
1323
1238
  };
1324
- const normalizeMethodSnippet = (methodInput, splitWord) => {
1239
+ var normalizeMethodSnippet = (methodInput, splitWord) => {
1325
1240
  const split1 = methodInput.split(splitWord);
1326
1241
  if (!split1[1]) {
1327
1242
  return methodInput;
@@ -1339,327 +1254,486 @@ const normalizeMethodSnippet = (methodInput, splitWord) => {
1339
1254
  return result;
1340
1255
  };
1341
1256
 
1342
- const templateQueryMethod = ({
1343
- classMethod,
1344
- httpMethod,
1345
- path,
1346
- pathParams,
1347
- responseClass,
1348
- methodParams,
1349
- apiGenName,
1350
- isFormUrlEncoded,
1351
- deprecated
1352
- }) => {
1353
- if (isFormUrlEncoded || deprecated) {
1354
- return "";
1355
- }
1356
- const isPostFetch = httpMethod === "post" && (path.includes("/table-query/") || path.endsWith("/list"));
1357
- const isAdmin = path.indexOf("/admin/") > 0;
1358
- const isGet = httpMethod === "get" || isPostFetch;
1359
- let queryMethod = isGet ? "useQuery" : "useMutation";
1360
- let mParams = "";
1361
- let mParamsNoTypes = "";
1362
- let newPath = `'${path}'`;
1363
- const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
1364
- for (const pathParam of sortedPathParams) {
1365
- const type = ParserUtils.parseType(pathParam);
1366
- if (pathParam.name !== "namespace") {
1367
- mParams += pathParam.name + `:${type}, `;
1368
- mParamsNoTypes += pathParam.name + ", ";
1369
- }
1370
- const pName = pathParam.name === "namespace" ? "this.namespace" : pathParam.name;
1371
- if (path.match(`{${pathParam.name}}`)) {
1372
- if (type === "string") {
1373
- newPath = `${newPath}.replace('{${pathParam.name}}', ${pName})`;
1374
- } else {
1375
- newPath = `${newPath}.replace('{${pathParam.name}}', String(${pName}))`;
1376
- }
1257
+ // src/helpers/SwaggerReaderHelpers.ts
1258
+ var GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
1259
+ var SwaggerReaderHelpers = class _SwaggerReaderHelpers {
1260
+ static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
1261
+ static parseAllEndpoints = async ({
1262
+ api,
1263
+ sdkName,
1264
+ serviceName
1265
+ }) => {
1266
+ const result = {
1267
+ admin: {
1268
+ arrayDefinitions: [],
1269
+ snippetMap: {},
1270
+ tagToClassImportsRecord: {},
1271
+ tagToEndpointClassesRecord: {},
1272
+ tagToSdkClientRecord: {},
1273
+ tagToSdkFunctionNamesRecord: {},
1274
+ tagToSdkImportsRecord: {},
1275
+ tagToEndpointQueryRecord: {},
1276
+ tagToSdkFunctionDescription: {}
1277
+ },
1278
+ public: {
1279
+ arrayDefinitions: [],
1280
+ snippetMap: {},
1281
+ tagToClassImportsRecord: {},
1282
+ tagToEndpointClassesRecord: {},
1283
+ tagToSdkClientRecord: {},
1284
+ tagToSdkFunctionNamesRecord: {},
1285
+ tagToSdkImportsRecord: {},
1286
+ tagToEndpointQueryRecord: {},
1287
+ tagToSdkFunctionDescription: {}
1288
+ }
1289
+ };
1290
+ const sortedPathsByLength = new Map(
1291
+ Object.entries(api.paths).sort((a, b) => {
1292
+ if (a[0].length === b[0].length) {
1293
+ return a[0].localeCompare(b[0]);
1294
+ } else {
1295
+ return a[0].length - b[0].length;
1296
+ }
1297
+ })
1298
+ );
1299
+ const sortedKeys = Array.from(sortedPathsByLength.keys());
1300
+ const servicePrefix = _SwaggerReaderHelpers.getServicePrefix(sortedKeys);
1301
+ const tagToClassMethodsMap = {
1302
+ admin: {},
1303
+ public: {}
1304
+ };
1305
+ for (const [path7, operation] of sortedPathsByLength) {
1306
+ if (path7.indexOf("/healthz") >= 0) {
1307
+ continue;
1308
+ }
1309
+ const isAdminEndpoint = path7.indexOf("/admin/") > -1;
1310
+ const picked = isAdminEndpoint ? result.admin : result.public;
1311
+ const {
1312
+ arrayDefinitions,
1313
+ snippetMap,
1314
+ tagToClassImportsRecord,
1315
+ tagToEndpointClassesRecord,
1316
+ tagToSdkClientRecord,
1317
+ tagToSdkFunctionNamesRecord,
1318
+ tagToSdkImportsRecord,
1319
+ tagToEndpointQueryRecord,
1320
+ tagToSdkFunctionDescription
1321
+ } = picked;
1322
+ const tagToClassMethodsMapByType = isAdminEndpoint ? tagToClassMethodsMap.admin : tagToClassMethodsMap.public;
1323
+ const generatedMethods = {};
1324
+ const httpMethods = Object.keys(operation);
1325
+ for (const httpMethod of httpMethods) {
1326
+ const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
1327
+ console.error(JSON.stringify({ path: path7, httpMethod }, null, 2));
1328
+ throw error;
1329
+ });
1330
+ if (!endpoint.tags) continue;
1331
+ const [tag] = endpoint.tags;
1332
+ const pathWithBase = `${api.basePath ?? ""}${path7}`;
1333
+ const permissionType = getPermissionType(getPermission(endpoint));
1334
+ tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
1335
+ const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
1336
+ const classMethod = ParserUtils.generateNaturalLangMethod({
1337
+ servicePrefix,
1338
+ path: path7,
1339
+ httpMethod,
1340
+ isForm,
1341
+ existingMethods: tagToClassMethodsMapByType[tag],
1342
+ permissionType
1343
+ });
1344
+ tagToClassMethodsMapByType[tag][classMethod] = `${path7} ${httpMethod}`;
1345
+ generatedMethods[`${path7} ${httpMethod}`] = `${classMethod}`;
1346
+ if (!snippetMap[pathWithBase]) {
1347
+ snippetMap[pathWithBase] = {};
1348
+ }
1349
+ const description = endpoint.description?.replace(/\s+/g, " ") || "";
1350
+ const responseClasses = ParserUtils.get2xxResponses(endpoint.responses);
1351
+ const responseClass = responseClasses.length > 1 ? null : responseClasses?.[0];
1352
+ const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
1353
+ tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
1354
+ if (responseClass) {
1355
+ tagToClassImportsRecord[className][responseClass] = `import { ${responseClass} } from '../../generated-definitions/${responseClass}.js'`;
1356
+ }
1357
+ if (responseClass && responseClass.endsWith("Array")) {
1358
+ arrayDefinitions.push(responseClass);
1359
+ }
1360
+ const queryParams = ParserUtils.filterQueryParameters(endpoint.parameters);
1361
+ const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
1362
+ const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
1363
+ let bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
1364
+ const deprecated = !!endpoint.deprecated;
1365
+ if (endpoint.requestBody) {
1366
+ bodyParams = [
1367
+ {
1368
+ name: "body",
1369
+ in: "body",
1370
+ schema: endpoint.requestBody.content["application/json"]?.schema
1371
+ }
1372
+ ];
1373
+ }
1374
+ const { methodImpl, methodParams, methodParamsNoTypes, importStatements } = templateMethod({
1375
+ classMethod,
1376
+ description,
1377
+ httpMethod,
1378
+ path: pathWithBase,
1379
+ pathParams,
1380
+ bodyParams,
1381
+ queryParams,
1382
+ isFormUrlEncoded,
1383
+ responseClasses,
1384
+ deprecated
1385
+ });
1386
+ tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
1387
+ const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1388
+ const queryMethodImpl = templateQueryMethod({
1389
+ classMethod,
1390
+ httpMethod,
1391
+ path: pathWithBase,
1392
+ pathParams,
1393
+ responseClasses,
1394
+ methodParams,
1395
+ apiGenName,
1396
+ deprecated,
1397
+ description
1398
+ });
1399
+ tagToEndpointQueryRecord[tag] = (tagToEndpointQueryRecord[tag] || "") + queryMethodImpl;
1400
+ const fnDescription = extractDescription(description, { isDeprecated: deprecated, responseClasses });
1401
+ const tagFnDescriptions = tagToSdkFunctionDescription[tag];
1402
+ tagToSdkFunctionDescription[tag] = {
1403
+ ...tagFnDescriptions,
1404
+ [classMethod]: fnDescription
1405
+ };
1406
+ const { generatedMethodString, snippetApiArgs, snippetMethod, snippetShell } = templateApiMethod({
1407
+ classMethod,
1408
+ httpMethod,
1409
+ path: pathWithBase,
1410
+ pathParams,
1411
+ bodyParams,
1412
+ responseClasses,
1413
+ classGenName,
1414
+ methodParams,
1415
+ methodParamsNoTypes,
1416
+ xSecurity: endpoint["x-security"]
1417
+ });
1418
+ tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
1419
+ tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + classMethod + ",";
1420
+ tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
1421
+ const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1422
+ const resultSnippet = templateSdkSnippet({
1423
+ serviceNameTitle,
1424
+ apiName: apiGenName,
1425
+ snippetMethod,
1426
+ snippetApiArgs
1427
+ });
1428
+ const currentSnippetMap = {};
1429
+ snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
1430
+ currentSnippetMap.web = resultSnippet;
1431
+ const generatedDirName = isAdminEndpoint ? "generated-admin" : "generated-public";
1432
+ currentSnippetMap.webGit = GIT_URL + `/sdk-${sdkName}/src/${generatedDirName}/${apiGenName}.ts`;
1433
+ currentSnippetMap.shell = snippetShell;
1434
+ }
1435
+ }
1436
+ for (const key in result) {
1437
+ result[key].arrayDefinitions = Array.from(new Set(result[key].arrayDefinitions));
1438
+ }
1439
+ return result;
1440
+ };
1441
+ };
1442
+
1443
+ // src/templates/template-api-index.ts
1444
+ var templateApiIndex = (serviceNameTitle, apiList) => {
1445
+ let imports = "";
1446
+ let returnStatement = "";
1447
+ for (const cl of apiList) {
1448
+ const dir = cl.toLowerCase().includes("admin") && cl !== "AdminApi" ? "generated-admin" : "generated-public";
1449
+ imports += `
1450
+ import { ${cl} } from './${dir}/${cl}.js'`;
1451
+ returnStatement += `
1452
+ ${cl}, `;
1453
+ }
1454
+ return `/**
1455
+ * AUTO GENERATED
1456
+ */
1457
+ ${imports}
1458
+ import { author, name, version } from '../package.json'
1459
+
1460
+ console.log(\`\${name}@\${version}\`)
1461
+
1462
+ const apis = {
1463
+ ${returnStatement}
1464
+ version: () => console.log({
1465
+ version,
1466
+ name,
1467
+ author
1468
+ })
1469
+ }
1470
+
1471
+ export const ${serviceNameTitle} = apis
1472
+ `;
1473
+ };
1474
+
1475
+ // src/templates/template-zod.ts
1476
+ var TemplateZod = class {
1477
+ duplicates;
1478
+ duplicateFound = false;
1479
+ //
1480
+ importClasses = /* @__PURE__ */ new Set();
1481
+ // --
1482
+ render = (fileName, definition, duplicates) => {
1483
+ this.duplicates = duplicates;
1484
+ const content = this.parseToZodSchema(definition, definition.required || []);
1485
+ const containsRecursiveType = this.importClasses.has(fileName);
1486
+ if (containsRecursiveType) {
1487
+ this.importClasses.delete(fileName);
1488
+ }
1489
+ let imports = "";
1490
+ for (const cl of Array.from(this.importClasses).sort()) {
1491
+ imports += `import { ${cl} } from './${cl}.js'
1492
+ `;
1493
+ }
1494
+ let exportedVariableString;
1495
+ let exportedTypeString;
1496
+ if (containsRecursiveType) {
1497
+ exportedVariableString = `
1498
+ export const ${fileName}: z.ZodType<${fileName}> = z.lazy(() =>
1499
+ ${content.schemaString}
1500
+ )
1501
+ `;
1502
+ exportedTypeString = `
1503
+ export interface ${fileName} {
1504
+ ${content.typeString}
1505
+ }
1506
+ `;
1507
+ } else {
1508
+ exportedVariableString = `export const ${fileName} = ${content.schemaString}`;
1509
+ exportedTypeString = `export interface ${fileName} extends z.TypeOf<typeof ${fileName}> {}`;
1510
+ }
1511
+ const template = `import { z } from 'zod'
1512
+ ${imports}
1513
+
1514
+ ${exportedVariableString}
1515
+
1516
+ ${exportedTypeString}
1517
+ `;
1518
+ return { buffer: template, duplicateFound: this.duplicateFound };
1519
+ };
1520
+ // --
1521
+ parseToZodSchema = (definition, requiredAttrs) => {
1522
+ if (definition.additionalProperties) {
1523
+ return this.parseToZodAttribute("", definition, []);
1524
+ }
1525
+ let properties;
1526
+ if (definition.properties) {
1527
+ properties = Object.entries(definition.properties);
1528
+ } else if (definition.items?.properties) {
1529
+ properties = Object.entries(definition.items.properties);
1530
+ } else {
1531
+ return {
1532
+ schemaString: "z.any()",
1533
+ typeString: "any"
1534
+ };
1535
+ }
1536
+ const schemaFields = [];
1537
+ const typeFields = [];
1538
+ for (const property of properties) {
1539
+ const [name, definition2] = property;
1540
+ const result = this.parseToZodAttribute(name, definition2, requiredAttrs);
1541
+ schemaFields.push(result.schemaString);
1542
+ typeFields.push(result.typeString);
1543
+ }
1544
+ if (definition?.type === "array") {
1545
+ return {
1546
+ schemaString: `z.array(z.object({${schemaFields.join(",")}}))`,
1547
+ typeString: typeFields.join(";")
1548
+ };
1549
+ }
1550
+ return {
1551
+ schemaString: `z.object({${schemaFields.join(",")}})`,
1552
+ typeString: typeFields.join(";")
1553
+ };
1554
+ };
1555
+ // --
1556
+ parseToZodAttribute = (name, definition, requiredAttrs) => {
1557
+ const isRequired = requiredAttrs.includes(name) || name === "";
1558
+ const schemaRequired = isRequired ? "" : ".nullish()";
1559
+ const typeRequired = isRequired ? "" : "?";
1560
+ const typeNullishability = isRequired ? "" : " | null | undefined";
1561
+ const schemaAttribute = name ? `'${name}':` : "";
1562
+ const typeAttribute = name ? `'${name}'${typeRequired}:` : "";
1563
+ const type = definition?.type;
1564
+ if (definition.properties) {
1565
+ const result = this.parseToZodSchema(definition, requiredAttrs);
1566
+ return {
1567
+ schemaString: `${schemaAttribute} ${result.schemaString}${schemaRequired}`,
1568
+ typeString: `${typeAttribute} ${result.typeString}${typeNullishability}`
1569
+ };
1570
+ } else if (type) {
1571
+ if (type === "object" && definition.additionalProperties) {
1572
+ const zodAttribute = this.parseToZodAttribute("", definition.additionalProperties, [""]);
1573
+ return {
1574
+ schemaString: `${schemaAttribute} z.record(${zodAttribute.schemaString})${schemaRequired}`,
1575
+ typeString: `${typeAttribute} Record<string, ${zodAttribute.typeString}>${typeNullishability}`
1576
+ };
1577
+ }
1578
+ if (type === "object" && !definition.additionalProperties && !name) {
1579
+ return {
1580
+ schemaString: `z.any()`,
1581
+ typeString: "any"
1582
+ };
1583
+ }
1584
+ if (type === "object" && !definition.additionalProperties) {
1585
+ return {
1586
+ schemaString: `${schemaAttribute} z.record(z.any())${schemaRequired}`,
1587
+ typeString: `${typeAttribute} Record<string, any>${typeNullishability}`
1588
+ };
1589
+ }
1590
+ if (type === "integer" || type === "number") {
1591
+ const effectiveType = getZodNumberType(type);
1592
+ return {
1593
+ schemaString: `${schemaAttribute} z.${effectiveType.schemaString}()${schemaRequired}`,
1594
+ typeString: `${typeAttribute} ${effectiveType.typeString}${typeNullishability}`
1595
+ };
1596
+ }
1597
+ if (type === "array") {
1598
+ const items = definition.items;
1599
+ const ref2 = items?.$ref;
1600
+ let model2;
1601
+ if (ref2) {
1602
+ const refType = ParserUtils.parseRefType(ref2);
1603
+ this.importClasses.add(refType);
1604
+ model2 = {
1605
+ schemaString: refType,
1606
+ typeString: refType
1607
+ };
1608
+ } else if (items) {
1609
+ if (items.type === "array") {
1610
+ const ref3 = items.items?.$ref;
1611
+ if (ref3) {
1612
+ const refType = ParserUtils.parseRefType(ref3);
1613
+ this.importClasses.add(refType);
1614
+ model2 = {
1615
+ schemaString: refType,
1616
+ typeString: refType
1617
+ };
1618
+ } else if (items.items) {
1619
+ model2 = this.parseEnumItems(items.items);
1620
+ }
1621
+ return {
1622
+ schemaString: `${schemaAttribute} z.array(z.array(${model2.schemaString}))${schemaRequired}`,
1623
+ typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
1624
+ };
1625
+ } else {
1626
+ model2 = this.parseEnumItems(items);
1627
+ }
1628
+ } else {
1629
+ return {
1630
+ schemaString: `${schemaAttribute} z.array(z.any())${schemaRequired}`,
1631
+ typeString: `${typeAttribute} any[]${typeNullishability}`
1632
+ };
1633
+ }
1634
+ return {
1635
+ schemaString: `${schemaAttribute} z.array(${model2.schemaString})${schemaRequired}`,
1636
+ typeString: `${typeAttribute} ${model2.typeString}[]${typeNullishability}`
1637
+ };
1638
+ }
1639
+ if (type !== "object") {
1640
+ const result = extractEnumObject(type, isRequired, definition.enum);
1641
+ return {
1642
+ schemaString: `${schemaAttribute} ${result.schemaString}`,
1643
+ typeString: `${typeAttribute} ${result.typeString}`
1644
+ };
1645
+ }
1646
+ }
1647
+ const ref = definition.$ref;
1648
+ let model = `z.record(z.any())`;
1649
+ if (ref) {
1650
+ model = ParserUtils.parseRefType(ref);
1651
+ const fullModelName = ref.replace("#/definitions/", "");
1652
+ this.duplicateFound = this.duplicates.has(fullModelName);
1653
+ if (this.duplicateFound) {
1654
+ model = this.duplicates.get(fullModelName);
1655
+ }
1656
+ this.importClasses.add(model);
1657
+ model = `${model}`;
1658
+ }
1659
+ return {
1660
+ schemaString: `${schemaAttribute} ${model}${schemaRequired}`,
1661
+ typeString: `${typeAttribute} ${model}${typeNullishability}`
1662
+ };
1663
+ };
1664
+ parseEnumItems = (items) => {
1665
+ if (items.enum) {
1666
+ const enumStr = items.enum.map((e) => {
1667
+ return `"${e}"`;
1668
+ });
1669
+ return {
1670
+ schemaString: `z.enum([${enumStr}])`,
1671
+ typeString: `(${enumStr.join(" | ")})`
1672
+ };
1673
+ }
1674
+ if (items.type === "object") {
1675
+ return this.parseToZodSchema(items, items.required);
1377
1676
  }
1378
- }
1379
- const resolvedResponseClass = responseClass || "unknown";
1380
- let _methodName = convertMethodName(classMethod, isPostFetch);
1381
- _methodName = isAdmin ? _methodName.replace("use", "useAdm") : _methodName;
1382
- const _responseType = resolvedResponseClass !== "unknown" ? `${resolvedResponseClass}` : "unknown";
1383
- const _methodParams = methodParams && methodParams.length > 0 ? `& { ${methodParams} }` : "";
1384
- const _methodParamsImpl = convertToMethodImplArgs(methodParams);
1385
- const queryMethodImpl = `
1386
-
1387
- export const ${_methodName} = (
1388
- sdk: AccelbyteSDK,
1389
- input: ApiArgs ${_methodParams},
1390
- options?: Omit<UseQueryOptions<${_responseType}, AxiosError<ApiError>>, 'queryKey'>,
1391
- callback?: (data: ${_responseType}) => void
1392
- ): UseQueryResult<${_responseType}, AxiosError<ApiError>> => {
1677
+ let effectiveType;
1678
+ if (items.type === "integer" || items.type === "number") {
1679
+ effectiveType = getZodNumberType(items.type);
1680
+ } else {
1681
+ effectiveType = { typeString: items.type, schemaString: items.type };
1682
+ }
1683
+ return {
1684
+ schemaString: `z.${effectiveType.schemaString}()`,
1685
+ typeString: effectiveType.typeString
1686
+ };
1687
+ };
1688
+ };
1689
+ var TemplateZodArray = class {
1393
1690
  //
1394
- const queryFn = (
1395
- sdk: AccelbyteSDK,
1396
- input: Parameters<typeof ${_methodName}>[1]
1397
- ) => async () => {
1398
- const data =
1399
- (await ${apiGenName}(sdk, { namespace: input.namespace }).
1400
- ${classMethod}(${_methodParamsImpl}))
1401
- callback && callback(data)
1402
- return data
1403
- }
1404
-
1405
- return ${queryMethod}<${_responseType}, AxiosError<ApiError>>({
1406
- queryKey: [${createQueryKey(apiGenName, classMethod)}, input],
1407
- queryFn: queryFn(sdk, input),
1408
- ...options
1409
- })
1410
- }
1691
+ render = (name) => {
1692
+ const cls = name.replace("Array", "");
1693
+ const template = `import { z } from 'zod'
1694
+ import { ${cls} } from './${cls}.js'
1411
1695
 
1412
- `;
1413
- const mutationMethodImpl = `
1696
+ export const ${name} = z.array(${cls})
1414
1697
 
1415
- export const ${_methodName} = (
1416
- sdk: AccelbyteSDK,
1417
- options?: Omit<UseMutationOptions<${_responseType}, AxiosError<ApiError>, ApiArgs ${_methodParams}>, 'mutationKey'>,
1418
- callback?: (data: ${_responseType}) => void
1419
- ): UseMutationResult<${_responseType}, AxiosError<ApiError>, ApiArgs ${_methodParams}> => {
1420
- //
1421
- const mutationFn = async (input: ApiArgs ${_methodParams}) => {
1422
- const data =
1423
- (await ${apiGenName}(sdk, { namespace: input.namespace, config: input.config }).
1424
- ${classMethod}(${_methodParamsImpl}))
1425
- callback && callback(data)
1426
- return data
1427
- }
1428
-
1429
- return useMutation({
1430
- mutationKey: [${createQueryKey(apiGenName, classMethod)}],
1431
- mutationFn,
1432
- ...options
1433
- })
1434
- }
1435
-
1698
+ export interface ${name} extends z.TypeOf<typeof ${name}> {}
1436
1699
  `;
1437
- return isGet ? queryMethodImpl : mutationMethodImpl;
1700
+ return template;
1701
+ };
1438
1702
  };
1439
- function createQueryKey(className, methodName) {
1440
- if (methodName.indexOf("_DEPRECATED") > 0) {
1441
- return "";
1703
+ var getZodNumberType = (type) => {
1704
+ if (type === "integer") {
1705
+ return {
1706
+ schemaString: "number().int",
1707
+ typeString: "number"
1708
+ };
1442
1709
  }
1443
- const prefixRegex = /^(get|create|update|delete|patch)[_]?/i;
1444
- const cleanedMethodName = methodName.replace(prefixRegex, "").trim();
1445
- const finalMethodName = cleanedMethodName.charAt(0).toUpperCase() + cleanedMethodName.slice(1);
1446
- return `Key_${className.replace("Api", "")}.${finalMethodName}`;
1447
- }
1448
- const prefixMappings = {
1449
- get: "use",
1450
- create: "useCreate",
1451
- patch: "usePatch",
1452
- update: "useUpdate",
1453
- delete: "useDelete"
1710
+ return {
1711
+ schemaString: type,
1712
+ typeString: type
1713
+ };
1454
1714
  };
1455
- function convertMethodName(classMethod, isPostFetch) {
1456
- for (const [originalPrefix, newPrefix] of Object.entries(prefixMappings)) {
1457
- if (classMethod.startsWith(originalPrefix)) {
1458
- if (isPostFetch) {
1459
- return classMethod.replace(originalPrefix, "useFetch");
1460
- }
1461
- const newMethodName = classMethod.replace(originalPrefix, newPrefix);
1462
- if (originalPrefix === "get") {
1463
- return newMethodName;
1464
- } else {
1465
- return newMethodName + "Mutation";
1466
- }
1467
- }
1468
- }
1469
- return classMethod;
1470
- }
1471
- function convertToMethodImplArgs(methodArgs) {
1472
- let properties = methodArgs.split(/,\s*(?![^{}]*\})/).map((prop) => prop.trim()).filter(Boolean);
1473
- let formattedProperties = [];
1474
- properties.forEach((prop) => {
1475
- if (prop.includes(": {")) {
1476
- const propertyName = prop.split(": {")[0].replace("?", "").trim();
1477
- formattedProperties.push(`input.${propertyName}`);
1478
- } else {
1479
- const colonIndex = prop.indexOf(":");
1480
- const propertyName = prop.substring(0, colonIndex).replace("?", "").trim();
1481
- formattedProperties.push(`input.${propertyName}`);
1482
- }
1483
- });
1484
- return formattedProperties.join(", ");
1485
- }
1486
-
1487
- const GIT_URL = "https://github.com/AccelByte/accelbyte-web-sdk/blob/main/packages";
1488
- class SwaggerReaderHelpers {
1489
- static getServicePrefix = (servicePaths) => servicePaths[servicePaths.length - 1].split("/")[1];
1490
- static parseAllEndpoints = async ({
1491
- api,
1492
- sdkName,
1493
- serviceName
1494
- }) => {
1495
- const result = {
1496
- admin: {
1497
- arrayDefinitions: [],
1498
- snippetMap: {},
1499
- tagToClassImportsRecord: {},
1500
- tagToEndpointClassesRecord: {},
1501
- tagToSdkClientRecord: {},
1502
- tagToSdkFunctionNamesRecord: {},
1503
- tagToSdkImportsRecord: {},
1504
- tagToEndpointQueryRecord: {}
1505
- },
1506
- public: {
1507
- arrayDefinitions: [],
1508
- snippetMap: {},
1509
- tagToClassImportsRecord: {},
1510
- tagToEndpointClassesRecord: {},
1511
- tagToSdkClientRecord: {},
1512
- tagToSdkFunctionNamesRecord: {},
1513
- tagToSdkImportsRecord: {},
1514
- tagToEndpointQueryRecord: {}
1515
- }
1516
- };
1517
- const sortedPathsByLength = new Map(Object.entries(api.paths).sort((a, b) => {
1518
- if (a[0].length === b[0].length) {
1519
- return a[0].localeCompare(b[0]);
1520
- } else {
1521
- return a[0].length - b[0].length;
1522
- }
1523
- }));
1524
- const sortedKeys = Array.from(sortedPathsByLength.keys());
1525
- const servicePrefix = SwaggerReaderHelpers.getServicePrefix(sortedKeys);
1526
- const tagToClassMethodsMap = {
1527
- admin: {},
1528
- public: {}
1715
+ var extractEnumObject = (type, isRequired, enumArr) => {
1716
+ const schemaRequired = isRequired ? "" : ".nullish()";
1717
+ const typeNullishability = isRequired ? "" : " | null | undefined";
1718
+ if (enumArr) {
1719
+ const enumStr = enumArr.map((e) => {
1720
+ return `"${e}"`;
1721
+ });
1722
+ return {
1723
+ schemaString: `z.enum([${enumStr}])${schemaRequired}`,
1724
+ typeString: `(${enumStr.join(" | ")}${typeNullishability})`
1529
1725
  };
1530
- for (const [path, operation] of sortedPathsByLength) {
1531
- if (path.indexOf("/healthz") >= 0) {
1532
- continue;
1533
- }
1534
- const isAdminEndpoint = path.indexOf("/admin/") > -1;
1535
- const picked = isAdminEndpoint ? result.admin : result.public;
1536
- const {
1537
- arrayDefinitions,
1538
- snippetMap,
1539
- tagToClassImportsRecord,
1540
- tagToEndpointClassesRecord,
1541
- tagToSdkClientRecord,
1542
- tagToSdkFunctionNamesRecord,
1543
- tagToSdkImportsRecord,
1544
- tagToEndpointQueryRecord
1545
- } = picked;
1546
- const tagToClassMethodsMapByType = isAdminEndpoint ? tagToClassMethodsMap.admin : tagToClassMethodsMap.public;
1547
- const httpMethods = Object.keys(operation);
1548
- for (const httpMethod of httpMethods) {
1549
- const endpoint = await Endpoint.parseAsync(operation[httpMethod]).catch((error) => {
1550
- console.error(JSON.stringify({ path, httpMethod }, null, 2));
1551
- throw error;
1552
- });
1553
- if (!endpoint.tags)
1554
- continue;
1555
- const [tag] = endpoint.tags;
1556
- const pathWithBase = `${api.basePath ?? ""}${path}`;
1557
- tagToClassMethodsMapByType[tag] = tagToClassMethodsMapByType[tag] ? tagToClassMethodsMapByType[tag] : {};
1558
- const isForm = endpoint.consumes && endpoint.consumes[0] === "application/x-www-form-urlencoded";
1559
- const classMethod = ParserUtils.generateNaturalLangMethod({
1560
- servicePrefix,
1561
- path,
1562
- httpMethod,
1563
- isForm,
1564
- existingMethods: tagToClassMethodsMapByType[tag]
1565
- });
1566
- tagToClassMethodsMapByType[tag][classMethod] = `${path} ${httpMethod}`;
1567
- if (!snippetMap[pathWithBase]) {
1568
- snippetMap[pathWithBase] = {};
1569
- }
1570
- const description = endpoint.description?.replace(/\s+/g, " ") || "";
1571
- const responseClass = ParserUtils.get2xxResponse(endpoint.responses);
1572
- const { className, classGenName } = ParserUtils.generateClassName(tag, isAdminEndpoint);
1573
- tagToClassImportsRecord[className] = tagToClassImportsRecord[className] ? tagToClassImportsRecord[className] : {};
1574
- if (responseClass) {
1575
- const importTypeClass = ParserUtils.parseRefType(responseClass);
1576
- tagToClassImportsRecord[className][importTypeClass] = `import { ${importTypeClass} } from '../../generated-definitions/${importTypeClass}.js'`;
1577
- }
1578
- if (responseClass && responseClass.endsWith("Array")) {
1579
- arrayDefinitions.push(responseClass);
1580
- }
1581
- const queryParams = ParserUtils.filterQueryParameters(endpoint.parameters);
1582
- const isFormUrlEncoded = ParserUtils.isFormUrlEncoded(httpMethod, endpoint.consumes);
1583
- const pathParams = ParserUtils.filterPathParams(endpoint.parameters);
1584
- let bodyParams = ParserUtils.filterBodyParams(endpoint.parameters);
1585
- const deprecated = !!endpoint.deprecated;
1586
- if (endpoint.requestBody) {
1587
- bodyParams = [
1588
- {
1589
- name: "body",
1590
- in: "body",
1591
- schema: endpoint.requestBody.content["application/json"]?.schema
1592
- }
1593
- ];
1594
- }
1595
- const { methodImpl, methodParams, methodParamsNoTypes, importStatements } = templateMethod({
1596
- classMethod: ParserUtils.addDeprecatedSuffix(deprecated, classMethod),
1597
- description,
1598
- httpMethod,
1599
- path: pathWithBase,
1600
- pathParams,
1601
- bodyParams,
1602
- queryParams,
1603
- isFormUrlEncoded,
1604
- responseClass,
1605
- deprecated
1606
- });
1607
- tagToEndpointClassesRecord[tag] = (tagToEndpointClassesRecord[tag] || "") + methodImpl;
1608
- const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1609
- const queryMethodImpl = templateQueryMethod({
1610
- classMethod: ParserUtils.addDeprecatedSuffix(deprecated, classMethod),
1611
- httpMethod,
1612
- path: pathWithBase,
1613
- pathParams,
1614
- responseClass,
1615
- methodParams,
1616
- apiGenName,
1617
- isFormUrlEncoded,
1618
- deprecated
1619
- });
1620
- tagToEndpointQueryRecord[tag] = (tagToEndpointQueryRecord[tag] || "") + queryMethodImpl;
1621
- const { generatedMethodString, snippetApiArgs, snippetMethod, snippetShell } = templateApiMethod({
1622
- classMethod: ParserUtils.addDeprecatedSuffix(deprecated, classMethod),
1623
- description,
1624
- httpMethod,
1625
- path: pathWithBase,
1626
- pathParams,
1627
- bodyParams,
1628
- responseClass,
1629
- classGenName,
1630
- methodParams,
1631
- methodParamsNoTypes,
1632
- deprecated,
1633
- xSecurity: endpoint["x-security"]
1634
- });
1635
- tagToSdkClientRecord[tag] = (tagToSdkClientRecord[tag] || "") + generatedMethodString;
1636
- tagToSdkFunctionNamesRecord[tag] = (tagToSdkFunctionNamesRecord[tag] || "") + ParserUtils.addDeprecatedSuffix(deprecated, classMethod) + ",";
1637
- tagToSdkImportsRecord[tag] = tagToSdkImportsRecord[tag] ? [.../* @__PURE__ */ new Set([...importStatements, ...tagToSdkImportsRecord[tag]])] : [...new Set(importStatements)];
1638
- const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1639
- const resultSnippet = templateSdkSnippet({
1640
- serviceNameTitle,
1641
- apiName: apiGenName,
1642
- snippetMethod,
1643
- snippetApiArgs
1644
- });
1645
- const currentSnippetMap = {};
1646
- snippetMap[pathWithBase][httpMethod] = currentSnippetMap;
1647
- currentSnippetMap.web = resultSnippet;
1648
- const generatedDirName = isAdminEndpoint ? "generated-admin" : "generated-public";
1649
- currentSnippetMap.webGit = GIT_URL + `/sdk-${sdkName}/src/${generatedDirName}/${apiGenName}.ts`;
1650
- currentSnippetMap.shell = snippetShell;
1651
- }
1652
- }
1653
- for (const key in result) {
1654
- result[key].arrayDefinitions = Array.from(new Set(result[key].arrayDefinitions));
1655
- }
1656
- return result;
1726
+ }
1727
+ return {
1728
+ schemaString: `z.${type}()${schemaRequired}`,
1729
+ typeString: `${type}${typeNullishability}`
1657
1730
  };
1658
- }
1731
+ };
1659
1732
 
1660
- class CodeGenerator {
1733
+ // src/CodeGenerator.ts
1734
+ var CodeGenerator = class _CodeGenerator {
1661
1735
  static srcFolder = () => CliParser.getOutputPath();
1662
- static getGeneratedFolder = (isAdmin) => isAdmin ? `${CodeGenerator.srcFolder()}/generated-admin` : `${CodeGenerator.srcFolder()}/generated-public`;
1736
+ static getGeneratedFolder = (isAdmin) => isAdmin ? `${_CodeGenerator.srcFolder()}/generated-admin` : `${_CodeGenerator.srcFolder()}/generated-public`;
1663
1737
  static getGeneratedSnippetsFolder = () => `${CliParser.getSnippetOutputPath()}/generated-snippets`;
1664
1738
  static prepareDirs = (DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES) => {
1665
1739
  ParserUtils.mkdirIfNotExist(DIST_DEFINITION_DIR);
@@ -1673,33 +1747,47 @@ class CodeGenerator {
1673
1747
  const serviceName = nameArray[0];
1674
1748
  const sdkName = nameArray[1];
1675
1749
  const swaggerFile = nameArray[2];
1676
- const parser = new SwaggerParser();
1750
+ const parser = new import_swagger_parser.default();
1677
1751
  const swaggerFilePath = `${CliParser.getSwaggersOutputPath()}/${swaggerFile}`;
1678
1752
  const api = await parser.parse(swaggerFilePath);
1679
1753
  const serviceNameTitle = ParserUtils.convertDashesToTitleCase(serviceName);
1680
1754
  const indexImportsSet = /* @__PURE__ */ new Set();
1755
+ const queryImportsSet = /* @__PURE__ */ new Set();
1681
1756
  const apiInfo = { ...api.info, "x-version": api["x-version"]?.version };
1682
1757
  console.log("----------\nGenerating API:", { title: apiInfo.title, version: apiInfo.version });
1683
- ParserUtils.syncPackageVersion(apiInfo, CliParser.skipVersionSync(), process.env.PRERELEASE_ID);
1684
- ParserUtils.writeXVersion(CodeGenerator.srcFolder(), api["x-version"], api.info);
1758
+ ParserUtils.writeXVersion(_CodeGenerator.srcFolder(), api["x-version"], api.info);
1685
1759
  const parsedInformation = await SwaggerReaderHelpers.parseAllEndpoints({ api, sdkName, serviceName });
1686
1760
  if (CliParser.getSnippetOutputPath()) {
1687
1761
  try {
1688
- ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify({
1689
- ...parsedInformation.public.snippetMap,
1690
- ...parsedInformation.admin.snippetMap
1691
- }, null, 2));
1762
+ ParserUtils.mkdirIfNotExist(_CodeGenerator.getGeneratedSnippetsFolder());
1763
+ ParserUtils.writeSnippetFile(
1764
+ _CodeGenerator.getGeneratedSnippetsFolder(),
1765
+ api.info.title,
1766
+ JSON.stringify(
1767
+ {
1768
+ ...parsedInformation.public.snippetMap,
1769
+ ...parsedInformation.admin.snippetMap
1770
+ },
1771
+ null,
1772
+ 2
1773
+ )
1774
+ );
1692
1775
  } catch (err) {
1693
- console.log("Generating snippets", err);
1776
+ console.error("Error generating snippets", err);
1694
1777
  }
1695
1778
  }
1696
- const DIST_DIR = (isAdmin) => `${CodeGenerator.getGeneratedFolder(isAdmin)}`;
1697
- const DIST_DIR_ENDPOINTS = (isAdmin) => path.join(DIST_DIR(isAdmin), "endpoints");
1698
- const DIST_DIR_QUERIES = (isAdmin) => path.join(DIST_DIR(isAdmin), "queries");
1699
- const DIST_DEFINITION_DIR = path.join(CodeGenerator.srcFolder(), "generated-definitions");
1700
- const targetSrcFolder = `${CodeGenerator.srcFolder()}/`;
1701
- CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
1779
+ if (CliParser.isGenerateSnippetOnly()) {
1780
+ console.log("\nSuccessfully generate SDK snippets only\n----------\n\n");
1781
+ return;
1782
+ }
1783
+ const DIST_DIR = (isAdmin) => `${_CodeGenerator.getGeneratedFolder(isAdmin)}`;
1784
+ const DIST_DIR_ENDPOINTS = (isAdmin) => import_path3.default.join(DIST_DIR(isAdmin), "endpoints");
1785
+ const DIST_DIR_QUERIES = (isAdmin) => import_path3.default.join(DIST_DIR(isAdmin), "queries");
1786
+ const DIST_DEFINITION_DIR = import_path3.default.join(_CodeGenerator.srcFolder(), "generated-definitions");
1787
+ const targetSrcFolder = `${_CodeGenerator.srcFolder()}/`;
1788
+ _CodeGenerator.prepareDirs(DIST_DEFINITION_DIR, DIST_DIR, DIST_DIR_ENDPOINTS, DIST_DIR_QUERIES);
1702
1789
  const mainApiList = [];
1790
+ const generatedDefinitions = [];
1703
1791
  const generatePublicOrAdmin = (isAdmin) => {
1704
1792
  const parsedInformationByType = isAdmin ? parsedInformation.admin : parsedInformation.public;
1705
1793
  const {
@@ -1709,7 +1797,8 @@ class CodeGenerator {
1709
1797
  tagToSdkClientRecord,
1710
1798
  tagToSdkFunctionNamesRecord,
1711
1799
  tagToSdkImportsRecord,
1712
- tagToEndpointQueryRecord
1800
+ tagToEndpointQueryRecord,
1801
+ tagToSdkFunctionDescription
1713
1802
  } = parsedInformationByType;
1714
1803
  const writeApiEndpointFiles = (isAdminEndpoint) => {
1715
1804
  const apiList = [];
@@ -1722,16 +1811,36 @@ class CodeGenerator {
1722
1811
  ParserUtils.writeClassFile(DIST_DIR_ENDPOINTS(isAdminEndpoint), classGenName, classBuffer, imports);
1723
1812
  const { apiGenName } = ParserUtils.generateApiName(tag, isAdminEndpoint);
1724
1813
  const queryBuffer = tagToEndpointQueryRecord[tag];
1725
- const queryFileName = ParserUtils.writeQueryFile(DIST_DIR_QUERIES(isAdminEndpoint), apiGenName, queryBuffer, apiImports, serviceNameTitle, tagToSdkFunctionNamesRecord[tag], imports);
1814
+ const queryFileName = !CliParser.skipReactQuery() && ParserUtils.writeQueryFile(
1815
+ DIST_DIR_QUERIES(isAdminEndpoint),
1816
+ apiGenName,
1817
+ queryBuffer,
1818
+ apiImports,
1819
+ serviceNameTitle,
1820
+ tagToSdkFunctionNamesRecord[tag],
1821
+ imports,
1822
+ sdkName
1823
+ );
1726
1824
  const apiBuffer = tagToSdkClientRecord[tag];
1727
- ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionNamesRecord[tag]);
1825
+ ParserUtils.writeApiFile(DIST_DIR(isAdminEndpoint), apiGenName, apiBuffer, imports, tagToSdkFunctionDescription[tag]);
1728
1826
  apiList.push(apiGenName);
1729
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder));
1730
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder));
1731
- queryFileName && indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`), targetSrcFolder));
1827
+ indexImportsSet.add(
1828
+ ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DIR_ENDPOINTS(isAdminEndpoint), `${classGenName}`), targetSrcFolder)
1829
+ );
1830
+ indexImportsSet.add(
1831
+ ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DIR(isAdminEndpoint), `${apiGenName}`), targetSrcFolder)
1832
+ );
1833
+ queryFileName && queryImportsSet.add(
1834
+ ParserUtils.getRelativePathToWebSdkSrcFolder(
1835
+ import_path3.default.join(DIST_DIR(isAdminEndpoint), "queries", `${queryFileName}`),
1836
+ targetSrcFolder
1837
+ )
1838
+ );
1732
1839
  }
1733
1840
  mainApiList.push(...apiList);
1734
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(CodeGenerator.srcFolder(), serviceNameTitle), targetSrcFolder));
1841
+ indexImportsSet.add(
1842
+ ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(_CodeGenerator.srcFolder(), serviceNameTitle), targetSrcFolder)
1843
+ );
1735
1844
  };
1736
1845
  const writeDefinitions = (api2) => {
1737
1846
  const duplicates = /* @__PURE__ */ new Map();
@@ -1739,19 +1848,21 @@ class CodeGenerator {
1739
1848
  for (const ref in definitions) {
1740
1849
  const definition = definitions[ref];
1741
1850
  const fileName = ParserUtils.parseRefType(ref);
1742
- const fileExist = fs.existsSync(path.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
1851
+ const fileExist = import_fs4.default.existsSync(import_path3.default.join(DIST_DEFINITION_DIR, `${fileName}.ts`));
1743
1852
  if (fileExist) {
1744
1853
  const duplicateName = ParserUtils.toCamelCaseWord(ref).replace(".", "").replace(".", "");
1745
1854
  duplicates.set(ref, duplicateName);
1746
1855
  }
1747
1856
  const { buffer } = new TemplateZod().render(fileName, definition, /* @__PURE__ */ new Map());
1857
+ generatedDefinitions.push(fileName);
1748
1858
  ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, fileName, buffer);
1749
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
1859
+ indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DEFINITION_DIR, fileName), targetSrcFolder));
1750
1860
  }
1751
1861
  for (const arrayClass of arrayDefinitions) {
1752
1862
  const buffer = new TemplateZodArray().render(arrayClass);
1863
+ generatedDefinitions.push(arrayClass);
1753
1864
  ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
1754
- indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
1865
+ indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(import_path3.default.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
1755
1866
  }
1756
1867
  };
1757
1868
  writeApiEndpointFiles(isAdmin);
@@ -1759,45 +1870,48 @@ class CodeGenerator {
1759
1870
  };
1760
1871
  generatePublicOrAdmin(true);
1761
1872
  generatePublicOrAdmin(false);
1762
- const apiIndexBuff = templateApiIndex(serviceName, serviceNameTitle, mainApiList);
1763
- ParserUtils.writeApiMainFile(CodeGenerator.srcFolder(), serviceNameTitle, apiIndexBuff);
1873
+ const apiIndexBuff = templateApiIndex(serviceNameTitle, mainApiList);
1874
+ ParserUtils.writeApiMainFile(_CodeGenerator.srcFolder(), serviceNameTitle, apiIndexBuff);
1764
1875
  console.log("\nCOMPLETED\n----------\n\n");
1765
- return indexImportsSet;
1876
+ return { indexImports: indexImportsSet, queryImports: queryImportsSet };
1766
1877
  };
1767
- }
1878
+ // end of main
1879
+ };
1768
1880
 
1769
- class SwaggerDownloader {
1881
+ // src/SwaggerDownloader.ts
1882
+ var https = __toESM(require("https"));
1883
+ var fs5 = __toESM(require("fs"));
1884
+ var path5 = __toESM(require("path"));
1885
+ var SwaggerDownloader = class _SwaggerDownloader {
1770
1886
  static getDestFile = (targetFileName) => {
1771
1887
  const destPath = CliParser.getResolvedSwaggersOutputPath();
1772
- const destFile = path__namespace.join(destPath, targetFileName);
1773
- if (fs__namespace.existsSync(destFile))
1774
- return destFile;
1775
- if (!fs__namespace.existsSync(destPath))
1776
- fs__namespace.mkdirSync(destPath);
1777
- fs__namespace.writeFileSync(destFile, "");
1888
+ const destFile = path5.join(destPath, targetFileName);
1889
+ if (fs5.existsSync(destFile)) return destFile;
1890
+ if (!fs5.existsSync(destPath)) fs5.mkdirSync(destPath);
1891
+ fs5.writeFileSync(destFile, "");
1778
1892
  return destFile;
1779
1893
  };
1894
+ // session-api.json contains illegal URL encoded character that breaks the codegen
1895
+ // e.g. "$ref": "#/definitions/map%5Bstring%5Dinterface%20%7B%7D"
1780
1896
  static postSanitizeDownloadedFile = (filePath) => {
1781
1897
  const searchStr = ["%5B", "%5D", "%20", "%7B", "%7D"];
1782
- fs__namespace.readFile(filePath, "utf8", (err, data) => {
1783
- if (err)
1784
- throw err;
1898
+ fs5.readFile(filePath, "utf8", (err, data) => {
1899
+ if (err) throw err;
1785
1900
  let result = data;
1786
1901
  searchStr.forEach((s) => {
1787
1902
  result = result.replace(new RegExp(s, "g"), " ");
1788
1903
  });
1789
- fs__namespace.writeFile(filePath, result, "utf8", (err2) => {
1790
- if (err2)
1791
- throw err2;
1904
+ fs5.writeFile(filePath, result, "utf8", (err2) => {
1905
+ if (err2) throw err2;
1792
1906
  console.log("File updated successfully.");
1793
1907
  });
1794
1908
  });
1795
1909
  };
1796
1910
  static downloadFile = async (targetFileName, url) => {
1797
- const destFile = SwaggerDownloader.getDestFile(targetFileName);
1911
+ const destFile = _SwaggerDownloader.getDestFile(targetFileName);
1798
1912
  let data = "";
1799
- return new Promise((resolve) => {
1800
- const request = https__namespace.get(url, function(response) {
1913
+ return new Promise((resolve2) => {
1914
+ const request = https.get(url, function(response) {
1801
1915
  response.on("data", (chunk) => {
1802
1916
  data += chunk;
1803
1917
  });
@@ -1805,11 +1919,11 @@ class SwaggerDownloader {
1805
1919
  if (response.statusCode !== 200) {
1806
1920
  console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
1807
1921
  } else {
1808
- fs__namespace.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
1809
- SwaggerDownloader.postSanitizeDownloadedFile(destFile);
1922
+ fs5.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
1923
+ _SwaggerDownloader.postSanitizeDownloadedFile(destFile);
1810
1924
  console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
1811
1925
  }
1812
- resolve(void 0);
1926
+ resolve2(void 0);
1813
1927
  });
1814
1928
  });
1815
1929
  request.on("error", (err) => {
@@ -1822,31 +1936,47 @@ class SwaggerDownloader {
1822
1936
  for (const ref in swaggers) {
1823
1937
  const targetFileName = swaggers[ref][2];
1824
1938
  const url = swaggers[ref][3];
1825
- await SwaggerDownloader.downloadFile(targetFileName, url);
1939
+ await _SwaggerDownloader.downloadFile(targetFileName, url);
1826
1940
  }
1827
1941
  };
1828
- }
1942
+ };
1829
1943
 
1830
- const generateSdk = async () => {
1944
+ // src/cli.ts
1945
+ var generateSdk = async () => {
1831
1946
  const arrayOfSets = await Promise.all(CliParser.getConfigFile().map((config) => CodeGenerator.main(config)));
1947
+ if (CliParser.isGenerateSnippetOnly()) {
1948
+ return;
1949
+ }
1832
1950
  const indexImportsSet = /* @__PURE__ */ new Set();
1951
+ const queryImportsSet = /* @__PURE__ */ new Set();
1833
1952
  const filenamesSet = /* @__PURE__ */ new Set();
1834
1953
  for (const set of arrayOfSets) {
1835
- set.forEach((value) => {
1836
- const fileName = path.basename(value);
1954
+ set.indexImports.forEach((value) => {
1955
+ const fileName = import_path4.default.basename(value);
1837
1956
  if (!filenamesSet.has(fileName)) {
1838
1957
  indexImportsSet.add(value);
1839
1958
  filenamesSet.add(fileName);
1840
1959
  }
1841
1960
  });
1961
+ set.queryImports.forEach((value) => {
1962
+ const fileName = import_path4.default.basename(value);
1963
+ if (!filenamesSet.has(fileName)) {
1964
+ queryImportsSet.add(value);
1965
+ }
1966
+ });
1842
1967
  }
1843
1968
  const indexImportsArray = Array.from(indexImportsSet).sort();
1969
+ const queryImportsArray = Array.from(queryImportsSet).sort();
1844
1970
  const filesToImport = indexImportsArray.map((fileToImport) => {
1845
1971
  return `export * from '${fileToImport.replace("\\", "/")}.js'`;
1846
1972
  });
1973
+ const queryFilesToImport = queryImportsArray.map((fileToImport) => {
1974
+ return `export * from '${fileToImport.replace("\\", "/")}.js'`;
1975
+ });
1847
1976
  ParserUtils.writeAllImportsFile(CliParser.getOutputPath(), filesToImport.join("\n"));
1977
+ ParserUtils.writeAllQueryImportsFile(CliParser.getOutputPath(), queryFilesToImport.join("\n"));
1848
1978
  };
1849
- yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
1979
+ import_yargs.default.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
1850
1980
  CliParser.createInstance(yargs2);
1851
1981
  SwaggerDownloader.main();
1852
1982
  }).command("generate-code", "Generate code based on downloaded swagger files", async (yargs2) => {
@@ -1869,5 +1999,11 @@ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
1869
1999
  }).option("output", {
1870
2000
  description: "Output path for generated code. Required for generate-code",
1871
2001
  type: "string"
2002
+ }).option("skipReactQuery", {
2003
+ description: "Skip generating react query",
2004
+ type: "boolean"
2005
+ }).option("snippetOnly", {
2006
+ description: "Only generate snippet",
2007
+ type: "boolean"
1872
2008
  }).demandCommand(1).help().argv;
1873
- //# sourceMappingURL=accelbyte-codegen.js.map
2009
+ //# sourceMappingURL=accelbyte-codegen.js.map