From 823ff2daeb006c3e2b25554ec61d78b9d3acd1a4 Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Tue, 19 Dec 2023 06:45:22 -1000 Subject: [PATCH 01/37] docs: fix constraint links (#1676) fix constraint links --- docs/constraints/CSharp.md | 6 +++--- docs/constraints/Dart.md | 6 +++--- docs/constraints/Go.md | 6 +++--- docs/constraints/Java.md | 6 +++--- docs/constraints/JavaScript.md | 6 +++--- docs/constraints/README.md | 4 +++- docs/constraints/Rust.md | 6 +++--- docs/constraints/TypeScript.md | 6 +++--- 8 files changed, 24 insertions(+), 22 deletions(-) diff --git a/docs/constraints/CSharp.md b/docs/constraints/CSharp.md index 32ca6904d7..17e1d5be9e 100644 --- a/docs/constraints/CSharp.md +++ b/docs/constraints/CSharp.md @@ -3,7 +3,7 @@ These are the C# specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For csharp `_` and `$` are an exception to this rule. | @@ -26,7 +26,7 @@ These are the constraints that is applied to object properties and the naming of ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| diff --git a/docs/constraints/Dart.md b/docs/constraints/Dart.md index dbd317ba41..d545a6f9bd 100644 --- a/docs/constraints/Dart.md +++ b/docs/constraints/Dart.md @@ -3,7 +3,7 @@ These are the Dart specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For dart `_` and `$` are an exception to this rule. | @@ -26,7 +26,7 @@ These are the constraints that is applied to object properties and the naming of ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| diff --git a/docs/constraints/Go.md b/docs/constraints/Go.md index 9c819fe526..ef693d8383 100644 --- a/docs/constraints/Go.md +++ b/docs/constraints/Go.md @@ -3,7 +3,7 @@ These are the Go specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For go `_` and `$` are an exception to this rule. | @@ -26,7 +26,7 @@ These are the constraints that is applied to object properties and the naming of ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| diff --git a/docs/constraints/Java.md b/docs/constraints/Java.md index 1a3072f9f4..29f0ff2f82 100644 --- a/docs/constraints/Java.md +++ b/docs/constraints/Java.md @@ -3,7 +3,7 @@ These are the Java specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For java `_` and `$` are an exception to this rule. | @@ -26,7 +26,7 @@ These are the constraints that is applied to object properties and the naming of ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| diff --git a/docs/constraints/JavaScript.md b/docs/constraints/JavaScript.md index ce3c090fbe..742a580086 100644 --- a/docs/constraints/JavaScript.md +++ b/docs/constraints/JavaScript.md @@ -3,7 +3,7 @@ These are the JavaScript specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For javascript `_` and `$` are an exception to this rule. | @@ -26,7 +26,7 @@ These are the constraints that is applied to object properties and the naming of ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| diff --git a/docs/constraints/README.md b/docs/constraints/README.md index 9100960a4d..7f3d71c1fa 100644 --- a/docs/constraints/README.md +++ b/docs/constraints/README.md @@ -12,6 +12,8 @@ class &name {} class 1name {} ``` +## Customization + There are many rules as such, but to get the full description about the default constraints here: - [C#](./constraints/CSharp.md) @@ -28,7 +30,7 @@ We define these as two types, either you only want to change part of the logic, - [Overwriting the formatter](../examples/overwrite-naming-formatting) and keep the rest of the constraints as is. - [Overwriting the entire naming constraint logic](../examples/overwrite-default-constraint) keeping none of the existing functionality which handles edge cases. It is recommended to **NOT** use this if it can be avoided, as you will limit yourself to what inputs can be generated to models. So make sure you know what you are doing :laughing: -# Type mapping +## Type mapping To make it easier to use the meta models in presets and generators, we need to figure out the types for each model. This is to enable you to access the types from a property rather then calling a function. This is especially relevant because Modelina cannot fit all use-cases out of the box, and we therefore strive to make it tailorable to what ever your needs may be. The type mapping is one of those things that enable you to fine tune the types for your purpose. Of course it's not all output formats that have a type such as JavaScript, therefore these are only used for strongly typed outputs. diff --git a/docs/constraints/Rust.md b/docs/constraints/Rust.md index e30e88effe..611532c9c5 100644 --- a/docs/constraints/Rust.md +++ b/docs/constraints/Rust.md @@ -3,7 +3,7 @@ These are the Rust specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For Rust `_`, ` ` and `$` are an exception to this rule. | @@ -25,7 +25,7 @@ These are the constraints that is applied to object properties and the naming of |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| diff --git a/docs/constraints/TypeScript.md b/docs/constraints/TypeScript.md index 3cc175fa0b..85fc33b9cc 100644 --- a/docs/constraints/TypeScript.md +++ b/docs/constraints/TypeScript.md @@ -3,7 +3,7 @@ These are the TypeScript specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. ## Model Naming -These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| @@ -14,7 +14,7 @@ These are the constraints that is applied to model naming. The `Rule key` is wha |NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| ## Property naming -These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| |NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For typescript `_` and `$` are an exception to this rule. | @@ -26,7 +26,7 @@ These are the constraints that is applied to object properties and the naming of ## Enum key constraints -These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](../constraints.md#Customization). +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). |Rule key|Rule|Resolution| |---|---|---| From 39e5c9335832202e4d604e1bee56e2b99715c874 Mon Sep 17 00:00:00 2001 From: Ashmit JaiSarita Gupta <43639341+devilkiller-ag@users.noreply.github.com> Date: Tue, 19 Dec 2023 22:29:52 +0530 Subject: [PATCH 02/37] docs: add python constraint docs (#1677) --- docs/constraints/Python.md | 41 ++++++++++++++++++++++++++++++++++++++ docs/constraints/README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 docs/constraints/Python.md diff --git a/docs/constraints/Python.md b/docs/constraints/Python.md new file mode 100644 index 0000000000..3aad65b5d8 --- /dev/null +++ b/docs/constraints/Python.md @@ -0,0 +1,41 @@ +# Python Constraints + +These are the Python specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. + +## Model Naming +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For python `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Python has a list of reserved keywords ([see the full list here](../../src/generators/python/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| + +## Property naming +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For python `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Python has a list of reserved keywords ([see the full list here](../../src/generators/python/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using camel case| +|NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + + +## Enum key constraints +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For python `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Python has a list of reserved keywords ([see the full list here](../../src/generators/python/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using constant case| +|NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + +## Constant +These are the constraints that are applied to constants. Currently, there are no hooks one can overwrite inside it. diff --git a/docs/constraints/README.md b/docs/constraints/README.md index 7f3d71c1fa..5d52fc4841 100644 --- a/docs/constraints/README.md +++ b/docs/constraints/README.md @@ -23,6 +23,7 @@ There are many rules as such, but to get the full description about the default - [JavaScript](./constraints/JavaScript.md) - [Rust](./constraints/Rust.md) - [TypeScript](./constraints/TypeScript.md) +- [Python](./constraints/Python.md) Even though there are many of these constraints, there might be reasons you want to customize the behavior to make it suit your use-case. Therefore each of the constraint rules can be overwritten completely and allow for you to implement your own behavior. From 99049837e0634db07d466ae27cc03e0788dfc72b Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Tue, 19 Dec 2023 07:01:53 -1000 Subject: [PATCH 03/37] docs: add devilkiller-ag as a contributor for doc, and maintenance (#1680) --- .all-contributorsrc | 4 +++- README.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 6712911bdc..1d833f2f89 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -782,7 +782,9 @@ "profile": "https://jaisarita.vercel.app/", "contributions": [ "code", - "design" + "design", + "doc", + "maintenance" ] } ], diff --git a/README.md b/README.md index f1a2f32ec2..955db31c36 100644 --- a/README.md +++ b/README.md @@ -417,7 +417,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Nilkanth Parmar
Nilkanth Parmar

💻 ⚠️ 💡 📖 - Ashmit JaiSarita Gupta
Ashmit JaiSarita Gupta

💻 🎨 + Ashmit JaiSarita Gupta
Ashmit JaiSarita Gupta

💻 🎨 📖 🚧 From 8390f85801b7dc378bbe042acf47d928640de4cb Mon Sep 17 00:00:00 2001 From: Harshil Jani Date: Wed, 20 Dec 2023 04:14:01 +0530 Subject: [PATCH 04/37] fix: set default to None for pydantic generator (#1663) --- .../__snapshots__/index.spec.ts.snap | 6 +++--- src/generators/python/presets/Pydantic.ts | 18 +++++++++++------- .../__snapshots__/Pydantic.spec.ts.snap | 4 ++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/examples/generate-python-pydantic-models/__snapshots__/index.spec.ts.snap b/examples/generate-python-pydantic-models/__snapshots__/index.spec.ts.snap index 39488f65e4..19d319f61c 100644 --- a/examples/generate-python-pydantic-models/__snapshots__/index.spec.ts.snap +++ b/examples/generate-python-pydantic-models/__snapshots__/index.spec.ts.snap @@ -3,10 +3,10 @@ exports[`Should be able to render python models and should log expected output to console: class-model 1`] = ` Array [ "class Root(BaseModel): - optionalField: Optional[str] = Field(alias='''this field is optional''') + optionalField: Optional[str] = Field(alias='''this field is optional''', default=None) requiredField: str = Field(alias='''this field is required''') - noDescription: Optional[str] = Field() - options: Optional[Options] = Field() + noDescription: Optional[str] = Field(default=None) + options: Optional[Options] = Field(default=None) ", ] `; diff --git a/src/generators/python/presets/Pydantic.ts b/src/generators/python/presets/Pydantic.ts index 7d787bb18e..b74ef6510a 100644 --- a/src/generators/python/presets/Pydantic.ts +++ b/src/generators/python/presets/Pydantic.ts @@ -18,14 +18,18 @@ const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType = { ); }, property(params) { - const type = params.property.required - ? params.property.property.type - : `Optional[${params.property.property.type}]`; - const alias = params.property.property.originalInput['description'] - ? `alias='''${params.property.property.originalInput['description']}'''` - : ''; + const { propertyName, required, property } = params.property; + const type = required ? property.type : `Optional[${property.type}]`; + const description = property.originalInput['description']; + const alias = description ? `alias='''${description}'''` : ''; + const defaultValue = required ? '' : 'default=None'; - return `${params.property.propertyName}: ${type} = Field(${alias})`; + if (alias && defaultValue) { + return `${propertyName}: ${type} = Field(${alias}, ${defaultValue})`; + } else if (alias) { + return `${propertyName}: ${type} = Field(${alias})`; + } + return `${propertyName}: ${type} = Field(${defaultValue})`; }, ctor: () => '', getter: () => '', diff --git a/test/generators/python/presets/__snapshots__/Pydantic.spec.ts.snap b/test/generators/python/presets/__snapshots__/Pydantic.spec.ts.snap index 7745d87060..a569da8c3b 100644 --- a/test/generators/python/presets/__snapshots__/Pydantic.spec.ts.snap +++ b/test/generators/python/presets/__snapshots__/Pydantic.spec.ts.snap @@ -5,7 +5,7 @@ exports[`PYTHON_PYDANTIC_PRESET should render pydantic for class 1`] = ` prop: Optional[str] = Field(alias='''test multi line - description''') - additionalProperties: Optional[dict[Any, Any]] = Field() + description''', default=None) + additionalProperties: Optional[dict[Any, Any]] = Field(default=None) " `; From 93251a69fc753bb9efb80dbef4c5d82e8b36ca3a Mon Sep 17 00:00:00 2001 From: asyncapi-bot Date: Wed, 20 Dec 2023 00:01:03 +0100 Subject: [PATCH 05/37] chore(release): v2.0.14 (#1681) --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6178eca89a..9574e6f9b6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@asyncapi/modelina", - "version": "2.0.13", + "version": "2.0.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@asyncapi/modelina", - "version": "2.0.13", + "version": "2.0.14", "license": "Apache-2.0", "dependencies": { "@apidevtools/json-schema-ref-parser": "^9.0.9", diff --git a/package.json b/package.json index 9d14076032..bc7a340031 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@asyncapi/modelina", - "version": "2.0.13", + "version": "2.0.14", "description": "Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents", "license": "Apache-2.0", "homepage": "https://www.modelina.org", From 3e32d5717188f141563efc52e2356921242dfe50 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Tue, 19 Dec 2023 13:21:17 -1000 Subject: [PATCH 06/37] docs: add Harshil-Jani as a contributor for code, and test (#1682) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 10 ++++++++++ README.md | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 1d833f2f89..5522246c73 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -786,6 +786,16 @@ "doc", "maintenance" ] + }, + { + "login": "Harshil-Jani", + "name": "Harshil Jani", + "avatar_url": "https://avatars.githubusercontent.com/u/79367883?v=4", + "profile": "http://harshil.prose.sh", + "contributions": [ + "code", + "test" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 955db31c36..947ab99ae3 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![Discussions](https://img.shields.io/github/discussions/asyncapi/modelina)](https://github.com/asyncapi/modelina/discussions) [![Website](https://img.shields.io/website?label=website&url=https%3A%2F%2Fwww.modelina.org)](https://www.modelina.org) [![Playground](https://img.shields.io/website?label=playground&url=https%3A%2F%2Fwww.modelina.org%2Fplayground)](https://www.modelina.org/playground) -[![All Contributors](https://img.shields.io/badge/all_contributors-72-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-73-orange.svg?style=flat-square)](#contributors-) Your one-stop tool for generating accurate and well-tested models for representing the message payloads. Use it as a tool in your development workflow, or a library in a larger integrations, entirely in your control. @@ -418,6 +418,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Nilkanth Parmar
Nilkanth Parmar

💻 ⚠️ 💡 📖 Ashmit JaiSarita Gupta
Ashmit JaiSarita Gupta

💻 🎨 📖 🚧 + Harshil Jani
Harshil Jani

💻 ⚠️ From 1237a8caddcd84cd7912d789e96901d72d2ae6ab Mon Sep 17 00:00:00 2001 From: Harshil Jani Date: Sat, 23 Dec 2023 03:43:41 +0530 Subject: [PATCH 07/37] docs: adding PR Template for modelina (#1683) docs: Adding PR Template for modelina Helpful for new contributors to consider being aware about lints and tests before rasing the PR and would eventually help better in maintaining the project. Signed-off-by: Harshil Jani --- .github/pull_request_template.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..cab14c8a62 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +## Description + + +## Related Issue + + +## Checklist +- [ ] The code follows the project's coding standards and is properly linted (`npm run lint`). +- [ ] Tests have been added or updated to cover the changes. +- [ ] Documentation has been updated to reflect the changes. +- [ ] All tests pass successfully locally.(`npm run test`). + +## Additional Notes + From 26a39535f7d440b7e84d430697f75d8ce11f9aae Mon Sep 17 00:00:00 2001 From: artur-ciocanu Date: Sat, 23 Dec 2023 05:21:18 -0800 Subject: [PATCH 08/37] feat: adding Scala generator (#1665) Co-authored-by: Artur Ciocanu --- examples/generate-scala-enums/README.md | 17 + examples/generate-scala-enums/index.spec.ts | 15 + examples/generate-scala-enums/index.ts | 20 + .../generate-scala-enums/package-lock.json | 10 + examples/generate-scala-enums/package.json | 12 + examples/generate-scala-models/README.md | 17 + examples/generate-scala-models/index.spec.ts | 15 + examples/generate-scala-models/index.ts | 41 ++ .../generate-scala-models/package-lock.json | 10 + examples/generate-scala-models/package.json | 12 + src/generators/scala/Constants.ts | 50 ++ src/generators/scala/ScalaConstrainer.ts | 156 ++++++ .../scala/ScalaDependencyManager.ts | 20 + src/generators/scala/ScalaFileGenerator.ts | 43 ++ src/generators/scala/ScalaGenerator.ts | 260 +++++++++ src/generators/scala/ScalaPreset.ts | 24 + src/generators/scala/ScalaRenderer.ts | 69 +++ .../scala/constrainer/ConstantConstrainer.ts | 7 + .../scala/constrainer/EnumConstrainer.ts | 105 ++++ .../scala/constrainer/ModelNameConstrainer.ts | 53 ++ .../constrainer/PropertyKeyConstrainer.ts | 80 +++ src/generators/scala/index.ts | 21 + .../scala/presets/DescriptionPreset.ts | 63 +++ src/generators/scala/presets/index.ts | 1 + .../scala/renderers/ClassRenderer.ts | 66 +++ .../scala/renderers/EnumRenderer.ts | 60 ++ test/TestUtils/TestRenderers.ts | 2 + test/generators/scala/Constants.spec.ts | 12 + .../generators/scala/ScalaConstrainer.spec.ts | 512 ++++++++++++++++++ test/generators/scala/ScalaGenerator.spec.ts | 211 ++++++++ test/generators/scala/ScalaRenderer.spec.ts | 41 ++ .../__snapshots__/ScalaGenerator.spec.ts.snap | 105 ++++ .../scala/presets/DescriptionPreset.spec.ts | 44 ++ .../DescriptionPreset.spec.ts.snap | 32 ++ 34 files changed, 2206 insertions(+) create mode 100644 examples/generate-scala-enums/README.md create mode 100644 examples/generate-scala-enums/index.spec.ts create mode 100644 examples/generate-scala-enums/index.ts create mode 100644 examples/generate-scala-enums/package-lock.json create mode 100644 examples/generate-scala-enums/package.json create mode 100644 examples/generate-scala-models/README.md create mode 100644 examples/generate-scala-models/index.spec.ts create mode 100644 examples/generate-scala-models/index.ts create mode 100644 examples/generate-scala-models/package-lock.json create mode 100644 examples/generate-scala-models/package.json create mode 100644 src/generators/scala/Constants.ts create mode 100644 src/generators/scala/ScalaConstrainer.ts create mode 100644 src/generators/scala/ScalaDependencyManager.ts create mode 100644 src/generators/scala/ScalaFileGenerator.ts create mode 100644 src/generators/scala/ScalaGenerator.ts create mode 100644 src/generators/scala/ScalaPreset.ts create mode 100644 src/generators/scala/ScalaRenderer.ts create mode 100644 src/generators/scala/constrainer/ConstantConstrainer.ts create mode 100644 src/generators/scala/constrainer/EnumConstrainer.ts create mode 100644 src/generators/scala/constrainer/ModelNameConstrainer.ts create mode 100644 src/generators/scala/constrainer/PropertyKeyConstrainer.ts create mode 100644 src/generators/scala/index.ts create mode 100644 src/generators/scala/presets/DescriptionPreset.ts create mode 100644 src/generators/scala/presets/index.ts create mode 100644 src/generators/scala/renderers/ClassRenderer.ts create mode 100644 src/generators/scala/renderers/EnumRenderer.ts create mode 100644 test/generators/scala/Constants.spec.ts create mode 100644 test/generators/scala/ScalaConstrainer.spec.ts create mode 100644 test/generators/scala/ScalaGenerator.spec.ts create mode 100644 test/generators/scala/ScalaRenderer.spec.ts create mode 100644 test/generators/scala/__snapshots__/ScalaGenerator.spec.ts.snap create mode 100644 test/generators/scala/presets/DescriptionPreset.spec.ts create mode 100644 test/generators/scala/presets/__snapshots__/DescriptionPreset.spec.ts.snap diff --git a/examples/generate-scala-enums/README.md b/examples/generate-scala-enums/README.md new file mode 100644 index 0000000000..167791ec4a --- /dev/null +++ b/examples/generate-scala-enums/README.md @@ -0,0 +1,17 @@ +# Scala Enums + +A basic example of how to use Modelina and output a Scala enumeration. + +## How to run this example + +Run this example using: + +```sh +npm i && npm run start +``` + +If you are on Windows, use the `start:windows` script instead: + +```sh +npm i && npm run start:windows +``` diff --git a/examples/generate-scala-enums/index.spec.ts b/examples/generate-scala-enums/index.spec.ts new file mode 100644 index 0000000000..7afa11cb9c --- /dev/null +++ b/examples/generate-scala-enums/index.spec.ts @@ -0,0 +1,15 @@ +const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { + return; +}); +import { generate } from './index'; + +describe('Should be able to render Kotlin Enums', () => { + afterAll(() => { + jest.restoreAllMocks(); + }); + test('and should log expected output to console', async () => { + await generate(); + expect(spy.mock.calls.length).toEqual(1); + expect(spy.mock.calls[0]).toMatchSnapshot(); + }); +}); diff --git a/examples/generate-scala-enums/index.ts b/examples/generate-scala-enums/index.ts new file mode 100644 index 0000000000..458cc94c8d --- /dev/null +++ b/examples/generate-scala-enums/index.ts @@ -0,0 +1,20 @@ +import { ScalaGenerator } from '../../src/generators/scala'; + +const generator = new ScalaGenerator(); +const jsonSchemaDraft7 = { + $schema: 'http://json-schema.org/draft-07/schema#', + additionalProperties: false, + $id: 'protocol', + type: ['string', 'int', 'boolean'], + enum: ['HTTP', 1, 'HTTPS', true] +}; + +export async function generate(): Promise { + const models = await generator.generate(jsonSchemaDraft7); + for (const model of models) { + console.log(model.result); + } +} +if (require.main === module) { + generate(); +} diff --git a/examples/generate-scala-enums/package-lock.json b/examples/generate-scala-enums/package-lock.json new file mode 100644 index 0000000000..71205d5b99 --- /dev/null +++ b/examples/generate-scala-enums/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "generate-scala-enums", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "hasInstallScript": true + } + } +} diff --git a/examples/generate-scala-enums/package.json b/examples/generate-scala-enums/package.json new file mode 100644 index 0000000000..f3f7301a7c --- /dev/null +++ b/examples/generate-scala-enums/package.json @@ -0,0 +1,12 @@ +{ + "config": { + "example_name": "generate-scala-enums" + }, + "scripts": { + "install": "cd ../.. && npm i", + "start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts", + "start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts", + "test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts", + "test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts" + } +} diff --git a/examples/generate-scala-models/README.md b/examples/generate-scala-models/README.md new file mode 100644 index 0000000000..c8770e41e7 --- /dev/null +++ b/examples/generate-scala-models/README.md @@ -0,0 +1,17 @@ +# Scala Data Models + +A basic example of how to use Modelina and output a Scala data model. + +## How to run this example + +Run this example using: + +```sh +npm i && npm run start +``` + +If you are on Windows, use the `start:windows` script instead: + +```sh +npm i && npm run start:windows +``` diff --git a/examples/generate-scala-models/index.spec.ts b/examples/generate-scala-models/index.spec.ts new file mode 100644 index 0000000000..010afc6245 --- /dev/null +++ b/examples/generate-scala-models/index.spec.ts @@ -0,0 +1,15 @@ +const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { + return; +}); +import { generate } from './index'; + +describe('Should be able to render Kotlin Models', () => { + afterAll(() => { + jest.restoreAllMocks(); + }); + test('and should log expected output to console', async () => { + await generate(); + expect(spy.mock.calls.length).toEqual(3); + expect(spy.mock.calls[0]).toMatchSnapshot(); + }); +}); diff --git a/examples/generate-scala-models/index.ts b/examples/generate-scala-models/index.ts new file mode 100644 index 0000000000..74cde5421c --- /dev/null +++ b/examples/generate-scala-models/index.ts @@ -0,0 +1,41 @@ +import { ScalaGenerator } from '../../src/generators/scala'; + +const generator = new ScalaGenerator(); +const jsonSchemaDraft7 = { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + additionalProperties: false, + properties: { + email: { + type: 'string', + format: 'email' + }, + cache: { + type: 'integer' + }, + website: { + type: 'object', + additionalProperties: false, + properties: { + domain: { + type: 'string', + format: 'url' + }, + protocol: { + type: 'string', + enum: ['HTTP', 'HTTPS'] + } + } + } + } +}; + +export async function generate(): Promise { + const models = await generator.generate(jsonSchemaDraft7); + for (const model of models) { + console.log(model.result); + } +} +if (require.main === module) { + generate(); +} diff --git a/examples/generate-scala-models/package-lock.json b/examples/generate-scala-models/package-lock.json new file mode 100644 index 0000000000..61b5cb38ef --- /dev/null +++ b/examples/generate-scala-models/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "generate-scala-models", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "hasInstallScript": true + } + } +} diff --git a/examples/generate-scala-models/package.json b/examples/generate-scala-models/package.json new file mode 100644 index 0000000000..5ca775bc64 --- /dev/null +++ b/examples/generate-scala-models/package.json @@ -0,0 +1,12 @@ +{ + "config": { + "example_name": "generate-scala-models" + }, + "scripts": { + "install": "cd ../.. && npm i", + "start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts", + "start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts", + "test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts", + "test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts" + } +} diff --git a/src/generators/scala/Constants.ts b/src/generators/scala/Constants.ts new file mode 100644 index 0000000000..69415eeb33 --- /dev/null +++ b/src/generators/scala/Constants.ts @@ -0,0 +1,50 @@ +import { checkForReservedKeyword } from '../../helpers'; + +export const RESERVED_SCALA_KEYWORDS = [ + 'abstract', + 'case', + 'catch', + 'class', + 'def', + 'do', + 'else', + 'extends', + 'false', + 'final', + 'finally', + 'for', + 'forSome', + 'if', + 'implicit', + 'import', + 'lazy', + 'match', + 'new', + 'null', + 'object', + 'override', + 'package', + 'private', + 'protected', + 'return', + 'sealed', + 'super', + 'this', + 'throw', + 'trait', + 'true', + 'try', + 'type', + 'val', + 'var', + 'while', + 'with', + 'yield' +]; + +export function isReservedScalaKeyword( + word: string, + forceLowerCase = true +): boolean { + return checkForReservedKeyword(word, RESERVED_SCALA_KEYWORDS, forceLowerCase); +} diff --git a/src/generators/scala/ScalaConstrainer.ts b/src/generators/scala/ScalaConstrainer.ts new file mode 100644 index 0000000000..f004c279ec --- /dev/null +++ b/src/generators/scala/ScalaConstrainer.ts @@ -0,0 +1,156 @@ +import { Constraints } from '../../helpers'; +import { ConstrainedEnumValueModel } from '../../models'; +import { + defaultEnumKeyConstraints, + defaultEnumValueConstraints +} from './constrainer/EnumConstrainer'; +import { defaultModelNameConstraints } from './constrainer/ModelNameConstrainer'; +import { defaultPropertyKeyConstraints } from './constrainer/PropertyKeyConstrainer'; +import { defaultConstantConstraints } from './constrainer/ConstantConstrainer'; +import { ScalaTypeMapping } from './ScalaGenerator'; + +function enumFormatToNumberType( + enumValueModel: ConstrainedEnumValueModel, + format: string | undefined +): string { + switch (format) { + case 'integer': + case 'int32': + return 'Int'; + case 'long': + case 'int64': + return 'Long'; + case 'float': + return 'Float'; + case 'double': + return 'Double'; + default: + return Number.isInteger(enumValueModel.value) ? 'Int' : 'Double'; + } +} + +function fromEnumValueToKotlinType( + enumValueModel: ConstrainedEnumValueModel, + format: string | undefined +): string { + switch (typeof enumValueModel.value) { + case 'boolean': + return 'Boolean'; + case 'number': + case 'bigint': + return enumFormatToNumberType(enumValueModel, format); + case 'object': + return 'Any'; + case 'string': + return 'String'; + default: + return 'Any'; + } +} + +/** + * Converts union of different number types to the most strict type it can be. + * + * int + double = double (long + double, float + double can never happen, otherwise this would be converted to double) + * int + float = float (long + float can never happen, otherwise this would be the case as well) + * int + long = long + * + * Basically a copy from JavaConstrainer.ts + */ +function interpretUnionValueType(types: string[]): string { + if (types.includes('Double')) { + return 'Double'; + } + + if (types.includes('Float')) { + return 'Float'; + } + + if (types.includes('Long')) { + return 'Long'; + } + + return 'Any'; +} + +export const ScalaDefaultTypeMapping: ScalaTypeMapping = { + Object({ constrainedModel }): string { + return constrainedModel.name; + }, + Reference({ constrainedModel }): string { + return constrainedModel.name; + }, + Any(): string { + return 'Any'; + }, + Float({ constrainedModel }): string { + return constrainedModel.options.format === 'float' ? 'Float' : 'Double'; + }, + Integer({ constrainedModel }): string { + return constrainedModel.options.format === 'long' || + constrainedModel.options.format === 'int64' + ? 'Long' + : 'Int'; + }, + String({ constrainedModel }): string { + switch (constrainedModel.options.format) { + case 'date': { + return 'java.time.LocalDate'; + } + case 'time': { + return 'java.time.OffsetTime'; + } + case 'dateTime': + case 'date-time': { + return 'java.time.OffsetDateTime'; + } + case 'binary': { + return 'Array[Byte]'; + } + default: { + return 'String'; + } + } + }, + Boolean(): string { + return 'Boolean'; + }, + // Since there are not tuples in Kotlin, we have to return a collection of `Any` + Tuple({ options }): string { + const isList = options.collectionType && options.collectionType === 'List'; + + return isList ? 'List[Any]' : 'Array[Any]'; + }, + Array({ constrainedModel, options }): string { + const isList = options.collectionType && options.collectionType === 'List'; + const type = constrainedModel.valueModel.type; + + return isList ? `List[${type}]` : `Array[${type}]`; + }, + Enum({ constrainedModel }): string { + const valueTypes = constrainedModel.values.map((enumValue) => + fromEnumValueToKotlinType(enumValue, constrainedModel.options.format) + ); + const uniqueTypes = [...new Set(valueTypes)]; + + // Enums cannot handle union types, default to a loose type + return uniqueTypes.length > 1 + ? interpretUnionValueType(uniqueTypes) + : uniqueTypes[0]; + }, + Union(): string { + // No Unions in Kotlin, use Any for now. + return 'Any'; + }, + Dictionary({ constrainedModel }): string { + return `Map[${constrainedModel.key.type}, ${constrainedModel.value.type}]`; + } +}; + +export const ScalaDefaultConstraints: Constraints = { + enumKey: defaultEnumKeyConstraints(), + enumValue: defaultEnumValueConstraints(), + modelName: defaultModelNameConstraints(), + propertyKey: defaultPropertyKeyConstraints(), + constant: defaultConstantConstraints() +}; diff --git a/src/generators/scala/ScalaDependencyManager.ts b/src/generators/scala/ScalaDependencyManager.ts new file mode 100644 index 0000000000..d49d728a54 --- /dev/null +++ b/src/generators/scala/ScalaDependencyManager.ts @@ -0,0 +1,20 @@ +import { AbstractDependencyManager } from '../AbstractDependencyManager'; +import { ScalaOptions } from './ScalaGenerator'; + +export class ScalaDependencyManager extends AbstractDependencyManager { + constructor( + public options: ScalaOptions, + dependencies: string[] = [] + ) { + super(dependencies); + } + + /** + * Adds a dependency package ensuring correct syntax. + * + * @param dependencyPackage package to import, for example `javax.validation.constraints.*` + */ + addDependency(dependencyPackage: string): void { + super.addDependency(`import ${dependencyPackage}`); + } +} diff --git a/src/generators/scala/ScalaFileGenerator.ts b/src/generators/scala/ScalaFileGenerator.ts new file mode 100644 index 0000000000..dab37a9636 --- /dev/null +++ b/src/generators/scala/ScalaFileGenerator.ts @@ -0,0 +1,43 @@ +import { ScalaGenerator, ScalaRenderCompleteModelOptions } from '.'; +import { InputMetaModel, OutputModel } from '../../models'; +import * as path from 'path'; +import { AbstractFileGenerator } from '../AbstractFileGenerator'; +import { FileHelpers } from '../../helpers'; + +export class ScalaFileGenerator + extends ScalaGenerator + implements AbstractFileGenerator +{ + /** + * Generates all the models to an output directory each model with their own separate files. + * + * @param input + * @param outputDirectory where you want the models generated to + * @param options + * @param ensureFilesWritten verify that the files is completely written before returning, this can happen if the file system is swamped with write requests. + */ + public async generateToFiles( + input: Record | InputMetaModel, + outputDirectory: string, + options: ScalaRenderCompleteModelOptions, + ensureFilesWritten = false + ): Promise { + let generatedModels = await this.generateCompleteModels(input, options); + //Filter anything out that have not been successfully generated + generatedModels = generatedModels.filter((outputModel) => { + return outputModel.modelName !== ''; + }); + for (const outputModel of generatedModels) { + const filePath = path.resolve( + outputDirectory, + `${outputModel.modelName}.scala` + ); + await FileHelpers.writerToFileSystem( + outputModel.result, + filePath, + ensureFilesWritten + ); + } + return generatedModels; + } +} diff --git a/src/generators/scala/ScalaGenerator.ts b/src/generators/scala/ScalaGenerator.ts new file mode 100644 index 0000000000..c765b8af8b --- /dev/null +++ b/src/generators/scala/ScalaGenerator.ts @@ -0,0 +1,260 @@ +import { + AbstractGenerator, + AbstractGeneratorRenderArgs, + AbstractGeneratorRenderCompleteModelArgs, + CommonGeneratorOptions, + defaultGeneratorOptions +} from '../AbstractGenerator'; +import { + ConstrainedEnumModel, + ConstrainedMetaModel, + ConstrainedObjectModel, + InputMetaModel, + MetaModel, + RenderOutput +} from '../../models'; +import { split, TypeMapping } from '../../helpers'; +import { ScalaPreset, SCALA_DEFAULT_PRESET } from './ScalaPreset'; +import { ClassRenderer } from './renderers/ClassRenderer'; +import { EnumRenderer } from './renderers/EnumRenderer'; +import { isReservedScalaKeyword } from './Constants'; +import { Logger } from '../..'; +import { + constrainMetaModel, + Constraints +} from '../../helpers/ConstrainHelpers'; +import { + ScalaDefaultConstraints, + ScalaDefaultTypeMapping +} from './ScalaConstrainer'; +import { DeepPartial, mergePartialAndDefault } from '../../utils/Partials'; +import { ScalaDependencyManager } from './ScalaDependencyManager'; + +export interface ScalaOptions extends CommonGeneratorOptions { + typeMapping: TypeMapping; + constraints: Constraints; + collectionType: 'List' | 'Array'; +} + +export type ScalaTypeMapping = TypeMapping< + ScalaOptions, + ScalaDependencyManager +>; + +export interface ScalaRenderCompleteModelOptions { + packageName: string; +} + +export class ScalaGenerator extends AbstractGenerator< + ScalaOptions, + ScalaRenderCompleteModelOptions +> { + static defaultOptions: ScalaOptions = { + ...defaultGeneratorOptions, + defaultPreset: SCALA_DEFAULT_PRESET, + collectionType: 'List', + typeMapping: ScalaDefaultTypeMapping, + constraints: ScalaDefaultConstraints + }; + + constructor(options?: DeepPartial) { + const realizedOptions = ScalaGenerator.getScalaOptions(options); + super('Scala', realizedOptions); + } + + /** + * Returns the Scala options by merging custom options with default ones. + */ + static getScalaOptions(options?: DeepPartial): ScalaOptions { + const optionsToUse = mergePartialAndDefault( + ScalaGenerator.defaultOptions, + options + ) as ScalaOptions; + //Always overwrite the dependency manager unless user explicitly state they want it (ignore default temporary dependency manager) + if (options?.dependencyManager === undefined) { + optionsToUse.dependencyManager = () => { + return new ScalaDependencyManager(optionsToUse); + }; + } + return optionsToUse; + } + + /** + * Wrapper to get an instance of the dependency manager + */ + getDependencyManager(options: ScalaOptions): ScalaDependencyManager { + return this.getDependencyManagerInstance(options) as ScalaDependencyManager; + } + + /** + * This function makes sure we split up the MetaModels accordingly to what we want to render as models. + */ + splitMetaModel(model: MetaModel): MetaModel[] { + const metaModelsToSplit = { + splitEnum: true, + splitObject: true + }; + return split(model, metaModelsToSplit); + } + + constrainToMetaModel( + model: MetaModel, + options: DeepPartial + ): ConstrainedMetaModel { + const optionsToUse = ScalaGenerator.getScalaOptions({ + ...this.options, + ...options + }); + const dependencyManagerToUse = this.getDependencyManager(optionsToUse); + return constrainMetaModel( + this.options.typeMapping, + this.options.constraints, + { + metaModel: model, + dependencyManager: dependencyManagerToUse, + options: this.options, + constrainedName: '' //This is just a placeholder, it will be constrained within the function + } + ); + } + + /** + * Render a scattered model, where the source code and library and model dependencies are separated. + * + * @param model + * @param inputModel + */ + render( + args: AbstractGeneratorRenderArgs + ): Promise { + const optionsToUse = ScalaGenerator.getScalaOptions({ + ...this.options, + ...args.options + }); + if (args.constrainedModel instanceof ConstrainedObjectModel) { + return this.renderClass( + args.constrainedModel, + args.inputModel, + optionsToUse + ); + } else if (args.constrainedModel instanceof ConstrainedEnumModel) { + return this.renderEnum( + args.constrainedModel, + args.inputModel, + optionsToUse + ); + } + Logger.warn( + `Scala generator, cannot generate this type of model, ${args.constrainedModel.name}` + ); + return Promise.resolve( + RenderOutput.toRenderOutput({ + result: '', + renderedName: '', + dependencies: [] + }) + ); + } + + /** + * Render a complete model result where the model code, library and model dependencies are all bundled appropriately. + * + * For Scala you need to specify which package the model is placed under. + * + * @param model + * @param inputModel + * @param options used to render the full output + */ + async renderCompleteModel( + args: AbstractGeneratorRenderCompleteModelArgs< + ScalaOptions, + ScalaRenderCompleteModelOptions + > + ): Promise { + const optionsToUse = ScalaGenerator.getScalaOptions({ + ...this.options, + ...args.options + }); + const outputModel = await this.render({ + ...args, + options: optionsToUse + }); + const packageName = this.sanitizePackageName( + args.completeOptions.packageName ?? 'Asyncapi.Models' + ); + const outputContent = `package ${packageName} +${outputModel.dependencies.join('\n')} + +${outputModel.result}`; + return RenderOutput.toRenderOutput({ + result: outputContent, + renderedName: outputModel.renderedName, + dependencies: outputModel.dependencies + }); + } + + private sanitizePackageName(packageName: string): string { + return packageName + .split('.') + .map((subpackage) => + isReservedScalaKeyword(subpackage, true) + ? `\`${subpackage}\`` + : subpackage + ) + .join('.'); + } + + async renderClass( + model: ConstrainedObjectModel, + inputModel: InputMetaModel, + options?: Partial + ): Promise { + const optionsToUse = ScalaGenerator.getScalaOptions({ + ...this.options, + ...options + }); + const dependencyManagerToUse = this.getDependencyManager(optionsToUse); + const presets = this.getPresets('class'); + const renderer = new ClassRenderer( + this.options, + this, + presets, + model, + inputModel, + dependencyManagerToUse + ); + const result = await renderer.runSelfPreset(); + return RenderOutput.toRenderOutput({ + result, + renderedName: model.name, + dependencies: dependencyManagerToUse.dependencies + }); + } + + async renderEnum( + model: ConstrainedEnumModel, + inputModel: InputMetaModel, + options?: Partial + ): Promise { + const optionsToUse = ScalaGenerator.getScalaOptions({ + ...this.options, + ...options + }); + const dependencyManagerToUse = this.getDependencyManager(optionsToUse); + const presets = this.getPresets('enum'); + const renderer = new EnumRenderer( + this.options, + this, + presets, + model, + inputModel, + dependencyManagerToUse + ); + const result = await renderer.runSelfPreset(); + return RenderOutput.toRenderOutput({ + result, + renderedName: model.name, + dependencies: dependencyManagerToUse.dependencies + }); + } +} diff --git a/src/generators/scala/ScalaPreset.ts b/src/generators/scala/ScalaPreset.ts new file mode 100644 index 0000000000..19388a4fdd --- /dev/null +++ b/src/generators/scala/ScalaPreset.ts @@ -0,0 +1,24 @@ +/* eslint-disable @typescript-eslint/ban-types */ +import { Preset, ClassPreset, EnumPreset } from '../../models'; +import { ScalaOptions } from './ScalaGenerator'; +import { + ClassRenderer, + SCALA_DEFAULT_CLASS_PRESET +} from './renderers/ClassRenderer'; +import { + EnumRenderer, + SCALA_DEFAULT_ENUM_PRESET +} from './renderers/EnumRenderer'; + +export type ClassPresetType = ClassPreset; +export type EnumPresetType = EnumPreset; + +export type ScalaPreset = Preset<{ + class: ClassPresetType; + enum: EnumPresetType; +}>; + +export const SCALA_DEFAULT_PRESET: ScalaPreset = { + class: SCALA_DEFAULT_CLASS_PRESET, + enum: SCALA_DEFAULT_ENUM_PRESET +}; diff --git a/src/generators/scala/ScalaRenderer.ts b/src/generators/scala/ScalaRenderer.ts new file mode 100644 index 0000000000..c5120264bd --- /dev/null +++ b/src/generators/scala/ScalaRenderer.ts @@ -0,0 +1,69 @@ +import { AbstractRenderer } from '../AbstractRenderer'; +import { ScalaGenerator, ScalaOptions } from './ScalaGenerator'; +import { ConstrainedMetaModel, InputMetaModel, Preset } from '../../models'; +import { FormatHelpers } from '../../helpers'; +import { ScalaDependencyManager } from './ScalaDependencyManager'; + +/** + * Common renderer for Scala + * + * @extends AbstractRenderer + */ +export abstract class ScalaRenderer< + RendererModelType extends ConstrainedMetaModel +> extends AbstractRenderer { + constructor( + options: ScalaOptions, + generator: ScalaGenerator, + presets: Array<[Preset, unknown]>, + model: RendererModelType, + inputModel: InputMetaModel, + public dependencyManager: ScalaDependencyManager + ) { + super(options, generator, presets, model, inputModel); + } + + renderComments(lines: string | string[]): string { + lines = FormatHelpers.breakLines(lines); + const newLiteral = lines.map((line) => ` * ${line}`).join('\n'); + return `/** +${newLiteral} + */`; + } + + renderAnnotation( + annotationName: string, + value?: any | Record + ): string { + const name = `@${annotationName}`; + + if (value === undefined || value === null) { + return name; + } + + if (typeof value !== 'object') { + return `${name}(${value})`; + } + + const entries = Object.entries(value || {}); + + if (entries.length === 0) { + return name; + } + + const values = concatenateEntries(entries); + return `${name}(${values})`; + } +} + +function concatenateEntries(entries: [string, unknown][] = []): string { + return entries + .map(([paramName, newValue]) => { + if (paramName && newValue !== undefined) { + return `${paramName}=${newValue}`; + } + return newValue; + }) + .filter((v) => v !== undefined) + .join(', '); +} diff --git a/src/generators/scala/constrainer/ConstantConstrainer.ts b/src/generators/scala/constrainer/ConstantConstrainer.ts new file mode 100644 index 0000000000..2c076ad46d --- /dev/null +++ b/src/generators/scala/constrainer/ConstantConstrainer.ts @@ -0,0 +1,7 @@ +import { ConstantConstraint } from '../../../helpers'; + +export function defaultConstantConstraints(): ConstantConstraint { + return () => { + return undefined; + }; +} diff --git a/src/generators/scala/constrainer/EnumConstrainer.ts b/src/generators/scala/constrainer/EnumConstrainer.ts new file mode 100644 index 0000000000..9ba2e2cb83 --- /dev/null +++ b/src/generators/scala/constrainer/EnumConstrainer.ts @@ -0,0 +1,105 @@ +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { ConstrainedEnumModel, EnumModel } from '../../../models'; +import { + NO_NUMBER_START_CHAR, + NO_DUPLICATE_ENUM_KEYS, + NO_EMPTY_VALUE, + NO_RESERVED_KEYWORDS +} from '../../../helpers/Constraints'; +import { + FormatHelpers, + EnumKeyConstraint, + EnumValueConstraint +} from '../../../helpers'; +import { isReservedScalaKeyword } from '../Constants'; + +export type ModelEnumKeyConstraints = { + NO_SPECIAL_CHAR: (value: string) => string; + NO_NUMBER_START_CHAR: (value: string) => string; + NO_DUPLICATE_KEYS: ( + constrainedEnumModel: ConstrainedEnumModel, + enumModel: EnumModel, + value: string, + namingFormatter: (value: string) => string + ) => string; + NO_EMPTY_VALUE: (value: string) => string; + NAMING_FORMATTER: (value: string) => string; + NO_RESERVED_KEYWORDS: (value: string) => string; +}; + +export const DefaultEnumKeyConstraints: ModelEnumKeyConstraints = { + NO_SPECIAL_CHAR: (value: string) => { + //Exclude ` ` because it gets formatted by NAMING_FORMATTER + //Exclude '_' because they are allowed as enum keys + return FormatHelpers.replaceSpecialCharacters(value, { + exclude: [' ', '_'], + separator: '_' + }); + }, + NO_NUMBER_START_CHAR, + NO_DUPLICATE_KEYS: NO_DUPLICATE_ENUM_KEYS, + NO_EMPTY_VALUE, + NAMING_FORMATTER: FormatHelpers.toConstantCase, + NO_RESERVED_KEYWORDS: (value: string) => { + return NO_RESERVED_KEYWORDS(value, isReservedScalaKeyword); + } +}; + +/** + * Default constraint logic for Scala, which converts the enum key into a key that is compatible with Scala + */ +export function defaultEnumKeyConstraints( + customConstraints?: Partial +): EnumKeyConstraint { + const constraints = { ...DefaultEnumKeyConstraints, ...customConstraints }; + + return ({ enumKey, enumModel, constrainedEnumModel }) => { + let constrainedEnumKey = enumKey; + constrainedEnumKey = constraints.NO_SPECIAL_CHAR(constrainedEnumKey); + constrainedEnumKey = constraints.NO_NUMBER_START_CHAR(constrainedEnumKey); + constrainedEnumKey = constraints.NO_EMPTY_VALUE(constrainedEnumKey); + constrainedEnumKey = constraints.NO_RESERVED_KEYWORDS(constrainedEnumKey); + //If the enum key has been manipulated, lets make sure it don't clash with existing keys + if (constrainedEnumKey !== enumKey) { + constrainedEnumKey = constraints.NO_DUPLICATE_KEYS( + constrainedEnumModel, + enumModel, + constrainedEnumKey, + constraints.NAMING_FORMATTER! + ); + } + constrainedEnumKey = constraints.NAMING_FORMATTER(constrainedEnumKey); + return constrainedEnumKey; + }; +} + +/** + * Convert the enum value to a value that is compatible with Scala + */ +export function defaultEnumValueConstraints(): EnumValueConstraint { + return ({ enumValue }) => { + let constrainedEnumValue = enumValue; + switch (typeof enumValue) { + case 'string': + case 'boolean': + constrainedEnumValue = `"${enumValue}"`; + break; + case 'bigint': + case 'number': { + constrainedEnumValue = enumValue; + break; + } + case 'object': { + constrainedEnumValue = `"${JSON.stringify(enumValue).replace( + /"/g, + '\\"' + )}"`; + break; + } + default: { + constrainedEnumValue = `"${JSON.stringify(enumValue)}"`; + } + } + return constrainedEnumValue; + }; +} diff --git a/src/generators/scala/constrainer/ModelNameConstrainer.ts b/src/generators/scala/constrainer/ModelNameConstrainer.ts new file mode 100644 index 0000000000..c9c523dff2 --- /dev/null +++ b/src/generators/scala/constrainer/ModelNameConstrainer.ts @@ -0,0 +1,53 @@ +import { + NO_NUMBER_START_CHAR, + NO_EMPTY_VALUE, + NO_RESERVED_KEYWORDS +} from '../../../helpers/Constraints'; +import { FormatHelpers, ModelNameConstraint } from '../../../helpers'; +import { isReservedScalaKeyword } from '../Constants'; + +export type ModelNameConstraints = { + NO_SPECIAL_CHAR: (value: string) => string; + NO_NUMBER_START_CHAR: (value: string) => string; + NO_EMPTY_VALUE: (value: string) => string; + NAMING_FORMATTER: (value: string) => string; + NO_RESERVED_KEYWORDS: (value: string) => string; +}; + +export const DefaultModelNameConstraints: ModelNameConstraints = { + NO_SPECIAL_CHAR: (value: string) => { + //Exclude ` ` because it gets formatted by NAMING_FORMATTER + //Exclude '_' because they are allowed + return FormatHelpers.replaceSpecialCharacters(value, { + exclude: [' ', '_'], + separator: '_' + }); + }, + NO_NUMBER_START_CHAR, + NO_EMPTY_VALUE, + NAMING_FORMATTER: (value: string) => { + return FormatHelpers.toPascalCase(value); + }, + NO_RESERVED_KEYWORDS: (value: string) => { + return NO_RESERVED_KEYWORDS(value, isReservedScalaKeyword); + } +}; + +/** + * Default constraint logic for Scala, which converts the model name into something that is compatible with Scala + */ +export function defaultModelNameConstraints( + customConstraints?: Partial +): ModelNameConstraint { + const constraints = { ...DefaultModelNameConstraints, ...customConstraints }; + + return ({ modelName }) => { + let constrainedValue = modelName; + constrainedValue = constraints.NO_SPECIAL_CHAR(constrainedValue); + constrainedValue = constraints.NO_NUMBER_START_CHAR(constrainedValue); + constrainedValue = constraints.NO_EMPTY_VALUE(constrainedValue); + constrainedValue = constraints.NO_RESERVED_KEYWORDS(constrainedValue); + constrainedValue = constraints.NAMING_FORMATTER(constrainedValue); + return constrainedValue; + }; +} diff --git a/src/generators/scala/constrainer/PropertyKeyConstrainer.ts b/src/generators/scala/constrainer/PropertyKeyConstrainer.ts new file mode 100644 index 0000000000..640761546c --- /dev/null +++ b/src/generators/scala/constrainer/PropertyKeyConstrainer.ts @@ -0,0 +1,80 @@ +import { ConstrainedObjectModel, ObjectModel } from '../../../models'; +import { + NO_NUMBER_START_CHAR, + NO_DUPLICATE_PROPERTIES, + NO_EMPTY_VALUE, + NO_RESERVED_KEYWORDS +} from '../../../helpers/Constraints'; +import { FormatHelpers, PropertyKeyConstraint } from '../../../helpers'; +import { isReservedScalaKeyword } from '../Constants'; + +export type PropertyKeyConstraintOptions = { + NO_SPECIAL_CHAR: (value: string) => string; + NO_NUMBER_START_CHAR: (value: string) => string; + NO_DUPLICATE_PROPERTIES: ( + constrainedObjectModel: ConstrainedObjectModel, + objectModel: ObjectModel, + propertyName: string, + namingFormatter: (value: string) => string + ) => string; + NO_EMPTY_VALUE: (value: string) => string; + NAMING_FORMATTER: (value: string) => string; + NO_RESERVED_KEYWORDS: (value: string) => string; +}; + +export const DefaultPropertyKeyConstraints: PropertyKeyConstraintOptions = { + NO_SPECIAL_CHAR: (value: string) => { + //Exclude ` ` because it gets formatted by NAMING_FORMATTER + //Exclude '_' because they are allowed + return FormatHelpers.replaceSpecialCharacters(value, { + exclude: [' ', '_'], + separator: '_' + }); + }, + NO_NUMBER_START_CHAR, + NO_DUPLICATE_PROPERTIES, + NO_EMPTY_VALUE, + NAMING_FORMATTER: FormatHelpers.toCamelCase, + NO_RESERVED_KEYWORDS: (value: string) => { + return NO_RESERVED_KEYWORDS(value, isReservedScalaKeyword); + } +}; +/** + * Default constraint logic for Scala, which converts the object property key into something that is compatible with Scala + */ +export function defaultPropertyKeyConstraints( + customConstraints?: Partial +): PropertyKeyConstraint { + const constraints = { + ...DefaultPropertyKeyConstraints, + ...customConstraints + }; + + return ({ objectPropertyModel, constrainedObjectModel, objectModel }) => { + let constrainedPropertyKey = objectPropertyModel.propertyName; + + constrainedPropertyKey = constraints.NO_SPECIAL_CHAR( + constrainedPropertyKey + ); + constrainedPropertyKey = constraints.NO_NUMBER_START_CHAR( + constrainedPropertyKey + ); + constrainedPropertyKey = constraints.NO_EMPTY_VALUE(constrainedPropertyKey); + constrainedPropertyKey = constraints.NO_RESERVED_KEYWORDS( + constrainedPropertyKey + ); + //If the property name has been manipulated, lets make sure it don't clash with existing properties + if (constrainedPropertyKey !== objectPropertyModel.propertyName) { + constrainedPropertyKey = constraints.NO_DUPLICATE_PROPERTIES( + constrainedObjectModel, + objectModel, + constrainedPropertyKey, + constraints.NAMING_FORMATTER + ); + } + constrainedPropertyKey = constraints.NAMING_FORMATTER( + constrainedPropertyKey + ); + return constrainedPropertyKey; + }; +} diff --git a/src/generators/scala/index.ts b/src/generators/scala/index.ts new file mode 100644 index 0000000000..d538f6c328 --- /dev/null +++ b/src/generators/scala/index.ts @@ -0,0 +1,21 @@ +export * from './ScalaGenerator'; +export * from './ScalaFileGenerator'; +export { SCALA_DEFAULT_PRESET } from './ScalaPreset'; +export type { ScalaPreset } from './ScalaPreset'; +export * from './presets'; + +export { + defaultEnumKeyConstraints as scalaDefaultEnumKeyConstraints, + DefaultEnumKeyConstraints as ScalaDefaultEnumKeyConstraints, + defaultEnumValueConstraints as scalaDefaultEnumValueConstraints +} from './constrainer/EnumConstrainer'; + +export { + DefaultModelNameConstraints as ScalaDefaultModelNameConstraints, + defaultModelNameConstraints as scalaDefaultModelNameConstraints +} from './constrainer/ModelNameConstrainer'; + +export { + DefaultPropertyKeyConstraints as ScalaDefaultPropertyKeyConstraints, + defaultPropertyKeyConstraints as scalaDefaultPropertyKeyConstraints +} from './constrainer/PropertyKeyConstrainer'; diff --git a/src/generators/scala/presets/DescriptionPreset.ts b/src/generators/scala/presets/DescriptionPreset.ts new file mode 100644 index 0000000000..a7fb1c7ac2 --- /dev/null +++ b/src/generators/scala/presets/DescriptionPreset.ts @@ -0,0 +1,63 @@ +import { ScalaRenderer } from '../ScalaRenderer'; +import { ScalaPreset } from '../ScalaPreset'; +import { FormatHelpers } from '../../../helpers'; +import { ConstrainedEnumModel, ConstrainedObjectModel } from '../../../models'; +function renderDescription({ + renderer, + content, + item +}: { + renderer: ScalaRenderer; + content: string; + item: ConstrainedObjectModel | ConstrainedEnumModel; +}): string { + if (!item.originalInput['description']) { + return content; + } + + let comment = `${item.originalInput['description']}`; + + if (item instanceof ConstrainedObjectModel) { + const properties = Object.keys(item.properties) + .map((key) => item.properties[`${key}`]) + .map((model) => { + const property = `@property ${model.propertyName}`; + const desc = model.property.originalInput['description']; + + return desc !== undefined ? `${property} ${desc}` : property; + }) + .join('\n'); + + comment += `\n\n${properties}`; + } + + const examples = Array.isArray(item.originalInput['examples']) + ? `Examples: \n${FormatHelpers.renderJSONExamples( + item.originalInput['examples'] + )}` + : null; + + if (examples !== null) { + comment += `\n\n${examples}`; + } + + return `${renderer.renderComments(comment)}\n${content}`; +} + +/** + * Preset which adds description to rendered model. + * + * @implements {ScalaPreset} + */ +export const SCALA_DESCRIPTION_PRESET: ScalaPreset = { + class: { + self({ renderer, model, content }) { + return renderDescription({ renderer, content, item: model }); + } + }, + enum: { + self({ renderer, model, content }) { + return renderDescription({ renderer, content, item: model }); + } + } +}; diff --git a/src/generators/scala/presets/index.ts b/src/generators/scala/presets/index.ts new file mode 100644 index 0000000000..e74c57b288 --- /dev/null +++ b/src/generators/scala/presets/index.ts @@ -0,0 +1 @@ +export * from './DescriptionPreset'; diff --git a/src/generators/scala/renderers/ClassRenderer.ts b/src/generators/scala/renderers/ClassRenderer.ts new file mode 100644 index 0000000000..d175300b07 --- /dev/null +++ b/src/generators/scala/renderers/ClassRenderer.ts @@ -0,0 +1,66 @@ +import { ScalaRenderer } from '../ScalaRenderer'; +import { + ConstrainedObjectModel, + ConstrainedObjectPropertyModel +} from '../../../models'; +import { ScalaOptions } from '../ScalaGenerator'; +import { ClassPresetType } from '../ScalaPreset'; + +function getPropertyType(property: ConstrainedObjectPropertyModel): string { + return property.required + ? property.property.type + : `Option[${property.property.type}]`; +} + +/** + * Renderer for Scala's `class` type + * + * @extends ScalaRenderer + */ +export class ClassRenderer extends ScalaRenderer { + async defaultSelf(hasProperties: boolean): Promise { + return hasProperties + ? await this.defaultWithProperties() + : `class ${this.model.name} {}`; + } + + private async defaultWithProperties(): Promise { + const content = [ + await this.renderProperties(), + await this.runAdditionalContentPreset() + ]; + + return `case class ${this.model.name}( +${this.indent(this.renderBlock(content, 2))} +)`; + } + + async renderProperties(): Promise { + const properties = this.model.properties || {}; + const content: string[] = []; + + for (const property of Object.values(properties)) { + const rendererProperty = await this.runPropertyPreset(property); + content.push(rendererProperty); + } + + return this.renderBlock(content); + } + + runPropertyPreset(property: ConstrainedObjectPropertyModel): Promise { + return this.runPreset('property', { property }); + } +} + +export const SCALA_DEFAULT_CLASS_PRESET: ClassPresetType = { + self({ renderer, model }) { + const hasProperties = Object.keys(model.properties).length > 0; + + return renderer.defaultSelf(hasProperties); + }, + property({ property }) { + const propertyType = getPropertyType(property); + + return `${property.propertyName}: ${propertyType},`; + } +}; diff --git a/src/generators/scala/renderers/EnumRenderer.ts b/src/generators/scala/renderers/EnumRenderer.ts new file mode 100644 index 0000000000..45986fb6a8 --- /dev/null +++ b/src/generators/scala/renderers/EnumRenderer.ts @@ -0,0 +1,60 @@ +import { ScalaRenderer } from '../ScalaRenderer'; +import { + ConstrainedEnumModel, + ConstrainedEnumValueModel +} from '../../../models'; +import { EnumPresetType } from '../ScalaPreset'; +import { ScalaOptions } from '../ScalaGenerator'; +import { FormatHelpers } from '../../../helpers'; + +/** + * Renderer for Scala's `enum` type + * + * @extends ScalaRenderer + */ +export class EnumRenderer extends ScalaRenderer { + async defaultSelf(): Promise { + const content = [ + await this.renderItems(), + await this.runFromValuePreset(), + await this.runAdditionalContentPreset() + ]; + return `object ${this.model.name} extends Enumeration { + type ${this.model.name} = Value + +${this.indent(this.renderBlock(content, 2))} +}`; + } + + async renderItems(): Promise { + const enums = this.model.values || []; + const items: string[] = []; + + for (const value of enums) { + const renderedItem = await this.runItemPreset(value); + items.push(renderedItem); + } + + const content = items.join('\n'); + return `${content}`; + } + + runItemPreset(item: ConstrainedEnumValueModel): Promise { + return this.runPreset('item', { item }); + } + + runFromValuePreset(): Promise { + return this.runPreset('fromValue'); + } +} + +export const SCALA_DEFAULT_ENUM_PRESET: EnumPresetType = { + self({ renderer }) { + return renderer.defaultSelf(); + }, + item({ item, model }) { + const key = FormatHelpers.toPascalCase(item.key); + + return `val ${key}: ${model.name}.Value = Value(${item.value})`; + } +}; diff --git a/test/TestUtils/TestRenderers.ts b/test/TestUtils/TestRenderers.ts index 56ca121ff8..063d71bf99 100644 --- a/test/TestUtils/TestRenderers.ts +++ b/test/TestUtils/TestRenderers.ts @@ -15,6 +15,7 @@ import { RustRenderer } from '../../src/generators/rust/RustRenderer'; import { PythonRenderer } from '../../src/generators/python/PythonRenderer'; import { KotlinRenderer } from '../../src/generators/kotlin/KotlinRenderer'; import { PhpRenderer } from '../../src/generators/php/PhpRenderer'; +import { ScalaRenderer } from '../../src/generators/scala/ScalaRenderer'; export class TestRenderer extends AbstractRenderer { constructor(presets = []) { @@ -43,3 +44,4 @@ export class MockRustRenderer extends RustRenderer {} export class MockPythonRenderer extends PythonRenderer {} export class MockKotlinRenderer extends KotlinRenderer {} export class MockPhpRenderer extends PhpRenderer {} +export class MockScalaRenderer extends ScalaRenderer {} diff --git a/test/generators/scala/Constants.spec.ts b/test/generators/scala/Constants.spec.ts new file mode 100644 index 0000000000..59da18ea3e --- /dev/null +++ b/test/generators/scala/Constants.spec.ts @@ -0,0 +1,12 @@ +import { isReservedScalaKeyword } from '../../../src/generators/scala/Constants'; + +describe('Reserved keywords', () => { + it('should return true if the word is a reserved keyword', () => { + expect(isReservedScalaKeyword('abstract')).toBe(true); + expect(isReservedScalaKeyword('type')).toBe(true); + }); + + it('should return false if the word is not a reserved keyword', () => { + expect(isReservedScalaKeyword('dinosaur')).toBe(false); + }); +}); diff --git a/test/generators/scala/ScalaConstrainer.spec.ts b/test/generators/scala/ScalaConstrainer.spec.ts new file mode 100644 index 0000000000..f1fd616ccf --- /dev/null +++ b/test/generators/scala/ScalaConstrainer.spec.ts @@ -0,0 +1,512 @@ +import { ScalaDefaultTypeMapping } from '../../../src/generators/scala/ScalaConstrainer'; +import { ScalaGenerator, ScalaOptions } from '../../../src/generators/scala'; +import { + ConstrainedAnyModel, + ConstrainedArrayModel, + ConstrainedBooleanModel, + ConstrainedDictionaryModel, + ConstrainedEnumModel, + ConstrainedEnumValueModel, + ConstrainedFloatModel, + ConstrainedIntegerModel, + ConstrainedObjectModel, + ConstrainedReferenceModel, + ConstrainedStringModel, + ConstrainedTupleModel, + ConstrainedTupleValueModel, + ConstrainedUnionModel +} from '../../../src'; +describe('ScalaConstrainer', () => { + describe('ObjectModel', () => { + test('should render the constrained name as type', () => { + const model = new ConstrainedObjectModel('test', undefined, {}, '', {}); + const type = ScalaDefaultTypeMapping.Object({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual(model.name); + }); + }); + describe('Reference', () => { + test('should render the constrained name as type', () => { + const refModel = new ConstrainedAnyModel('test', undefined, {}, ''); + const model = new ConstrainedReferenceModel( + 'test', + undefined, + {}, + '', + refModel + ); + const type = ScalaDefaultTypeMapping.Reference({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual(model.name); + }); + }); + describe('Any', () => { + test('should render type', () => { + const model = new ConstrainedAnyModel('test', undefined, {}, ''); + const type = ScalaDefaultTypeMapping.Any({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Any'); + }); + }); + describe('Float', () => { + test('should render type', () => { + const model = new ConstrainedFloatModel('test', undefined, {}, ''); + const type = ScalaDefaultTypeMapping.Float({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Double'); + }); + test('should render Float when format has number format', () => { + const model = new ConstrainedFloatModel( + 'test', + {}, + { format: 'float' }, + '' + ); + const type = ScalaDefaultTypeMapping.Float({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Float'); + }); + }); + describe('Integer', () => { + test('should render type', () => { + const model = new ConstrainedIntegerModel('test', undefined, {}, ''); + const type = ScalaDefaultTypeMapping.Integer({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Int'); + }); + test('should render Int when format has integer format', () => { + const model = new ConstrainedIntegerModel( + 'test', + {}, + { format: 'int32' }, + '' + ); + const type = ScalaDefaultTypeMapping.Integer({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Int'); + }); + test('should render Long when format has long format', () => { + const model = new ConstrainedIntegerModel( + 'test', + {}, + { format: 'long' }, + '' + ); + const type = ScalaDefaultTypeMapping.Integer({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Long'); + }); + test('should render Long when format has int64 format', () => { + const model = new ConstrainedIntegerModel( + 'test', + {}, + { format: 'int64' }, + '' + ); + const type = ScalaDefaultTypeMapping.Integer({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Long'); + }); + }); + describe('String', () => { + test('should render type', () => { + const model = new ConstrainedStringModel('test', undefined, {}, ''); + const type = ScalaDefaultTypeMapping.String({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('String'); + }); + test('should render LocalDate when format has date format', () => { + const model = new ConstrainedStringModel( + 'test', + {}, + { format: 'date' }, + '' + ); + const type = ScalaDefaultTypeMapping.String({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('java.time.LocalDate'); + }); + test('should render OffsetTime when format has time format', () => { + const model = new ConstrainedStringModel( + 'test', + {}, + { format: 'time' }, + '' + ); + const type = ScalaDefaultTypeMapping.String({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('java.time.OffsetTime'); + }); + test('should render OffsetDateTime when format has dateTime format', () => { + const model = new ConstrainedStringModel( + 'test', + {}, + { format: 'dateTime' }, + '' + ); + const type = ScalaDefaultTypeMapping.String({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('java.time.OffsetDateTime'); + }); + test('should render OffsetDateTime when format has date-time format', () => { + const model = new ConstrainedStringModel( + 'test', + {}, + { format: 'date-time' }, + '' + ); + const type = ScalaDefaultTypeMapping.String({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('java.time.OffsetDateTime'); + }); + test('should render byte when format has binary format', () => { + const model = new ConstrainedStringModel( + 'test', + {}, + { format: 'binary' }, + '' + ); + const type = ScalaDefaultTypeMapping.String({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Array[Byte]'); + }); + }); + + describe('Boolean', () => { + test('should render type', () => { + const model = new ConstrainedBooleanModel('test', undefined, {}, ''); + const type = ScalaDefaultTypeMapping.Boolean({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Boolean'); + }); + }); + + describe('Tuple', () => { + test('should render type', () => { + const stringModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'String' + ); + const tupleValueModel = new ConstrainedTupleValueModel(0, stringModel); + const model = new ConstrainedTupleModel('test', undefined, {}, '', [ + tupleValueModel + ]); + const type = ScalaDefaultTypeMapping.Tuple({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('List[Any]'); + }); + test('should render multiple tuple types', () => { + const stringModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'String' + ); + const tupleValueModel0 = new ConstrainedTupleValueModel(0, stringModel); + const tupleValueModel1 = new ConstrainedTupleValueModel(1, stringModel); + const model = new ConstrainedTupleModel('test', undefined, {}, '', [ + tupleValueModel0, + tupleValueModel1 + ]); + const type = ScalaDefaultTypeMapping.Tuple({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('List[Any]'); + }); + }); + + describe('Array', () => { + test('should render type', () => { + const arrayModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'String' + ); + const model = new ConstrainedArrayModel( + 'test', + undefined, + {}, + '', + arrayModel + ); + const options: ScalaOptions = { + ...ScalaGenerator.defaultOptions, + collectionType: 'Array' + }; + const type = ScalaDefaultTypeMapping.Array({ + constrainedModel: model, + options, + dependencyManager: undefined as never + }); + expect(type).toEqual('Array[String]'); + }); + test('should render array as a list', () => { + const arrayModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'String' + ); + const model = new ConstrainedArrayModel( + 'test', + undefined, + {}, + '', + arrayModel + ); + const options: ScalaOptions = { + ...ScalaGenerator.defaultOptions, + collectionType: 'List' + }; + const type = ScalaDefaultTypeMapping.Array({ + constrainedModel: model, + options, + dependencyManager: undefined as never + }); + expect(type).toEqual('List[String]'); + }); + }); + + describe('Enum', () => { + test('should render string enum values as String type', () => { + const enumValue = new ConstrainedEnumValueModel( + 'test', + 'string type', + {} + ); + const model = new ConstrainedEnumModel('test', undefined, {}, '', [ + enumValue + ]); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('String'); + }); + test('should render boolean enum values as boolean type', () => { + const enumValue = new ConstrainedEnumValueModel('test', true, {}); + const model = new ConstrainedEnumModel('test', undefined, {}, '', [ + enumValue + ]); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Boolean'); + }); + test('should render generic number enum value with format', () => { + const enumValue = new ConstrainedEnumValueModel('test', 123, {}); + const model = new ConstrainedEnumModel('test', undefined, {}, '', [ + enumValue + ]); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Int'); + }); + test('should render generic number enum value with float format as float type', () => { + const enumValue = new ConstrainedEnumValueModel('test', 12.0, {}); + const model = new ConstrainedEnumModel( + 'test', + {}, + { format: 'float' }, + '', + [enumValue] + ); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Float'); + }); + test('should render generic number enum value with double format as double type', () => { + const enumValue = new ConstrainedEnumValueModel('test', 12.0, {}); + const model = new ConstrainedEnumModel( + 'test', + {}, + { format: 'double' }, + '', + [enumValue] + ); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Double'); + }); + test('should render object enum value as generic Object', () => { + const enumValue = new ConstrainedEnumValueModel('test', {}, {}); + const model = new ConstrainedEnumModel('test', undefined, {}, '', [ + enumValue + ]); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Any'); + }); + test('should render multiple value types as generic Object', () => { + const enumValue2 = new ConstrainedEnumValueModel('test', true, {}); + const enumValue1 = new ConstrainedEnumValueModel( + 'test', + 'string type', + {} + ); + const model = new ConstrainedEnumModel('test', undefined, {}, '', [ + enumValue1, + enumValue2 + ]); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Any'); + }); + test('should render double and integer as double type', () => { + const enumValue2 = new ConstrainedEnumValueModel('test', 123, {}); + const enumValue1 = new ConstrainedEnumValueModel('test', 123.12, {}); + const model = new ConstrainedEnumModel('test', undefined, {}, '', [ + enumValue1, + enumValue2 + ]); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Double'); + }); + test('should render int and long as long type', () => { + const enumValue2 = new ConstrainedEnumValueModel('test', 123, {}); + const enumValue1 = new ConstrainedEnumValueModel('test', 123, {}); + const model = new ConstrainedEnumModel( + 'test', + {}, + { format: 'long' }, + '', + [enumValue1, enumValue2] + ); + const type = ScalaDefaultTypeMapping.Enum({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Long'); + }); + }); + + describe('Union', () => { + test('should render type', () => { + const unionModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'str' + ); + const model = new ConstrainedUnionModel('test', undefined, {}, '', [ + unionModel + ]); + const type = ScalaDefaultTypeMapping.Union({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Any'); + }); + }); + + describe('Dictionary', () => { + test('should render type', () => { + const keyModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'String' + ); + const valueModel = new ConstrainedStringModel( + 'test', + undefined, + {}, + 'String' + ); + const model = new ConstrainedDictionaryModel( + 'test', + undefined, + {}, + '', + keyModel, + valueModel + ); + const type = ScalaDefaultTypeMapping.Dictionary({ + constrainedModel: model, + options: ScalaGenerator.defaultOptions, + dependencyManager: undefined as never + }); + expect(type).toEqual('Map[String, String]'); + }); + }); +}); diff --git a/test/generators/scala/ScalaGenerator.spec.ts b/test/generators/scala/ScalaGenerator.spec.ts new file mode 100644 index 0000000000..7fab2302cd --- /dev/null +++ b/test/generators/scala/ScalaGenerator.spec.ts @@ -0,0 +1,211 @@ +import { ScalaGenerator } from '../../../src/generators/scala'; + +describe('ScalaGenerator', () => { + let generator: ScalaGenerator; + beforeEach(() => { + generator = new ScalaGenerator(); + }); + afterEach(() => { + jest.restoreAllMocks(); + }); + + test('should not render reserved keyword', async () => { + const doc = { + $id: 'Address', + type: 'object', + properties: { + class: { type: 'string' } + }, + additionalProperties: false + }; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); + + test('should render `case class` type', async () => { + const doc = { + $id: 'Address', + type: 'object', + properties: { + street_name: { type: 'string' }, + city: { type: 'string', description: 'City description' }, + state: { type: 'string' }, + house_number: { type: 'number' }, + marriage: { + type: 'boolean', + description: 'Status if marriage live in given house' + }, + members: { + oneOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }] + }, + array_type: { + type: 'array', + items: [{ type: 'string' }, { type: 'number' }] + }, + date: { type: 'string', format: 'date' }, + time: { type: 'string', format: 'time' }, + dateTime: { type: 'string', format: 'date-time' }, + binary: { type: 'string', format: 'binary' } + }, + patternProperties: { + '^S(.?*)test&': { + type: 'string' + } + }, + required: ['street_name', 'city', 'state', 'house_number', 'array_type'] + }; + + const expectedDependencies = []; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + expect(models[0].dependencies).toEqual(expectedDependencies); + }); + + test('should render `enum class` type (string type)', async () => { + const doc = { + $id: 'States', + type: 'string', + enum: ['Texas', 'Alabama', 'California', 'New York'] + }; + const expectedDependencies = []; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + expect(models[0].dependencies).toEqual(expectedDependencies); + }); + + test('should render `enum` type (integer type)', async () => { + const doc = { + $id: 'Numbers', + type: 'integer', + enum: [0, 1, 2, 3] + }; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); + + test('should render `enum` type (union type)', async () => { + const doc = { + $id: 'Union', + type: ['string', 'integer', 'boolean'], + enum: ['Texas', 'Alabama', 0, 1, '1', true, { test: 'test' }] + }; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); + + test('should render enums with translated special characters', async () => { + const doc = { + $id: 'States', + enum: ['test+', 'test', 'test-', 'test?!', '*test'] + }; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); + + test('should render List type for collections', async () => { + const doc = { + $id: 'CustomClass', + type: 'object', + additionalProperties: false, + properties: { + arrayType: { + type: 'array', + items: { type: 'integer' }, + additionalItems: false + } + } + }; + + generator = new ScalaGenerator({ collectionType: 'List' }); + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); + + test('should render models and their dependencies', async () => { + const doc = { + $id: 'Address', + type: 'object', + properties: { + street_name: { type: 'string' }, + city: { type: 'string', description: 'City description' }, + state: { type: 'string' }, + house_number: { type: 'number' }, + marriage: { + type: 'boolean', + description: 'Status if marriage live in given house' + }, + members: { + oneOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }] + }, + array_type: { + type: 'array', + items: [{ type: 'string' }, { type: 'number' }] + }, + other_model: { + type: 'object', + $id: 'OtherModel', + properties: { street_name: { type: 'string' } } + } + }, + patternProperties: { + '^S(.?*)test&': { + type: 'string' + } + }, + required: ['street_name', 'city', 'state', 'house_number', 'array_type'] + }; + const config = { packageName: 'test.package' }; + const models = await generator.generateCompleteModels(doc, config); + expect(models).toHaveLength(2); + expect(models[0].result).toMatchSnapshot(); + expect(models[1].result).toMatchSnapshot(); + }); + test('should escape reserved keywords in package name', async () => { + const doc = { + $id: 'Address', + type: 'object', + properties: { + street_name: { type: 'string' }, + city: { type: 'string', description: 'City description' }, + state: { type: 'string' }, + house_number: { type: 'number' }, + marriage: { + type: 'boolean', + description: 'Status if marriage live in given house' + }, + members: { + oneOf: [{ type: 'string' }, { type: 'number' }, { type: 'boolean' }] + }, + array_type: { + type: 'array', + items: [{ type: 'string' }, { type: 'number' }] + } + }, + patternProperties: { + '^S(.?*)test&': { + type: 'string' + } + }, + required: ['street_name', 'city', 'state', 'house_number', 'array_type'] + }; + const config = { packageName: 'test.class.package' }; + const models = await generator.generateCompleteModels(doc, config); + + const expectedPackageDeclaration = 'package test.`class`.`package'; + expect(models[0].result).toContain(expectedPackageDeclaration); + }); +}); diff --git a/test/generators/scala/ScalaRenderer.spec.ts b/test/generators/scala/ScalaRenderer.spec.ts new file mode 100644 index 0000000000..1b19e1b7e6 --- /dev/null +++ b/test/generators/scala/ScalaRenderer.spec.ts @@ -0,0 +1,41 @@ +import { ScalaGenerator } from '../../../src/generators/scala'; +import { ScalaRenderer } from '../../../src/generators/scala/ScalaRenderer'; +import { ConstrainedObjectModel, InputMetaModel } from '../../../src/models'; +import { MockScalaRenderer } from '../../TestUtils/TestRenderers'; + +describe('ScalaRenderer', () => { + let renderer: ScalaRenderer; + beforeEach(() => { + renderer = new MockScalaRenderer( + ScalaGenerator.defaultOptions, + new ScalaGenerator(), + [], + new ConstrainedObjectModel('', undefined, '', {}), + new InputMetaModel() + ); + }); + + describe('renderComments()', () => { + test('Should be able to render comments', () => { + expect(renderer.renderComments('someComment')).toEqual(`/** + * someComment + */`); + }); + }); + + describe('renderAnnotation()', () => { + test('Should render', () => { + expect(renderer.renderAnnotation('someComment')).toEqual('@someComment'); + }); + test('Should be able to render multiple values', () => { + expect( + renderer.renderAnnotation('someComment', { test: 1, cool: '"story"' }) + ).toEqual('@someComment(test=1, cool="story")'); + }); + test('Should be able to render one value', () => { + expect( + renderer.renderAnnotation('someComment', { test: '"test2"' }) + ).toEqual('@someComment(test="test2")'); + }); + }); +}); diff --git a/test/generators/scala/__snapshots__/ScalaGenerator.spec.ts.snap b/test/generators/scala/__snapshots__/ScalaGenerator.spec.ts.snap new file mode 100644 index 0000000000..717eef2ed4 --- /dev/null +++ b/test/generators/scala/__snapshots__/ScalaGenerator.spec.ts.snap @@ -0,0 +1,105 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`ScalaGenerator should not render reserved keyword 1`] = ` +"case class Address( + reservedClass: Option[String], +)" +`; + +exports[`ScalaGenerator should render \`case class\` type 1`] = ` +"case class Address( + streetName: String, + city: String, + state: String, + houseNumber: Double, + marriage: Option[Boolean], + members: Option[Any], + arrayType: List[Any], + date: Option[java.time.LocalDate], + time: Option[java.time.OffsetTime], + dateTime: Option[java.time.OffsetDateTime], + binary: Option[Array[Byte]], + additionalProperties: Option[Map[String, Any]], +)" +`; + +exports[`ScalaGenerator should render \`enum class\` type (string type) 1`] = ` +"object States extends Enumeration { + type States = Value + + val Texas: States.Value = Value(\\"Texas\\") + val Alabama: States.Value = Value(\\"Alabama\\") + val California: States.Value = Value(\\"California\\") + val NewYork: States.Value = Value(\\"New York\\") +}" +`; + +exports[`ScalaGenerator should render \`enum\` type (integer type) 1`] = ` +"object Numbers extends Enumeration { + type Numbers = Value + + val Number_0: Numbers.Value = Value(0) + val Number_1: Numbers.Value = Value(1) + val Number_2: Numbers.Value = Value(2) + val Number_3: Numbers.Value = Value(3) +}" +`; + +exports[`ScalaGenerator should render \`enum\` type (union type) 1`] = ` +"object Union extends Enumeration { + type Union = Value + + val Texas: Union.Value = Value(\\"Texas\\") + val Alabama: Union.Value = Value(\\"Alabama\\") + val Number_0: Union.Value = Value(0) + val Number_1: Union.Value = Value(1) + val ReservedNumber_1: Union.Value = Value(\\"1\\") + val ReservedTrue: Union.Value = Value(\\"true\\") + val CurlyleftQuotationTestQuotationColonQuotationTestQuotationCurlyright: Union.Value = Value(\\"{\\\\\\"test\\\\\\":\\\\\\"test\\\\\\"}\\") +}" +`; + +exports[`ScalaGenerator should render List type for collections 1`] = ` +"case class CustomClass( + arrayType: Option[List[Int]], +)" +`; + +exports[`ScalaGenerator should render enums with translated special characters 1`] = ` +"object States extends Enumeration { + type States = Value + + val TestPlus: States.Value = Value(\\"test+\\") + val Test: States.Value = Value(\\"test\\") + val TestMinus: States.Value = Value(\\"test-\\") + val TestQuestionExclamation: States.Value = Value(\\"test?!\\") + val AsteriskTest: States.Value = Value(\\"*test\\") +}" +`; + +exports[`ScalaGenerator should render models and their dependencies 1`] = ` +"package test.\`package\` + + +case class Address( + streetName: String, + city: String, + state: String, + houseNumber: Double, + marriage: Option[Boolean], + members: Option[Any], + arrayType: List[Any], + otherModel: Option[OtherModel], + additionalProperties: Option[Map[String, Any]], +)" +`; + +exports[`ScalaGenerator should render models and their dependencies 2`] = ` +"package test.\`package\` + + +case class OtherModel( + streetName: Option[String], + additionalProperties: Option[Map[String, Any]], +)" +`; diff --git a/test/generators/scala/presets/DescriptionPreset.spec.ts b/test/generators/scala/presets/DescriptionPreset.spec.ts new file mode 100644 index 0000000000..6d78deabf0 --- /dev/null +++ b/test/generators/scala/presets/DescriptionPreset.spec.ts @@ -0,0 +1,44 @@ +import { + ScalaGenerator, + SCALA_DESCRIPTION_PRESET +} from '../../../../src/generators/scala'; + +describe('SCALA_DESCRIPTION_PRESET', () => { + let generator: ScalaGenerator; + beforeEach(() => { + generator = new ScalaGenerator({ presets: [SCALA_DESCRIPTION_PRESET] }); + }); + + test('should render description and examples for class', async () => { + const doc = { + $id: 'Clazz', + type: 'object', + description: 'Description for class', + examples: [{ prop: 'value' }], + properties: { + prop: { + type: 'string', + description: 'Description for prop', + examples: ['exampleValue'] + } + } + }; + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); + + test('should render description and examples for enum', async () => { + const doc = { + $id: 'Enum', + type: 'string', + description: 'Description for enum', + examples: ['value'], + enum: ['on', 'off'] + }; + + const models = await generator.generate(doc); + expect(models).toHaveLength(1); + expect(models[0].result).toMatchSnapshot(); + }); +}); diff --git a/test/generators/scala/presets/__snapshots__/DescriptionPreset.spec.ts.snap b/test/generators/scala/presets/__snapshots__/DescriptionPreset.spec.ts.snap new file mode 100644 index 0000000000..9ed63ab635 --- /dev/null +++ b/test/generators/scala/presets/__snapshots__/DescriptionPreset.spec.ts.snap @@ -0,0 +1,32 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`SCALA_DESCRIPTION_PRESET should render description and examples for class 1`] = ` +"/** + * Description for class + * + * @property prop Description for prop + * @property additionalProperties + * + * Examples: + * {\\"prop\\":\\"value\\"} + */ +case class Clazz( + prop: Option[String], + additionalProperties: Option[Map[String, Any]], +)" +`; + +exports[`SCALA_DESCRIPTION_PRESET should render description and examples for enum 1`] = ` +"/** + * Description for enum + * + * Examples: + * value + */ +object Enum extends Enumeration { + type Enum = Value + + val On: Enum.Value = Value(\\"on\\") + val Off: Enum.Value = Value(\\"off\\") +}" +`; From cdadedf614f2d85fa426c49592cfbae5fc71049e Mon Sep 17 00:00:00 2001 From: asyncapi-bot Date: Sat, 23 Dec 2023 14:34:05 +0100 Subject: [PATCH 09/37] chore(release): v2.1.0 (#1684) Co-authored-by: asyncapi-bot --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9574e6f9b6..6a3ee911c1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@asyncapi/modelina", - "version": "2.0.14", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@asyncapi/modelina", - "version": "2.0.14", + "version": "2.1.0", "license": "Apache-2.0", "dependencies": { "@apidevtools/json-schema-ref-parser": "^9.0.9", diff --git a/package.json b/package.json index bc7a340031..533b73147a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@asyncapi/modelina", - "version": "2.0.14", + "version": "2.1.0", "description": "Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents", "license": "Apache-2.0", "homepage": "https://www.modelina.org", From 3561ba0989cb52a843d2914726bbac84c687a1f4 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sat, 23 Dec 2023 03:35:02 -1000 Subject: [PATCH 10/37] chore: add artur-ciocanu as a contributor for code, example, and 2 more (#1685) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> Co-authored-by: Jonas Lagoni --- .all-contributorsrc | 5 ++++- README.md | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 5522246c73..f0b774e576 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -341,7 +341,10 @@ "profile": "https://github.com/artur-ciocanu", "contributions": [ "code", - "bug" + "bug", + "example", + "doc", + "test" ] }, { diff --git a/README.md b/README.md index 947ab99ae3..2ed79fbaf4 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org PanMan
PanMan

📖 - artur-ciocanu
artur-ciocanu

💻 🐛 + artur-ciocanu
artur-ciocanu

💻 🐛 💡 📖 ⚠️ Cyprian Gracz
Cyprian Gracz

💻 ⚠️ 🐛 Leigh Johnson
Leigh Johnson

💻 ⚠️ 💡 📖 🚧 👀 Nitin Tejuja
Nitin Tejuja

⚠️ 💡 From e18b4a76a1cf69446db660f49c4d39875071526d Mon Sep 17 00:00:00 2001 From: Mintu Gogoi <127925465+Min2who@users.noreply.github.com> Date: Tue, 26 Dec 2023 11:27:08 +0530 Subject: [PATCH 11/37] test: add test for cpp constraint (#1687) --- .../constrainer/ConstantConstrainer.spec.ts | 10 + .../constrainer/EnumConstrainer.spec.ts | 182 ++++++++++++++++++ .../constrainer/ModelNameConstrainer.spec.ts | 78 ++++++++ .../PropertyKeyConstrainer.spec.ts | 106 ++++++++++ 4 files changed, 376 insertions(+) create mode 100644 test/generators/cplusplus/constrainer/ConstantConstrainer.spec.ts create mode 100644 test/generators/cplusplus/constrainer/EnumConstrainer.spec.ts create mode 100644 test/generators/cplusplus/constrainer/ModelNameConstrainer.spec.ts create mode 100644 test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts diff --git a/test/generators/cplusplus/constrainer/ConstantConstrainer.spec.ts b/test/generators/cplusplus/constrainer/ConstantConstrainer.spec.ts new file mode 100644 index 0000000000..a709c50ee6 --- /dev/null +++ b/test/generators/cplusplus/constrainer/ConstantConstrainer.spec.ts @@ -0,0 +1,10 @@ +import { defaultConstantConstraints } from '../../../../src/generators/cplusplus/constrainer/ConstantConstrainer'; + +describe('defaultConstantConstraints', () => { + it('should return undefined', () => { + const constraints = defaultConstantConstraints(); + const context = { constrainedMetaModel: {} as any }; + const result = constraints(context); + expect(result).toBeUndefined(); + }); +}); diff --git a/test/generators/cplusplus/constrainer/EnumConstrainer.spec.ts b/test/generators/cplusplus/constrainer/EnumConstrainer.spec.ts new file mode 100644 index 0000000000..fbb1224d87 --- /dev/null +++ b/test/generators/cplusplus/constrainer/EnumConstrainer.spec.ts @@ -0,0 +1,182 @@ +import { CplusplusDefaultConstraints } from '../../../../src/generators/cplusplus/CplusplusConstrainer'; +import { EnumModel } from '../../../../src/models/MetaModel'; +import { + ConstrainedEnumModel, + ConstrainedEnumValueModel +} from '../../../../src'; +import { + defaultEnumKeyConstraints, + ModelEnumKeyConstraints, + DefaultEnumKeyConstraints +} from '../../../../src/generators/cplusplus/constrainer/EnumConstrainer'; + +describe('EnumConstrainer', () => { + const enumModel = new EnumModel('test', undefined, {}, []); + const constrainedEnumModel = new ConstrainedEnumModel( + 'test', + undefined, + {}, + '', + [] + ); + + describe('enum keys', () => { + test('should never render special chars', () => { + const constrainedKey = CplusplusDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '%' + }); + expect(constrainedKey).toEqual('percent'); + }); + + test('should not render number as start char', () => { + const constrainedKey = CplusplusDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '1' + }); + expect(constrainedKey).toEqual('number_1'); + }); + + test('should not contain duplicate keys', () => { + const existingConstrainedEnumValueModel = new ConstrainedEnumValueModel( + 'EMPTY', + 'return', + 'return' + ); + const constrainedEnumModel = new ConstrainedEnumModel( + 'test', + undefined, + {}, + '', + [existingConstrainedEnumValueModel] + ); + const constrainedKey = CplusplusDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedKey).toEqual('empty'); + }); + + test('should never contain empty keys', () => { + const constrainedKey = CplusplusDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedKey).toEqual('empty'); + }); + + test('should use constant naming format', () => { + const constrainedKey = CplusplusDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: 'some weird_value!"#2' + }); + expect(constrainedKey).toEqual( + 'some_space_weird_value_exclamation_quotation_hash_2' + ); + }); + + test('should never render reserved keywords', () => { + const constrainedKey = CplusplusDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: 'return' + }); + expect(constrainedKey).toEqual('reserved_return'); + }); + }); + + describe('enum values', () => { + test('should render string values', () => { + const constrainedValue = CplusplusDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: 'string value' + }); + expect(constrainedValue).toEqual('"string value"'); + }); + + test('should render boolean values', () => { + const constrainedValue = CplusplusDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: true + }); + expect(constrainedValue).toEqual('"true"'); + }); + + test('should render numbers', () => { + const constrainedValue = CplusplusDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: 123 + }); + expect(constrainedValue).toEqual(123); + }); + + test('should render object', () => { + const constrainedValue = CplusplusDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: { test: 'test' } + }); + expect(constrainedValue).toEqual('"{\\"test\\":\\"test\\"}"'); + }); + + test('should render unknown value', () => { + const constrainedValue = CplusplusDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: undefined + }); + expect(constrainedValue).toEqual(`"undefined"`); + }); + }); + + describe('custom constraints', () => { + test('should be able to overwrite all hooks for enum key', () => { + const mockedConstraintCallbacks: Partial = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultEnumKeyConstraints( + mockedConstraintCallbacks + ); + constrainFunction({ enumModel, constrainedEnumModel, enumKey: '' }); + //Expect all callbacks to be called + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + + test('should be able to overwrite one hook for enum key', () => { + const spies = [ + jest.spyOn(DefaultEnumKeyConstraints, 'NO_SPECIAL_CHAR'), + jest.spyOn(DefaultEnumKeyConstraints, 'NO_NUMBER_START_CHAR'), + jest.spyOn(DefaultEnumKeyConstraints, 'NO_DUPLICATE_KEYS'), + jest.spyOn(DefaultEnumKeyConstraints, 'NO_EMPTY_VALUE'), + jest.spyOn(DefaultEnumKeyConstraints, 'NO_RESERVED_KEYWORDS') + ]; + const jestCallback = jest.fn().mockReturnValue(''); + const constrainFunction = defaultEnumKeyConstraints({ + NAMING_FORMATTER: jestCallback + }); + const constrainedValue = constrainFunction({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedValue).toEqual(''); + for (const jestMockCallback of spies) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + }); +}); diff --git a/test/generators/cplusplus/constrainer/ModelNameConstrainer.spec.ts b/test/generators/cplusplus/constrainer/ModelNameConstrainer.spec.ts new file mode 100644 index 0000000000..a83c300ecb --- /dev/null +++ b/test/generators/cplusplus/constrainer/ModelNameConstrainer.spec.ts @@ -0,0 +1,78 @@ +import { CplusplusDefaultConstraints } from './../../../../src/generators/cplusplus/CplusplusConstrainer'; +import { + ModelNameConstraints, + DefaultModelNameConstraints, + defaultModelNameConstraints +} from './../../../../src/generators/cplusplus/constrainer/ModelNameConstrainer'; + +describe('ModelNameConstrainer', () => { + test('should never render special chars', () => { + const constrainedKey = CplusplusDefaultConstraints.modelName({ + modelName: '%' + }); + expect(constrainedKey).toEqual('percent'); + }); + test('should never render number as start char', () => { + const constrainedKey = CplusplusDefaultConstraints.modelName({ + modelName: '1' + }); + expect(constrainedKey).toEqual('number_1'); + }); + test('should never contain empty name', () => { + const constrainedKey = CplusplusDefaultConstraints.modelName({ + modelName: '' + }); + expect(constrainedKey).toEqual('empty'); + }); + test('should use constant naming format', () => { + const constrainedKey = CplusplusDefaultConstraints.modelName({ + modelName: 'some weird_value!"#2' + }); + expect(constrainedKey).toEqual( + 'some_space_weird_value_exclamation_quotation_hash_2' + ); + }); + test('should never render reserved keywords', () => { + const constrainedKey = CplusplusDefaultConstraints.modelName({ + modelName: 'return' + }); + expect(constrainedKey).toEqual('reserved_return'); + }); + describe('custom constraints', () => { + test('should be able to overwrite all hooks', () => { + const mockedConstraintCallbacks: ModelNameConstraints = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultModelNameConstraints( + mockedConstraintCallbacks + ); + constrainFunction({ modelName: '' }); + //Expect all callbacks to be called + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + test('should be able to overwrite one hooks', () => { + //All but NAMING_FORMATTER, as we customize that + const spies = [ + jest.spyOn(DefaultModelNameConstraints, 'NO_SPECIAL_CHAR'), + jest.spyOn(DefaultModelNameConstraints, 'NO_NUMBER_START_CHAR'), + jest.spyOn(DefaultModelNameConstraints, 'NO_EMPTY_VALUE'), + jest.spyOn(DefaultModelNameConstraints, 'NO_RESERVED_KEYWORDS') + ]; + const jestCallback = jest.fn().mockReturnValue(''); + const constrainFunction = defaultModelNameConstraints({ + NAMING_FORMATTER: jestCallback + }); + const constrainedValue = constrainFunction({ modelName: '' }); + expect(constrainedValue).toEqual(''); + for (const jestMockCallback of spies) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + }); +}); diff --git a/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts b/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts new file mode 100644 index 0000000000..d4126c7829 --- /dev/null +++ b/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts @@ -0,0 +1,106 @@ +import { CplusplusDefaultConstraints } from '../../../../src/generators/cplusplus/CplusplusConstrainer'; +import { + ConstrainedObjectModel, + ConstrainedObjectPropertyModel, + ObjectModel, + ObjectPropertyModel +} from '../../../../src'; +import { + DefaultPropertyKeyConstraints, + PropertyKeyConstraintOptions, + defaultPropertyKeyConstraints +} from '../../../../src/generators/cplusplus/constrainer/PropertyKeyConstrainer'; + +describe('C++ PropertyKeyConstrainer', () => { + const objectModel = new ObjectModel('test', undefined, {}, {}); + const constrainedObjectModel = new ConstrainedObjectModel( + 'test', + undefined, + {}, + '', + {} + ); + + const constrainPropertyName = (propertyName: string) => { + const objectPropertyModel = new ObjectPropertyModel( + propertyName, + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + return defaultPropertyKeyConstraints()({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + }; + test('should never render special chars', () => { + const constrainedKey = constrainPropertyName('%'); + expect(constrainedKey).toEqual('percent'); + }); + test('should not render number as start char', () => { + const constrainedKey = constrainPropertyName('1'); + expect(constrainedKey).toEqual('number_1'); + }); + test('should never contain empty name', () => { + const constrainedKey = constrainPropertyName(''); + expect(constrainedKey).toEqual('empty'); + }); + test('should use constant naming format', () => { + const constrainedKey = constrainPropertyName('some weird_value!"#2'); + expect(constrainedKey).toEqual( + 'some_space_weird_value_exclamation_quotation_hash_2' + ); + }); + test('should not contain duplicate properties', () => { + const objectPropertyModel = new ObjectPropertyModel( + 'reservedReturn', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + 'reservedReturn', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + const constrainedKey = defaultPropertyKeyConstraints()({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + expect(constrainedKey).toEqual('reserved_return'); + }); + test('should never render reserved keywords', () => { + const constrainedKey = constrainPropertyName('return'); + expect(constrainedKey).toEqual('return'); + }); + test('should handle custom constraints', () => { + const customConstraints: Partial = { + NAMING_FORMATTER: (value: string) => value.toUpperCase(), + NO_SPECIAL_CHAR: (value: string) => value.replace(/[^\w\s]/gi, ''), + NO_EMPTY_VALUE: (value: string) => value || 'default' + }; + + const constrainedKey = defaultPropertyKeyConstraints(customConstraints)({ + constrainedObjectModel, + objectModel, + objectPropertyModel: new ObjectPropertyModel('', false, objectModel), + constrainedObjectPropertyModel: new ConstrainedObjectPropertyModel( + '', + '', + false, + constrainedObjectModel + ) + }); + + expect(constrainedKey).toEqual('_DEFAULT'); + }); +}); From cbf55179f37adaa9b67564b2fc022615d7c66095 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Mon, 25 Dec 2023 22:06:10 -1000 Subject: [PATCH 12/37] docs: add Min2who as a contributor for test (#1694) --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index f0b774e576..335805d7e2 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -799,6 +799,15 @@ "code", "test" ] + }, + { + "login": "Min2who", + "name": "Mintu Gogoi", + "avatar_url": "https://avatars.githubusercontent.com/u/127925465?v=4", + "profile": "https://mintu-portfolio.netlify.app/", + "contributions": [ + "test" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 2ed79fbaf4..77656f660f 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![Discussions](https://img.shields.io/github/discussions/asyncapi/modelina)](https://github.com/asyncapi/modelina/discussions) [![Website](https://img.shields.io/website?label=website&url=https%3A%2F%2Fwww.modelina.org)](https://www.modelina.org) [![Playground](https://img.shields.io/website?label=playground&url=https%3A%2F%2Fwww.modelina.org%2Fplayground)](https://www.modelina.org/playground) -[![All Contributors](https://img.shields.io/badge/all_contributors-73-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-74-orange.svg?style=flat-square)](#contributors-) Your one-stop tool for generating accurate and well-tested models for representing the message payloads. Use it as a tool in your development workflow, or a library in a larger integrations, entirely in your control. @@ -419,6 +419,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Nilkanth Parmar
Nilkanth Parmar

💻 ⚠️ 💡 📖 Ashmit JaiSarita Gupta
Ashmit JaiSarita Gupta

💻 🎨 📖 🚧 Harshil Jani
Harshil Jani

💻 ⚠️ + Mintu Gogoi
Mintu Gogoi

⚠️ From 7546743750661a435348b17bc7773db25b62b8c2 Mon Sep 17 00:00:00 2001 From: Ankur Singh Date: Wed, 27 Dec 2023 11:22:59 +0530 Subject: [PATCH 13/37] docs: improves the contributing docs (#1698) --- docs/contributing.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/contributing.md b/docs/contributing.md index 9834925908..88ae1ade3f 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -35,7 +35,7 @@ Adding examples is quite straight forward, so don't feel shy! Here's how to do i 1. Adapt [this testing file](https://github.com/asyncapi/modelina/blob/1e71b3b2cab6bc2c277001fcafe7e1b8ed175ce9/examples/TEMPLATE/index.spec.ts#L4) for your use case. In most cases, it could be as simple as changing the title of the test! 1. Add your example to our overall list of [examples](https://github.com/asyncapi/modelina/blob/master/examples/README.md). -Aaaand you are done! :tada: +Aaaand you are done! 🎉 ### Adding a new preset Presets are for when you want to customize the generated output, they work like middleware that layers on top of each other, you can read more [about presets here](./presets.md). @@ -83,7 +83,7 @@ describe('LANGUAGE_MY_PRESET', () => { ``` Remember to replace `LANGUAGE` and `Language` with the appropriate values. -Aaaand you are done! :tada: +Aaaand you are done! 🎉 ### Adding a new input processor Input processors are the translators from inputs to MetaModel (read more about [the input processing here](./input-processing.md)). @@ -103,7 +103,7 @@ Thats it for the code and tests, now all that remains is docs and examples! :fir 2. Add the [usage example to the usage document](./usage.md). 3. Add the new supported input to the [main readme file](../README.md#features). -Aaaand you are done! :tada: +Aaaand you are done! 🎉 ### Adding a new generator Generators sits as the core of Modelina, which frames the core concepts of what you can generate. Therefore it's also no small task to create a new one, so dont get discourage, we are here to help you! @@ -167,4 +167,4 @@ That said, here is a general rundown on what's triggered by each PR: - [Coverall](https://github.com/asyncapi/modelina/blob/master/.github/workflows/coverall.yml) ensures we get test coverage statistics in each PR, thus ensuring we see how it affects overall test coverage. It creates a comment on the PR with the coverage status. - [SonarCloud](https://sonarcloud.io/dashboard?id=asyncapi_generator-model-sdk) runs a code analysis to ensure no bugs, security concerns, code smells, or duplicated code blocks. Make sure you address any concerns found by this bot, because it generates a comment to the PR if it finds any issue. -At the end of the day, sometimes checks just fail, based on weird dependency problems. If any test failures occur that don't look like a problem you can fix, simply tag one of the maintainers. We're there to help! :smile: +At the end of the day, sometimes checks just fail, based on weird dependency problems. If any test failures occur that don't look like a problem you can fix, simply tag one of the maintainers. We're there to help! 😀 From d974d2e93d02e0ddb064ed72b6a1db2a1f78ab12 Mon Sep 17 00:00:00 2001 From: Devansh Mahant <86195162+devansh-m12@users.noreply.github.com> Date: Wed, 27 Dec 2023 11:24:03 +0530 Subject: [PATCH 14/37] docs: update Emojis Not Rendering Properly in docs (#1699) --- docs/contributing.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/contributing.md b/docs/contributing.md index 88ae1ade3f..5e944abc7c 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -83,7 +83,7 @@ describe('LANGUAGE_MY_PRESET', () => { ``` Remember to replace `LANGUAGE` and `Language` with the appropriate values. -Aaaand you are done! 🎉 +Aaaand you are done! 🎉 ### Adding a new input processor Input processors are the translators from inputs to MetaModel (read more about [the input processing here](./input-processing.md)). @@ -98,12 +98,12 @@ Here is how you can add a new input processor: 7. Add your input processor as part of the [main input processor](../src/processors/InputProcessor.ts) 8. Add a [test for the main input processor](../test/processors/InputProcessor.spec.ts) to ensure that your input processor are accessed accordingly. -Thats it for the code and tests, now all that remains is docs and examples! :fire: +Thats it for the code and tests, now all that remains is docs and examples! 🔥 1. [Add a new example](#adding-examples) showcasing the new supported input. 2. Add the [usage example to the usage document](./usage.md). 3. Add the new supported input to the [main readme file](../README.md#features). -Aaaand you are done! 🎉 +Aaaand you are done! 🎉 ### Adding a new generator Generators sits as the core of Modelina, which frames the core concepts of what you can generate. Therefore it's also no small task to create a new one, so dont get discourage, we are here to help you! @@ -167,4 +167,4 @@ That said, here is a general rundown on what's triggered by each PR: - [Coverall](https://github.com/asyncapi/modelina/blob/master/.github/workflows/coverall.yml) ensures we get test coverage statistics in each PR, thus ensuring we see how it affects overall test coverage. It creates a comment on the PR with the coverage status. - [SonarCloud](https://sonarcloud.io/dashboard?id=asyncapi_generator-model-sdk) runs a code analysis to ensure no bugs, security concerns, code smells, or duplicated code blocks. Make sure you address any concerns found by this bot, because it generates a comment to the PR if it finds any issue. -At the end of the day, sometimes checks just fail, based on weird dependency problems. If any test failures occur that don't look like a problem you can fix, simply tag one of the maintainers. We're there to help! 😀 +At the end of the day, sometimes checks just fail, based on weird dependency problems. If any test failures occur that don't look like a problem you can fix, simply tag one of the maintainers. We're there to help! 😄 From 0652c6999cc482beb5da37f20ed8d2e7287e1196 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Tue, 26 Dec 2023 19:55:42 -1000 Subject: [PATCH 15/37] docs: add devansh-m12 as a contributor for doc (#1704) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 335805d7e2..ef18e312b9 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -808,6 +808,15 @@ "contributions": [ "test" ] + }, + { + "login": "devansh-m12", + "name": "Devansh Mahant", + "avatar_url": "https://avatars.githubusercontent.com/u/86195162?v=4", + "profile": "https://github.com/devansh-m12", + "contributions": [ + "doc" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 77656f660f..efecff2e2d 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![Discussions](https://img.shields.io/github/discussions/asyncapi/modelina)](https://github.com/asyncapi/modelina/discussions) [![Website](https://img.shields.io/website?label=website&url=https%3A%2F%2Fwww.modelina.org)](https://www.modelina.org) [![Playground](https://img.shields.io/website?label=playground&url=https%3A%2F%2Fwww.modelina.org%2Fplayground)](https://www.modelina.org/playground) -[![All Contributors](https://img.shields.io/badge/all_contributors-74-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-75-orange.svg?style=flat-square)](#contributors-) Your one-stop tool for generating accurate and well-tested models for representing the message payloads. Use it as a tool in your development workflow, or a library in a larger integrations, entirely in your control. @@ -420,6 +420,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Ashmit JaiSarita Gupta
Ashmit JaiSarita Gupta

💻 🎨 📖 🚧 Harshil Jani
Harshil Jani

💻 ⚠️ Mintu Gogoi
Mintu Gogoi

⚠️ + Devansh Mahant
Devansh Mahant

📖 From 0408e99b3f66cbe9f3f7b6eb53c5f7c81cb83be6 Mon Sep 17 00:00:00 2001 From: Devansh Mahant <86195162+devansh-m12@users.noreply.github.com> Date: Wed, 27 Dec 2023 11:26:41 +0530 Subject: [PATCH 16/37] docs: update Emojis Not Rendering Properly (#1702) --- docs/champions.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/champions.md b/docs/champions.md index ad34748e90..e14e2b473a 100644 --- a/docs/champions.md +++ b/docs/champions.md @@ -18,23 +18,23 @@ You can checkout the [CODEOWNERS file](../CODEOWNERS) for an updated list of mai These are the areas that we mainly focus on getting having champions and where you can help out. However, keep in mind it is not limited to these alone. -### :running: Core champions +### 🏃 Core champions There is not one area that interest you, but rather the library as a whole, where you want to maintain and push forward the project and it's mission. -### :books: Doc champions +### 📚 Doc champions Doc champions are those who focus on the documentation and how users best go from 0 to 100 in order to use Modelina. Maybe you like to write technical documentation, or you love making tutorials, this would be for you! -### :trident: Input champions +### 🔱 Input champions Input champions are those who take charge of the input processing, it can either be a specific input processor (such as JSON Schema or AsyncAPI) or multiple. They maintain the process of converting the input to the internal model which Modelina can use to generate outputs to. -### :wrench: Language champions +### 🔧 Language champions Language champions are those who maintain of a specific language output, it can either be a specific generator (such as TypeScript or Java) or or multiple. They maintain the process of converting the internal model into usable data models in their respective language. -### :sparkles: Website champions +### ✨ Website champions Website champions are those who focus on the website (this includes playground). Maybe you are a designer or coder that loves to create great interactions for user, then this is would be for you! @@ -125,4 +125,4 @@ Maintainers should feel free to pleasantly disagree with the work and decisions There can be countless reasons why you want to step down as a champion and it is entirely your provocative at any time. -To step down as a champion make a PR removing your name from the [CODEOWNERS file](../CODEOWNERS) and thats it :v: +To step down as a champion make a PR removing your name from the [CODEOWNERS file](../CODEOWNERS) and thats it ✌️ From ee34ae2411bc867e93b9bf77a7eef19b01cd126b Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Wed, 27 Dec 2023 06:07:38 -1000 Subject: [PATCH 17/37] fix: expose scala generator and update docs and examples (#1691) --- README.md | 10 +-- docs/integration.md | 2 +- docs/languages/Java.md | 2 +- docs/languages/Scala.md | 36 +++++++++ docs/usage.md | 7 +- examples/README.md | 81 +++++++++++++++---- .../dart-generate-json-annotation/README.md | 2 +- .../package-lock.json | 10 +++ .../package.json | 9 +++ .../README.md | 0 .../__snapshots__/index.spec.ts.snap | 0 .../index.spec.ts | 0 .../index.ts | 0 .../package-lock.json | 0 .../package.json | 0 .../__snapshots__/index.spec.ts.snap | 14 ++++ examples/generate-scala-enums/index.ts | 2 +- .../__snapshots__/index.spec.ts.snap | 11 +++ examples/generate-scala-models/index.ts | 2 +- .../README.md | 0 .../maven-project/.gitignore | 0 .../maven-project/README.md | 0 .../maven-project/asyncapi.json | 0 .../maven-project/pom.xml | 0 .../scripts/modelina/generate.ts | 0 .../scripts/modelina/package-lock.json | 0 .../scripts/modelina/package.json | 0 .../com/mycompany/app/AnonymousSchema_1.java | 0 .../package-lock.json | 2 +- .../package.json | 2 +- .../scala-generate-documentation/README.md | 15 ++++ .../__snapshots__/index.spec.ts.snap | 14 ++++ .../index.spec.ts | 15 ++++ .../scala-generate-documentation/index.ts | 28 +++++++ .../package-lock.json | 10 +++ .../scala-generate-documentation/package.json | 10 +++ jest.config.js | 2 +- modelina-website/scripts/build-examples.js | 2 +- package.json | 4 +- src/generators/index.ts | 1 + 40 files changed, 258 insertions(+), 35 deletions(-) create mode 100644 docs/languages/Scala.md create mode 100644 examples/dart-generate-json-annotation/package-lock.json create mode 100644 examples/dart-generate-json-annotation/package.json rename examples/{php-generate-models => generate-php-models}/README.md (100%) rename examples/{php-generate-models => generate-php-models}/__snapshots__/index.spec.ts.snap (100%) rename examples/{php-generate-models => generate-php-models}/index.spec.ts (100%) rename examples/{php-generate-models => generate-php-models}/index.ts (100%) rename examples/{php-generate-models => generate-php-models}/package-lock.json (100%) rename examples/{php-generate-models => generate-php-models}/package.json (100%) create mode 100644 examples/generate-scala-enums/__snapshots__/index.spec.ts.snap create mode 100644 examples/generate-scala-models/__snapshots__/index.spec.ts.snap rename examples/{integrate-modelina-into-maven => integrate-with-maven}/README.md (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/.gitignore (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/README.md (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/asyncapi.json (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/pom.xml (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/scripts/modelina/generate.ts (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/scripts/modelina/package-lock.json (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/scripts/modelina/package.json (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/maven-project/src/main/java/com/mycompany/app/AnonymousSchema_1.java (100%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/package-lock.json (72%) rename examples/{integrate-modelina-into-maven => integrate-with-maven}/package.json (87%) create mode 100644 examples/scala-generate-documentation/README.md create mode 100644 examples/scala-generate-documentation/__snapshots__/index.spec.ts.snap create mode 100644 examples/scala-generate-documentation/index.spec.ts create mode 100644 examples/scala-generate-documentation/index.ts create mode 100644 examples/scala-generate-documentation/package-lock.json create mode 100644 examples/scala-generate-documentation/package.json diff --git a/README.md b/README.md index efecff2e2d..71329d22f0 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,6 @@ Your one-stop tool for generating accurate and well-tested models for representi - [Installing Modelina](#installing-modelina) - [AsyncAPI CLI](#asyncapi-cli) - [Features](#features) -- [Roadmap](#roadmap) - [Requirements](#requirements) - [Documentation](#documentation) - [Examples](#examples) @@ -266,13 +265,12 @@ The following table provides a short summary of available features for supported PHP Class and enum generation: custom indentation type and size, descriptions, etc + + Scala + Class and enum generation: custom indentation type and size, descriptions, etc + -## Roadmap -This is the roadmap that is currently in focus by the [CODEOWNERS](./CODEOWNERS) - -- [1 year roadmap](https://github.com/asyncapi/modelina/milestone/4) - ## Requirements The following are a requirement in order to use Modelina. diff --git a/docs/integration.md b/docs/integration.md index 786995da29..d3aaa071a1 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -64,7 +64,7 @@ There are at least two ways you can integrate Modelina into your build process f - DO work with other inputs then AsyncAPI - DO work when needing extensive build options and configurations -Checkout the Maven example here: [Integrate Modelina into Maven](../examples/integrate-modelina-into-maven) +Checkout the Maven example here: [Integrate Modelina into Maven](../examples/integrate-with-maven) **AsyncAPI CLI** diff --git a/docs/languages/Java.md b/docs/languages/Java.md index d16a820e39..6b5197a490 100644 --- a/docs/languages/Java.md +++ b/docs/languages/Java.md @@ -95,4 +95,4 @@ Currently not supported, [let everyone know you need it](https://github.com/asyn Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! ## Integrate Modelina into Maven -We have created an example Maven project to show you how to generate AsyncAPI payload models from your AsyncAPI file and integrate it into the build process. [You can find the integration example here](../integration.md#integrate-modelina-into-maven). \ No newline at end of file +We have created an example Maven project to show you how to generate AsyncAPI payload models from your AsyncAPI file and integrate it into the build process. [You can find the integration example here](../integration.md#integrate-with-maven). \ No newline at end of file diff --git a/docs/languages/Scala.md b/docs/languages/Scala.md new file mode 100644 index 0000000000..249be7b0df --- /dev/null +++ b/docs/languages/Scala.md @@ -0,0 +1,36 @@ +# Scala + +There are special use-cases that each language supports; this document pertains to **Scala models**. + + + + + +- [Description Present](#description-present) +- [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality) + * [To and from JSON](#to-and-from-json) + * [To and from XML](#to-and-from-xml) + * [To and from binary](#to-and-from-binary) + + + +## Description Present + +By default, descriptions are not rendered for the model; you can change that by applying `SCALA_DESCRIPTION_PRESET`. + +Check out this [example for a live demonstration](../../examples/php-generate-documentation-preset). + +## Generate serializer and deserializer functionality + +The most widely used usecase for Modelina is to generate models that include serilization and deserialization functionality to convert the models into payload data. This payload data can of course be many different kinds, JSON, XML, raw binary, you name it. + +As you normally only need one library to do this, we developers can never get enough with creating new stuff, therefore there might be one specific library you need or want to integrate with. Therefore there is not one specific preset that offers everything. Below is a list of all the supported serialization presets. + +### To and from JSON +Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! + +### To and from XML +Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! + +### To and from binary +Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! diff --git a/docs/usage.md b/docs/usage.md index 247faf4a9e..4862187807 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -35,6 +35,7 @@ For more specific integration options, please check out the [integration documen - [Generate Kotlin models](#generate-kotlin-models) - [Generate C++ (cplusplus) models](#generate-c-cplusplus-models) - [Generate PHP models](#generate-php-models) +- [Generate Scala models](#generate-scala-models) @@ -201,4 +202,8 @@ C++ is one of the many output languages we support. Check out this [basic exampl ## Generate PHP models -PHP is one of the many output languages we support. Check out this [basic example for a live demonstration](../examples/php-generate-models/) and the following [PHP documentation for more advanced use-cases](./languages/Php.md). \ No newline at end of file +PHP is one of the many output languages we support. Check out this [basic example for a live demonstration](../examples/generate-php-models/) and the following [PHP documentation for more advanced use-cases](./languages/Php.md). + +## Generate Scala models + +Scala is one of the many output languages we support. Check out this [basic example for a live demonstration](../examples/generate-scala-models/) and the following [Scala documentation for more advanced use-cases](./languages/Scala.md). \ No newline at end of file diff --git a/examples/README.md b/examples/README.md index 67911e0fc1..41d24576c4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -16,13 +16,19 @@ We love contributions and new examples that does not already exist, you can foll - [General examples](#general-examples) - [Simple generator examples](#simple-generator-examples) - [Integrations](#integrations) -- [Python](#python) -- [JavaScript](#javascript) -- [Java](#java) -- [C#](#c%23) -- [TypeScript](#typescript) -- [Kotlin](#kotlin) -- [PHP](#php) +- [Language examples](#language-examples) + * [Python](#python) + * [JavaScript](#javascript) + * [Java](#java) + * [C#](#c%23) + * [TypeScript](#typescript) + * [Kotlin](#kotlin) + * [PHP](#php) + * [Scala](#scala) + * [Rust](#rust) + * [Dart](#dart) + * [Go](#go) + * [C++](#c) - [Other examples](#other-examples) @@ -65,27 +71,37 @@ These are all the basic generator examples that shows a bare minimal example of - [generate-javascript-models](./generate-javascript-models) - A basic example to generate JavaScript data models - [generate-kotlin-models](./generate-kotlin-models) - A basic example to generate Kotlin data models - [generate-cplusplus-models](./generate-cplusplus-models) - A basic example to generate C++ data models +- [generate-php-models](./generate-cplusplus-models) - A basic example to generate PHP data models +- [generate-scala-models](./generate-cplusplus-models) - A basic example to generate Scala data models ## Integrations These are examples of how you can integrate Modelina into a specific scenario: - [integrate-with-react](./integrate-with-react) - A basic example that shows how you can integrate Modelina with React. - [integrate-with-next](./integrate-with-next) - A basic example that shows how you can integrate Modelina with Next. -- [integrate-modelina-into-maven](./integrate-modelina-into-maven) - A basic example that shows how you can integrate Modelina into the Java Maven build process. +- [integrate-with-maven](./integrate-with-maven) - A basic example that shows how you can integrate Modelina into the Java Maven build process. -## Python +## Language examples +These are all the examples for each language; + +### Python These are all specific examples only relevant to the Python generator: +- [generate-python-models](./generate-python-models) - A basic example showing how to generate Python models. +- [generate-python-complete-models](./generate-python-complete-models) - A basic example showing how to generate complete Python models. - [generate-python-pydantic-models](./generate-python-pydantic-models) - An example showing how to generate Python pydantic models. - [python-generate-json-serializer-and-deseriazlier](./python-generate-json-serializer-and-deserializer) - An example that shows how to generate the models with JSON serializer and deserializer. -## JavaScript +### JavaScript These are all specific examples only relevant to the JavaScript generator: +- [generate-javascript-models](./generate-javascript-models) - A basic example to generate JavaScript data models - [javascript-use-esm](./javascript-use-esm) - A basic example that generate the models to use ESM module system. - [javascript-use-cjs](./javascript-use-cjs) - A basic example that generate the models to use CJS module system. - [javascript-generate-marshalling](./javascript-generate-marshalling) - A basic example of how to use the un/marshalling functionality of the javascript class. - [javascript-generate-example](./javascript-generate-example) - A basic example of how to use Modelina and output a JavaScript class with an example function. -## Java +### Java These are all specific examples only relevant to the Java generator: + +- [generate-java-models](./generate-java-models) - A basic example to generate Java data models. - [java-generate-tostring](./java-generate-tostring) - A basic example that shows how to generate models that overwrite the `toString` method - [java-change-collection-type](./java-change-collection-type) - An example to render collections as List in Java. - [java-generate-hashcode](./java-generate-hashcode) - A basic example that shows how to generate models that overwrite the `hashCode` method @@ -95,10 +111,12 @@ These are all specific examples only relevant to the Java generator: - [java-generate-equals](./java-generate-equals) - A basic example that shows how to generate models that overwrite the `equal` method - [java-generate-javax-constraint-annotation](./java-generate-javax-constraint-annotation) - A basic example that shows how Java data models having `javax.validation.constraints` annotations can be generated. - [java-generate-javadoc](./java-generate-javadoc) - A basic example of how to generate Java models including JavaDocs. -- [integrate-modelina-into-maven](./integrate-modelina-into-maven/) - A basic example that shows how you can integrate Modelina into the Java Maven build process. +- [integrate-into-maven](./integrate-with-maven/) - A basic example that shows how you can integrate Modelina into the Java Maven build process. -## C# +### C# These are all specific examples only relevant to the C# generator: + +- [generate-csharp-models](./generate-csharp-models) - A basic example to generate C# data models - [csharp-generate-equals-and-hashcode](./csharp-generate-equals-and-hashcode) - A basic example on how to generate models that overwrite the `Equal` and `GetHashCode` methods - [csharp-generate-json-serializer](./csharp-generate-json-serializer) - A basic example on how to generate models that include function to serialize the data models to and from JSON with System.Text.Json. - [csharp-generate-newtonsoft-serializer](./csharp-generate-newtonsoft-serializer) - A basic example on how to generate models that include function to serialize the data models to and form JSON with Newtonsoft. @@ -107,8 +125,10 @@ These are all specific examples only relevant to the C# generator: - [csharp-generate-records](./csharp-generate-records) - A basic example that shows how to change C# model type from class to record. - [csharp-generate-handle-nullable](./csharp-generate-handle-nullable) - A basic example that shows how generate code than handles nullable mode and prevent warnings. -## TypeScript +### TypeScript These are all specific examples only relevant to the TypeScript generator: + +- [generate-typescript-models](./generate-typescript-models) - A basic example to generate TypeScript data models - [typescript-interface](./typescript-interface) - A basic TypeScript generator that outputs interfaces. - [typescript-enum-type](./typescript-enum-type) - A basic example of how to use Modelina can output different types of enums in TypeScript. - [typescript-generate-example](./typescript-generate-example) - A basic example of how to use Modelina and output a TypeScript class with an example function. @@ -118,19 +138,46 @@ These are all specific examples only relevant to the TypeScript generator: - [typescript-use-cjs](./typescript-use-cjs) - A basic example that generate the models to use CJS module system. - [typescript-generate-jsonbinpack](./typescript-generate-jsonbinpack) - A basic example showing how to generate models that include [jsonbinpack](https://github.com/sourcemeta/jsonbinpack) functionality. -## Kotlin +### Kotlin These are all specific examples only relevant to the Kotlin generator: + +- [generate-kotlin-models](./generate-kotlin-models) - A basic example to generate Kotlin data models - [generate-kotlin-enums](./generate-kotlin-enums) - [kotlin-generate-kdoc](./kotlin-generate-kdoc) - [kotlin-generate-javax-constraint-annotations](./kotlin-generate-javax-constraint-annotation) - [kotlin-change-collection-type](./kotlin-change-collection-type) -## PHP +### PHP These are all specific examples only relevant to the PHP generator: -- [php-generate-models](./php-generate-models) - A basic example of how to use Modelina and output a PHP class. + +- [generate-php-models](./generate-cplusplus-models) - A basic example to generate PHP data models - [php-generate-complete-models](./php-generate-complete-models) - An example that will output PHP complete class with dependencies and headers. - [php-generate-documentation-preset](./php-generate-documentation-preset) - An example that will output PHP complete class with documentation. +### Scala +These are all specific examples only relevant to the Scala generator: +- [generate-scala-models](./generate-scala-models) - A basic example to generate Scala data models +- [generate-scala-enums](./generate-scala-enums) - A basic example of how to use Modelina and output a Scala enums. +- [scala-generate-documentation](./scala-generate-documentation) - A basic example of how to use Modelina and output a Scala models that include descriptions. + +### Rust +These are all specific examples only relevant to the Rust generator; +- [rust-generate-crate](./rust-generate-crate) - A basic example showing how to generate a Rust package. + +### Dart +These are all specific examples only relevant to the Dart generator: +- [generate-dart-models](./generate-dart-models) - A basic example showing how to generate Python models. +- [dart-generate-json-annotation](./dart-generate-json-annotation) - A basic example of how to use Modelina and output Dart models that include JSON annotations. + +### Go +These are all specific examples only relevant to the Go generator; +- [generate-go-enums](./generate-go-enums) - A basic example showing how to generate a Go enums. +- [generate-go-models](./generate-go-models) - A basic example showing how to generate a Go models. + +### C++ +These are all specific examples only relevant to the C++ generator; +- [generate-cplusplus-models](./generate-cplusplus-models) - A basic example showing how to generate a C++ models. + ## Other examples Miscellaneous examples that do not fit into the otherwise grouping. - [TEMPLATE](./TEMPLATE) - A basic template used to create new examples. diff --git a/examples/dart-generate-json-annotation/README.md b/examples/dart-generate-json-annotation/README.md index c4eb09990d..a6a0d256cb 100644 --- a/examples/dart-generate-json-annotation/README.md +++ b/examples/dart-generate-json-annotation/README.md @@ -1,6 +1,6 @@ # Dart Data Models with json_annotation -A basic example of how to use Modelina and output a Go data model. +A basic example of how to use Modelina and output Dart models that include JSON annotations. ## How to run this example diff --git a/examples/dart-generate-json-annotation/package-lock.json b/examples/dart-generate-json-annotation/package-lock.json new file mode 100644 index 0000000000..ddc523b671 --- /dev/null +++ b/examples/dart-generate-json-annotation/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "dart-generate-json-annotation", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "hasInstallScript": true + } + } +} diff --git a/examples/dart-generate-json-annotation/package.json b/examples/dart-generate-json-annotation/package.json new file mode 100644 index 0000000000..b835668f31 --- /dev/null +++ b/examples/dart-generate-json-annotation/package.json @@ -0,0 +1,9 @@ +{ + "config" : { "example_name" : "dart-generate-json-annotation" }, "scripts": { + "install": "cd ../.. && npm i", + "start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts", + "start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts", + "test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts", + "test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts" + } +} diff --git a/examples/php-generate-models/README.md b/examples/generate-php-models/README.md similarity index 100% rename from examples/php-generate-models/README.md rename to examples/generate-php-models/README.md diff --git a/examples/php-generate-models/__snapshots__/index.spec.ts.snap b/examples/generate-php-models/__snapshots__/index.spec.ts.snap similarity index 100% rename from examples/php-generate-models/__snapshots__/index.spec.ts.snap rename to examples/generate-php-models/__snapshots__/index.spec.ts.snap diff --git a/examples/php-generate-models/index.spec.ts b/examples/generate-php-models/index.spec.ts similarity index 100% rename from examples/php-generate-models/index.spec.ts rename to examples/generate-php-models/index.spec.ts diff --git a/examples/php-generate-models/index.ts b/examples/generate-php-models/index.ts similarity index 100% rename from examples/php-generate-models/index.ts rename to examples/generate-php-models/index.ts diff --git a/examples/php-generate-models/package-lock.json b/examples/generate-php-models/package-lock.json similarity index 100% rename from examples/php-generate-models/package-lock.json rename to examples/generate-php-models/package-lock.json diff --git a/examples/php-generate-models/package.json b/examples/generate-php-models/package.json similarity index 100% rename from examples/php-generate-models/package.json rename to examples/generate-php-models/package.json diff --git a/examples/generate-scala-enums/__snapshots__/index.spec.ts.snap b/examples/generate-scala-enums/__snapshots__/index.spec.ts.snap new file mode 100644 index 0000000000..bb22915bf8 --- /dev/null +++ b/examples/generate-scala-enums/__snapshots__/index.spec.ts.snap @@ -0,0 +1,14 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Should be able to render Kotlin Enums and should log expected output to console 1`] = ` +Array [ + "object Protocol extends Enumeration { + type Protocol = Value + + val Http: Protocol.Value = Value(\\"HTTP\\") + val Number_1: Protocol.Value = Value(1) + val Https: Protocol.Value = Value(\\"HTTPS\\") + val ReservedTrue: Protocol.Value = Value(\\"true\\") +}", +] +`; diff --git a/examples/generate-scala-enums/index.ts b/examples/generate-scala-enums/index.ts index 458cc94c8d..f7a97fd1c3 100644 --- a/examples/generate-scala-enums/index.ts +++ b/examples/generate-scala-enums/index.ts @@ -1,4 +1,4 @@ -import { ScalaGenerator } from '../../src/generators/scala'; +import { ScalaGenerator } from '../../src'; const generator = new ScalaGenerator(); const jsonSchemaDraft7 = { diff --git a/examples/generate-scala-models/__snapshots__/index.spec.ts.snap b/examples/generate-scala-models/__snapshots__/index.spec.ts.snap new file mode 100644 index 0000000000..ec03215492 --- /dev/null +++ b/examples/generate-scala-models/__snapshots__/index.spec.ts.snap @@ -0,0 +1,11 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Should be able to render Kotlin Models and should log expected output to console 1`] = ` +Array [ + "case class Root( + email: Option[String], + cache: Option[Int], + website: Option[Website], +)", +] +`; diff --git a/examples/generate-scala-models/index.ts b/examples/generate-scala-models/index.ts index 74cde5421c..37ce750028 100644 --- a/examples/generate-scala-models/index.ts +++ b/examples/generate-scala-models/index.ts @@ -1,4 +1,4 @@ -import { ScalaGenerator } from '../../src/generators/scala'; +import { ScalaGenerator } from '../../src'; const generator = new ScalaGenerator(); const jsonSchemaDraft7 = { diff --git a/examples/integrate-modelina-into-maven/README.md b/examples/integrate-with-maven/README.md similarity index 100% rename from examples/integrate-modelina-into-maven/README.md rename to examples/integrate-with-maven/README.md diff --git a/examples/integrate-modelina-into-maven/maven-project/.gitignore b/examples/integrate-with-maven/maven-project/.gitignore similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/.gitignore rename to examples/integrate-with-maven/maven-project/.gitignore diff --git a/examples/integrate-modelina-into-maven/maven-project/README.md b/examples/integrate-with-maven/maven-project/README.md similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/README.md rename to examples/integrate-with-maven/maven-project/README.md diff --git a/examples/integrate-modelina-into-maven/maven-project/asyncapi.json b/examples/integrate-with-maven/maven-project/asyncapi.json similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/asyncapi.json rename to examples/integrate-with-maven/maven-project/asyncapi.json diff --git a/examples/integrate-modelina-into-maven/maven-project/pom.xml b/examples/integrate-with-maven/maven-project/pom.xml similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/pom.xml rename to examples/integrate-with-maven/maven-project/pom.xml diff --git a/examples/integrate-modelina-into-maven/maven-project/scripts/modelina/generate.ts b/examples/integrate-with-maven/maven-project/scripts/modelina/generate.ts similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/scripts/modelina/generate.ts rename to examples/integrate-with-maven/maven-project/scripts/modelina/generate.ts diff --git a/examples/integrate-modelina-into-maven/maven-project/scripts/modelina/package-lock.json b/examples/integrate-with-maven/maven-project/scripts/modelina/package-lock.json similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/scripts/modelina/package-lock.json rename to examples/integrate-with-maven/maven-project/scripts/modelina/package-lock.json diff --git a/examples/integrate-modelina-into-maven/maven-project/scripts/modelina/package.json b/examples/integrate-with-maven/maven-project/scripts/modelina/package.json similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/scripts/modelina/package.json rename to examples/integrate-with-maven/maven-project/scripts/modelina/package.json diff --git a/examples/integrate-modelina-into-maven/maven-project/src/main/java/com/mycompany/app/AnonymousSchema_1.java b/examples/integrate-with-maven/maven-project/src/main/java/com/mycompany/app/AnonymousSchema_1.java similarity index 100% rename from examples/integrate-modelina-into-maven/maven-project/src/main/java/com/mycompany/app/AnonymousSchema_1.java rename to examples/integrate-with-maven/maven-project/src/main/java/com/mycompany/app/AnonymousSchema_1.java diff --git a/examples/integrate-modelina-into-maven/package-lock.json b/examples/integrate-with-maven/package-lock.json similarity index 72% rename from examples/integrate-modelina-into-maven/package-lock.json rename to examples/integrate-with-maven/package-lock.json index 925777425c..1caacfbbed 100644 --- a/examples/integrate-modelina-into-maven/package-lock.json +++ b/examples/integrate-with-maven/package-lock.json @@ -1,5 +1,5 @@ { - "name": "integrate-modelina-into-maven", + "name": "integrate-with-maven", "lockfileVersion": 3, "requires": true, "packages": { diff --git a/examples/integrate-modelina-into-maven/package.json b/examples/integrate-with-maven/package.json similarity index 87% rename from examples/integrate-modelina-into-maven/package.json rename to examples/integrate-with-maven/package.json index 1425f5cf7d..6e1edf3e3b 100644 --- a/examples/integrate-modelina-into-maven/package.json +++ b/examples/integrate-with-maven/package.json @@ -1,6 +1,6 @@ { "config": { - "example_name": "integrate-modelina-into-maven" + "example_name": "integrate-with-maven" }, "scripts": { "install": "(cd ../.. && npm i) && cd maven-project/scripts/modelina && npm i", diff --git a/examples/scala-generate-documentation/README.md b/examples/scala-generate-documentation/README.md new file mode 100644 index 0000000000..82893d8e30 --- /dev/null +++ b/examples/scala-generate-documentation/README.md @@ -0,0 +1,15 @@ +# Scala Generate Models With Documentation Preset + +## How to run this example + +Run this example using: + +```sh +npm i && npm run start +``` + +If you are on Windows, use the `start:windows` script instead: + +```sh +npm i && npm run start:windows +``` diff --git a/examples/scala-generate-documentation/__snapshots__/index.spec.ts.snap b/examples/scala-generate-documentation/__snapshots__/index.spec.ts.snap new file mode 100644 index 0000000000..e1acc66d66 --- /dev/null +++ b/examples/scala-generate-documentation/__snapshots__/index.spec.ts.snap @@ -0,0 +1,14 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Should be able to render Scala models that include documentation and should log expected output to console 1`] = ` +Array [ + "/** + * Description for class + * + * @property email Description for the email property + */ +case class Root( + email: Option[String], +)", +] +`; diff --git a/examples/scala-generate-documentation/index.spec.ts b/examples/scala-generate-documentation/index.spec.ts new file mode 100644 index 0000000000..62cc087f01 --- /dev/null +++ b/examples/scala-generate-documentation/index.spec.ts @@ -0,0 +1,15 @@ +const spy = jest.spyOn(global.console, 'log').mockImplementation(() => { + return; +}); +import { generate } from './index'; + +describe('Should be able to render Scala models that include documentation', () => { + afterAll(() => { + jest.restoreAllMocks(); + }); + test('and should log expected output to console', async () => { + await generate(); + expect(spy.mock.calls.length).toEqual(1); + expect(spy.mock.calls[0]).toMatchSnapshot(); + }); +}); diff --git a/examples/scala-generate-documentation/index.ts b/examples/scala-generate-documentation/index.ts new file mode 100644 index 0000000000..a5ddc6c493 --- /dev/null +++ b/examples/scala-generate-documentation/index.ts @@ -0,0 +1,28 @@ +import { SCALA_DESCRIPTION_PRESET, ScalaGenerator } from '../../src'; + +const generator = new ScalaGenerator({ + presets: [SCALA_DESCRIPTION_PRESET] +}); +const jsonSchemaDraft7 = { + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + additionalProperties: false, + description: 'Description for class', + properties: { + email: { + type: 'string', + format: 'email', + description: 'Description for the email property' + } + } +}; + +export async function generate(): Promise { + const models = await generator.generate(jsonSchemaDraft7); + for (const model of models) { + console.log(model.result); + } +} +if (require.main === module) { + generate(); +} diff --git a/examples/scala-generate-documentation/package-lock.json b/examples/scala-generate-documentation/package-lock.json new file mode 100644 index 0000000000..35603bba82 --- /dev/null +++ b/examples/scala-generate-documentation/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "scala-generate-documentation", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "hasInstallScript": true + } + } +} diff --git a/examples/scala-generate-documentation/package.json b/examples/scala-generate-documentation/package.json new file mode 100644 index 0000000000..8d3eaa0b00 --- /dev/null +++ b/examples/scala-generate-documentation/package.json @@ -0,0 +1,10 @@ +{ + "config" : { "example_name" : "scala-generate-documentation" }, + "scripts": { + "install": "cd ../.. && npm i", + "start": "../../node_modules/.bin/ts-node --cwd ../../ ./examples/$npm_package_config_example_name/index.ts", + "start:windows": "..\\..\\node_modules\\.bin\\ts-node --cwd ..\\..\\ .\\examples\\%npm_package_config_example_name%\\index.ts", + "test": "../../node_modules/.bin/jest --config=../../jest.config.js ./examples/$npm_package_config_example_name/index.spec.ts", + "test:windows": "..\\..\\node_modules\\.bin\\jest --config=..\\..\\jest.config.js examples/%npm_package_config_example_name%/index.spec.ts" + } +} diff --git a/jest.config.js b/jest.config.js index 78d5ad22d0..4e6ff5d0a0 100644 --- a/jest.config.js +++ b/jest.config.js @@ -11,7 +11,7 @@ module.exports = { // Test spec file resolution pattern // Matches parent folder `__tests__` and filename // should contain `test` or `spec`. - testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$', + testRegex: '((\\.|/)(test|spec))\\.[jt]sx?$', // Module file extensions for importing moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], testTimeout: 10000, diff --git a/modelina-website/scripts/build-examples.js b/modelina-website/scripts/build-examples.js index 1caa89c799..8097bea769 100644 --- a/modelina-website/scripts/build-examples.js +++ b/modelina-website/scripts/build-examples.js @@ -31,7 +31,7 @@ const nameMapping = [ const examplesToIgnore = [ 'integrate-with-react', 'integrate-with-next', - 'integrate-modelina-into-maven', + 'integrate-with-maven', 'TEMPLATE' ] diff --git a/package.json b/package.json index 533b73147a..32f587c203 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,7 @@ "docker:test:blackbox": "docker compose run modelina npm run test:blackbox", "test": "npm run test:library && npm run test:examples", "test:update": "npm run test:library -- -u && npm run test:examples:update", - "test:library": "cross-env CI=true jest --coverage --testPathIgnorePatterns ./test/blackbox --testPathIgnorePatterns ./test/runtime --testPathIgnorePatterns ./examples", + "test:library": "cross-env CI=true jest --coverage --testPathIgnorePatterns ./test/blackbox --testPathIgnorePatterns ./modelina-website --testPathIgnorePatterns ./test/runtime --testPathIgnorePatterns ./examples", "test:examples": "npm run test:examples:regular && npm run test:examples:websites", "test:examples:update": "npm run test:examples:regular -- -u && npm run test:examples:websites -- -u", "test:examples:regular": "cross-env CI=true jest ./examples --testPathIgnorePatterns ./examples/integrate-with-react --testPathIgnorePatterns ./examples/integrate-with-next", @@ -123,7 +123,7 @@ "lint": "eslint --max-warnings 0 --config .eslintrc .", "lint:fix": "eslint --max-warnings 0 --config .eslintrc . --fix", "release": "semantic-release", - "generate:readme:toc": "markdown-toc -i README.md && markdown-toc -i ./docs/other-tools.md && markdown-toc -i ./docs/languages/Php.md && markdown-toc -i ./docs/languages/Cplusplus.md && markdown-toc -i ./examples/README.md && markdown-toc -i ./docs/languages/Python.md && markdown-toc -i ./docs/usage.md && markdown-toc -i ./docs/integration.md && markdown-toc -i ./docs/advanced.md && markdown-toc -i ./docs/languages/Dart.md && markdown-toc -i ./docs/languages/TypeScript.md && markdown-toc -i ./docs/languages/Java.md && markdown-toc -i ./docs/languages/JavaScript.md && markdown-toc -i ./docs/languages/Csharp.md && markdown-toc -i ./docs/README.md && markdown-toc -i ./docs/generators.md && markdown-toc -i ./docs/presets.md", + "generate:readme:toc": "markdown-toc -i README.md && markdown-toc -i ./docs/other-tools.md && markdown-toc -i ./docs/languages/Scala.md && markdown-toc -i ./docs/languages/Php.md && markdown-toc -i ./docs/languages/Cplusplus.md && markdown-toc -i ./examples/README.md && markdown-toc -i ./docs/languages/Python.md && markdown-toc -i ./docs/usage.md && markdown-toc -i ./docs/integration.md && markdown-toc -i ./docs/advanced.md && markdown-toc -i ./docs/languages/Dart.md && markdown-toc -i ./docs/languages/TypeScript.md && markdown-toc -i ./docs/languages/Java.md && markdown-toc -i ./docs/languages/JavaScript.md && markdown-toc -i ./docs/languages/Csharp.md && markdown-toc -i ./docs/README.md && markdown-toc -i ./docs/generators.md && markdown-toc -i ./docs/presets.md", "generate:assets": "npm run build:prod && npm run docs && npm run generate:readme:toc && npm run format", "bump:version": "npm --no-git-tag-version --allow-same-version version $VERSION", "prepublishOnly": "npm run build:prod && npm run generate:readme:toc && npm run format", diff --git a/src/generators/index.ts b/src/generators/index.ts index 9a76050899..3cad3a112a 100644 --- a/src/generators/index.ts +++ b/src/generators/index.ts @@ -11,4 +11,5 @@ export * from './go'; export * from './rust'; export * from './kotlin'; export * from './cplusplus'; +export * from './scala'; export * from './AbstractFileGenerator'; From 147d0dcb6cd577a40d6d2f447a03720491d821cf Mon Sep 17 00:00:00 2001 From: asyncapi-bot Date: Wed, 27 Dec 2023 17:23:54 +0100 Subject: [PATCH 18/37] chore(release): v2.1.1 (#1706) Co-authored-by: asyncapi-bot --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6a3ee911c1..707514e08f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@asyncapi/modelina", - "version": "2.1.0", + "version": "2.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@asyncapi/modelina", - "version": "2.1.0", + "version": "2.1.1", "license": "Apache-2.0", "dependencies": { "@apidevtools/json-schema-ref-parser": "^9.0.9", diff --git a/package.json b/package.json index 32f587c203..3e895bf582 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@asyncapi/modelina", - "version": "2.1.0", + "version": "2.1.1", "description": "Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents", "license": "Apache-2.0", "homepage": "https://www.modelina.org", From 1ebfd0e7ce83d8249c6b07910b997adafe8fde73 Mon Sep 17 00:00:00 2001 From: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> Date: Wed, 27 Dec 2023 21:56:33 +0530 Subject: [PATCH 19/37] docs: updated wrong section name in NAMING_FORMATTER in constraint docs for all languages (#1688) --- docs/constraints/CSharp.md | 4 ++-- docs/constraints/Dart.md | 4 ++-- docs/constraints/Go.md | 4 ++-- docs/constraints/Java.md | 4 ++-- docs/constraints/JavaScript.md | 4 ++-- docs/constraints/Rust.md | 2 +- docs/constraints/TypeScript.md | 4 ++-- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/constraints/CSharp.md b/docs/constraints/CSharp.md index 17e1d5be9e..556cfd7a9a 100644 --- a/docs/constraints/CSharp.md +++ b/docs/constraints/CSharp.md @@ -21,7 +21,7 @@ These are the constraints that is applied to object properties and the naming of |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|C# has a list of reserved keywords ([see the full list here](../../src/generators/csharp/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using pascal case| |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| @@ -34,7 +34,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|C# has a list of reserved keywords ([see the full list here](../../src/generators/csharp/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant diff --git a/docs/constraints/Dart.md b/docs/constraints/Dart.md index d545a6f9bd..1639f0a2d2 100644 --- a/docs/constraints/Dart.md +++ b/docs/constraints/Dart.md @@ -21,7 +21,7 @@ These are the constraints that is applied to object properties and the naming of |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Dart has a list of reserved keywords ([see the full list here](../../src/generators/dart/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using pascal case| |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| @@ -34,7 +34,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Dart has a list of reserved keywords ([see the full list here](../../src/generators/dart/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant diff --git a/docs/constraints/Go.md b/docs/constraints/Go.md index ef693d8383..7ee88faddb 100644 --- a/docs/constraints/Go.md +++ b/docs/constraints/Go.md @@ -21,7 +21,7 @@ These are the constraints that is applied to object properties and the naming of |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Go has a list of reserved keywords ([see the full list here](../../src/generators/go/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using pascal case| |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| @@ -34,7 +34,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Go has a list of reserved keywords ([see the full list here](../../src/generators/go/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant diff --git a/docs/constraints/Java.md b/docs/constraints/Java.md index 29f0ff2f82..60db4a7b80 100644 --- a/docs/constraints/Java.md +++ b/docs/constraints/Java.md @@ -21,7 +21,7 @@ These are the constraints that is applied to object properties and the naming of |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Java has a list of reserved keywords ([see the full list here](../../src/generators/java/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using pascal case| |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| @@ -34,7 +34,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Java has a list of reserved keywords ([see the full list here](../../src/generators/java/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant diff --git a/docs/constraints/JavaScript.md b/docs/constraints/JavaScript.md index 742a580086..96b685be25 100644 --- a/docs/constraints/JavaScript.md +++ b/docs/constraints/JavaScript.md @@ -21,7 +21,7 @@ These are the constraints that is applied to object properties and the naming of |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|JavaScript has a list of reserved keywords ([see the full list here](../../src/generators/javascript/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using pascal case| |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| @@ -34,7 +34,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|JavaScript has a list of reserved keywords ([see the full list here](../../src/generators/javascript/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant diff --git a/docs/constraints/Rust.md b/docs/constraints/Rust.md index 611532c9c5..fd304b7e28 100644 --- a/docs/constraints/Rust.md +++ b/docs/constraints/Rust.md @@ -33,7 +33,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|Rust has a list of reserved keywords ([see the full list here](../../src/generators/rust/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant diff --git a/docs/constraints/TypeScript.md b/docs/constraints/TypeScript.md index 85fc33b9cc..41095ddcfa 100644 --- a/docs/constraints/TypeScript.md +++ b/docs/constraints/TypeScript.md @@ -21,7 +21,7 @@ These are the constraints that is applied to object properties and the naming of |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|TypeScript has a list of reserved keywords ([see the full list here](../../src/generators/typescript/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using pascal case| |NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| @@ -34,7 +34,7 @@ These are the constraints that is applied to enum keys. The `Rule key` is what y |NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| |NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | |NO_RESERVED_KEYWORDS|No reserved keywords|TypeScript has a list of reserved keywords ([see the full list here](../../src/generators/typescript/Constants.ts))| -|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using pascal case| |NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| ## Constant From 4bb59d8af05e22c486f121a8a960b3a8912e73dd Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Wed, 27 Dec 2023 06:27:09 -1000 Subject: [PATCH 20/37] docs: add officialasishkumar as a contributor for doc (#1707) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index ef18e312b9..2f19c78ed9 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -817,6 +817,15 @@ "contributions": [ "doc" ] + }, + { + "login": "officialasishkumar", + "name": "Asish Kumar", + "avatar_url": "https://avatars.githubusercontent.com/u/87874775?v=4", + "profile": "https://github.com/officialasishkumar", + "contributions": [ + "doc" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 71329d22f0..093b1a8e19 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![Discussions](https://img.shields.io/github/discussions/asyncapi/modelina)](https://github.com/asyncapi/modelina/discussions) [![Website](https://img.shields.io/website?label=website&url=https%3A%2F%2Fwww.modelina.org)](https://www.modelina.org) [![Playground](https://img.shields.io/website?label=playground&url=https%3A%2F%2Fwww.modelina.org%2Fplayground)](https://www.modelina.org/playground) -[![All Contributors](https://img.shields.io/badge/all_contributors-75-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-76-orange.svg?style=flat-square)](#contributors-) Your one-stop tool for generating accurate and well-tested models for representing the message payloads. Use it as a tool in your development workflow, or a library in a larger integrations, entirely in your control. @@ -419,6 +419,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Harshil Jani
Harshil Jani

💻 ⚠️ Mintu Gogoi
Mintu Gogoi

⚠️ Devansh Mahant
Devansh Mahant

📖 + Asish Kumar
Asish Kumar

📖 From 37a5306bd9d8170bb6880bd05a37f6c9cd771d2c Mon Sep 17 00:00:00 2001 From: Ankur Singh Date: Thu, 28 Dec 2023 19:03:31 +0530 Subject: [PATCH 21/37] docs: adds C++ constraint docs (#1696) --- docs/constraints/Cplusplus.md | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/constraints/Cplusplus.md diff --git a/docs/constraints/Cplusplus.md b/docs/constraints/Cplusplus.md new file mode 100644 index 0000000000..e95c1e484e --- /dev/null +++ b/docs/constraints/Cplusplus.md @@ -0,0 +1,41 @@ +# C++ Constraints + +These are the C++ specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](../input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. + +## Model Naming +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For C++ `_` are an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|C++ has a list of reserved keywords ([see the full list here](../../src/generators/cplusplus/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using snake case| + +## Property naming +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For C++ `_` are an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|C++ has a list of reserved keywords ([see the full list here](../../src/generators/cplusplus/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Property naming is formatted using snake case| +|NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + + +## Enum key constraints +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](./README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For C++ `_` are an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|C++ has a list of reserved keywords ([see the full list here](../../src/generators/cplusplus/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Enum key is formatted using snake case| +|NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + +## Constant +These are the constraints that are applied to constants. Currently, there are no hooks one can overwrite inside it. From ad36dfb842039f0b162c7c3a5e08f310a825064c Mon Sep 17 00:00:00 2001 From: sheshe1 <92985478+anchalpanwar17@users.noreply.github.com> Date: Thu, 28 Dec 2023 21:48:08 +0530 Subject: [PATCH 22/37] chore(website): update the store link in footer (#1705) Co-authored-by: Ashmit JaiSarita Gupta <43639341+devilkiller-ag@users.noreply.github.com>%0ACo-authored-by: Jonas Lagoni --- modelina-website/src/components/layouts/Footer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modelina-website/src/components/layouts/Footer.tsx b/modelina-website/src/components/layouts/Footer.tsx index 34fd458060..a9bdd37231 100644 --- a/modelina-website/src/components/layouts/Footer.tsx +++ b/modelina-website/src/components/layouts/Footer.tsx @@ -58,7 +58,7 @@ export default function Footer() {
  • Date: Fri, 29 Dec 2023 00:33:54 +0530 Subject: [PATCH 23/37] test: added test for PHP constraint (#1695) --- .../constrainer/ConstantConstrainer.spec.ts | 19 ++ .../php/constrainer/EnumConstrainer.spec.ts | 167 ++++++++++++++++ .../constrainer/ModelNameConstrainer.spec.ts | 75 ++++++++ .../PropertyKeyConstrainer.spec.ts | 179 ++++++++++++++++++ 4 files changed, 440 insertions(+) create mode 100644 test/generators/php/constrainer/ConstantConstrainer.spec.ts create mode 100644 test/generators/php/constrainer/EnumConstrainer.spec.ts create mode 100644 test/generators/php/constrainer/ModelNameConstrainer.spec.ts create mode 100644 test/generators/php/constrainer/PropertyKeyConstrainer.spec.ts diff --git a/test/generators/php/constrainer/ConstantConstrainer.spec.ts b/test/generators/php/constrainer/ConstantConstrainer.spec.ts new file mode 100644 index 0000000000..71202cdf05 --- /dev/null +++ b/test/generators/php/constrainer/ConstantConstrainer.spec.ts @@ -0,0 +1,19 @@ +import { defaultConstantConstraints } from '../../../../src/generators/php/constrainer/ConstantConstrainer'; + +const mockConstantContext = { + constrainedMetaModel: {} as any +}; + +describe('defaultConstantConstraints', () => { + it('should return a function that returns undefined', () => { + const constantConstraintsFunction = defaultConstantConstraints(); + const result = constantConstraintsFunction(mockConstantContext); + expect(result).toBeUndefined(); + }); + + it('should return a ConstantConstraint type', () => { + const constantConstraintsFunction = defaultConstantConstraints(); + const result = constantConstraintsFunction; + expect(typeof result).toBe('function'); + }); +}); diff --git a/test/generators/php/constrainer/EnumConstrainer.spec.ts b/test/generators/php/constrainer/EnumConstrainer.spec.ts new file mode 100644 index 0000000000..6295e5407b --- /dev/null +++ b/test/generators/php/constrainer/EnumConstrainer.spec.ts @@ -0,0 +1,167 @@ +import { PhpDefaultConstraints } from '../../../../src/generators/php/PhpConstrainer'; +import { EnumModel } from '../../../../src/models/MetaModel'; +import { + ConstrainedEnumModel, + ConstrainedEnumValueModel +} from '../../../../src'; +import { + defaultEnumKeyConstraints, + ModelEnumKeyConstraints +} from '../../../../src/generators/php/constrainer/EnumConstrainer'; + +describe('Php EnumConstrainer', () => { + const enumModel = new EnumModel('test', undefined, {}, []); + const constrainedEnumModel = new ConstrainedEnumModel( + 'test', + undefined, + {}, + '', + [] + ); + + describe('enum keys', () => { + test('should never render special chars', () => { + const constrainedKey = PhpDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '%' + }); + expect(constrainedKey).toEqual('PERCENT'); + }); + + test('should not render number as start char', () => { + const constrainedKey = PhpDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '1' + }); + expect(constrainedKey).toEqual('NUMBER_1'); + }); + + test('should not contain duplicate keys', () => { + const existingConstrainedEnumValueModel = new ConstrainedEnumValueModel( + 'EMPTY', + 'return', + 'return' + ); + const constrainedEnumModel = new ConstrainedEnumModel( + 'test', + undefined, + {}, + '', + [existingConstrainedEnumValueModel] + ); + const constrainedKey = PhpDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedKey).toEqual('RESERVED_EMPTY'); + }); + + test('should never contain empty keys', () => { + const constrainedKey = PhpDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedKey).toEqual('RESERVED_EMPTY'); + }); + + test('should use constant naming format', () => { + const constrainedKey = PhpDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: 'some weird_value!"#2' + }); + expect(constrainedKey).toEqual( + 'SOME_WEIRD_VALUE_EXCLAMATION_QUOTATION_HASH_2' + ); + }); + + test('should never render reserved keywords', () => { + const constrainedKey = PhpDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: 'return' + }); + expect(constrainedKey).toEqual('RESERVED_RETURN'); + }); + }); + + describe('enum values', () => { + test('should render string values', () => { + const constrainedValue = PhpDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: 'string value' + }); + expect(constrainedValue).toEqual('"string value"'); + }); + test('should render boolean values', () => { + const constrainedBooleanValue = PhpDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: true + }); + expect(constrainedBooleanValue).toEqual('"true"'); + }); + + test('should render numbers', () => { + const constrainedNumberValue = PhpDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: 123 + }); + expect(constrainedNumberValue).toEqual(123); + }); + + test('should render object values', () => { + const constrainedObjectValue = PhpDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: { test: 'test' } + }); + expect(constrainedObjectValue).toEqual('"{\\"test\\":\\"test\\"}"'); + }); + + test('should render unknown value', () => { + const constrainedUnknownValue = PhpDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: undefined + }); + expect(constrainedUnknownValue).toEqual(`"undefined"`); + }); + }); + + describe('custom constraints', () => { + test('should be able to overwrite all hooks for enum key', () => { + const mockedConstraintCallbacks: Partial = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultEnumKeyConstraints( + mockedConstraintCallbacks + ); + constrainFunction({ enumModel, constrainedEnumModel, enumKey: '' }); + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + test('should be able to overwrite specific hooks for enum key', () => { + const mockedConstraintCallbacks: Partial = { + NAMING_FORMATTER: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultEnumKeyConstraints( + mockedConstraintCallbacks + ); + constrainFunction({ enumModel, constrainedEnumModel, enumKey: '' }); + + expect(mockedConstraintCallbacks.NAMING_FORMATTER).toHaveBeenCalled(); + }); + }); +}); diff --git a/test/generators/php/constrainer/ModelNameConstrainer.spec.ts b/test/generators/php/constrainer/ModelNameConstrainer.spec.ts new file mode 100644 index 0000000000..5eb4e22de5 --- /dev/null +++ b/test/generators/php/constrainer/ModelNameConstrainer.spec.ts @@ -0,0 +1,75 @@ +import { + DefaultModelNameConstraints, + defaultModelNameConstraints, + ModelNameConstraints +} from '../../../../src/generators/php/constrainer/ModelNameConstrainer'; + +describe('PHP ModelNameConstrainer', () => { + const PhpDefaultConstraints: ModelNameConstraints = + DefaultModelNameConstraints; + + test('should replace special characters with underscores', () => { + const constrainedName = PhpDefaultConstraints.NO_SPECIAL_CHAR('name%$test'); + expect(constrainedName).toEqual('name_percent_dollar_test'); + }); + + test('should handle number start characters', () => { + const constrainedName = PhpDefaultConstraints.NO_NUMBER_START_CHAR('1Test'); + expect(constrainedName).toEqual('number_1Test'); + }); + + test('should handle empty value by default', () => { + const constrainedName = PhpDefaultConstraints.NO_EMPTY_VALUE(''); + expect(constrainedName).toEqual('empty'); + }); + + test('should convert to PascalCase by default', () => { + const constrainedName = PhpDefaultConstraints.NAMING_FORMATTER('test_name'); + expect(constrainedName).toEqual('TestName'); + }); + + test('should handle reserved PHP keywords', () => { + const constrainedName = + PhpDefaultConstraints.NO_RESERVED_KEYWORDS('return'); + expect(constrainedName).toEqual('reserved_return'); + }); + + describe('Custom PHP constraints', () => { + test('should be able to overwrite all hooks for PHP', () => { + const mockedConstraintCallbacks: Partial = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultModelNameConstraints( + mockedConstraintCallbacks + ); + constrainFunction({ modelName: '' }); + // Expect all callbacks to be called + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + + test('should be able to overwrite one hook for PHP', () => { + // All but NAMING_FORMATTER, as we customize that + const spies = [ + jest.spyOn(DefaultModelNameConstraints, 'NO_SPECIAL_CHAR'), + jest.spyOn(DefaultModelNameConstraints, 'NO_NUMBER_START_CHAR'), + jest.spyOn(DefaultModelNameConstraints, 'NO_EMPTY_VALUE'), + jest.spyOn(DefaultModelNameConstraints, 'NO_RESERVED_KEYWORDS') + ]; + const jestCallback = jest.fn().mockReturnValue(''); + const constrainFunction = defaultModelNameConstraints({ + NAMING_FORMATTER: jestCallback + }); + const constrainedValue = constrainFunction({ modelName: '' }); + expect(constrainedValue).toEqual(''); + for (const jestMockCallback of spies) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + }); +}); diff --git a/test/generators/php/constrainer/PropertyKeyConstrainer.spec.ts b/test/generators/php/constrainer/PropertyKeyConstrainer.spec.ts new file mode 100644 index 0000000000..3547b6f40c --- /dev/null +++ b/test/generators/php/constrainer/PropertyKeyConstrainer.spec.ts @@ -0,0 +1,179 @@ +import { PhpDefaultConstraints } from '../../../../src/generators/php/PhpConstrainer'; +import { + ConstrainedObjectModel, + ObjectModel, + ConstrainedObjectPropertyModel, + ObjectPropertyModel +} from '../../../../src'; +import { + defaultPropertyKeyConstraints, + PropertyKeyConstraintOptions +} from '../../../../src/generators/php/constrainer/PropertyKeyConstrainer'; + +describe('PropertyKeyConstrainer for PHP', () => { + const objectModel = new ObjectModel('test', undefined, {}, {}); + const constrainedObjectModel = new ConstrainedObjectModel( + 'test', + undefined, + {}, + '', + {} + ); + + const constrainPropertyName = (propertyName: string) => { + const objectPropertyModel = new ObjectPropertyModel( + propertyName, + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + return PhpDefaultConstraints.propertyKey({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + }; + + afterEach(() => { + jest.restoreAllMocks(); + }); + + test('should never render special chars for PHP', () => { + const constrainedKey = constrainPropertyName('%'); + expect(constrainedKey).toEqual('percent'); + }); + + test('should not render number as start char for PHP', () => { + const constrainedKey = constrainPropertyName('1'); + expect(constrainedKey).toEqual('number_1'); + }); + + test('should never contain empty name for PHP', () => { + const constrainedKey = constrainPropertyName(''); + expect(constrainedKey).toEqual('reservedEmpty'); + }); + + test('should use camelCase naming format for PHP', () => { + const constrainedKey = constrainPropertyName('some weird_value!"#2'); + expect(constrainedKey).toEqual('someWeirdValueExclamationQuotationHash_2'); + }); + + test('should never render reserved keywords for PHP', () => { + const constrainedKey = constrainPropertyName('return'); + expect(constrainedKey).toEqual('reservedReturn'); + }); + + describe('custom constraints for PHP', () => { + test('should be able to overwrite all hooks for PHP', () => { + const mockedConstraintCallbacks: Partial = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultPropertyKeyConstraints( + mockedConstraintCallbacks + ); + const objectPropertyModel = new ObjectPropertyModel( + '', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + constrainFunction({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + test('should be able to overwrite NO_SPECIAL_CHAR hook for PHP', () => { + const mockedConstraintCallbacks: Partial = { + NO_SPECIAL_CHAR: jest.fn().mockImplementation((value: string) => { + return value.replace(/[@#$%^&*]/g, ''); + }), + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + + const constrainFunction = defaultPropertyKeyConstraints( + mockedConstraintCallbacks + ); + + const objectPropertyModel = new ObjectPropertyModel( + '', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + + const result = constrainFunction({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + expect(result).toEqual(''); + expect(mockedConstraintCallbacks.NO_SPECIAL_CHAR).toHaveBeenCalled(); + }); + + test('should be able to overwrite NO_EMPTY_VALUE hook for PHP', () => { + const mockedConstraintCallbacks: Partial = { + NO_EMPTY_VALUE: jest.fn().mockImplementation((value: string) => { + return value.trim(); + }), + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + + const constrainFunction = defaultPropertyKeyConstraints( + mockedConstraintCallbacks + ); + + const objectPropertyModel = new ObjectPropertyModel( + '', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + + const result = constrainFunction({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + expect(result).toEqual(''); + expect(mockedConstraintCallbacks.NO_EMPTY_VALUE).toHaveBeenCalled(); + }); + }); +}); From ec745f53e066c05e465c2f87fc61f17357ec9b29 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Fri, 29 Dec 2023 14:46:36 -1000 Subject: [PATCH 24/37] docs: add ankur0904 as a contributor for doc (#1709) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 2f19c78ed9..01dbc45b09 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -826,6 +826,15 @@ "contributions": [ "doc" ] + }, + { + "login": "ankur0904", + "name": "Ankur Singh", + "avatar_url": "https://avatars.githubusercontent.com/u/98346896?v=4", + "profile": "https://github.com/ankur0904", + "contributions": [ + "doc" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 093b1a8e19..0b1ee3ba45 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![Discussions](https://img.shields.io/github/discussions/asyncapi/modelina)](https://github.com/asyncapi/modelina/discussions) [![Website](https://img.shields.io/website?label=website&url=https%3A%2F%2Fwww.modelina.org)](https://www.modelina.org) [![Playground](https://img.shields.io/website?label=playground&url=https%3A%2F%2Fwww.modelina.org%2Fplayground)](https://www.modelina.org/playground) -[![All Contributors](https://img.shields.io/badge/all_contributors-76-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-77-orange.svg?style=flat-square)](#contributors-) Your one-stop tool for generating accurate and well-tested models for representing the message payloads. Use it as a tool in your development workflow, or a library in a larger integrations, entirely in your control. @@ -420,6 +420,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Mintu Gogoi
    Mintu Gogoi

    ⚠️ Devansh Mahant
    Devansh Mahant

    📖 Asish Kumar
    Asish Kumar

    📖 + Ankur Singh
    Ankur Singh

    📖 From 3df0fe39fc420ff9cfc2c0bf1734286dcc8b41f3 Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Sat, 30 Dec 2023 14:24:31 -1000 Subject: [PATCH 25/37] chore: add artur-ciocanu as scala champion (#1686) --- CODEOWNERS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CODEOWNERS b/CODEOWNERS index ea345570f9..fd26d550f1 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -52,3 +52,6 @@ # Language Champions for PHP and it's presets */generators/php @ferror + +# Language Champions for Scala and it's presets +*/generators/scala @artur-ciocanu \ No newline at end of file From 4d9a55cf9b1c9a1cba39ea6eb039b1dd2c84c9fb Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sat, 30 Dec 2023 14:25:38 -1000 Subject: [PATCH 26/37] docs: add artur-ciocanu as a contributor for maintenance (#1714) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 3 ++- README.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 01dbc45b09..589f0b1105 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -344,7 +344,8 @@ "bug", "example", "doc", - "test" + "test", + "maintenance" ] }, { diff --git a/README.md b/README.md index 0b1ee3ba45..31d00001c2 100644 --- a/README.md +++ b/README.md @@ -361,7 +361,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org PanMan
    PanMan

    📖 - artur-ciocanu
    artur-ciocanu

    💻 🐛 💡 📖 ⚠️ + artur-ciocanu
    artur-ciocanu

    💻 🐛 💡 📖 ⚠️ 🚧 Cyprian Gracz
    Cyprian Gracz

    💻 ⚠️ 🐛 Leigh Johnson
    Leigh Johnson

    💻 ⚠️ 💡 📖 🚧 👀 Nitin Tejuja
    Nitin Tejuja

    ⚠️ 💡 From 44e1893caf74d4b83adea9c45345fd49050943a3 Mon Sep 17 00:00:00 2001 From: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> Date: Mon, 1 Jan 2024 02:33:28 +0530 Subject: [PATCH 27/37] docs: added php constraint docs (#1711) Signed-off-by: Asish Kumar --- docs/constraints/PHP.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/constraints/PHP.md diff --git a/docs/constraints/PHP.md b/docs/constraints/PHP.md new file mode 100644 index 0000000000..dc3fc60655 --- /dev/null +++ b/docs/constraints/PHP.md @@ -0,0 +1,41 @@ +# PHP Constraints + +These are the PHP specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](https://github.com/asyncapi/modelina/blob/master/docs/input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. + +## Model Naming +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/blob/master/docs/README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For PHP `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Scala has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/php/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case.| + +## Property naming +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/blob/master/docs/README.md#Customization). +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For PHP `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Scala has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/php/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using camel case. | +|NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + + +## Enum key constraints +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/tree/master/docs/README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For PHP `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Scala has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/php/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using constant case. | +|NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + +## Constant +These are the constraints that are applied to constants. Currently, there are no hooks one can overwrite inside it. From ccd02aa7d48d754910c5205503f90b648428b8a0 Mon Sep 17 00:00:00 2001 From: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> Date: Mon, 1 Jan 2024 02:37:28 +0530 Subject: [PATCH 28/37] docs: added kotlin constraint docs (#1712) --- docs/constraints/Kotlin.md | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/constraints/Kotlin.md diff --git a/docs/constraints/Kotlin.md b/docs/constraints/Kotlin.md new file mode 100644 index 0000000000..eaad2935d8 --- /dev/null +++ b/docs/constraints/Kotlin.md @@ -0,0 +1,41 @@ +# Kotlin Constraints + +These are the Kotlin specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](https://github.com/asyncapi/modelina/blob/master/docs/input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. + +## Model Naming +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/blob/master/docs/README.md). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For kotlin `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Kotlin has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/kotlin/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case.| + +## Property naming +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/blob/master/docs/README.md). +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For kotlin `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Kotlin has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/kotlin/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using camel case. | +|NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found. | + + +## Enum key constraints +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/tree/master/docs/README.md). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For kotlin `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Kotlin has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/kotlin/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using constant case. | +|NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found. | + +## Constant +These are the constraints that are applied to constants. Currently, there are no hooks one can overwrite inside it. \ No newline at end of file From 014fc784e16c2e809883524ac6bac3a8441fe61f Mon Sep 17 00:00:00 2001 From: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> Date: Mon, 1 Jan 2024 02:38:40 +0530 Subject: [PATCH 29/37] docs: added scala constraint docs (#1710) --- docs/constraints/Scala.md | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/constraints/Scala.md diff --git a/docs/constraints/Scala.md b/docs/constraints/Scala.md new file mode 100644 index 0000000000..808f0081e5 --- /dev/null +++ b/docs/constraints/Scala.md @@ -0,0 +1,41 @@ +# Scala Constraints + +These are the Scala specific constraints applied to the MetaModel before reaching the presets. [Read here to get a more general idea on the overall process](https://github.com/asyncapi/modelina/blob/master/docs/input-processing.md) of converting a MetaModel to a ConstrainedMetaModel. + +## Model Naming +These are the constraints that is applied to model naming. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/blob/master/docs/README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For scala `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character| +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Scala has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/scala/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Model name is formatted using pascal case.| + +## Property naming +These are the constraints that is applied to object properties and the naming of them. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/blob/master/docs/README.md#Customization). +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For scala `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Scala has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/scala/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Property name is formatted using camel case. | +|NO_DUPLICATE_PROPERTIES|No duplicate properties|If any of the above constraints changes the property name, we must make sure that no duplicates exist within the same object. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found. | + + +## Enum key constraints +These are the constraints that is applied to enum keys. The `Rule key` is what you can use in the options to overwrite the default behavior. See [constraint customization](https://github.com/asyncapi/modelina/tree/master/docs/README.md#Customization). + +|Rule key|Rule|Resolution| +|---|---|---| +|NO_SPECIAL_CHAR|No special characters| Special characters are replaced by their name, for example `!` is replaced with `exclamation`. For scala `_` is an exception to this rule. | +|NO_NUMBER_START_CHAR|No numbers as starting characters|Default behavior is pre pending `number_` in front of the first character. | +|NO_EMPTY_VALUE|No empty values|Default behavior is to use `empty` as name. | +|NO_RESERVED_KEYWORDS|No reserved keywords|Scala has a list of reserved keywords ([see the full list here](https://github.com/asyncapi/modelina/blob/master/src/generators/scala/Constants.ts))| +|NAMING_FORMATTER|Must be formatted equally|Enum name is formatted using constant case. | +|NO_DUPLICATE_KEYS|No duplicate enum keys|If any of the above constraints changes the enum key, we must make sure that no duplicates exist within the same enum. If any is encountered `reserved_` is pre-pended. This is done recursively until no duplicates are found.| + +## Constant +These are the constraints that are applied to constants. Currently, there are no hooks one can overwrite inside it. From bffee57b1f63c0d7a46df2ca1d5d36bb3237fca9 Mon Sep 17 00:00:00 2001 From: Ashmit JaiSarita Gupta <43639341+devilkiller-ag@users.noreply.github.com> Date: Tue, 2 Jan 2024 01:33:22 +0530 Subject: [PATCH 30/37] test: add python constraint tests (#1703) --- .../constrainer/EnumConstrainer.spec.ts | 2 +- .../constrainer/ModelNameConstrainer.spec.ts | 2 +- .../PropertyKeyConstrainer.spec.ts | 2 +- .../constrainer/ConstantConstrainer.spec.ts | 19 ++ .../constrainer/EnumConstrainer.spec.ts | 134 +++++++++++++ .../constrainer/ModelNameConstrainer.spec.ts | 76 ++++++++ .../PropertyKeyConstrainer.spec.ts | 183 ++++++++++++++++++ 7 files changed, 415 insertions(+), 3 deletions(-) create mode 100644 test/generators/python/constrainer/ConstantConstrainer.spec.ts create mode 100644 test/generators/python/constrainer/EnumConstrainer.spec.ts create mode 100644 test/generators/python/constrainer/ModelNameConstrainer.spec.ts create mode 100644 test/generators/python/constrainer/PropertyKeyConstrainer.spec.ts diff --git a/test/generators/javascript/constrainer/EnumConstrainer.spec.ts b/test/generators/javascript/constrainer/EnumConstrainer.spec.ts index 53e11edcec..e5d08d778e 100644 --- a/test/generators/javascript/constrainer/EnumConstrainer.spec.ts +++ b/test/generators/javascript/constrainer/EnumConstrainer.spec.ts @@ -59,7 +59,7 @@ describe('EnumConstrainer', () => { }); expect(constrainedKey).toEqual(''); }); - test('should use constant naming format', () => { + test('should use pascal naming format', () => { const constrainedKey = JavaScriptDefaultConstraints.enumKey({ enumModel, constrainedEnumModel, diff --git a/test/generators/javascript/constrainer/ModelNameConstrainer.spec.ts b/test/generators/javascript/constrainer/ModelNameConstrainer.spec.ts index 5cae1a39f8..edd4531e86 100644 --- a/test/generators/javascript/constrainer/ModelNameConstrainer.spec.ts +++ b/test/generators/javascript/constrainer/ModelNameConstrainer.spec.ts @@ -23,7 +23,7 @@ describe('ModelNameConstrainer', () => { }); expect(constrainedKey).toEqual('Empty'); }); - test('should use constant naming format', () => { + test('should use pascal naming format', () => { const constrainedKey = JavaScriptDefaultConstraints.modelName({ modelName: 'some weird_value!"#2' }); diff --git a/test/generators/javascript/constrainer/PropertyKeyConstrainer.spec.ts b/test/generators/javascript/constrainer/PropertyKeyConstrainer.spec.ts index 330e8c36a6..f53bd83d87 100644 --- a/test/generators/javascript/constrainer/PropertyKeyConstrainer.spec.ts +++ b/test/generators/javascript/constrainer/PropertyKeyConstrainer.spec.ts @@ -52,7 +52,7 @@ describe('PropertyKeyConstrainer', () => { const constrainedKey = constrainPropertyName(''); expect(constrainedKey).toEqual('empty'); }); - test('should use constant naming format', () => { + test('should use pascal naming format', () => { const constrainedKey = constrainPropertyName('some weird_value!"#2'); expect(constrainedKey).toEqual('someWeirdValueExclamationQuotationHash_2'); }); diff --git a/test/generators/python/constrainer/ConstantConstrainer.spec.ts b/test/generators/python/constrainer/ConstantConstrainer.spec.ts new file mode 100644 index 0000000000..f41fcc3fad --- /dev/null +++ b/test/generators/python/constrainer/ConstantConstrainer.spec.ts @@ -0,0 +1,19 @@ +import { defaultConstantConstraints } from '../../../../src/generators/python/constrainer/ConstantConstrainer'; + +const mockConstantContext = { + constrainedMetaModel: {} as any +}; + +describe('defaultConstantConstraints', () => { + it('should return a function that returns undefined', () => { + const constantConstraintsFunction = defaultConstantConstraints(); + const result = constantConstraintsFunction(mockConstantContext); + expect(result).toBeUndefined(); + }); + + it('should return a ConstantConstraint type', () => { + const constantConstraintsFunction = defaultConstantConstraints(); + const result = constantConstraintsFunction; + expect(typeof result).toBe('function'); + }); +}); diff --git a/test/generators/python/constrainer/EnumConstrainer.spec.ts b/test/generators/python/constrainer/EnumConstrainer.spec.ts new file mode 100644 index 0000000000..7a9635ceed --- /dev/null +++ b/test/generators/python/constrainer/EnumConstrainer.spec.ts @@ -0,0 +1,134 @@ +import { PythonDefaultConstraints } from '../../../../src/generators/python/PythonConstrainer'; +import { EnumModel } from '../../../../src/models/MetaModel'; +import { + ConstrainedEnumModel, + ConstrainedEnumValueModel +} from '../../../../src'; + +describe('EnumConstrainer', () => { + const enumModel = new EnumModel('test', undefined, {}, []); + const constrainedEnumModel = new ConstrainedEnumModel( + 'test', + undefined, + {}, + '', + [] + ); + + describe('enum keys', () => { + test('should never render special chars', () => { + const constrainedKey = PythonDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '%' + }); + expect(constrainedKey).toEqual('PERCENT'); + }); + + test('should not render number as start char', () => { + const constrainedKey = PythonDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '1' + }); + expect(constrainedKey).toEqual('NUMBER_1'); + }); + + test('should not contain duplicate keys', () => { + const existingConstrainedEnumValueModel = new ConstrainedEnumValueModel( + 'EMPTY', + 'return', + 'return' + ); + const constrainedEnumModel = new ConstrainedEnumModel( + 'test', + undefined, + {}, + '', + [existingConstrainedEnumValueModel] + ); + const constrainedKey = PythonDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedKey).toEqual('RESERVED_EMPTY'); + }); + + test('should never contain empty keys', () => { + const constrainedKey = PythonDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: '' + }); + expect(constrainedKey).toEqual('EMPTY'); + }); + + test('should use constant naming format', () => { + const constrainedKey = PythonDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: 'some weird_value!"#2' + }); + expect(constrainedKey).toEqual( + 'SOME_WEIRD_VALUE_EXCLAMATION_QUOTATION_HASH_2' + ); + }); + + test('should never render reserved keywords', () => { + const constrainedKey = PythonDefaultConstraints.enumKey({ + enumModel, + constrainedEnumModel, + enumKey: 'return' + }); + expect(constrainedKey).toEqual('RESERVED_RETURN'); + }); + }); + + describe('enum values', () => { + test('should render value as is', () => { + const constrainedValue = PythonDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: 'string value' + }); + expect(constrainedValue).toEqual('"string value"'); + }); + + test('should render boolean values', () => { + const constrainedValue = PythonDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: true + }); + expect(constrainedValue).toEqual('"true"'); + }); + + test('should render numbers', () => { + const constrainedValue = PythonDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: 123 + }); + expect(constrainedValue).toEqual(123); + }); + + test('should render object', () => { + const constrainedValue = PythonDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: { test: 'test' } + }); + expect(constrainedValue).toEqual('"{\\"test\\":\\"test\\"}"'); + }); + + test('should render unknown value', () => { + const constrainedValue = PythonDefaultConstraints.enumValue({ + enumModel, + constrainedEnumModel, + enumValue: undefined + }); + expect(constrainedValue).toEqual(`"undefined"`); + }); + }); +}); diff --git a/test/generators/python/constrainer/ModelNameConstrainer.spec.ts b/test/generators/python/constrainer/ModelNameConstrainer.spec.ts new file mode 100644 index 0000000000..3ee47faf81 --- /dev/null +++ b/test/generators/python/constrainer/ModelNameConstrainer.spec.ts @@ -0,0 +1,76 @@ +import { PythonDefaultConstraints } from '../../../../src/generators/python/PythonConstrainer'; +import { + DefaultModelNameConstraints, + defaultModelNameConstraints, + ModelNameConstraints +} from '../../../../src/generators/python/constrainer/ModelNameConstrainer'; + +describe('ModelNameConstrainer', () => { + test('should never render special chars', () => { + const constrainedKey = PythonDefaultConstraints.modelName({ + modelName: '%' + }); + expect(constrainedKey).toEqual('Percent'); + }); + test('should never render number as start char', () => { + const constrainedKey = PythonDefaultConstraints.modelName({ + modelName: '1' + }); + expect(constrainedKey).toEqual('Number_1'); + }); + test('should never contain empty name', () => { + const constrainedKey = PythonDefaultConstraints.modelName({ + modelName: '' + }); + expect(constrainedKey).toEqual('Empty'); + }); + test('should use pascal naming format', () => { + const constrainedKey = PythonDefaultConstraints.modelName({ + modelName: 'some weird_value!"#2' + }); + expect(constrainedKey).toEqual('SomeWeirdValueExclamationQuotationHash_2'); + }); + test('should never render reserved keywords', () => { + const constrainedKey = PythonDefaultConstraints.modelName({ + modelName: 'return' + }); + expect(constrainedKey).toEqual('ReservedReturn'); + }); + describe('custom constraints', () => { + test('should be able to overwrite all hooks', () => { + const mockedConstraintCallbacks: ModelNameConstraints = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultModelNameConstraints( + mockedConstraintCallbacks + ); + constrainFunction({ modelName: '' }); + //Expect all callbacks to be called + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + test('should be able to overwrite one hooks', () => { + //All but NAMING_FORMATTER, as we customize that + const spies = [ + jest.spyOn(DefaultModelNameConstraints, 'NO_SPECIAL_CHAR'), + jest.spyOn(DefaultModelNameConstraints, 'NO_NUMBER_START_CHAR'), + jest.spyOn(DefaultModelNameConstraints, 'NO_EMPTY_VALUE'), + jest.spyOn(DefaultModelNameConstraints, 'NO_RESERVED_KEYWORDS') + ]; + const jestCallback = jest.fn().mockReturnValue(''); + const constrainFunction = defaultModelNameConstraints({ + NAMING_FORMATTER: jestCallback + }); + const constrainedValue = constrainFunction({ modelName: '' }); + expect(constrainedValue).toEqual(''); + for (const jestMockCallback of spies) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + }); +}); diff --git a/test/generators/python/constrainer/PropertyKeyConstrainer.spec.ts b/test/generators/python/constrainer/PropertyKeyConstrainer.spec.ts new file mode 100644 index 0000000000..8f3d8b83ca --- /dev/null +++ b/test/generators/python/constrainer/PropertyKeyConstrainer.spec.ts @@ -0,0 +1,183 @@ +import { PythonDefaultConstraints } from '../../../../src/generators/python/PythonConstrainer'; +import { + ConstrainedObjectModel, + ConstrainedObjectPropertyModel, + ObjectModel, + ObjectPropertyModel +} from '../../../../src'; +import { + DefaultPropertyKeyConstraints, + defaultPropertyKeyConstraints, + PropertyKeyConstraintOptions +} from '../../../../src/generators/python/constrainer/PropertyKeyConstrainer'; + +describe('PropertyKeyConstrainer', () => { + const objectModel = new ObjectModel('test', undefined, {}, {}); + const constrainedObjectModel = new ConstrainedObjectModel( + 'test', + undefined, + {}, + '', + {} + ); + + const constrainPropertyName = (propertyName: string) => { + const objectPropertyModel = new ObjectPropertyModel( + propertyName, + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + return PythonDefaultConstraints.propertyKey({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + }; + + test('should never render special chars', () => { + const constrainedKey = constrainPropertyName('%'); + expect(constrainedKey).toEqual('percent'); + }); + test('should not render number as start char', () => { + const constrainedKey = constrainPropertyName('1'); + expect(constrainedKey).toEqual('number_1'); + }); + test('should never contain empty name', () => { + const constrainedKey = constrainPropertyName(''); + expect(constrainedKey).toEqual('empty'); + }); + test('should use camel naming format', () => { + const constrainedKey = constrainPropertyName('some weird_value!"#2'); + expect(constrainedKey).toEqual('someWeirdValueExclamationQuotationHash_2'); + }); + test('should not contain duplicate properties', () => { + const objectModel = new ObjectModel('test', undefined, {}, {}); + const constrainedObjectModel = new ConstrainedObjectModel( + 'test', + undefined, + {}, + '', + {} + ); + const objectPropertyModel = new ObjectPropertyModel( + 'reservedReturn', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + 'reservedReturn', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + const objectPropertyModel2 = new ObjectPropertyModel( + 'return', + false, + objectModel + ); + const constrainedObjectPropertyModel2 = new ConstrainedObjectPropertyModel( + 'return', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + constrainedObjectModel.properties['reservedReturn'] = + constrainedObjectPropertyModel; + constrainedObjectModel.properties['return'] = + constrainedObjectPropertyModel2; + const constrainedKey = PythonDefaultConstraints.propertyKey({ + constrainedObjectModel, + objectModel, + objectPropertyModel: objectPropertyModel2, + constrainedObjectPropertyModel: constrainedObjectPropertyModel2 + }); + expect(constrainedKey).toEqual('reservedReservedReturn'); + }); + test('should never render reserved keywords', () => { + const constrainedKey = constrainPropertyName('return'); + expect(constrainedKey).toEqual('reservedReturn'); + }); + describe('custom constraints', () => { + test('should be able to overwrite all hooks', () => { + const mockedConstraintCallbacks: Partial = { + NAMING_FORMATTER: jest.fn().mockReturnValue(''), + NO_SPECIAL_CHAR: jest.fn().mockReturnValue(''), + NO_NUMBER_START_CHAR: jest.fn().mockReturnValue(''), + NO_EMPTY_VALUE: jest.fn().mockReturnValue(''), + NO_RESERVED_KEYWORDS: jest.fn().mockReturnValue('') + }; + const constrainFunction = defaultPropertyKeyConstraints( + mockedConstraintCallbacks + ); + const objectPropertyModel = new ObjectPropertyModel( + '', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + constrainFunction({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + //Expect all callbacks to be called + for (const jestMockCallback of Object.values(mockedConstraintCallbacks)) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + test('should be able to overwrite one hooks', () => { + //All but NAMING_FORMATTER, as we customize that + const spies = [ + jest.spyOn(DefaultPropertyKeyConstraints, 'NO_SPECIAL_CHAR'), + jest.spyOn(DefaultPropertyKeyConstraints, 'NO_NUMBER_START_CHAR'), + jest.spyOn(DefaultPropertyKeyConstraints, 'NO_EMPTY_VALUE'), + jest.spyOn(DefaultPropertyKeyConstraints, 'NO_RESERVED_KEYWORDS'), + jest.spyOn(DefaultPropertyKeyConstraints, 'NO_DUPLICATE_PROPERTIES') + ]; + const overwrittenDefaultFunction = jest.spyOn( + DefaultPropertyKeyConstraints, + 'NAMING_FORMATTER' + ); + const jestCallback = jest.fn().mockReturnValue(''); + const constrainFunction = defaultPropertyKeyConstraints({ + NAMING_FORMATTER: jestCallback + }); + const objectPropertyModel = new ObjectPropertyModel( + '', + false, + objectModel + ); + const constrainedObjectPropertyModel = new ConstrainedObjectPropertyModel( + '', + '', + objectPropertyModel.required, + constrainedObjectModel + ); + const constrainedValue = constrainFunction({ + constrainedObjectModel, + objectModel, + objectPropertyModel, + constrainedObjectPropertyModel + }); + expect(constrainedValue).toEqual(''); + expect(jestCallback).toHaveBeenCalled(); + expect(overwrittenDefaultFunction).not.toHaveBeenCalled(); + for (const jestMockCallback of spies) { + expect(jestMockCallback).toHaveBeenCalled(); + } + }); + }); +}); From 3df342f2ab605394da4e7878d1947778c61a7e3a Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Mon, 1 Jan 2024 10:06:13 -1000 Subject: [PATCH 31/37] docs: add devilkiller-ag as a contributor for doc, maintenance, and 4 more (#1716) * update README.md * update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 4 +++- README.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 589f0b1105..55a26a255b 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -788,7 +788,9 @@ "code", "design", "doc", - "maintenance" + "maintenance", + "test", + "review" ] }, { diff --git a/README.md b/README.md index 31d00001c2..acfe5e9928 100644 --- a/README.md +++ b/README.md @@ -415,7 +415,7 @@ Thanks go out to these wonderful people ([emoji key](https://allcontributors.org Nilkanth Parmar
    Nilkanth Parmar

    💻 ⚠️ 💡 📖 - Ashmit JaiSarita Gupta
    Ashmit JaiSarita Gupta

    💻 🎨 📖 🚧 + Ashmit JaiSarita Gupta
    Ashmit JaiSarita Gupta

    💻 🎨 📖 🚧 ⚠️ 👀 Harshil Jani
    Harshil Jani

    💻 ⚠️ Mintu Gogoi
    Mintu Gogoi

    ⚠️ Devansh Mahant
    Devansh Mahant

    📖 From e7c7418ba85fc7507e73c4f50083b0f79e673765 Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Thu, 4 Jan 2024 09:57:20 -1000 Subject: [PATCH 32/37] docs: bundle of small changes (#1720) --- README.md | 2 +- docs/README.md | 8 +++++--- docs/advanced.md | 7 ++++++- docs/constraints/README.md | 6 +++++- docs/languages/Cplusplus.md | 8 ++++---- docs/languages/Csharp.md | 7 +++++-- docs/languages/Go.md | 25 ++++++++++++++++++++++++- docs/languages/Kotlin.md | 12 +++++++----- docs/languages/Php.md | 7 +++++++ docs/languages/Scala.md | 2 +- docs/usage.md | 2 +- modelina-website/scripts/build-docs.js | 4 +++- 12 files changed, 69 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index acfe5e9928..986614fc60 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ The following table provides a short summary of available features for supported We support the following JSON Schema versions: Draft-4, Draft-6 and Draft-7 - OpenAPI + OpenAPI We support the following OpenAPI versions: Swagger 2.0 and OpenAPI 3.0, which generates models for all the defined request and response payloads. diff --git a/docs/README.md b/docs/README.md index 83b34f3286..5b194699bd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -63,13 +63,15 @@ No one wants to read the code to find information about it, instead use the [/ap ### Languages Each language has its own limitations, corner cases, and features; thus, each language has separate documentation. +- [C++](./languages/Cplusplus.md) - [C#](./languages/Csharp.md) - [Dart](./languages/Dart.md) - [Go](./languages/Go.md) - [Java](./languages/Java.md) - [JavaScript](./languages/JavaScript.md) -- [Rust](./languages/Rust.md) +- [Kotlin](./languages/Kotlin.md) +- [PHP](./languages/Php.md) - [Python](./languages/Python.md) +- [Rust](./languages/Rust.md) +- [Scala](./languages/Scala.md) - [TypeScript](./languages/TypeScript.md) -- [Kotlin](./languages/Kotlin.md) -- [C++](./languages/Cplusplus.md) diff --git a/docs/advanced.md b/docs/advanced.md index c94b68aeba..c15cf124f8 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -47,12 +47,17 @@ Check out this [example out for a live demonstration](../examples/include-custom One of the primary use-cases for the generated models, is to serialize and deserilize it to for example JSON, XML or binary. Each generator can have multiple ways to achieve this, and even support multiple libraries. This is achieved through presets, you can find them here for each output: +- [C++](./languages/Cplusplus.md#generate-serializer-and-deserializer-functionality) - [C#](./languages/Csharp.md#generate-serializer-and-deserializer-functionality) - [Dart](./languages/Dart.md#generate-serializer-and-deserializer-functionality) -- Go currently does not support this. +- [Go](./languages/Go.md#generate-serializer-and-deserializer-functionality) - [Java](./languages/Java.md#generate-serializer-and-deserializer-functionality) - [JavaScript](./languages/JavaScript.md#generate-serializer-and-deserializer-functionality) +- [Kotlin](./languages/Kotlin.md#generate-serializer-and-deserializer-functionality) +- [PHP](./languages/Php.md#generate-serializer-and-deserializer-functionality) +- [Python](./languages/Python.md#generate-serializer-and-deserializer-functionality) - [Rust](./languages/Rust.md) +- [Scala](./languages/Scala.md#generate-serializer-and-deserializer-functionality) - [TypeScript](./languages/TypeScript.md#generate-serializer-and-deserializer-functionality) ## Adapting input and outputs diff --git a/docs/constraints/README.md b/docs/constraints/README.md index 5d52fc4841..7db869a3b8 100644 --- a/docs/constraints/README.md +++ b/docs/constraints/README.md @@ -16,14 +16,18 @@ class 1name {} There are many rules as such, but to get the full description about the default constraints here: +- [C++](./constraints/Csplusplus.md) - [C#](./constraints/CSharp.md) - [Dart](./constraints/Dart.md) - [Go](./constraints/Go.md) - [Java](./constraints/Java.md) - [JavaScript](./constraints/JavaScript.md) +- [Kotlin](./constraints/Kotlin.md) +- [PHP](./constraints/PHP.md) +- [Python](./constraints/Python.md) - [Rust](./constraints/Rust.md) +- [Scala](./constraints/Scala.md) - [TypeScript](./constraints/TypeScript.md) -- [Python](./constraints/Python.md) Even though there are many of these constraints, there might be reasons you want to customize the behavior to make it suit your use-case. Therefore each of the constraint rules can be overwritten completely and allow for you to implement your own behavior. diff --git a/docs/languages/Cplusplus.md b/docs/languages/Cplusplus.md index a3f08057b1..ce51094a89 100644 --- a/docs/languages/Cplusplus.md +++ b/docs/languages/Cplusplus.md @@ -1,10 +1,6 @@ # C++ There are special use-cases that each language supports; this document pertains to **C++ models**. -Limitations: -- We use v17 of C++ as our baseline. -- Circular models are not supported. - @@ -16,6 +12,10 @@ Limitations: +Current limitations of C++: +- We use v17 of C++ as our baseline. +- Circular models are not supported. + ## Generate serializer and deserializer functionality The most widely used usecase for Modelina is to generate models that include serialization and deserialization functionality to convert the models into payload data. This payload data can of course be many different kinds, JSON, XML, raw binary, you name it. diff --git a/docs/languages/Csharp.md b/docs/languages/Csharp.md index 7015ff91bd..965735b8c1 100644 --- a/docs/languages/Csharp.md +++ b/docs/languages/Csharp.md @@ -87,11 +87,14 @@ Check out this [example for a live demonstration](../../examples/csharp-overwrit If you want the generated models to inherit from a custom class, you can overwrite the existing rendering behavior and create your own class setup. +Check out this [example for a live demonstration](../../examples/csharp-generate-json-serializer). + + ## Generate models as records Since C# 9 the language now supports records as an alternative to classes suitable for roles like DTO's. Modelina can generate records by setting the `modelType: record` option. Note that this renderer does not support the `autoImplementedProperties` option as this is default with records. -Check out this [example for a live demonstration](../../examples/csharp-generate-records). +Check out this [example for a live demonstration](../../examples/csharp-use-inheritance). ## Generate code that handles nullable mode @@ -106,4 +109,4 @@ This is the most asked questions and answers which should be your GOTO list to c ### Why is the type `dynamic` or `dynamic[]` when it should be `X`? Often times you might encounter variables which as of type `dynamic` or `dynamic[]`, which is our fallback type when we cannot accurately find the right type. -**If you are encountering this when your input is JSON Schema/OpenAPI/AsyncAPI**, it most likely is because of a property being defined as having multiple types as a union, which the C# generator cannot natively handle and fallback to `dynamic`. For arrays, you have to remember that `additionalItems` is by default `true`, this means that even though you use `items: { type: "string"}` by not setting `additionalItems: false`, it's the same as setting `items: { type: ["array", "boolean", "integer", "null", "number", "object", "string"]}`. \ No newline at end of file +**If you are encountering this when your input is JSON Schema/OpenAPI/AsyncAPI**, it most likely is because of a property being defined as having multiple types as a union, which the C# generator cannot natively handle and fallback to `dynamic`. \ No newline at end of file diff --git a/docs/languages/Go.md b/docs/languages/Go.md index 7b15f3e5d3..7cfa209ce8 100644 --- a/docs/languages/Go.md +++ b/docs/languages/Go.md @@ -1,4 +1,27 @@ # Go There are special use-cases that each language supports; this document pertains to **Go models**. -At the moment, Go models have no specific features. + + + +- [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality) + * [To and from JSON](#to-and-from-json) + * [To and from XML](#to-and-from-xml) + * [To and from binary](#to-and-from-binary) + + + +## Generate serializer and deserializer functionality + +The most widely used usecase for Modelina is to generate models that include serialization and deserialization functionality to convert the models into payload data. This payload data can of course be many different kinds, JSON, XML, raw binary, you name it. + +As you normally only need one library to do this, we developers can never get enough with creating new stuff, therefore there might be one specific library you need or want to integrate with. Therefore there is not one specific preset that offers everything. Below is a list of all the supported serialization presets. + +### To and from JSON +Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! + +### To and from XML +Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! + +### To and from binary +Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! diff --git a/docs/languages/Kotlin.md b/docs/languages/Kotlin.md index 57fcbc66b0..093acb12ae 100644 --- a/docs/languages/Kotlin.md +++ b/docs/languages/Kotlin.md @@ -1,11 +1,11 @@ # Kotlin -There are special use-cases that each language supports; this document pertains to **Kotlin models**. +There are special use cases that each language supports; this document pertains to **Kotlin models**. -Since `data classes` are used for every model that has got properties, there is no need for additional settings or +Since `data classes` are used for every model that has properties, there is no need for additional settings or features to generate `toString()`, `equals()`, `hashCode()`, getters or setters. -Classes without properties are depicted by usual `classes`, they get no `toString()`, `equals()` or `hashCode()` +Classes without properties are depicted by usual `classes`, they get no `toString()`, `equals()`, or `hashCode()` implementation. The default one should suffice here. @@ -28,7 +28,7 @@ Check out this [example for a live demonstration](../../examples/kotlin-generate ## Change the collection type for arrays -Sometimes, we might want to render a different collection type, and instead of the default `Array` use as `List` type. To do so, provide the option `collectionType: 'List'`. +Sometimes, we might want to render a different collection type, and instead of the default `Array` use it as a `List` type. To do so, provide the option `collectionType: 'List'`. Check out this [example for a live demonstration](../../examples/kotlin-change-collection-type). @@ -40,13 +40,15 @@ Check out this [example for a live demonstration](../../examples/kotlin-generate ## Generate serializer and deserializer functionality -The most widely used usecase for Modelina is to generate models that include serialization and deserialization functionality to convert the models into payload data. This payload data can of course be many kinds, JSON, XML, raw binary, you name it. +The most widely used use case for Modelina is to generate models that include serialization and deserialization functionality to convert the models into payload data. This payload data can of course be many kinds, JSON, XML, raw binary, you name it. As you normally only need one library to do this, we developers can never get enough with creating new stuff, therefore there might be one specific library you need or want to integrate with. Therefore, there is not one specific preset that offers everything. Below is a list of all the supported serialization presets. ### To and from JSON Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! + ### To and from XML Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! + ### To and from binary Currently not supported, [let everyone know you need it](https://github.com/asyncapi/modelina/issues/new?assignees=&labels=enhancement&template=enhancement.md)! diff --git a/docs/languages/Php.md b/docs/languages/Php.md index d69b3b5fa4..1c7b6a739c 100644 --- a/docs/languages/Php.md +++ b/docs/languages/Php.md @@ -8,6 +8,7 @@ There are special use-cases that each language supports; this document pertains - [Description Present](#description-present) - [Generate serializer and deserializer functionality](#generate-serializer-and-deserializer-functionality) * [To and from JSON](#to-and-from-json) + + [Generate json_encode function](#generate-json_encode-function) * [To and from XML](#to-and-from-xml) * [To and from binary](#to-and-from-binary) @@ -29,6 +30,12 @@ Therefore, there is not one specific preset that offers everything. Below is a l ### To and from JSON +Here are all the supported presets and the libraries they use for converting to and from JSON: + +- [Generate json_encode function](#generate-json_encode-function) + +#### Generate json_encode function + Objects in PHP can generally be serialized to JSON using the [`json_encode()` function](https://www.php.net/manual/en/function.json-encode.php). To ensure that the data is serialized correctly, the [`JsonSerializable` interface](https://www.php.net/manual/en/class.jsonserializable.php) needs to be implemented. This will ensure that, for example, enum values and property names are serialized correctly. diff --git a/docs/languages/Scala.md b/docs/languages/Scala.md index 249be7b0df..01c893474b 100644 --- a/docs/languages/Scala.md +++ b/docs/languages/Scala.md @@ -18,7 +18,7 @@ There are special use-cases that each language supports; this document pertains By default, descriptions are not rendered for the model; you can change that by applying `SCALA_DESCRIPTION_PRESET`. -Check out this [example for a live demonstration](../../examples/php-generate-documentation-preset). +Check out this [example for a live demonstration](../../examples/scala-generate-documentation). ## Generate serializer and deserializer functionality diff --git a/docs/usage.md b/docs/usage.md index 4862187807..d0699d77ec 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -124,7 +124,7 @@ These are the current known limitation of the Swagger 2.0 input. Through the Swagger 2.0 Schema you are able to use `discriminator` for achieving polymorphism. Current version of Modelina does not generate the expected inheritance of models, instead it's current behavior is to [merge the schemas together](./inputs/JSON_Schema.md#processing-sub-schemas). This means you will still get access to the properties that missing inherited model has, but without the inheritance. -Long term if this is something you wish was supported, voice your [opionion here](https://github.com/asyncapi/modelina/issues/108). +Long term if this is something you wish was supported, voice your [opinion here](https://github.com/asyncapi/modelina/issues/108). ## Generate models from OpenAPI documents diff --git a/modelina-website/scripts/build-docs.js b/modelina-website/scripts/build-docs.js index c434dcea43..55b44803f1 100644 --- a/modelina-website/scripts/build-docs.js +++ b/modelina-website/scripts/build-docs.js @@ -23,7 +23,9 @@ function prepareContent(content) { // Use correct example links content = content.replace(/\]\((.*?)examples\/(.*?)\/?\)/g, '](/examples?selectedExample=$2)'); - + content = content.replace('/examples?selectedExample=integrate-with-react', 'https://github.com/asyncapi/modelina/tree/master/examples/integrate-with-react'); + content = content.replace('/examples?selectedExample=integrate-with-next', 'https://github.com/asyncapi/modelina/tree/master/examples/integrate-with-next'); + content = content.replace('/examples?selectedExample=integrate-with-maven', 'https://github.com/asyncapi/modelina/tree/master/examples/integrate-with-maven'); // Replace all references to local images for docs content = content.replace(/"(.*?)\/img\/(.*?)"/g, '"/img/docs/img/$2"'); From 89a0f6e21866f71160136f0f52eb0efea532131a Mon Sep 17 00:00:00 2001 From: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> Date: Sat, 6 Jan 2024 20:43:26 +0530 Subject: [PATCH 33/37] docs: updated footer with heart emoji (#1728) --- modelina-website/src/components/layouts/Footer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modelina-website/src/components/layouts/Footer.tsx b/modelina-website/src/components/layouts/Footer.tsx index a9bdd37231..c775289a6c 100644 --- a/modelina-website/src/components/layouts/Footer.tsx +++ b/modelina-website/src/components/layouts/Footer.tsx @@ -225,7 +225,7 @@ export default function Footer() {

    Made with{' '} - :love: by + ❤️ by the AsyncAPI Initiative.

    From e4c4d6cd532e569934a1adee365eea6d55461614 Mon Sep 17 00:00:00 2001 From: Asish Kumar <87874775+officialasishkumar@users.noreply.github.com> Date: Wed, 10 Jan 2024 00:36:19 +0530 Subject: [PATCH 34/37] docs: fixed highlight in docs (#1721) Co-authored-by: Jonas Lagoni --- modelina-website/src/components/docs/Docs.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modelina-website/src/components/docs/Docs.tsx b/modelina-website/src/components/docs/Docs.tsx index a8545fb8a5..69d00a95f4 100644 --- a/modelina-website/src/components/docs/Docs.tsx +++ b/modelina-website/src/components/docs/Docs.tsx @@ -25,7 +25,7 @@ const Docs: React.FC = ({ source, slug, router }) => { * Render the menu items dynamically in a depth first approach */ const renderMenuTree = (value: any, isRoot: boolean) => { - const isSelected = value.slug === `/docs/${slug}`; + const isSelected = value.slug === `${slug}`; if (value.type === 'dir') { const hasRootReadme = value.content !== null; let headerReadme; @@ -33,7 +33,7 @@ const Docs: React.FC = ({ source, slug, router }) => { headerReadme = (

  • { setShowMenu(false); }} @@ -59,7 +59,7 @@ const Docs: React.FC = ({ source, slug, router }) => { return (
  • { setShowMenu(false); }} From 073c79534b7d5d2b0d19f2bdcb77533e0567e4b1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 06:18:17 +0100 Subject: [PATCH 35/37] chore(deps): bump follow-redirects from 1.15.1 to 1.15.4 in /examples/integrate-with-react (#1736) --- examples/integrate-with-react/package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/integrate-with-react/package-lock.json b/examples/integrate-with-react/package-lock.json index 66ed57fe46..c76cbf6176 100644 --- a/examples/integrate-with-react/package-lock.json +++ b/examples/integrate-with-react/package-lock.json @@ -7555,9 +7555,9 @@ "integrity": "sha512-0sQoMh9s0BYsm+12Huy/rkKxVu4R1+r96YX5cG44rHV0pQ6iC3Q+mkoMFaGWObMFYQxCVT+ssG1ksneA2MI9KQ==" }, "node_modules/follow-redirects": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", - "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==", + "version": "1.15.4", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", + "integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==", "funding": [ { "type": "individual", @@ -21258,9 +21258,9 @@ "integrity": "sha512-0sQoMh9s0BYsm+12Huy/rkKxVu4R1+r96YX5cG44rHV0pQ6iC3Q+mkoMFaGWObMFYQxCVT+ssG1ksneA2MI9KQ==" }, "follow-redirects": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", - "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==" + "version": "1.15.4", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.4.tgz", + "integrity": "sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw==" }, "fork-ts-checker-webpack-plugin": { "version": "6.5.2", From 2358a96ff932bd9373468a7e0380022f9b7d205a Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Thu, 11 Jan 2024 11:57:50 -1000 Subject: [PATCH 36/37] chore: fix linting --- src/generators/python/presets/Pydantic.ts | 2 +- .../cplusplus/constrainer/PropertyKeyConstrainer.spec.ts | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/generators/python/presets/Pydantic.ts b/src/generators/python/presets/Pydantic.ts index 747086457e..39e2b7f052 100644 --- a/src/generators/python/presets/Pydantic.ts +++ b/src/generators/python/presets/Pydantic.ts @@ -21,7 +21,7 @@ const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType = { property(params) { let type = params.property.property.type; const propertyName = params.property.propertyName; - + if (params.property.property instanceof ConstrainedUnionModel) { const unionTypes = params.property.property.union.map( (unionModel) => unionModel.type diff --git a/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts b/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts index d4126c7829..994b3d6b57 100644 --- a/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts +++ b/test/generators/cplusplus/constrainer/PropertyKeyConstrainer.spec.ts @@ -1,4 +1,3 @@ -import { CplusplusDefaultConstraints } from '../../../../src/generators/cplusplus/CplusplusConstrainer'; import { ConstrainedObjectModel, ConstrainedObjectPropertyModel, @@ -6,7 +5,6 @@ import { ObjectPropertyModel } from '../../../../src'; import { - DefaultPropertyKeyConstraints, PropertyKeyConstraintOptions, defaultPropertyKeyConstraints } from '../../../../src/generators/cplusplus/constrainer/PropertyKeyConstrainer'; From 1d30ddaf3f0cda8d640498304c12a2d27e54d9ed Mon Sep 17 00:00:00 2001 From: Jonas Lagoni Date: Thu, 11 Jan 2024 12:09:43 -1000 Subject: [PATCH 37/37] chore: remove unused directory --- .../com/mycompany/app/AnonymousSchema_1.class | Bin 941 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 examples/integrate-modelina-into-maven/maven-project/target/classes/com/mycompany/app/AnonymousSchema_1.class diff --git a/examples/integrate-modelina-into-maven/maven-project/target/classes/com/mycompany/app/AnonymousSchema_1.class b/examples/integrate-modelina-into-maven/maven-project/target/classes/com/mycompany/app/AnonymousSchema_1.class deleted file mode 100644 index 1f54842c8e7c92d8d7ea128dd20099c390fa7ef7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 941 zcmb7CT~8B16g{*3*tV{M2nc>Fm=rWjOo$I^jD%={*%U*yuVlK6W$NxsvolNVztTiw z;)6fHA7#ALR#0mqyxfnObLQTA?tK68^&5aqtcC~}RuYr(Y)Ez>^pK0efNyD|hnXpC zJ2{k@*nbeB%rM&*M}nt9_xNtNFB8X5p<9(Q%*7{nZI>(Ed(5!BS7@g)*-=(?Q@N$J zal$F1Ed!5z)wjYrnZM6c-WSO`YcvoAnJ&4Fy7go_c*;{wA>th8(uSy$$-1qgrY zc_LpZ-{0cYjyL=Y8KNDnWxkyXYo!fwi(&IrtD5NcOTQ3z81A2i$q-K7z-=0=L|>F4 z@Y9hGDO;qhMseNJVZ#R!=MWK+`7My0ArvRi$XC|CVD=*g0p`g1M}RUek&VUx%wvHv z(gK&s{z?9Xr4MxZJGuT(@)ca2kRK5`AWn7t-e)ZRUAi%1`x$&QYh OAn%8}Nh+*7TmA`AD&%+o