@cap-js/cds-typer 0.24.0 → 0.26.0
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 +28 -2
- package/README.md +19 -0
- package/lib/cli.js +30 -14
- package/lib/compile.js +3 -3
- package/lib/components/enum.js +19 -10
- package/lib/components/identifier.js +1 -1
- package/lib/components/inline.js +81 -26
- package/lib/components/javascript.js +28 -0
- package/lib/components/property.js +12 -0
- package/lib/components/wrappers.js +27 -4
- package/lib/csn.js +90 -26
- package/lib/file.js +166 -44
- package/lib/logging.js +5 -1
- package/lib/resolution/builtin.js +3 -2
- package/lib/resolution/entity.js +46 -7
- package/lib/resolution/resolver.js +60 -20
- package/lib/typedefs.d.ts +83 -13
- package/lib/util.js +4 -3
- package/lib/visitor.js +199 -79
- package/package.json +10 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,31 @@ All notable changes to this project will be documented in this file.
|
|
|
4
4
|
This project adheres to [Semantic Versioning](http://semver.org/).
|
|
5
5
|
The format is based on [Keep a Changelog](http://keepachangelog.com/).
|
|
6
6
|
|
|
7
|
-
## Version 0.
|
|
7
|
+
## Version 0.27.0 - TBD
|
|
8
|
+
|
|
9
|
+
## Version 0.26.0 - 2024-09-11
|
|
10
|
+
### Added
|
|
11
|
+
- Added a CLI option `--useEntitiesProxy`. When set to `true`, all entities are wrapped into `Proxy` objects during runtime, allowing top level imports of entity types.
|
|
12
|
+
- Added a static `.kind` property for entities and types, which contains `'entity'` or `'type'` respectively
|
|
13
|
+
- Apps need to provide `@sap/cds` version `8.2` or higher.
|
|
14
|
+
- Apps need to provide `@cap-js/cds-types` version `0.6.4` or higher.
|
|
15
|
+
- Typed methods are now generated for calls of unbound actions. Named and positional call styles are supported, e.g. `service.action({one, two})` and `service.action(one, two)`.
|
|
16
|
+
- Action parameters can be optional in the named call style (`service.action({one:1, ...})`).
|
|
17
|
+
- Actions for ABAP RFC modules cannot be called with positional parameters, but only with named ones. They have 'parameter categories' (import/export/changing/tables) that cannot be called in a flat order.
|
|
18
|
+
- Services now have their own export (named like the service itself). The current default export is not usable in some scenarios from CommonJS modules.
|
|
19
|
+
- Enums and operation parameters can have doc comments
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## Version 0.25.0 - 2024-08-13
|
|
23
|
+
### Added
|
|
24
|
+
- Declaring a type alias on an enum in cds now also exports it on value level in the resulting type
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
- Classes representing views and projections will no longer carry ancestry to avoid clashes thereof with aliases fields
|
|
28
|
+
|
|
29
|
+
### Changed
|
|
30
|
+
- All properties are now preceeded with the `declare` modifier to pass strict tsconfigs using `useDefineForClassFields` or `noImplicitOverride`
|
|
31
|
+
- The static `actions` property of generated classes now includes the types from all inherited classes to also suggest actions defined in a base entity/aspect/type.
|
|
8
32
|
|
|
9
33
|
## Version 0.24.0 - 2024-07-18
|
|
10
34
|
### Fixed
|
|
@@ -16,10 +40,12 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/).
|
|
|
16
40
|
- The TypeScript task for `cds build` no longer looks for tsconfig.json to determine if the project has TS nature and instead checks the dependencies in the project's package.json for an occurrence of `typescript`
|
|
17
41
|
|
|
18
42
|
## Version 0.23.0 - 2024-07-04
|
|
43
|
+
|
|
19
44
|
### Fixed
|
|
20
45
|
- Plurals no longer have `is_singular` attached in the resulting .js files
|
|
21
46
|
- Properties are properly propagated beyond just one level of inheritance
|
|
22
47
|
|
|
48
|
+
|
|
23
49
|
## Version 0.22.0 - 2024-06-20
|
|
24
50
|
### Fixed
|
|
25
51
|
- Fixed a bug where keys would sometimes inconsistently become nullable
|
|
@@ -72,7 +98,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/).
|
|
|
72
98
|
- Importing an enum into a service will now generate an alias to the original enum, instead of incorrectly duplicating the definition
|
|
73
99
|
- Returning entities from actions/ functions and using them as parameters will now properly use the singular inflection instead of returning an array thereof
|
|
74
100
|
- Aspects are now consistently named and called in their singular form
|
|
75
|
-
- Only detect inflection clash if singular and plural share the same namespace. This also no longer reports `sap.common` as erroneous during type creation
|
|
101
|
+
- Only detect inflection clash if singular and plural share the same namespace. This also no longer reports `sap.common` as erroneous during type creation
|
|
76
102
|
|
|
77
103
|
## Version 0.19.0 - 2024-03-28
|
|
78
104
|
### Added
|
package/README.md
CHANGED
|
@@ -9,6 +9,25 @@ Generates `.ts` files for a CDS model to receive code completion in VS Code.
|
|
|
9
9
|
|
|
10
10
|
Exhaustive documentation can be found on [CAPire](https://cap.cloud.sap/docs/tools/cds-typer).
|
|
11
11
|
|
|
12
|
+
## Known Restrictions
|
|
13
|
+
|
|
14
|
+
Certain language features of CDS can not be represented in TypeScript.
|
|
15
|
+
Trying to generate types for models using these features will therefore result in incorrect or broken TypeScript code.
|
|
16
|
+
|
|
17
|
+
### Changing Types
|
|
18
|
+
|
|
19
|
+
While the following is valid CDS, there is no TypeScript equivalent that would allow the type of an inherited property to change (TS2416).
|
|
20
|
+
|
|
21
|
+
```cds
|
|
22
|
+
entity A {
|
|
23
|
+
foo: Integer
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
entity B: A {
|
|
27
|
+
foo: String
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
12
31
|
## Support, Feedback, Contributing
|
|
13
32
|
|
|
14
33
|
This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/cap-js/cds-typer/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).
|
package/lib/cli.js
CHANGED
|
@@ -12,6 +12,9 @@ const { EOL } = require('node:os')
|
|
|
12
12
|
const EOL2 = EOL + EOL
|
|
13
13
|
const toolName = 'cds-typer'
|
|
14
14
|
|
|
15
|
+
// @ts-expect-error - nope, it is actually there. Types just seem to be out of sync.
|
|
16
|
+
const lls = cds.log.levels
|
|
17
|
+
|
|
15
18
|
const flags = {
|
|
16
19
|
outputDirectory: {
|
|
17
20
|
desc: 'Root directory to write the generated files to.',
|
|
@@ -23,15 +26,20 @@ const flags = {
|
|
|
23
26
|
},
|
|
24
27
|
logLevel: {
|
|
25
28
|
desc: `Minimum log level that is printed.${EOL}The default is only used if no explicit value is passed${EOL}and there is no configuration passed via cds.env either.`,
|
|
26
|
-
allowed: Object.keys(
|
|
27
|
-
allowedHint: Object.keys(
|
|
28
|
-
defaultHint: _keyFor(
|
|
29
|
-
default: cds?.env?.log?.levels?.['cds-typer'] ?? _keyFor(
|
|
29
|
+
allowed: Object.keys(lls).concat(Object.keys(deprecated)),
|
|
30
|
+
allowedHint: Object.keys(lls).join(' | '), // FIXME: remove once old levels are faded out
|
|
31
|
+
defaultHint: _keyFor(lls.ERROR),
|
|
32
|
+
default: cds?.env?.log?.levels?.['cds-typer'] ?? _keyFor(lls.ERROR),
|
|
30
33
|
},
|
|
31
34
|
jsConfigPath: {
|
|
32
35
|
desc: `Path to where the jsconfig.json should be written.${EOL}If specified, ${toolName} will create a jsconfig.json file and${EOL}set it up to restrict property usage in types entities to${EOL}existing properties only.`,
|
|
33
36
|
type: 'string'
|
|
34
37
|
},
|
|
38
|
+
useEntitiesProxy: {
|
|
39
|
+
desc: `If set to true the 'cds.entities' exports in the generated 'index.js'${EOL}files will be wrapped in 'Proxy' objects\nso static import/require calls can be used everywhere.${EOL}${EOL}WARNING: entity properties can still only be accessed after${EOL}'cds.entities' has been loaded`,
|
|
40
|
+
allowed: ['true', 'false'],
|
|
41
|
+
default: 'false'
|
|
42
|
+
},
|
|
35
43
|
version: {
|
|
36
44
|
desc: 'Prints the version of this tool.'
|
|
37
45
|
},
|
|
@@ -53,25 +61,32 @@ const flags = {
|
|
|
53
61
|
}
|
|
54
62
|
|
|
55
63
|
const hint = () => 'Missing or invalid parameter(s). Call with --help for more details.'
|
|
56
|
-
|
|
64
|
+
/**
|
|
65
|
+
* @param {string} s - the string to indent
|
|
66
|
+
* @param {string} indentation - the indentation to use
|
|
67
|
+
*/
|
|
68
|
+
const indent = (s, indentation) => s
|
|
69
|
+
.split(EOL)
|
|
70
|
+
.map((/** @type {string} */ line) => `${indentation}${line}`)
|
|
71
|
+
.join(EOL)
|
|
57
72
|
|
|
58
73
|
const help = () => `SYNOPSIS${EOL2}` +
|
|
59
74
|
indent('cds-typer [cds file | "*"]', ' ') + EOL2 +
|
|
60
75
|
indent(`Generates type information based on a CDS model.${EOL}Call with at least one positional parameter pointing${EOL}to the (root) CDS file you want to compile.`, ' ') + EOL2 +
|
|
61
76
|
`OPTIONS${EOL2}` +
|
|
62
77
|
Object.entries(flags)
|
|
63
|
-
.sort()
|
|
78
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
64
79
|
.map(([key, value]) => {
|
|
65
80
|
let s = indent(`--${key}`, ' ')
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
}
|
|
81
|
+
// @ts-expect-error - not going to check presence of each property. Same for the following expect-errors.
|
|
82
|
+
if (value.allowedHint) s += ` ${value.allowedHint}`
|
|
83
|
+
// @ts-expect-error
|
|
84
|
+
else if (value.allowed) s += `: <${value.allowed.join(' | ')}>`
|
|
85
|
+
else if ('type' in value && value.type) s += `: <${value.type}>`
|
|
86
|
+
// @ts-expect-error
|
|
73
87
|
if (value.defaultHint || value.default) {
|
|
74
88
|
s += EOL
|
|
89
|
+
// @ts-expect-error
|
|
75
90
|
s += indent(`(default: ${value.defaultHint ?? value.default})`, ' ')
|
|
76
91
|
}
|
|
77
92
|
s += `${EOL2}${indent(value.desc, ' ')}`
|
|
@@ -81,7 +96,7 @@ const help = () => `SYNOPSIS${EOL2}` +
|
|
|
81
96
|
|
|
82
97
|
const version = () => require('../package.json').version
|
|
83
98
|
|
|
84
|
-
const main = async args => {
|
|
99
|
+
const main = async (/** @type {any} */ args) => {
|
|
85
100
|
if ('help' in args.named) {
|
|
86
101
|
console.log(help())
|
|
87
102
|
process.exit(0)
|
|
@@ -107,6 +122,7 @@ const main = async args => {
|
|
|
107
122
|
// temporary fix until rootDir is faded out
|
|
108
123
|
outputDirectory: [args.named.outputDirectory, args.named.rootDir].find(d => d !== './') ?? './',
|
|
109
124
|
logLevel: args.named.logLevel,
|
|
125
|
+
useEntitiesProxy: args.named.useEntitiesProxy === 'true',
|
|
110
126
|
jsConfigPath: args.named.jsConfigPath,
|
|
111
127
|
inlineDeclarations: args.named.inlineDeclarations,
|
|
112
128
|
propertiesOptional: args.named.propertiesOptional === 'true',
|
package/lib/compile.js
CHANGED
|
@@ -26,7 +26,7 @@ const writeJsConfig = path => {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
if (fs.existsSync(path)) {
|
|
29
|
-
const currentContents = JSON.parse(fs.readFileSync(path))
|
|
29
|
+
const currentContents = JSON.parse(fs.readFileSync(path, 'utf8'))
|
|
30
30
|
if (currentContents?.compilerOptions?.checkJs) {
|
|
31
31
|
LOG.warn(`jsconfig at location ${path} already exists. Attempting to merge.`)
|
|
32
32
|
}
|
|
@@ -39,7 +39,7 @@ const writeJsConfig = path => {
|
|
|
39
39
|
|
|
40
40
|
/**
|
|
41
41
|
* Compiles a CSN object to Typescript types.
|
|
42
|
-
* @param {{xtended: CSN, inferred: CSN}} csn - csn tuple
|
|
42
|
+
* @param {{xtended: import('./typedefs').resolver.CSN, inferred: import('./typedefs').resolver.CSN}} csn - csn tuple
|
|
43
43
|
* @param {CompileParameters} parameters - path to root directory for all generated files, min log level
|
|
44
44
|
*/
|
|
45
45
|
const compileFromCSN = async (csn, parameters) => {
|
|
@@ -57,7 +57,7 @@ const compileFromCSN = async (csn, parameters) => {
|
|
|
57
57
|
|
|
58
58
|
/**
|
|
59
59
|
* Compiles a .cds file to Typescript types.
|
|
60
|
-
* @param {string} inputFile - path to input .cds file
|
|
60
|
+
* @param {string | string[]} inputFile - path to input .cds file
|
|
61
61
|
* @param {CompileParameters} parameters - path to root directory for all generated files, min log level, etc.
|
|
62
62
|
*/
|
|
63
63
|
const compileFromFile = async (inputFile, parameters) => {
|
package/lib/components/enum.js
CHANGED
|
@@ -19,6 +19,11 @@ const uniqueValues = kvs => new Set(kvs.map(([,v]) => v?.val ?? v)) // in case
|
|
|
19
19
|
const stringifyEnumType = kvs => [...uniqueValues(kvs)].join(' | ')
|
|
20
20
|
|
|
21
21
|
// in case of strings, wrap in quotes and fallback to key to make sure values are attached for every key
|
|
22
|
+
/**
|
|
23
|
+
* @param {string} key - the key of the enum
|
|
24
|
+
* @param {any} value - the value of the enum
|
|
25
|
+
* @param {string | import('../typedefs').resolver.ref} enumType - the type of the enum
|
|
26
|
+
*/
|
|
22
27
|
const enumVal = (key, value, enumType) => enumType === 'cds.String' ? JSON.stringify(`${value ?? key}`) : value
|
|
23
28
|
|
|
24
29
|
/**
|
|
@@ -41,14 +46,16 @@ const enumVal = (key, value, enumType) => enumType === 'cds.String' ? JSON.strin
|
|
|
41
46
|
* const E = { a: 'A', b: 'B' }
|
|
42
47
|
* type E = 'A' | 'B'
|
|
43
48
|
* ```
|
|
44
|
-
* @param {Buffer} buffer - Buffer to write into
|
|
49
|
+
* @param {import('../file').Buffer} buffer - Buffer to write into
|
|
45
50
|
* @param {string} name - local name of the enum, i.e. the name under which it should be created in the .ts file
|
|
46
51
|
* @param {[string, string][]} kvs - list of key-value pairs
|
|
47
52
|
* @param {object} options - options for printing the enum
|
|
53
|
+
* @param {string[]} doc - the enum docs
|
|
48
54
|
*/
|
|
49
|
-
function printEnum(buffer, name, kvs, options = {}) {
|
|
55
|
+
function printEnum(buffer, name, kvs, options = {}, doc=[]) {
|
|
50
56
|
const opts = {...{export: true}, ...options}
|
|
51
57
|
buffer.add('// enum')
|
|
58
|
+
if (opts.export) doc.forEach(d => { buffer.add(d) })
|
|
52
59
|
buffer.addIndentedBlock(`${opts.export ? 'export ' : ''}const ${name} = {`, () =>
|
|
53
60
|
kvs.forEach(([k, v]) => { buffer.add(`${normalise(k)}: ${v},`) })
|
|
54
61
|
, '} as const;')
|
|
@@ -60,12 +67,13 @@ function printEnum(buffer, name, kvs, options = {}) {
|
|
|
60
67
|
* Converts a CSN type describing an enum into a list of kv-pairs.
|
|
61
68
|
* Values from CSN are unwrapped from their `.val` structure and
|
|
62
69
|
* will fall back to the key if no value is provided.
|
|
63
|
-
* @param {
|
|
64
|
-
* @param {{unwrapVals: boolean}} options - if `unwrapVals` is passed,
|
|
70
|
+
* @param {import('../typedefs').resolver.EnumCSN} enumCsn - the CSN type describing the enum
|
|
71
|
+
* @param {{unwrapVals: boolean} | {}} options - if `unwrapVals` is passed,
|
|
65
72
|
* then the CSN structure `{val:x}` is flattened to just `x`.
|
|
66
73
|
* Retaining `val` is closer to the actual CSN structure and should be used where we want
|
|
67
74
|
* to mimic the runtime as closely as possible (inline enum types).
|
|
68
75
|
* Stripping that additional wrapper would be more readable for users.
|
|
76
|
+
* @returns {[string, any][]}
|
|
69
77
|
* @example
|
|
70
78
|
* ```ts
|
|
71
79
|
* const csn = {enum: {X: {val: 'a'}, Y: {val: 'b'}, Z: {}}}
|
|
@@ -74,10 +82,10 @@ function printEnum(buffer, name, kvs, options = {}) {
|
|
|
74
82
|
* ```
|
|
75
83
|
*/
|
|
76
84
|
const csnToEnumPairs = ({enum: enm, type}, options = {}) => {
|
|
77
|
-
|
|
85
|
+
const actualOptions = {...{unwrapVals: true}, ...options}
|
|
78
86
|
return Object.entries(enm).map(([k, v]) => {
|
|
79
87
|
const val = enumVal(k, v.val, type)
|
|
80
|
-
return [k, (
|
|
88
|
+
return [k, (actualOptions.unwrapVals ? val : { val })]
|
|
81
89
|
})
|
|
82
90
|
}
|
|
83
91
|
|
|
@@ -91,11 +99,12 @@ const propertyToInlineEnumName = (entity, property) => `${entity}_${property}`
|
|
|
91
99
|
* A type is considered to be an inline enum, iff it has a `.enum` property
|
|
92
100
|
* _and_ its type is a CDS primitive, i.e. it is not contained in `cds.definitions`.
|
|
93
101
|
* If it is contained there, then it is a standard enum declaration that has its own name.
|
|
94
|
-
* @param {{type: string}} element - the element to check
|
|
95
|
-
* @param {
|
|
96
|
-
* @returns
|
|
102
|
+
* @param {{type: string | import('../typedefs').resolver.ref, [key: string]: any}} element - the element to check
|
|
103
|
+
* @param {import('../typedefs').resolver.CSN} csn - the CSN model
|
|
104
|
+
* @returns {element is import('../typedefs').resolver.EnumCSN}
|
|
97
105
|
*/
|
|
98
|
-
const isInlineEnumType = (element, csn) => element.enum
|
|
106
|
+
const isInlineEnumType = (element, csn) => element.enum
|
|
107
|
+
&& !(typeof element.type === 'string' && element.type in csn.definitions)
|
|
99
108
|
|
|
100
109
|
/**
|
|
101
110
|
* Stringifies an enum into a runtime artifact.
|
|
@@ -15,7 +15,7 @@ const normalise = ident => ident && !isValidIdent.test(ident)
|
|
|
15
15
|
* @param {string} ident - the identifier to extract the last part from
|
|
16
16
|
* @returns {string} the last part of the identifier
|
|
17
17
|
*/
|
|
18
|
-
const last = ident => ident.split('.').at(-1)
|
|
18
|
+
const last = ident => ident.split('.').at(-1) ?? ident
|
|
19
19
|
|
|
20
20
|
module.exports = {
|
|
21
21
|
normalise,
|
package/lib/components/inline.js
CHANGED
|
@@ -3,6 +3,10 @@ const { normalise } = require('./identifier')
|
|
|
3
3
|
const { docify } = require('./wrappers')
|
|
4
4
|
|
|
5
5
|
/** @typedef {import('../resolution/resolver').TypeResolveInfo} TypeResolveInfo */
|
|
6
|
+
/** @typedef {import('../typedefs').visitor.Inflection} Inflection */
|
|
7
|
+
/** @typedef {import('../typedefs').resolver.PropertyModifier} PropertyModifier */
|
|
8
|
+
/** @typedef {import('../visitor').Visitor} Visitor */
|
|
9
|
+
/** @typedef {{typeName: string, typeInfo: TypeResolveInfo}} TypeResolveInfo_ */
|
|
6
10
|
|
|
7
11
|
/**
|
|
8
12
|
* Inline declarations of types can come in different flavours.
|
|
@@ -12,15 +16,17 @@ const { docify } = require('./wrappers')
|
|
|
12
16
|
*/
|
|
13
17
|
class InlineDeclarationResolver {
|
|
14
18
|
/**
|
|
15
|
-
* @param {
|
|
16
|
-
* @param {
|
|
17
|
-
* @param {
|
|
18
|
-
* @param {
|
|
19
|
+
* @param {object} options - options to be passed to the resolver
|
|
20
|
+
* @param {string} options.fq - full qualifier of the type
|
|
21
|
+
* @param {TypeResolveInfo_} options.type - type info so far
|
|
22
|
+
* @param {import('../file').Buffer} options.buffer - the buffer to write into
|
|
23
|
+
* @param {PropertyModifier[]} options.modifiers - modifiers to add to each generated property
|
|
24
|
+
* @param {string} [options.statementEnd] - statement ending character
|
|
19
25
|
* @protected
|
|
20
26
|
* @abstract
|
|
21
27
|
*/
|
|
22
28
|
// eslint-disable-next-line no-unused-vars
|
|
23
|
-
printInlineType(fq, type, buffer, statementEnd) { /* abstract */ }
|
|
29
|
+
printInlineType({fq, type, buffer, modifiers, statementEnd}) { /* abstract */ }
|
|
24
30
|
|
|
25
31
|
/**
|
|
26
32
|
* Attempts to resolve a type that could reference another type.
|
|
@@ -39,6 +45,8 @@ class InlineDeclarationResolver {
|
|
|
39
45
|
for (const [subname, subelement] of Object.entries(items ?? {})) {
|
|
40
46
|
// in inline definitions, we sometimes have to resolve first
|
|
41
47
|
// FIXME: does this tie in with how we sometimes end up with resolved typed in resolveType()?
|
|
48
|
+
// FIXME2: I don't think the if branch is actually called in real world situations.
|
|
49
|
+
// so we can probably get rid of this distinction and make #resolveTypeName private again
|
|
42
50
|
const se = (typeof subelement === 'string')
|
|
43
51
|
? this.visitor.resolver.resolveTypeName(subelement)
|
|
44
52
|
: subelement
|
|
@@ -58,13 +66,15 @@ class InlineDeclarationResolver {
|
|
|
58
66
|
|
|
59
67
|
/**
|
|
60
68
|
* Visits a single element in an entity.
|
|
61
|
-
* @param {
|
|
62
|
-
* @param {
|
|
63
|
-
* @param {
|
|
64
|
-
* @param {
|
|
69
|
+
* @param {object} options - options
|
|
70
|
+
* @param {string} options.name - name of the element
|
|
71
|
+
* @param {import('../typedefs').resolver.EntityCSN} options.element - CSN data belonging to the the element.
|
|
72
|
+
* @param {SourceFile} options.file - the namespace file the surrounding entity is being printed into.
|
|
73
|
+
* @param {Buffer} options.buffer - buffer to add the definition to. If no buffer is passed, the passed file's class buffer is used instead.
|
|
74
|
+
* @param {PropertyModifier[]} options.modifiers - modifiers to add to each generated property
|
|
65
75
|
* @public
|
|
66
76
|
*/
|
|
67
|
-
visitElement(name, element, file, buffer = file.classes) {
|
|
77
|
+
visitElement({name, element, file, buffer = file.classes, modifiers = []}) {
|
|
68
78
|
this.depth++
|
|
69
79
|
for (const d of docify(element.doc)) {
|
|
70
80
|
buffer.add(d)
|
|
@@ -72,7 +82,7 @@ class InlineDeclarationResolver {
|
|
|
72
82
|
const type = this.visitor.resolver.resolveAndRequire(element, file)
|
|
73
83
|
this.depth--
|
|
74
84
|
if (this.depth === 0) {
|
|
75
|
-
this.printInlineType(name, type, buffer)
|
|
85
|
+
this.printInlineType({fq: name, type, buffer, modifiers})
|
|
76
86
|
}
|
|
77
87
|
return type
|
|
78
88
|
}
|
|
@@ -89,7 +99,7 @@ class InlineDeclarationResolver {
|
|
|
89
99
|
|
|
90
100
|
/**
|
|
91
101
|
* It returns TypeScript datatype for provided TS property
|
|
92
|
-
* @param {
|
|
102
|
+
* @param {TypeResolveInfo_} type - type of the property
|
|
93
103
|
* @param {string} typeName - name of the TypeScript property
|
|
94
104
|
* @returns {string} the datatype to be presented on TypeScript layer
|
|
95
105
|
* @public
|
|
@@ -98,7 +108,16 @@ class InlineDeclarationResolver {
|
|
|
98
108
|
return type.typeInfo.isNotNull ? typeName : `${typeName} | null`
|
|
99
109
|
}
|
|
100
110
|
|
|
101
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* Stringifies additional modifiers for a property
|
|
113
|
+
* @param {(PropertyModifier)[]} modifiers - modifiers to stringify
|
|
114
|
+
* @returns {string} the modifiers as a string
|
|
115
|
+
*/
|
|
116
|
+
stringifyModifiers (modifiers) {
|
|
117
|
+
return modifiers?.length > 0 ? modifiers.join(' ') + ' ' : ''
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** @param {Visitor} visitor - the visitor */
|
|
102
121
|
constructor(visitor) {
|
|
103
122
|
this.visitor = visitor
|
|
104
123
|
// type resolution might recurse. This indicator is used to determine
|
|
@@ -148,24 +167,42 @@ class InlineDeclarationResolver {
|
|
|
148
167
|
* ```
|
|
149
168
|
*/
|
|
150
169
|
class FlatInlineDeclarationResolver extends InlineDeclarationResolver {
|
|
151
|
-
|
|
152
|
-
|
|
170
|
+
/**
|
|
171
|
+
* @param {string} p - prefix to use
|
|
172
|
+
*/
|
|
153
173
|
prefix(p) {
|
|
154
174
|
return p ? `${p}_` : ''
|
|
155
175
|
}
|
|
156
176
|
|
|
157
|
-
|
|
177
|
+
/**
|
|
178
|
+
* @param {object} options - options
|
|
179
|
+
* @param {string} options.prefix - prefix to use
|
|
180
|
+
* @param {TypeResolveInfo_} options.type - type to flatten
|
|
181
|
+
* @param {PropertyModifier[]} options.modifiers - modifiers to add to each generated property
|
|
182
|
+
* @returns {string[]} the flattened properties
|
|
183
|
+
*/
|
|
184
|
+
flatten({prefix, type, modifiers}) {
|
|
158
185
|
return type.typeInfo.structuredType
|
|
159
|
-
? Object.entries(type.typeInfo.structuredType).map(
|
|
160
|
-
|
|
186
|
+
? Object.entries(type.typeInfo.structuredType).map(
|
|
187
|
+
([k,v]) => this.flatten({prefix: `${this.prefix(prefix)}${k}`, type: v, modifiers}) // for flat we pass the modifiers!
|
|
188
|
+
).flat()
|
|
189
|
+
: [`${this.stringifyModifiers(modifiers)}${normalise(prefix)}${this.getPropertyTypeSeparator()} ${this.getPropertyDatatype(type)}`]
|
|
161
190
|
}
|
|
162
191
|
|
|
163
|
-
|
|
164
|
-
|
|
192
|
+
/**
|
|
193
|
+
* @override
|
|
194
|
+
* @type {InlineDeclarationResolver['printInlineType']}
|
|
195
|
+
*/
|
|
196
|
+
printInlineType({fq, type, buffer, modifiers}) {
|
|
197
|
+
for(const prop of this.flatten({prefix: fq, type, modifiers}).flat()) {
|
|
165
198
|
buffer.add(prop)
|
|
166
199
|
}
|
|
167
200
|
}
|
|
168
201
|
|
|
202
|
+
/**
|
|
203
|
+
* @override
|
|
204
|
+
* @type {InlineDeclarationResolver['getTypeLookup']}
|
|
205
|
+
*/
|
|
169
206
|
getTypeLookup(members) {
|
|
170
207
|
return `['${members.join('_')}']`
|
|
171
208
|
}
|
|
@@ -189,39 +226,57 @@ class FlatInlineDeclarationResolver extends InlineDeclarationResolver {
|
|
|
189
226
|
* ```
|
|
190
227
|
*/
|
|
191
228
|
class StructuredInlineDeclarationResolver extends InlineDeclarationResolver {
|
|
229
|
+
/** @param {Visitor} visitor - the visitor */
|
|
192
230
|
constructor(visitor) {
|
|
193
231
|
super(visitor)
|
|
194
232
|
this.printDepth = 0
|
|
195
233
|
}
|
|
196
234
|
|
|
197
|
-
|
|
235
|
+
/**
|
|
236
|
+
* @param {object} options - options
|
|
237
|
+
* @param {string} options.fq - full qualifier of the type
|
|
238
|
+
* @param {TypeResolveInfo_} options.type - type info so far
|
|
239
|
+
* @param {Buffer} options.buffer - the buffer to write into
|
|
240
|
+
* @param {PropertyModifier[]} [options.modifiers] - modifiers to add to each generated property
|
|
241
|
+
* @param {string} [options.statementEnd] - statement ending character
|
|
242
|
+
* FIXME: reuse type
|
|
243
|
+
*/
|
|
244
|
+
flatten({fq, type, buffer, modifiers = [], statementEnd = ';'}) {
|
|
198
245
|
// in addition to the regular depth during resolution, we may have another depth while printing
|
|
199
246
|
// nested types on which the line ending depends
|
|
200
247
|
this.printDepth++
|
|
201
248
|
const lineEnding = this.printDepth > 1 ? ',' : statementEnd
|
|
202
249
|
if (type.typeInfo.structuredType) {
|
|
203
|
-
const prefix =
|
|
250
|
+
const prefix = fq ? `${this.stringifyModifiers(modifiers)}${normalise(fq)}${this.getPropertyTypeSeparator()}`: ''
|
|
204
251
|
buffer.add(`${prefix} {`)
|
|
205
252
|
buffer.indent()
|
|
206
253
|
for (const [n, t] of Object.entries(type.typeInfo.structuredType)) {
|
|
207
|
-
this.flatten(n, t, buffer)
|
|
254
|
+
this.flatten({fq: n, type: t, buffer})
|
|
208
255
|
}
|
|
209
256
|
buffer.outdent()
|
|
210
257
|
buffer.add(`}${this.getPropertyDatatype(type, '')}${lineEnding}`)
|
|
211
258
|
} else {
|
|
212
|
-
buffer.add(`${normalise(
|
|
259
|
+
buffer.add(`${this.stringifyModifiers(modifiers)}${normalise(fq)}${this.getPropertyTypeSeparator()} ${this.getPropertyDatatype(type)}${lineEnding}`)
|
|
213
260
|
}
|
|
214
261
|
this.printDepth--
|
|
215
262
|
return buffer
|
|
216
263
|
}
|
|
217
264
|
|
|
218
|
-
|
|
265
|
+
/**
|
|
266
|
+
* @override
|
|
267
|
+
* @type {InlineDeclarationResolver['printInlineType']}
|
|
268
|
+
*/
|
|
269
|
+
printInlineType({fq, type, buffer, modifiers, statementEnd}) {
|
|
219
270
|
// FIXME: indent not quite right
|
|
220
271
|
const sub = new Buffer()
|
|
221
272
|
sub.currentIndent = buffer.currentIndent
|
|
222
|
-
buffer.add(this.flatten(
|
|
273
|
+
buffer.add(this.flatten({fq, type, buffer: sub, modifiers, statementEnd}).join())
|
|
223
274
|
}
|
|
224
275
|
|
|
276
|
+
/**
|
|
277
|
+
* @override
|
|
278
|
+
* @type {InlineDeclarationResolver['getTypeLookup']}
|
|
279
|
+
*/
|
|
225
280
|
getTypeLookup(members) {
|
|
226
281
|
return members.map(m => `['${m}']`).join('')
|
|
227
282
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/* eslint-disable no-undef */
|
|
2
|
+
// this function will be stringified as part of the generated types and is not supposed to be used internally
|
|
3
|
+
// @ts-nocheck
|
|
4
|
+
const proxyAccessFunction = function (fqParts, opts = {}) {
|
|
5
|
+
const { target, customProps } = { target: {}, customProps: [], ...opts }
|
|
6
|
+
const fq = fqParts.join('.')
|
|
7
|
+
return new Proxy(target, {
|
|
8
|
+
get: function (target, prop) {
|
|
9
|
+
if (cds.entities) {
|
|
10
|
+
target.__proto__ = cds.entities[fq]
|
|
11
|
+
// overwrite/simplify getter after cds.entities is accessible
|
|
12
|
+
this.get = (target, prop) => target[prop]
|
|
13
|
+
return target[prop]
|
|
14
|
+
}
|
|
15
|
+
// we already know the name so we skip the cds.entities proxy access
|
|
16
|
+
if (prop === 'name') return fq
|
|
17
|
+
// custom properties access on 'target' as well as cached _entity property access goes here
|
|
18
|
+
if (Object.hasOwn(target, prop)) return target[prop]
|
|
19
|
+
// inline enums have to be caught here for first time access, as they do not exist on the entity
|
|
20
|
+
if (customProps.includes(prop)) return target[prop]
|
|
21
|
+
// last but not least we pass the property access to cds.entities
|
|
22
|
+
throw new Error(`Property ${prop} does not exist on entity '${fq}' or cds.entities is not yet defined. Ensure the CDS runtime is fully booted before accessing properties.`)
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
}.toString()
|
|
26
|
+
/* eslint-enable no-undef */
|
|
27
|
+
|
|
28
|
+
module.exports = { proxyAccessFunction }
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Determines the proper modifiers for a property.
|
|
3
|
+
* For most properties, this will be "declare". But for some properties,
|
|
4
|
+
* like fields of a type, we don't want any modifiers.
|
|
5
|
+
* @param {import('../typedefs').resolver.EntityCSN} element - The element to determine the modifiers for.
|
|
6
|
+
* @returns {import('../typedefs').resolver.PropertyModifier[]} The modifiers for the property.
|
|
7
|
+
*/
|
|
8
|
+
const getPropertyModifiers = element => element?.parent?.kind !== 'type' ? ['declare'] : []
|
|
9
|
+
|
|
10
|
+
module.exports = {
|
|
11
|
+
getPropertyModifiers
|
|
12
|
+
}
|
|
@@ -45,6 +45,24 @@ const createArrayOf = t => `Array<${t}>`
|
|
|
45
45
|
*/
|
|
46
46
|
const createObjectOf = t => `{${t}}`
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Wraps types into a union type string
|
|
50
|
+
* @param {string[]} types - an array of types
|
|
51
|
+
* @returns {string}
|
|
52
|
+
*/
|
|
53
|
+
const createUnionOf = (...types) => types.join(' | ')
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Wraps type into a promise
|
|
57
|
+
* @param {string} t - the type to wrap.
|
|
58
|
+
* @returns {string}
|
|
59
|
+
* @example
|
|
60
|
+
* ```js
|
|
61
|
+
* createPromiseOf('string') // -> 'Promise<string>'
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
const createPromiseOf = t => `Promise<${t}>`
|
|
65
|
+
|
|
48
66
|
/**
|
|
49
67
|
* Wraps type into a deep require (removes all posibilities of undefined recursively).
|
|
50
68
|
* @param {string} t - the singular type name.
|
|
@@ -55,17 +73,22 @@ const deepRequire = (t, lookup = '') => `${base}.DeepRequired<${t}>${lookup}`
|
|
|
55
73
|
|
|
56
74
|
/**
|
|
57
75
|
* Puts a passed string in docstring format.
|
|
58
|
-
* @param {string} doc - raw string to docify. May contain linebreaks.
|
|
76
|
+
* @param {string | undefined} doc - raw string to docify. May contain linebreaks.
|
|
59
77
|
* @returns {string[]} an array of lines wrapped in doc format. The result is not
|
|
60
78
|
* concatenated to be properly indented by `buffer.add(...)`.
|
|
61
79
|
*/
|
|
62
|
-
const docify = doc =>
|
|
63
|
-
|
|
64
|
-
|
|
80
|
+
const docify = doc => {
|
|
81
|
+
if (!doc) return []
|
|
82
|
+
const lines = doc.split(/\r?\n/).map(l => l.trim().replaceAll('*/', '*\\/')) // mask any */ with *\/
|
|
83
|
+
if (lines.length === 1) return [`/** ${lines[0]} */`] // one-line doc
|
|
84
|
+
return ['/**'].concat(lines.map(line => `* ${line}`)).concat(['*/'])
|
|
85
|
+
}
|
|
65
86
|
|
|
66
87
|
module.exports = {
|
|
67
88
|
createArrayOf,
|
|
68
89
|
createObjectOf,
|
|
90
|
+
createPromiseOf,
|
|
91
|
+
createUnionOf,
|
|
69
92
|
createToOneAssociation,
|
|
70
93
|
createToManyAssociation,
|
|
71
94
|
createCompositionOfOne,
|