ondc-code-generator 0.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.
Files changed (139) hide show
  1. package/.idea/code-generator.iml +12 -0
  2. package/.idea/modules.xml +8 -0
  3. package/.idea/vcs.xml +6 -0
  4. package/LICENSE +21 -0
  5. package/README.md +0 -0
  6. package/custom-loader.js +4 -0
  7. package/dist/Generator/config-compiler.js +53 -0
  8. package/dist/Generator/config-validator.js +21 -0
  9. package/dist/Generator/generators/classes/abstract-generator.js +16 -0
  10. package/dist/Generator/generators/documentation/markdown-message-generator.js +37 -0
  11. package/dist/Generator/generators/documentation/md-generator.js +57 -0
  12. package/dist/Generator/generators/markdown-message-generator.js +25 -0
  13. package/dist/Generator/generators/python/py-generator.js +1 -0
  14. package/dist/Generator/generators/typescript/templates/json-path-utils.js +15 -0
  15. package/dist/Generator/generators/typescript/templates/validation-utils.js +91 -0
  16. package/dist/Generator/generators/typescript/ts-ast.js +50 -0
  17. package/dist/Generator/generators/typescript/ts-generator.js +184 -0
  18. package/dist/Generator/pipline.js +1 -0
  19. package/dist/Generator/validators/abstract-validator.js +6 -0
  20. package/dist/Generator/validators/config-validator.js +32 -0
  21. package/dist/Generator/validators/session-data-config/session-data-validator.js +35 -0
  22. package/dist/Generator/validators/tests-config/sub-validations.js +194 -0
  23. package/dist/Generator/validators/tests-config/test-list-validator.js +36 -0
  24. package/dist/Generator/validators/tests-config/test-validator.js +24 -0
  25. package/dist/Generator/validators/validation-error.js +9 -0
  26. package/dist/constants/operations.js +17 -0
  27. package/dist/constants/syntax.js +75 -0
  28. package/dist/index.js +39 -0
  29. package/dist/services/rename-later/main.js +1 -0
  30. package/dist/services/rename-later/parser.js +22 -0
  31. package/dist/services/rename-later/tokens.js +32 -0
  32. package/dist/services/rename-later/tokens1.js +33 -0
  33. package/dist/services/return-complier/ast-functions/compile-to-markdown.js +66 -0
  34. package/dist/services/return-complier/ast-functions/semantic-validations.js +30 -0
  35. package/dist/services/return-complier/ast.js +92 -0
  36. package/dist/services/return-complier/combined.js +7 -0
  37. package/dist/services/return-complier/parser.js +95 -0
  38. package/dist/services/return-complier/tokens.js +144 -0
  39. package/dist/services/schema-service.js +29 -0
  40. package/dist/types/build.js +1 -0
  41. package/dist/types/compiler-types.js +4 -0
  42. package/dist/types/config-types.js +1 -0
  43. package/dist/types/error-codes.js +1 -0
  44. package/dist/types/general-types.js +1 -0
  45. package/dist/utils/config-utils/json-schema-utils.js +91 -0
  46. package/dist/utils/config-utils/yaml.js +16 -0
  47. package/dist/utils/file-system.js +1 -0
  48. package/dist/utils/fs-utils.js +20 -0
  49. package/dist/utils/general-utils/string-utils.js +56 -0
  50. package/dist/utils/general-utils/test-object-utils.js +12 -0
  51. package/dist/utils/general-utils/validation-utils.js +21 -0
  52. package/dist/utils/json-path-utils/extract-string-paths.js +113 -0
  53. package/dist/utils/json-path-utils/paths.js +46 -0
  54. package/dist/utils/logger.js +41 -0
  55. package/docs/error-gen.md +33 -0
  56. package/docs/return-grammer.md +23 -0
  57. package/docs/sampleConfig.md +39 -0
  58. package/generated/L1-validations/api-tests/cancel.ts +569 -0
  59. package/generated/L1-validations/api-tests/confirm.ts +1162 -0
  60. package/generated/L1-validations/api-tests/init.ts +1063 -0
  61. package/generated/L1-validations/api-tests/on_cancel.ts +2069 -0
  62. package/generated/L1-validations/api-tests/on_confirm.ts +2219 -0
  63. package/generated/L1-validations/api-tests/on_init.ts +1949 -0
  64. package/generated/L1-validations/api-tests/on_search.ts +1574 -0
  65. package/generated/L1-validations/api-tests/on_select.ts +1723 -0
  66. package/generated/L1-validations/api-tests/on_status.ts +2221 -0
  67. package/generated/L1-validations/api-tests/on_update.ts +1969 -0
  68. package/generated/L1-validations/api-tests/search.ts +695 -0
  69. package/generated/L1-validations/api-tests/select.ts +994 -0
  70. package/generated/L1-validations/api-tests/status.ts +443 -0
  71. package/generated/L1-validations/api-tests/update.ts +898 -0
  72. package/generated/L1-validations/error.ts +64 -0
  73. package/generated/L1-validations/index.ts +138 -0
  74. package/generated/L1-validations/page/index.html +2118 -0
  75. package/generated/L1-validations/page/style.css +225 -0
  76. package/generated/L1-validations/readme.md +1779 -0
  77. package/generated/L1-validations/types/test-config.ts +27 -0
  78. package/generated/L1-validations/utils/json-path-utils.ts +17 -0
  79. package/generated/L1-validations/utils/validation-utils.ts +116 -0
  80. package/generated-structure/api-tests/search.ts +24 -0
  81. package/generated-structure/error.ts +0 -0
  82. package/generated-structure/index.ts +0 -0
  83. package/generated-structure/types/test-config.ts +21 -0
  84. package/nodemon.json +5 -0
  85. package/package.json +40 -0
  86. package/samples/build.yaml +24799 -0
  87. package/samples/output.md +91 -0
  88. package/samples/output.ts +27 -0
  89. package/samples/selections.json +216 -0
  90. package/samples/validation-config.json +3422 -0
  91. package/samples/x-validations.yaml +2893 -0
  92. package/src/constants/operations.ts +19 -0
  93. package/src/constants/syntax.ts +81 -0
  94. package/src/example.ts +25 -0
  95. package/src/generator/config-compiler.ts +122 -0
  96. package/src/generator/generators/classes/abstract-generator.ts +29 -0
  97. package/src/generator/generators/documentation/markdown-message-generator.ts +43 -0
  98. package/src/generator/generators/documentation/md-generator.ts +76 -0
  99. package/src/generator/generators/documentation/templates/index.mustache +36 -0
  100. package/src/generator/generators/documentation/templates/style.css +204 -0
  101. package/src/generator/generators/python/py-generator.ts +0 -0
  102. package/src/generator/generators/typescript/templates/api-test.mustache +7 -0
  103. package/src/generator/generators/typescript/templates/json-path-utils.ts +17 -0
  104. package/src/generator/generators/typescript/templates/schema-template.mustache +18 -0
  105. package/src/generator/generators/typescript/templates/test-config.mustache +28 -0
  106. package/src/generator/generators/typescript/templates/test-object.mustache +20 -0
  107. package/src/generator/generators/typescript/templates/validation-code.mustache +39 -0
  108. package/src/generator/generators/typescript/templates/validation-utils.ts +117 -0
  109. package/src/generator/generators/typescript/ts-ast.ts +72 -0
  110. package/src/generator/generators/typescript/ts-generator.ts +275 -0
  111. package/src/generator/validators/abstract-validator.ts +23 -0
  112. package/src/generator/validators/config-validator.ts +55 -0
  113. package/src/generator/validators/session-data-config/session-data-validator.ts +58 -0
  114. package/src/generator/validators/tests-config/sub-validations.ts +302 -0
  115. package/src/generator/validators/tests-config/test-list-validator.ts +59 -0
  116. package/src/generator/validators/tests-config/test-validator.ts +69 -0
  117. package/src/index.ts +2 -0
  118. package/src/services/return-complier/ast-functions/compile-to-markdown.ts +152 -0
  119. package/src/services/return-complier/ast-functions/semantic-validations.ts +44 -0
  120. package/src/services/return-complier/ast.ts +147 -0
  121. package/src/services/return-complier/combined.ts +8 -0
  122. package/src/services/return-complier/parser.ts +128 -0
  123. package/src/services/return-complier/tokens.ts +184 -0
  124. package/src/services/schema-service.ts +42 -0
  125. package/src/types/build.ts +51 -0
  126. package/src/types/compiler-types.ts +3 -0
  127. package/src/types/config-types.ts +27 -0
  128. package/src/types/error-codes.ts +6 -0
  129. package/src/types/general-types.ts +2 -0
  130. package/src/utils/config-utils/json-schema-utils.ts +150 -0
  131. package/src/utils/config-utils/yaml.ts +17 -0
  132. package/src/utils/fs-utils.ts +32 -0
  133. package/src/utils/general-utils/string-utils.ts +76 -0
  134. package/src/utils/general-utils/test-object-utils.ts +14 -0
  135. package/src/utils/general-utils/validation-utils.ts +30 -0
  136. package/src/utils/json-path-utils/extract-string-paths.ts +139 -0
  137. package/src/utils/json-path-utils/paths.ts +44 -0
  138. package/src/utils/logger.ts +53 -0
  139. package/tsconfig.json +17 -0
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="WEB_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />
6
+ <excludeFolder url="file://$MODULE_DIR$/temp" />
7
+ <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
+ </content>
9
+ <orderEntry type="inheritedJdk" />
10
+ <orderEntry type="sourceFolder" forTests="false" />
11
+ </component>
12
+ </module>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/code-generator.iml" filepath="$PROJECT_DIR$/.idea/code-generator.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ONDC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
File without changes
@@ -0,0 +1,4 @@
1
+ import { register } from "node:module";
2
+ import { pathToFileURL } from "node:url";
3
+
4
+ register("ts-node/esm", pathToFileURL("./"));
@@ -0,0 +1,53 @@
1
+ import { loadAndDereferenceYaml } from "../utils/config-utils/yaml.js";
2
+ import { SchemaExtactionService } from "../services/schema-service.js";
3
+ import logger from "../utils/logger.js";
4
+ import { SupportedLanguages } from "../types/compiler-types.js";
5
+ import { TypescriptGenerator } from "./generators/typescript/ts-generator.js";
6
+ import { ConfigValidator } from "./validators/config-validator.js";
7
+ const defaultConfig = {
8
+ removeRequiredfromSchema: true,
9
+ removeEnumsfromSchema: true,
10
+ };
11
+ export class ConfigCompiler {
12
+ constructor(language) {
13
+ // 1. extract build, create schemas , extract possible paths , extract errorcodes
14
+ this.initialize = async (buildYaml, generatorConfig = {}) => {
15
+ const finalConfig = { ...defaultConfig, ...generatorConfig };
16
+ this.buildData = await loadAndDereferenceYaml(buildYaml);
17
+ this.jsonSchemas = await this.SchemaExtactionService.extractSchemas(this.buildData, finalConfig.removeRequiredfromSchema, finalConfig.removeEnumsfromSchema);
18
+ this.possibleJsonPahts = this.SchemaExtactionService.extractPossiblePaths(this.jsonSchemas);
19
+ const errors = this.buildData["x-errorcodes"];
20
+ this.errorDefinitions = errors.code;
21
+ };
22
+ this.performValidations = async (valConfig) => {
23
+ try {
24
+ if (!this.buildData)
25
+ throw new Error("Build data not initialized");
26
+ if (!this.jsonSchemas)
27
+ throw new Error("Schemas not initialized");
28
+ if (!this.possibleJsonPahts)
29
+ throw new Error("Possible paths not initialized");
30
+ if (!this.errorDefinitions)
31
+ throw new Error("Error definitions not initialized");
32
+ await new ConfigValidator("", valConfig, this.possibleJsonPahts, this.errorDefinitions).validate();
33
+ }
34
+ catch (e) {
35
+ logger.error(e);
36
+ throw new Error("Validation failed");
37
+ }
38
+ };
39
+ this.generateCode = async (valConfig) => {
40
+ await this.performValidations(valConfig);
41
+ // Generate code based on the language
42
+ switch (this.language) {
43
+ case SupportedLanguages.Typescript:
44
+ await new TypescriptGenerator(valConfig, this.errorDefinitions ?? [], "./L1-validations").generateCode();
45
+ break;
46
+ default:
47
+ throw new Error("Language not supported");
48
+ }
49
+ };
50
+ this.language = language;
51
+ this.SchemaExtactionService = new SchemaExtactionService();
52
+ }
53
+ }
@@ -0,0 +1,21 @@
1
+ /*
2
+ validations:
3
+ a single test object validations:
4
+ 1. name validations
5
+ 2. scope validation
6
+ 3. variable validation
7
+ 4. continue and return validations
8
+ 5. errorcode validations
9
+ 6. json path validations
10
+ 7. external data validations
11
+
12
+ upper validations:
13
+ 1. unique names
14
+ 2. _session_data_ are valid
15
+ 3. _tests_ are valid
16
+
17
+ x-errorcode validations:
18
+ 1. all codes are unique
19
+ */
20
+ export class ConfigValidator {
21
+ }
@@ -0,0 +1,16 @@
1
+ /*
2
+ 1. generate code for session_data
3
+ 1. a function take in payload and update the session_data in cache
4
+ 2. get function which returns the session_data object
5
+ 2. generate code for test-objects
6
+ 1. single test object generation
7
+ 1. handle nested
8
+ 2. combine all the tests
9
+ */
10
+ export class CodeGenerator {
11
+ constructor(validationConfig, errorCodes, rootPath = "./") {
12
+ this.validationConfig = validationConfig;
13
+ this.rootPath = rootPath;
14
+ this.errorCodes = errorCodes;
15
+ }
16
+ }
@@ -0,0 +1,37 @@
1
+ import { CompileToMarkdown } from "../../../services/return-complier/ast-functions/compile-to-markdown.js";
2
+ import { buildAstFromInput } from "../../../services/return-complier/combined.js";
3
+ import Mustache from "mustache";
4
+ import { addBlockquoteToMarkdown, addTabToMarkdown, ConvertArrayToStringsInTestObject, } from "../../../utils/general-utils/string-utils.js";
5
+ import { TestObjectSyntax } from "../../../constants/syntax";
6
+ export function markdownMessageGenerator(returnInput, variableValues, startingPointer, skipInput) {
7
+ const ast = buildAstFromInput(returnInput);
8
+ const returnTemplate = CompileToMarkdown(ast, startingPointer, 0, false);
9
+ if (variableValues[TestObjectSyntax.Scope]) {
10
+ const scope = variableValues[TestObjectSyntax.Scope];
11
+ for (const key in variableValues) {
12
+ if (Object.values(TestObjectSyntax).includes(key)) {
13
+ continue;
14
+ }
15
+ const path = variableValues[key];
16
+ const pathWithoutDollar = path.slice(2);
17
+ variableValues[key] = `${scope}.${pathWithoutDollar}`;
18
+ }
19
+ }
20
+ let finalReturn = Mustache.render(returnTemplate, ConvertArrayToStringsInTestObject(variableValues));
21
+ console.log(finalReturn);
22
+ if (skipInput) {
23
+ let skipMarkdown = `Note: **Condition ${startingPointer}** can be skipped if the following conditions are met:`;
24
+ const letters = "BCDEFGHIJKLMNOPQRSTUVWXYZ";
25
+ let index = 0;
26
+ for (const skip of skipInput) {
27
+ const skipAst = buildAstFromInput(skip);
28
+ const skipTemplate = CompileToMarkdown(skipAst, letters[index], 0, false);
29
+ const finalSkip = Mustache.render(skipTemplate, ConvertArrayToStringsInTestObject(variableValues));
30
+ skipMarkdown += `\n\n${finalSkip}`;
31
+ index++;
32
+ }
33
+ const blockSkip = addTabToMarkdown(addBlockquoteToMarkdown(skipMarkdown));
34
+ finalReturn += `\n\n${blockSkip}`;
35
+ }
36
+ return finalReturn;
37
+ }
@@ -0,0 +1,57 @@
1
+ import { ConfigSyntax, TestObjectSyntax } from "../../../constants/syntax.js";
2
+ import { CodeGenerator } from "../classes/abstract-generator.js";
3
+ import { markdownMessageGenerator } from "./markdown-message-generator.js";
4
+ import { writeFileWithFsExtra } from "../../../utils/fs-utils.js";
5
+ import { marked } from "marked";
6
+ import Mustache from "mustache";
7
+ import { readFileSync } from "fs";
8
+ import path from "path";
9
+ import { fileURLToPath } from "url";
10
+ import { addTabToMarkdown } from "../../../utils/general-utils/string-utils.js";
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+ export class MarkdownDocGenerator extends CodeGenerator {
14
+ constructor() {
15
+ super(...arguments);
16
+ this.generateValidationCode = async () => {
17
+ const testConfig = this.validationConfig[ConfigSyntax.Tests];
18
+ let finalMarkdown = "";
19
+ for (const key in testConfig) {
20
+ const testObjects = testConfig[key];
21
+ const betaConfig = {
22
+ [TestObjectSyntax.Name]: key,
23
+ [TestObjectSyntax.Return]: testObjects,
24
+ };
25
+ const md = this.generateMarkdownForTest(betaConfig);
26
+ finalMarkdown += `\n\n${md}`;
27
+ }
28
+ const cssData = readFileSync(path.resolve(__dirname, "./templates/style.css"), "utf-8");
29
+ const htmlTemplate = readFileSync(path.resolve(__dirname, "./templates/index.mustache"), "utf-8");
30
+ writeFileWithFsExtra(this.rootPath, "./readme.md", finalMarkdown);
31
+ writeFileWithFsExtra(this.rootPath, "./page/index.html", Mustache.render(htmlTemplate, {
32
+ content: await this.generateHtmlCode(finalMarkdown),
33
+ }));
34
+ writeFileWithFsExtra(this.rootPath, "./page/style.css", cssData);
35
+ };
36
+ this.generateCode = async () => {
37
+ await this.generateValidationCode();
38
+ };
39
+ this.generateMarkdownForTest = (testObject) => {
40
+ const ret = testObject[TestObjectSyntax.Return];
41
+ if (typeof ret === "string") {
42
+ const skip = testObject[TestObjectSyntax.Continue];
43
+ return markdownMessageGenerator(ret, testObject, testObject[TestObjectSyntax.Name], skip ? [skip] : undefined);
44
+ }
45
+ const subMardowns = ret.map((r) => {
46
+ return this.generateMarkdownForTest(r);
47
+ });
48
+ return `- **${testObject[TestObjectSyntax.Name]}** : All the following sub conditions must pass as per the api requirement\n\n${addTabToMarkdown(subMardowns.join("\n\n"))}`;
49
+ };
50
+ this.generateHtmlCode = async (markdownData) => {
51
+ return await marked(markdownData);
52
+ };
53
+ }
54
+ generateSessionDataCode() {
55
+ throw new Error("Method not implemented.");
56
+ }
57
+ }
@@ -0,0 +1,25 @@
1
+ import { CompileToMarkdown } from "../../services/return-complier/ast-functions/compile-to-markdown.js";
2
+ import { buildAstFromInput } from "../../services/return-complier/combined.js";
3
+ import Mustache from "mustache";
4
+ import { addBlockquoteToMarkdown, ConvertArrayToStringsInTestObject, } from "../../utils/general-utils/string-utils.js";
5
+ export function markdownMessageGenerator(returnInput, variableValues, startingPointer, skipInput) {
6
+ const ast = buildAstFromInput(returnInput);
7
+ const returnTemplate = CompileToMarkdown(ast, startingPointer, 0, false);
8
+ let finalReturn = Mustache.render(returnTemplate, ConvertArrayToStringsInTestObject(variableValues));
9
+ console.log(finalReturn);
10
+ if (skipInput) {
11
+ let skipMarkdown = `Note: **Condition ${startingPointer}** can be skipped if the following conditions are met:`;
12
+ const letters = "BCDEFGHIJKLMNOPQRSTUVWXYZ";
13
+ let index = 0;
14
+ for (const skip of skipInput) {
15
+ const skipAst = buildAstFromInput(skip);
16
+ const skipTemplate = CompileToMarkdown(skipAst, letters[index], 0, false);
17
+ const finalSkip = Mustache.render(skipTemplate, ConvertArrayToStringsInTestObject(variableValues));
18
+ skipMarkdown += `\n\n${finalSkip}`;
19
+ index++;
20
+ }
21
+ const blockSkip = addBlockquoteToMarkdown(skipMarkdown);
22
+ finalReturn += `\n###\n${blockSkip}`;
23
+ }
24
+ return finalReturn;
25
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,15 @@
1
+ import jsonpath from "jsonpath";
2
+ function getJsonPath(payload, path) {
3
+ let output = jsonpath.query(payload, path);
4
+ if (isListOfStringsOrNull(output)) {
5
+ output = output.map((o) => (o === null ? "null" : o));
6
+ }
7
+ return output.length === 0 ? [] : output;
8
+ }
9
+ function isListOfStringsOrNull(variable) {
10
+ return (Array.isArray(variable) &&
11
+ variable.every((item) => item === null || typeof item === "string"));
12
+ }
13
+ export default {
14
+ getJsonPath,
15
+ };
@@ -0,0 +1,91 @@
1
+ function areUnique(operand) {
2
+ const valuesSet = new Set(operand);
3
+ return valuesSet.size === operand.length;
4
+ }
5
+ function arePresent(operand) {
6
+ return noneIn(operand, ["", "null", "undefined"]) && operand.length > 0;
7
+ }
8
+ function allIn(left, right) {
9
+ return left.every((v) => right.includes(v));
10
+ }
11
+ function anyIn(left, right) {
12
+ return left.some((v) => right.includes(v));
13
+ }
14
+ function noneIn(left, right) {
15
+ return left.every((v) => !right.includes(v));
16
+ }
17
+ function equalTo(left, right) {
18
+ if (left.length !== right.length)
19
+ return false;
20
+ return left.every((v, i) => v === right[i]);
21
+ }
22
+ function greaterThan(left, right) {
23
+ // Check if all elements in an array are ISO 8601 dates
24
+ const areAllISO = (arr) => arr.every((v) => isISO8601(v));
25
+ // Check if all elements in an array are numbers
26
+ const areAllNumbers = (arr) => arr.every((v) => !isNaN(Number(v)));
27
+ if (areAllISO(left) && areAllISO(right)) {
28
+ // Compare ISO 8601 dates
29
+ const leftDates = left.map((date) => new Date(date).getTime());
30
+ const rightDates = right.map((date) => new Date(date).getTime());
31
+ return leftDates.every((ld, index) => ld > rightDates[index] || index >= rightDates.length);
32
+ }
33
+ else if (areAllNumbers(left) && areAllNumbers(right)) {
34
+ // Compare numbers
35
+ const leftNumbers = left.map(Number);
36
+ const rightNumbers = right.map(Number);
37
+ return leftNumbers.every((ln, index) => ln > rightNumbers[index] || index >= rightNumbers.length);
38
+ }
39
+ // If neither condition is met, return false
40
+ return false;
41
+ }
42
+ function lessThan(left, right) {
43
+ // Check if all elements in an array are ISO 8601 dates
44
+ const areAllISO = (arr) => arr.every((v) => isISO8601(v));
45
+ // Check if all elements in an array are numbers
46
+ const areAllNumbers = (arr) => arr.every((v) => !isNaN(Number(v)));
47
+ if (areAllISO(left) && areAllISO(right)) {
48
+ // Compare ISO 8601 dates
49
+ const leftDates = left.map((date) => new Date(date).getTime());
50
+ const rightDates = right.map((date) => new Date(date).getTime());
51
+ return leftDates.every((ld, index) => ld < rightDates[index] || index >= rightDates.length);
52
+ }
53
+ else if (areAllNumbers(left) && areAllNumbers(right)) {
54
+ // Compare numbers
55
+ const leftNumbers = left.map(Number);
56
+ const rightNumbers = right.map(Number);
57
+ return leftNumbers.every((ln, index) => ln < rightNumbers[index] || index >= rightNumbers.length);
58
+ }
59
+ // If neither condition is met, return false
60
+ return false;
61
+ }
62
+ function followRegex(left, regexArray) {
63
+ for (const regex of regexArray) {
64
+ const re = new RegExp(regex);
65
+ if (left.some((v) => !re.test(v)))
66
+ return false;
67
+ }
68
+ return true;
69
+ }
70
+ function isISO8601(str) {
71
+ // Regular expression to match ISO 8601 format
72
+ const iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
73
+ // Check if the string matches the ISO 8601 format
74
+ if (!iso8601Regex.test(str)) {
75
+ return false;
76
+ }
77
+ // Check if the string is a valid date
78
+ const date = new Date(str);
79
+ return !isNaN(date.getTime());
80
+ }
81
+ export default {
82
+ areUnique,
83
+ arePresent,
84
+ allIn,
85
+ anyIn,
86
+ noneIn,
87
+ equalTo,
88
+ followRegex,
89
+ greaterThan,
90
+ lessThan,
91
+ };
@@ -0,0 +1,50 @@
1
+ import { buildAstFromInput } from "../../../services/return-complier/combined.js";
2
+ import { AllIn, AnyIn, AreUnique, EqualTo, FollowRegex, GreaterThan, LessThan, NoneIn, ArePresent, } from "../../../services/return-complier/tokens.js";
3
+ const uniaryFunction = {
4
+ [AreUnique.LABEL ?? "are unique"]: "areUnique",
5
+ [ArePresent.LABEL ?? "are present"]: "arePresent",
6
+ };
7
+ const binaryFunction = {
8
+ [AllIn.LABEL ?? "all in"]: "allIn",
9
+ [AnyIn.LABEL ?? "any in"]: "anyIn",
10
+ [FollowRegex.LABEL ?? "follow regex"]: "followRegex",
11
+ [NoneIn.LABEL ?? "none in"]: "noneIn",
12
+ [EqualTo.LABEL ?? "equal to"]: "equalTo",
13
+ [GreaterThan.LABEL ?? "greater than"]: "greaterThan",
14
+ [LessThan.LABEL ?? "less than"]: "lessThan",
15
+ };
16
+ function compileToTs(node) {
17
+ if (node.type === "returnStatement") {
18
+ const returnNode = node;
19
+ return compileToTs(returnNode.expression);
20
+ }
21
+ if (node.type === "binaryOperator") {
22
+ const binaryNode = node;
23
+ const lhs = compileToTs(binaryNode.lhs);
24
+ const rhs = compileToTs(binaryNode.rhs);
25
+ return `(${lhs}) ${binaryNode.operator} (${rhs})`;
26
+ }
27
+ if (node.type === "notOperator") {
28
+ const notNode = node;
29
+ const expression = compileToTs(notNode.expression);
30
+ return `!(${expression})`;
31
+ }
32
+ if (node.type === "customUniaryFunction") {
33
+ const unary = node;
34
+ const func = uniaryFunction[unary.customFunction];
35
+ const varName = unary.expression.name;
36
+ return `validations.${func}(${varName})`;
37
+ }
38
+ if (node.type === "customBinaryFunction") {
39
+ const binary = node;
40
+ const func = binaryFunction[binary.customFunction];
41
+ const lhs = binary.lhs.name;
42
+ const rhs = binary.rhs.name;
43
+ return `validations.${func}(${lhs}, ${rhs})`;
44
+ }
45
+ throw new Error("Unknown node type");
46
+ }
47
+ export const compileInputToTs = (input) => {
48
+ const ast = buildAstFromInput(input);
49
+ return compileToTs(ast);
50
+ };
@@ -0,0 +1,184 @@
1
+ import { readFileSync } from "fs";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { ConfigSyntax, TestObjectSyntax } from "../../../constants/syntax.js";
5
+ import Mustache from "mustache";
6
+ import { markdownMessageGenerator } from "../documentation/markdown-message-generator.js";
7
+ import { getVariablesFromTest as extractVariablesFromText } from "../../../utils/general-utils/test-object-utils.js";
8
+ import { ConvertArrayToString } from "../../../utils/general-utils/string-utils.js";
9
+ import { compileInputToTs } from "./ts-ast.js";
10
+ import { CodeGenerator } from "../classes/abstract-generator.js";
11
+ import { writeAndFormatCode } from "../../../utils/fs-utils.js";
12
+ import logger from "../../../utils/logger.js";
13
+ import { MarkdownDocGenerator } from "../documentation/md-generator.js";
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = path.dirname(__filename);
16
+ export class TypescriptGenerator extends CodeGenerator {
17
+ constructor() {
18
+ super(...arguments);
19
+ this.generateSessionDataCode = async () => {
20
+ throw new Error("Method not implemented.");
21
+ };
22
+ this.generateValidationCode = async () => {
23
+ const testConfig = this.validationConfig[ConfigSyntax.Tests];
24
+ for (const key in testConfig) {
25
+ const testObjects = testConfig[key];
26
+ const betaConfig = {
27
+ [TestObjectSyntax.Name]: key,
28
+ [TestObjectSyntax.Return]: testObjects,
29
+ };
30
+ const testFunction = await this.generateTestFunction(betaConfig);
31
+ const apiTestTemplate = readFileSync(path.resolve(__dirname, "./templates/api-test.mustache"), "utf-8");
32
+ const finalCode = Mustache.render(apiTestTemplate, {
33
+ functionCode: testFunction.code,
34
+ });
35
+ await writeAndFormatCode(this.rootPath, `./api-tests/${key}.ts`, finalCode, "typescript");
36
+ }
37
+ };
38
+ this.generateCode = async () => {
39
+ const jsonPathUtilsCode = readFileSync(path.resolve(__dirname, "./templates/json-path-utils.ts"), "utf-8");
40
+ const validtionUtils = readFileSync(path.resolve(__dirname, "./templates/validation-utils.ts"), "utf-8");
41
+ const typesTemplate = readFileSync(path.resolve(__dirname, "./templates/test-config.mustache"), "utf-8");
42
+ const typesCode = Mustache.render(typesTemplate, {
43
+ externalData: this.getExternalKeys(),
44
+ });
45
+ writeAndFormatCode(this.rootPath, "./utils/json-path-utils.ts", jsonPathUtilsCode, "typescript");
46
+ writeAndFormatCode(this.rootPath, "./utils/validation-utils.ts", validtionUtils, "typescript");
47
+ writeAndFormatCode(this.rootPath, "./types/test-config.ts", typesCode, "typescript");
48
+ await this.generateValidationCode();
49
+ await writeAndFormatCode(this.rootPath, "error.ts", this.generateErrorFile(this.errorCodes), "typescript");
50
+ await writeAndFormatCode(this.rootPath, "index.ts", this.generateIndexFile(Object.keys(this.validationConfig[ConfigSyntax.Tests])), "typescript");
51
+ await new MarkdownDocGenerator(this.validationConfig, this.errorCodes, this.rootPath).generateCode();
52
+ };
53
+ this.generateTestFunction = async (testObject) => {
54
+ const template = readFileSync(path.resolve(__dirname, "./templates/test-object.mustache"), "utf-8");
55
+ const view = {
56
+ name: testObject[TestObjectSyntax.Name],
57
+ scopePath: testObject[TestObjectSyntax.Scope] ?? "$",
58
+ variables: this.createVariablesCode(testObject),
59
+ hasContinue: testObject[TestObjectSyntax.Continue] ? true : false,
60
+ skipCheckStatement: testObject[TestObjectSyntax.Continue]
61
+ ? compileInputToTs(testObject[TestObjectSyntax.Continue])
62
+ : undefined,
63
+ validationCode: await this.createValidationLogicCode(testObject),
64
+ };
65
+ return {
66
+ funcName: testObject[TestObjectSyntax.Name],
67
+ code: Mustache.render(template, view),
68
+ };
69
+ };
70
+ this.createValidationLogicCode = async (testObject) => {
71
+ const template = readFileSync(path.resolve(__dirname, "./templates/validation-code.mustache"), "utf-8");
72
+ const skip = testObject[TestObjectSyntax.Continue];
73
+ const skipList = skip ? [skip] : undefined;
74
+ if (typeof testObject[TestObjectSyntax.Return] === "string") {
75
+ const returnStatement = compileInputToTs(testObject[TestObjectSyntax.Return]);
76
+ return Mustache.render(template, {
77
+ isNested: false,
78
+ returnStatement: returnStatement,
79
+ errorCode: testObject[TestObjectSyntax.ErrorCode] ?? 30000,
80
+ errorDescription: this.CreateErrorMarkdown(testObject, skipList),
81
+ });
82
+ }
83
+ else {
84
+ const subObjects = testObject[TestObjectSyntax.Return];
85
+ const functionCodes = [];
86
+ for (const subObject of subObjects) {
87
+ const func = await this.generateTestFunction(subObject);
88
+ functionCodes.push(func);
89
+ }
90
+ const names = functionCodes.map((f) => {
91
+ return { name: f.funcName };
92
+ });
93
+ logger.debug(JSON.stringify(names));
94
+ return Mustache.render(template, {
95
+ isNested: true,
96
+ nestedFunctions: functionCodes.map((f) => f.code).join("\n"),
97
+ names: names,
98
+ });
99
+ }
100
+ };
101
+ }
102
+ CreateErrorMarkdown(testObject, skipList) {
103
+ return markdownMessageGenerator(testObject[TestObjectSyntax.Return], testObject, "A", skipList);
104
+ }
105
+ createVariablesCode(testObject) {
106
+ const variables = [];
107
+ const varNames = extractVariablesFromText(testObject);
108
+ for (const name of varNames) {
109
+ const value = testObject[name];
110
+ const final = typeof value === "string"
111
+ ? `payloadUtils.getJsonPath(testObj, '${value}')`
112
+ : ConvertArrayToString(value);
113
+ variables.push({
114
+ name: name,
115
+ value: final,
116
+ });
117
+ }
118
+ return variables;
119
+ }
120
+ generateErrorFile(errors) {
121
+ console.log(errors);
122
+ const allCodes = errors.map((error) => error.code);
123
+ if (allCodes.length !== new Set(allCodes).size) {
124
+ throw new Error("Duplicate error codes found");
125
+ }
126
+ errors.push({
127
+ code: 20006,
128
+ Description: "Invalid response does not meet API contract specifications",
129
+ });
130
+ errors.push({
131
+ code: 30000,
132
+ Description: "Invalid request does not meet API contract specifications",
133
+ });
134
+ const errorConstant = `
135
+ const errors = [
136
+ ${errors.map((error) => `{code: ${error.code}, message: "${error.Description}"}`).join(",\n")}
137
+ ];
138
+ `;
139
+ const errorFunction = `export function getError(code: number) {
140
+ const error = errors.find((error) => error.code === code);
141
+ if (!error) {
142
+ throw new Error(\`Error code \${code} not found\`);
143
+ }
144
+ return error;
145
+ }`;
146
+ return `${errorConstant}\n${errorFunction}`;
147
+ }
148
+ getExternalKeys() {
149
+ const apis = Object.keys(this.validationConfig[ConfigSyntax.SessionData]);
150
+ const result = [];
151
+ for (const api of apis) {
152
+ const keys = Object.keys(this.validationConfig[ConfigSyntax.SessionData][api]);
153
+ for (const key of keys) {
154
+ result.push({ name: key });
155
+ }
156
+ }
157
+ return result;
158
+ }
159
+ generateIndexFile(apis) {
160
+ const importsCode = apis
161
+ .map((api) => `import ${api} from "./api-tests/${api}";`)
162
+ .join("\n");
163
+ const masterFunction = `
164
+ export function performL1Validations(action: string, payload: any,allErrors = false, externalData = {}) {
165
+ switch (action) {
166
+ ${apis
167
+ .map((api) => `case "${api}": return ${api}({
168
+ payload: payload,
169
+ externalData: externalData,
170
+ config: {
171
+ runAllValidations: allErrors,
172
+ },
173
+ });`)
174
+ .join("\n")}
175
+ default:
176
+ throw new Error("Action not found");
177
+ }
178
+ }`;
179
+ return `
180
+ ${importsCode}
181
+ ${masterFunction}
182
+ `;
183
+ }
184
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,6 @@
1
+ export class TestObjectValidator {
2
+ constructor(testObject, path) {
3
+ this.targetObject = testObject;
4
+ this.validtionPath = path;
5
+ }
6
+ }