@cap-js/cds-typer 0.2.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,43 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ This project adheres to [Semantic Versioning](http://semver.org/).
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/).
6
+
7
+
8
+ ## Version 0.2.5-beta.1 - 2023-06-13
9
+
10
+ ### Changed
11
+
12
+ - Bump version
13
+
14
+ ## Version 0.2.4 - 2023-06-12
15
+ - Enable use of annotated singular/ plural names in associations/ compositions
16
+ - Rename package from `@sap/cds-dts-generator` to `@cap-js/cds-typer`
17
+
18
+ ## Version 0.2.3 - 2023-05-17
19
+ - Add missing library files
20
+
21
+ ## Version 0.2.2 - 2023-05-17
22
+ - Make class hierarchy flatter
23
+
24
+ ## Version 0.2.1 - 2023-05-16
25
+ - Add missing files
26
+
27
+ ## Version 0.2.0 - 2023-05-15
28
+ - use native Typescript AST in unit tests
29
+ - add `propertiesOptional` flag
30
+ - support flat, as well as nested inline declarations
31
+ - support `typeof` syntax
32
+ - read rudimentary configuration from cds.env
33
+ - export bound and unbound actions
34
+ - allow inline type definitions within compositions
35
+ - enable use of additional type libraries (HANA types available as first library)
36
+ - provide proper JSDoc for all modules
37
+ - export entity types for singular variants alongside plural types
38
+ ## Version 0.1.1 - 2023-01-26
39
+ - add TL;DR section to README
40
+ - allow multiple positional arguments
41
+
42
+ ## Version 0.1.0
43
+ - initial code base
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,192 @@
1
+ # CDS type generator for JavaScript
2
+
3
+ ## About this project
4
+
5
+ Generates `.ts` files for a CDS model to receive code completion in VS Code.
6
+
7
+
8
+ ## Requirements and Setup
9
+
10
+
11
+ ### Building the Project Yourself
12
+ Clone the repository and install the dependencies running `npm i` from the project's root directory.
13
+
14
+
15
+ ### Usage
16
+ The type generator is currently meant as a standalone tool and can be installed and used independently of other CDS environments (sans its dependency to the cds compiler).
17
+
18
+ #### Quickstart
19
+ Assuming you have the following CDS project structure:
20
+
21
+ ```
22
+ /home/
23
+ ├── mybookshop/
24
+ │ ├── db/
25
+ │ │ └── schema.cds
26
+ │ ├── srv/
27
+ │ │ └── service.js
28
+ ```
29
+
30
+ a typical workflow to generate types for your CDS project could look something like this:
31
+
32
+ ```sh
33
+ git clone https://this/repo cds-js-type-generator
34
+ cd cds-js-type-generator
35
+ npm i
36
+ node ./index.js \
37
+ --rootDir /home/mybookshop/@types \
38
+ --jsConfigPath /home/mybookshop \
39
+ /home/mybookshop/srv/schema.cds
40
+ ```
41
+
42
+ You would then end up with a `jsconfig.json` file in the project's root and a directory `@types`, which contains your entities and their accompanying types in a directory structure. The directory structure directly reflects the namespaces you have defined your entities in. They have to be imported in any JavaScript-based service handlers you want to have type support in and can replace calls to `cds.entities(...)`:
43
+
44
+ ```js
45
+ // srv/service.js
46
+ const { Books } = require('my.bookshop')
47
+
48
+ ```
49
+
50
+ becomes
51
+
52
+ ```js
53
+ // srv/service.js
54
+
55
+ const { Books } = require('../@types/mybookshop')
56
+ ```
57
+
58
+ From that point on you should receive code completion from the type system for `Books`.
59
+
60
+ #### CLI
61
+ _cds-typer_ comes with rudimentary CLI support and a few command line options:
62
+
63
+ - `--help`: prints all available parameters.
64
+ - `--rootDir`: specifies the root directory where all generated files should be put. Defaults to the CWD.
65
+ - `--jsConfigPath`: specifies the path to the `jsconfig.json` file to generate. Usually your project's root directory. If specified, a config file is created that restricts the usage of types even further:
66
+
67
+ ```js
68
+ // generated .ts file
69
+ class Book {
70
+ title: string;
71
+ }
72
+
73
+ // some hook in your service
74
+ SELECT(Books, b => {
75
+ b.title // 👍 no problem, property exists
76
+ b.numberOfPages // ❌ property does not exist
77
+ })
78
+ ```
79
+ With the generated config in place, the language server will display an error, telling you that `numberOfPages` does not exist in this context. Without the config it would just infer it as `any`.
80
+
81
+ - `--loglevel`: minimum log level that should be printed. Defaults to `NONE`. Available log levels roughly follow [Microsoft's dotnet log levels](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel?view=dotnet-plat-ext-6.0):
82
+
83
+ ```
84
+ TRACE
85
+ DEBUG
86
+ INFO
87
+ WARNING
88
+ ERROR
89
+ CRITICAL
90
+ NONE
91
+ ```
92
+
93
+ The utility expects (at least) one path to a `.cds` file as positional parameter which serves as entry point to the model in question, e.g.:
94
+
95
+ ```sh
96
+ cds-typer ./path/to/my/model/model.cds --rootDir /tmp/
97
+ ```
98
+
99
+ Note that you can also pass multiple paths or `"*"` as glob pattern (with quotes to circumvent expansion by the shell). This passes the pattern on to the compiler where the [regular resolve strategy](https://cap.cloud.sap/docs/node.js/cds-compile?q=compiler#cds-resolve) is used.
100
+
101
+ #### Programmatically
102
+ The main API for using _cds-typer_ within another project is contained in [`compile.js`](https://github.tools.sap/cap/cds-typer/blob/master/lib/compile.js), specifically:
103
+
104
+ - `compileFromFile(…)` to parse a `.cds` file. This involves compiling it to CSN first.
105
+ - `compileFromCSN(…)` to directly compile from CSN object. This is useful when you already have your CSN available as part of a tool chain. ⚠️ **WARNING**: the application of `cdstyper` may be impure, meaning that it _could_ alter the provided CSN. If you use the typer this way, you may want to apply it as last step of your tool chain.
106
+
107
+
108
+ ### Features
109
+ #### Plural Types
110
+ While CDS encourages the use of plural form for defined entities, their OOP equivalent classes are usually named in singular. _cds-typer_ automatically transforms entity names to singular and adds the plural form for arrays:
111
+
112
+ ```cds
113
+ entity Books : cuid {
114
+
115
+ }
116
+ ```
117
+
118
+ becomes
119
+
120
+ ```ts
121
+ class Book {
122
+
123
+ }
124
+
125
+ class Books extends Array<Book> {}
126
+ ```
127
+
128
+ If you need to customise the singular or plural form, or if your entities are already in singular form, you can do so using annotations:
129
+
130
+ ```cds
131
+ @singular: 'Mouse'
132
+ entity Mice {}
133
+
134
+ @plural: 'SomeListList'
135
+ entity SomeList {}
136
+ ```
137
+
138
+ results in
139
+
140
+ ```ts
141
+ class Mouse { … }
142
+ class Mice extends Array<Mouse> { … }
143
+
144
+ class SomeList { … }
145
+ class SomeListList extends Array<SomeList> { … }
146
+ ```
147
+
148
+ ### Relation to _cds2types_
149
+ This project is inspired by the existing [_cds2types_](https://github.com/mrbandler/cds2types), but differs in a few aspects:
150
+
151
+ #### Reworked Imports
152
+ Instead of one monolithic `.d.ts` file containing all entities in nested namespaces, multiple files are generated where each namespace is represented by a directory structure. This facilicates simpler imports in a more Java-esque style:
153
+
154
+ ```js
155
+ const types = require('./cds2types/compiled.d.ts')
156
+
157
+ console.log(types.sap.cap.bookshop.Books) // a class
158
+ ```
159
+
160
+ becomes
161
+
162
+ ```js
163
+ const { Books } = require('./cds-typer/sap/cap/bookshop')
164
+
165
+ console.log(Books) // the same class
166
+ ```
167
+
168
+ #### Usable in Javascript Projects
169
+ Generated code is usable from within plain Javascript projects. The code generated by _cds2types_ would represent each cds-entity as an interface, which are not visible to Javascript projects. _cds-typer_ uses classes instead.
170
+
171
+ #### Faster
172
+ _cds2types_ takes a detour to create a Typescript AST first and then print out the formatted source files. _cds-typer_ directly walks the linked CSN and creates strings on the fly. Also, file operations are `async`. These two changes speed up _cds-typer_ by around one to two orders of magnitude compared to _cds2types_.
173
+
174
+ #### Small Footprint
175
+ _cds-typer_ tries to keep its dependency footprint as small as possible. Libraries like `typescript` are only needed as dev dependencies.
176
+
177
+
178
+
179
+
180
+
181
+
182
+ ## Support, Feedback, Contributing
183
+
184
+ This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/SAP/cds-dts-generator/issues). Contribution and feedback are encouraged and always welcome. For more information about how to contribute, the project structure, as well as additional contribution information, see our [Contribution Guidelines](CONTRIBUTING.md).
185
+
186
+ ## Code of Conduct
187
+
188
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone. By participating in this project, you agree to abide by its [Code of Conduct](CODE_OF_CONDUCT.md) at all times.
189
+
190
+ ## Licensing
191
+
192
+ Copyright 2022-2022 SAP SE or an SAP affiliate company and cds-dts-generator contributors. Please see our [LICENSE](LICENSE) for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available [via the REUSE tool](https://api.reuse.software/info/github.com/SAP/cds-dts-generator).
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ const compile = require('./lib/compile')
2
+
3
+ module.exports = {
4
+ compile
5
+ }
package/lib/cli.js ADDED
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable no-console */
3
+ 'use strict'
4
+
5
+ const { compileFromFile } = require('./compile')
6
+ const { parseCommandlineArgs } = require('./util')
7
+ const { Levels } = require('./logging')
8
+ const path = require('path')
9
+
10
+ const toolName = 'cds-typer'
11
+
12
+ const flags = {
13
+ // FIXME: remove asap
14
+ rootDir: {
15
+ desc: '[DEPRICATED] use outputDirectory instead',
16
+ default: './',
17
+ },
18
+ outputDirectory: {
19
+ desc: 'root directory to write generated files to',
20
+ default: './',
21
+ },
22
+ help: {
23
+ desc: 'this text',
24
+ },
25
+ logLevel: {
26
+ desc: `minimum log level`,
27
+ allowed: Object.keys(Levels),
28
+ default: Object.keys(Levels).at(-1),
29
+ },
30
+ jsConfigPath: {
31
+ desc: `Path to where the jsconfig.json should be written. If specified, ${toolName} will create a jsconfig.json file and set it up to restrict property usage in types entities to existing properties only.`,
32
+ },
33
+ version: {
34
+ desc: 'prints the version of this tool'
35
+ },
36
+ inlineDeclarations: {
37
+ desc: 'whether to resolve inline type declarations flat (x_a, x_b, ...) or structured (x: {a, b})',
38
+ allowed: ['flat', 'structured'],
39
+ default: 'structured'
40
+ },
41
+ propertiesOptional: {
42
+ desc: 'if set to true, properties in entities are always generated as optional (a?: T)',
43
+ allowed: ['true', 'false'],
44
+ default: 'true'
45
+ }
46
+ }
47
+
48
+ const hint = () => console.log('Missing or invalid parameter(s). Call with --help for more details.')
49
+
50
+ const help = () =>
51
+ console.log(
52
+ '[SYNOPSIS]\n' +
53
+ 'Call with at least one positional parameter pointing to the (root) CDS file you want to compile.\n' +
54
+ 'Additionaly, you can use the following parameters:\n' +
55
+ Object.entries(flags)
56
+ .sort()
57
+ .map(([key, value]) => {
58
+ let s = `--${key}: ${value.desc}`
59
+ if (value.allowed) {
60
+ s += ` [allowed: ${value.allowed.join(' | ')}]`
61
+ }
62
+ if (value.default) {
63
+ s += ` (default: ${value.default})`
64
+ }
65
+ return s
66
+ }
67
+ ).join('\n\n')
68
+ )
69
+
70
+ const version = () => console.log(require('../package.json').version)
71
+
72
+ const main = async (args) => {
73
+ if ('help' in args.named) {
74
+ help()
75
+ process.exit(0)
76
+ }
77
+ if ('version' in args.named) {
78
+ version()
79
+ process.exit(0)
80
+ }
81
+ if (args.positional.length === 0) {
82
+ hint()
83
+ process.exit(1)
84
+ }
85
+ if (args.named.jsConfigPath && !args.named.jsConfigPath.endsWith('jsconfig.json')) {
86
+ args.named.jsConfigPath = path.join(args.named.jsConfigPath, 'jsconfig.json')
87
+ }
88
+ compileFromFile(args.positional, {
89
+ // temporary fix until rootDir is faded out
90
+ outputDirectory: [args.named.outputDirectory, args.named.rootDir].find(d => d !== './') ?? './',
91
+ logLevel: Levels[args.named.logLevel],
92
+ jsConfigPath: args.named.jsConfigPath,
93
+ inlineDeclarations: args.named.inlineDeclarations,
94
+ propertiesOptional: args.named.propertiesOptional === 'true'
95
+ })
96
+ }
97
+
98
+ if (require.main === module) {
99
+ main(parseCommandlineArgs(process.argv.slice(2), flags))
100
+ }