@accelbyte/codegen 1.0.1 → 1.0.4

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.
@@ -9,6 +9,7 @@ var path = require('path');
9
9
  var SwaggerParser = require('@apidevtools/swagger-parser');
10
10
  var fastJsonPatch = require('fast-json-patch');
11
11
  var _ = require('lodash');
12
+ var semver = require('semver');
12
13
  var https = require('https');
13
14
 
14
15
  function _interopNamespaceDefault(e) {
@@ -174,7 +175,14 @@ class ParserUtils {
174
175
  };
175
176
  static parseQueryParamAttributeDefault = (definition) => {
176
177
  const attrName = definition.name.slice(definition.name.lastIndexOf(".") + 1);
177
- const defaultValue = definition.type === "string" ? `'${definition.default}'` : definition.default;
178
+ let defaultValue = definition.default;
179
+ if (definition.type === "array" && Array.isArray(definition.default)) {
180
+ const mappedDefaultValue = definition.default.map((defaultValue2) => typeof defaultValue2 === "string" ? `'${defaultValue2}'` : defaultValue2);
181
+ defaultValue = `[${mappedDefaultValue.join(", ")}]`;
182
+ }
183
+ if (definition.type === "string") {
184
+ defaultValue = `'${definition.default}'`;
185
+ }
178
186
  return `${attrName}: ${defaultValue}`;
179
187
  };
180
188
  static parseType = (pathParam) => {
@@ -403,6 +411,19 @@ class ParserUtils {
403
411
  const fileContent = templateClass(apiName, apiBuffer, imports);
404
412
  fs.writeFileSync(`${distDir}/${apiName}.ts`, ParserUtils.prependCopyrightHeader(fileContent));
405
413
  }
414
+ static writeXVersion(distDir, xversionJson, apiInfo) {
415
+ if (xversionJson) {
416
+ console.log("x-version:", xversionJson);
417
+ fs.writeFileSync(`${distDir}/version.json`, JSON.stringify(xversionJson, null, 2));
418
+ } else {
419
+ const customVersion = {
420
+ ...apiInfo,
421
+ gitHash: apiInfo.version
422
+ };
423
+ console.error("!!!! Missing x-version for ", distDir, customVersion);
424
+ fs.writeFileSync(`${distDir}/version.json`, JSON.stringify(customVersion, null, 2));
425
+ }
426
+ }
406
427
  static writeApiFile(distDir, apiName, apiBuffer, imports, returnMethods) {
407
428
  const newImports = [];
408
429
  imports.forEach((el, index) => {
@@ -440,7 +461,7 @@ class ParserUtils {
440
461
  ` + fileContent.trim();
441
462
  fs.writeFileSync(pathToChangelog, fileContent, "utf-8");
442
463
  }
443
- static syncPackageVersion(apiInfo, isAdminWebSdk) {
464
+ static syncPackageVersion(apiInfo, isAdminWebSdk, prereleaseId) {
444
465
  if (isAdminWebSdk) {
445
466
  return;
446
467
  }
@@ -449,9 +470,18 @@ class ParserUtils {
449
470
  let swaggerVersion = apiInfo.version ? apiInfo.version : UNDEFINED_SWAGGER_SEMVER;
450
471
  swaggerVersion = Number(swaggerVersion.replace(".", "").replace(".", ""));
451
472
  swaggerVersion = isNaN(swaggerVersion) ? 0 : swaggerVersion;
452
- const semver = packageJSON.version.split(".").map((numStr) => Number(numStr));
453
- const newSemver = [semver[0], swaggerVersion, ++semver[2]];
454
- packageJSON.version = newSemver[0] + "." + newSemver[1] + "." + newSemver[2];
473
+ const currentSemver = packageJSON.version;
474
+ let nextSemver = [semver.major(currentSemver), swaggerVersion, semver.patch(currentSemver)].join(".");
475
+ if (!prereleaseId) {
476
+ nextSemver = semver.inc(nextSemver, "patch");
477
+ } else {
478
+ const currentPrerelease = semver.prerelease(currentSemver);
479
+ if (currentPrerelease) {
480
+ nextSemver += `-${currentPrerelease.join(".")}`;
481
+ }
482
+ nextSemver = semver.inc(nextSemver, "prerelease", void 0, prereleaseId);
483
+ }
484
+ packageJSON.version = nextSemver;
455
485
  fs.writeFileSync(pathToPackageJSON, JSON.stringify(packageJSON, null, 2));
456
486
  ParserUtils.syncChangelog(packageJSON.version);
457
487
  }
@@ -531,6 +561,9 @@ class ParserUtils {
531
561
  */
532
562
  ${content}`;
533
563
  };
564
+ static sortPathParamsByPath = (pathParams, path2) => {
565
+ return pathParams.sort((a, b) => path2.indexOf(a.name) - path2.indexOf(b.name));
566
+ };
534
567
  }
535
568
  const mappedMethod = (httpMethod, isForm) => {
536
569
  if (httpMethod === "get") {
@@ -626,10 +659,11 @@ const EndpointParameters = zod.z.object({
626
659
  in: EndpointParametersIn,
627
660
  required: zod.z.boolean().nullish(),
628
661
  schema: Schema.nullish(),
629
- default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()]).nullish(),
662
+ default: zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number(), zod.z.array(zod.z.any())]).nullish(),
630
663
  enum: zod.z.array(zod.z.union([zod.z.boolean(), zod.z.string(), zod.z.number()])).nullish(),
631
664
  items: zod.z.object({
632
- type: zod.z.string()
665
+ type: zod.z.string(),
666
+ enum: zod.z.array(zod.z.any()).nullish()
633
667
  }).nullish()
634
668
  });
635
669
  const Endpoint = zod.z.object({
@@ -702,7 +736,8 @@ const templateMethod = ({
702
736
  let methodParamsNoTypes = "";
703
737
  let newPath = `'${path}'`;
704
738
  let importStatements = [];
705
- for (const pathParam of pathParams) {
739
+ const sortedPathParams = ParserUtils.sortPathParamsByPath(pathParams, path);
740
+ for (const pathParam of sortedPathParams) {
706
741
  const type = ParserUtils.parseType(pathParam);
707
742
  if (pathParam.name !== "namespace") {
708
743
  methodParams += pathParam.name + `:${type}, `;
@@ -1198,6 +1233,8 @@ class CodeGenerator {
1198
1233
  continue;
1199
1234
  } else if (!CliParser.isAdmin() && isAdminEndpoint) {
1200
1235
  continue;
1236
+ } else if (path2.indexOf("/healthz") >= 0) {
1237
+ continue;
1201
1238
  }
1202
1239
  const httpMethods = Object.keys(operation);
1203
1240
  for (const httpMethod of httpMethods) {
@@ -1307,19 +1344,20 @@ class CodeGenerator {
1307
1344
  const DIST_ENDPOINTS_DIR = path.join(DIST_DIR, "endpoints");
1308
1345
  const DIST_DEFINITION_DIR = path.join(DIST_DIR, "definitions");
1309
1346
  const swaggerFilePath = `${CliParser.getSwaggersOutputPath()}/${swaggerFile}`;
1310
- const swaggerPatchedFilePath = `${CodeGenerator.getPatchedDir()}/${swaggerFile}`;
1311
- const swaggerPatchFilePath = `${swaggerFilePath}patch`;
1312
- ParserUtils.applyPatchIfExists(swaggerFilePath, swaggerPatchFilePath, swaggerPatchedFilePath, CodeGenerator.getPatchedDir());
1313
- const api = await parser.parse(swaggerPatchedFilePath);
1347
+ const api = await parser.parse(swaggerFilePath);
1314
1348
  const indexImportsSet = /* @__PURE__ */ new Set();
1315
1349
  console.log("----------\nGenerating API:", { title: api.info.title, version: api.info.version });
1316
1350
  ParserUtils.mkdirIfNotExist(DIST_DIR);
1317
1351
  ParserUtils.mkdirIfNotExist(DIST_DEFINITION_DIR);
1318
1352
  ParserUtils.mkdirIfNotExist(DIST_ENDPOINTS_DIR);
1319
- ParserUtils.syncPackageVersion(api.info, CliParser.isAdmin());
1353
+ ParserUtils.syncPackageVersion(api.info, CliParser.isAdmin(), process.env.PRERELEASE_ID);
1320
1354
  const { apiArgumentsByTag, apiBufferByTag, classBufferByTag, dependenciesByTag, classImports, arrayDefinitions, snippetMap } = await CodeGenerator.iterateApi(api, serviceName);
1321
1355
  if (CliParser.getSnippetOutputPath()) {
1322
- ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify(snippetMap, null, 2));
1356
+ try {
1357
+ ParserUtils.writeSnippetFile(CodeGenerator.getGeneratedSnippetsFolder(), api.info.title, JSON.stringify(snippetMap, null, 2));
1358
+ } catch (err) {
1359
+ console.log("Generating snippets", err);
1360
+ }
1323
1361
  }
1324
1362
  const targetSrcFolder = `${CliParser.getOutputPath()}/`;
1325
1363
  const apiList = [];
@@ -1369,6 +1407,7 @@ class CodeGenerator {
1369
1407
  ParserUtils.writeDefinitionFile(DIST_DEFINITION_DIR, arrayClass, buffer);
1370
1408
  indexImportsSet.add(ParserUtils.getRelativePathToWebSdkSrcFolder(path.join(DIST_DEFINITION_DIR, arrayClass), targetSrcFolder));
1371
1409
  }
1410
+ ParserUtils.writeXVersion(DIST_DIR, api["x-version"], api.info);
1372
1411
  console.log("\nCOMPLETED\n----------\n\n");
1373
1412
  return indexImportsSet;
1374
1413
  };
@@ -1403,13 +1442,19 @@ class SwaggerDownloader {
1403
1442
  };
1404
1443
  static downloadFile = (targetFileName, url) => {
1405
1444
  const destFile = SwaggerDownloader.getDestFile(targetFileName);
1406
- const file = fs__namespace.createWriteStream(destFile);
1445
+ let data = "";
1407
1446
  const request = https__namespace.get(url, function(response) {
1408
- response.pipe(file);
1409
- file.on("finish", () => {
1410
- file.close();
1411
- SwaggerDownloader.postSanitizeDownloadedFile(destFile);
1412
- console.log(`SwaggerDownload ${url} completed`);
1447
+ response.on("data", (chunk) => {
1448
+ data += chunk;
1449
+ });
1450
+ response.on("end", () => {
1451
+ if (response.statusCode !== 200) {
1452
+ console.log(`SwaggerDownload error with status code: ${response.statusCode}`);
1453
+ } else {
1454
+ fs__namespace.writeFileSync(destFile, JSON.stringify(JSON.parse(data), null, 2), "utf-8");
1455
+ SwaggerDownloader.postSanitizeDownloadedFile(destFile);
1456
+ console.log(`SwaggerDownload ${url} completed with status code: ${response.statusCode}`);
1457
+ }
1413
1458
  });
1414
1459
  });
1415
1460
  request.on("error", (err) => {
@@ -1423,7 +1468,6 @@ class SwaggerDownloader {
1423
1468
  const url = swaggers[ref][3];
1424
1469
  SwaggerDownloader.downloadFile(targetFileName, url);
1425
1470
  }
1426
- console.log("\n----------\n SwaggerDownloader COMPLETED.\n----------\n\n");
1427
1471
  };
1428
1472
  }
1429
1473
 
@@ -1431,7 +1475,7 @@ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
1431
1475
  CliParser.createInstance(yargs2);
1432
1476
  SwaggerDownloader.main();
1433
1477
  }).command("generate-code", "Generate code based on downloaded swagger files", async (yargs2) => {
1434
- yargs2.check(({ output, swaggersOutput }) => {
1478
+ yargs2.check(({ output }) => {
1435
1479
  if (!output?.trim()) {
1436
1480
  throw new Error("output is required for generate-code");
1437
1481
  }
@@ -1452,7 +1496,7 @@ yargs.command("download-swaggers", "Download swaggers JSON files", (yargs2) => {
1452
1496
  }
1453
1497
  const indexImportsArray = Array.from(indexImportsSet);
1454
1498
  const filesToImport = indexImportsArray.map((fileToImport) => {
1455
- return `export * from '${fileToImport.replace("\\", "/")}'`;
1499
+ return `export * from '${fileToImport.replace("\\", "/")}.js'`;
1456
1500
  });
1457
1501
  ParserUtils.writeAllImportsFile(CliParser.getOutputPath(), filesToImport.join("\n"), CliParser.isAdmin());
1458
1502
  }).option("config", {