@goast/kotlin 0.5.8 → 0.5.9-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.
Files changed (118) hide show
  1. package/LICENSE +21 -21
  2. package/assets/client/okhttp3/ApiAbstractions.kt +30 -30
  3. package/assets/client/okhttp3/ApiClient.kt +253 -253
  4. package/assets/client/okhttp3/ApiResponse.kt +43 -43
  5. package/assets/client/okhttp3/Errors.kt +21 -21
  6. package/assets/client/okhttp3/PartConfig.kt +11 -11
  7. package/assets/client/okhttp3/RequestConfig.kt +18 -18
  8. package/assets/client/okhttp3/RequestMethod.kt +8 -8
  9. package/assets/client/okhttp3/ResponseExtensions.kt +24 -24
  10. package/assets/client/spring-reactive-web-clients/ApiRequestFile.kt +33 -33
  11. package/esm/src/ast/references/jackson.d.ts +8 -5
  12. package/esm/src/ast/references/jackson.d.ts.map +1 -1
  13. package/esm/src/ast/references/jackson.js +14 -6
  14. package/esm/src/config.d.ts +10 -0
  15. package/esm/src/config.d.ts.map +1 -1
  16. package/esm/src/config.js +1 -0
  17. package/esm/src/generators/services/okhttp3-clients/okhttp3-client-generator.d.ts.map +1 -1
  18. package/esm/src/generators/services/okhttp3-clients/okhttp3-client-generator.js +36 -32
  19. package/esm/src/generators/services/okhttp3-clients/okhttp3-clients-generator.d.ts.map +1 -1
  20. package/esm/src/generators/services/okhttp3-clients/okhttp3-clients-generator.js +22 -6
  21. package/esm/src/generators/services/spring-controllers/spring-controller-generator.d.ts.map +1 -1
  22. package/esm/src/generators/services/spring-controllers/spring-controller-generator.js +23 -13
  23. package/esm/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.d.ts.map +1 -1
  24. package/esm/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.js +4 -1
  25. package/package.json +2 -2
  26. package/script/src/ast/references/jackson.d.ts +8 -5
  27. package/script/src/ast/references/jackson.d.ts.map +1 -1
  28. package/script/src/ast/references/jackson.js +20 -7
  29. package/script/src/config.d.ts +10 -0
  30. package/script/src/config.d.ts.map +1 -1
  31. package/script/src/config.js +1 -0
  32. package/script/src/generators/services/okhttp3-clients/okhttp3-client-generator.d.ts.map +1 -1
  33. package/script/src/generators/services/okhttp3-clients/okhttp3-client-generator.js +36 -32
  34. package/script/src/generators/services/okhttp3-clients/okhttp3-clients-generator.d.ts.map +1 -1
  35. package/script/src/generators/services/okhttp3-clients/okhttp3-clients-generator.js +22 -6
  36. package/script/src/generators/services/spring-controllers/spring-controller-generator.d.ts.map +1 -1
  37. package/script/src/generators/services/spring-controllers/spring-controller-generator.js +23 -13
  38. package/script/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.d.ts.map +1 -1
  39. package/script/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.js +4 -1
  40. package/src/mod.ts +0 -8
  41. package/src/src/assets.ts +0 -9
  42. package/src/src/ast/_index.ts +0 -66
  43. package/src/src/ast/common.ts +0 -1
  44. package/src/src/ast/index.ts +0 -1
  45. package/src/src/ast/node.ts +0 -10
  46. package/src/src/ast/nodes/annotation.ts +0 -79
  47. package/src/src/ast/nodes/argument.ts +0 -62
  48. package/src/src/ast/nodes/call.ts +0 -75
  49. package/src/src/ast/nodes/class.ts +0 -178
  50. package/src/src/ast/nodes/collection-literal.ts +0 -49
  51. package/src/src/ast/nodes/constructor.ts +0 -126
  52. package/src/src/ast/nodes/doc-tag.ts +0 -138
  53. package/src/src/ast/nodes/doc.ts +0 -111
  54. package/src/src/ast/nodes/enum-value.ts +0 -100
  55. package/src/src/ast/nodes/enum.ts +0 -163
  56. package/src/src/ast/nodes/function.ts +0 -178
  57. package/src/src/ast/nodes/generic-parameter.ts +0 -54
  58. package/src/src/ast/nodes/init-block.ts +0 -38
  59. package/src/src/ast/nodes/interface.ts +0 -133
  60. package/src/src/ast/nodes/lambda-type.ts +0 -73
  61. package/src/src/ast/nodes/lambda.ts +0 -74
  62. package/src/src/ast/nodes/object.ts +0 -102
  63. package/src/src/ast/nodes/parameter.ts +0 -118
  64. package/src/src/ast/nodes/property.ts +0 -225
  65. package/src/src/ast/nodes/reference.ts +0 -178
  66. package/src/src/ast/nodes/string.ts +0 -114
  67. package/src/src/ast/nodes/types.ts +0 -23
  68. package/src/src/ast/references/index.ts +0 -10
  69. package/src/src/ast/references/jackson.ts +0 -44
  70. package/src/src/ast/references/jakarta.ts +0 -14
  71. package/src/src/ast/references/java.ts +0 -27
  72. package/src/src/ast/references/kotlin.ts +0 -41
  73. package/src/src/ast/references/kotlinx.ts +0 -14
  74. package/src/src/ast/references/okhttp3.ts +0 -5
  75. package/src/src/ast/references/reactor.ts +0 -5
  76. package/src/src/ast/references/spring-reactive.ts +0 -33
  77. package/src/src/ast/references/spring.ts +0 -86
  78. package/src/src/ast/references/swagger.ts +0 -23
  79. package/src/src/ast/utils/get-kotlin-builder-options.ts +0 -19
  80. package/src/src/ast/utils/to-kt-node.ts +0 -31
  81. package/src/src/ast/utils/write-kt-annotations.ts +0 -15
  82. package/src/src/ast/utils/write-kt-arguments.ts +0 -45
  83. package/src/src/ast/utils/write-kt-enum-values.ts +0 -27
  84. package/src/src/ast/utils/write-kt-generic-parameters.ts +0 -12
  85. package/src/src/ast/utils/write-kt-members.ts +0 -25
  86. package/src/src/ast/utils/write-kt-node.ts +0 -37
  87. package/src/src/ast/utils/write-kt-parameters.ts +0 -25
  88. package/src/src/common-results.ts +0 -4
  89. package/src/src/config.ts +0 -48
  90. package/src/src/file-builder.ts +0 -112
  91. package/src/src/generators/file-generator.ts +0 -29
  92. package/src/src/generators/index.ts +0 -5
  93. package/src/src/generators/models/args.ts +0 -136
  94. package/src/src/generators/models/index.ts +0 -4
  95. package/src/src/generators/models/model-generator.ts +0 -725
  96. package/src/src/generators/models/models-generator.ts +0 -65
  97. package/src/src/generators/models/models.ts +0 -95
  98. package/src/src/generators/services/okhttp3-clients/args.ts +0 -90
  99. package/src/src/generators/services/okhttp3-clients/index.ts +0 -4
  100. package/src/src/generators/services/okhttp3-clients/models.ts +0 -73
  101. package/src/src/generators/services/okhttp3-clients/okhttp3-client-generator.ts +0 -609
  102. package/src/src/generators/services/okhttp3-clients/okhttp3-clients-generator.ts +0 -169
  103. package/src/src/generators/services/okhttp3-clients/refs.ts +0 -59
  104. package/src/src/generators/services/spring-controllers/args.ts +0 -95
  105. package/src/src/generators/services/spring-controllers/index.ts +0 -4
  106. package/src/src/generators/services/spring-controllers/models.ts +0 -76
  107. package/src/src/generators/services/spring-controllers/refs.ts +0 -17
  108. package/src/src/generators/services/spring-controllers/spring-controller-generator.ts +0 -1097
  109. package/src/src/generators/services/spring-controllers/spring-controllers-generator.ts +0 -140
  110. package/src/src/generators/services/spring-reactive-web-clients/args.ts +0 -103
  111. package/src/src/generators/services/spring-reactive-web-clients/index.ts +0 -4
  112. package/src/src/generators/services/spring-reactive-web-clients/models.ts +0 -62
  113. package/src/src/generators/services/spring-reactive-web-clients/refs.ts +0 -11
  114. package/src/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.ts +0 -583
  115. package/src/src/generators/services/spring-reactive-web-clients/spring-reactive-web-clients-generator.ts +0 -125
  116. package/src/src/import-collection.ts +0 -98
  117. package/src/src/types.ts +0 -3
  118. package/src/src/utils.ts +0 -47
@@ -1,725 +0,0 @@
1
- import {
2
- type ApiSchema,
3
- type ApiSchemaKind,
4
- type ApiSchemaProperty,
5
- type AppendValue,
6
- type AppendValueGroup,
7
- appendValueGroup,
8
- type BasicAppendValue,
9
- builderTemplate as s,
10
- createOverwriteProxy,
11
- DEFAULT_IGNORED_SCHEMA_PROPERTIES,
12
- getSchemaReference,
13
- getSourceDisplayName,
14
- type MaybePromise,
15
- modify,
16
- modifyEach,
17
- notNullish,
18
- resolveAnyOfAndAllOf,
19
- type SourceBuilder,
20
- toCasing,
21
- } from '@goast/core';
22
-
23
- import { kt } from '../../ast/index.js';
24
- import { KotlinFileBuilder } from '../../file-builder.js';
25
- import { getSourceDocLine } from '../../utils.js';
26
- import { KotlinFileGenerator } from '../file-generator.js';
27
- import type { DefaultKotlinModelGeneratorArgs as Args } from './index.js';
28
- import type { KotlinModelGeneratorContext, KotlinModelGeneratorOutput } from './models.js';
29
-
30
- type Context = KotlinModelGeneratorContext;
31
- type Output = KotlinModelGeneratorOutput;
32
- type Builder = KotlinFileBuilder;
33
-
34
- export interface KotlinModelGenerator<TOutput extends Output = Output> {
35
- generate(ctx: Context): MaybePromise<TOutput>;
36
- }
37
-
38
- export class DefaultKotlinModelGenerator extends KotlinFileGenerator<Context, Output> implements KotlinModelGenerator {
39
- public generate(ctx: Context): MaybePromise<KotlinModelGeneratorOutput> {
40
- if (/\/(anyOf|allOf)(\/[0-9]+)?$/.test(ctx.schema.$src.path)) {
41
- // Do not generate types that are only used for anyOf and/or allOf
42
- return { type: kt.refs.any({ nullable: true }) };
43
- }
44
-
45
- const schemaReference = getSchemaReference(ctx.schema, DEFAULT_IGNORED_SCHEMA_PROPERTIES);
46
- if (schemaReference !== ctx.schema) {
47
- const typeName = this.getDeclarationTypeName(ctx, { schema: schemaReference });
48
- const packageName = this.getPackageName(ctx, { schema: schemaReference });
49
- return { type: kt.reference(typeName, packageName) };
50
- }
51
-
52
- if (this.shouldGenerateTypeDeclaration(ctx, { schema: ctx.schema })) {
53
- const typeName = this.getDeclarationTypeName(ctx, { schema: ctx.schema });
54
- const packageName = this.getPackageName(ctx, { schema: ctx.schema });
55
- const filePath = `${ctx.config.outputDir}/${packageName.replace(/\./g, '/')}/${typeName}.kt`;
56
-
57
- console.log(
58
- `Generating model ${getSourceDisplayName(ctx.data, ctx.schema)} [${packageName}.${typeName}] to ${filePath}...`,
59
- );
60
- const builder = new KotlinFileBuilder(packageName, ctx.config);
61
- builder.append(this.getFileContent(ctx, {}));
62
- builder.writeToFile(filePath);
63
-
64
- return { type: kt.reference(typeName, packageName) };
65
- } else {
66
- return { type: this.getType(ctx, { schema: ctx.schema }) };
67
- }
68
- }
69
-
70
- protected getFileContent(ctx: Context, _args: Args.GetFileContent): AppendValueGroup<Builder> {
71
- return appendValueGroup<Builder>(
72
- [this.getSchemaDeclaration(ctx, { schema: this.normalizeSchema(ctx, { schema: ctx.schema }) })],
73
- '\n\n',
74
- );
75
- }
76
-
77
- protected getSchemaDeclaration(ctx: Context, args: Args.GetSchemaDeclaration): AppendValue<Builder> {
78
- const { schema } = args;
79
-
80
- if (schema.kind === 'object') {
81
- return schema.discriminator ? this.getInterface(ctx, { schema }) : this.getClass(ctx, { schema });
82
- } else if (schema.enum !== undefined && schema.enum.length > 0) {
83
- return this.getEnum(ctx, { schema });
84
- }
85
-
86
- return '// The generator was not able to generate this schema.\n// This should not happend. If you see this comment, please open an Issue on Github.';
87
- }
88
-
89
- protected getClass(ctx: Context, args: Args.GetClass): kt.Class<Builder> {
90
- const { schema } = args;
91
- const inheritedSchemas = this.getInheritedSchemas(ctx, { schema });
92
- const parameters = this.getClassProperties(ctx, { schema });
93
-
94
- return kt.class(this.getDeclarationTypeName(ctx, { schema }), {
95
- doc: kt.doc(this.getSchemaDocDescription(ctx, { schema })),
96
- annotations: [
97
- this.getJacksonJsonClassDescriptionAnnotation(ctx, { schema }),
98
- schema.deprecated ? kt.annotation(kt.refs.deprecated(), [kt.argument(kt.string(''))]) : null,
99
- ],
100
- classKind: parameters.length === 0 ? null : 'data',
101
- implements: inheritedSchemas.map((schema) => this.getType(ctx, { schema, nullable: false })),
102
- primaryConstructor: kt.constructor(
103
- parameters.map((property) => this.getClassParameter(ctx, { ...args, inheritedSchemas, parameters, property })),
104
- ),
105
- members: [
106
- ...(schema.additionalProperties !== undefined && schema.additionalProperties !== false
107
- ? [
108
- this.getAdditionalPropertiesProperty(ctx, { schema }),
109
- this.getAdditionalPropertiesSetter(ctx, { schema }),
110
- this.getAdditionalPropertiesGetter(ctx, { schema }),
111
- ]
112
- : []),
113
- ],
114
- });
115
- }
116
-
117
- protected getInterface(ctx: Context, args: Args.GetInterface): kt.Interface<Builder> {
118
- const { schema } = args;
119
-
120
- return kt.interface(this.getDeclarationTypeName(ctx, { schema }), {
121
- doc: kt.doc(this.getSchemaDocDescription(ctx, { schema })),
122
- annotations: [
123
- this.getJacksonJsonTypeInfoAnnotation(ctx, { schema }),
124
- this.getJacksonJsonSubTypesAnnotation(ctx, { schema }),
125
- this.getJacksonJsonClassDescriptionAnnotation(ctx, { schema }),
126
- schema.deprecated ? kt.annotation(kt.refs.deprecated(), [kt.argument(kt.string(''))]) : null,
127
- ].filter(notNullish),
128
- members: this.sortProperties(ctx, { schema, properties: schema.properties.values() }).map((property) =>
129
- this.getInterfaceProperty(ctx, { schema, property })
130
- ),
131
- });
132
- }
133
-
134
- protected getEnum(ctx: Context, args: Args.GetEnum): kt.Enum<Builder> {
135
- const { schema } = args;
136
-
137
- const name = this.getDeclarationTypeName(ctx, { schema });
138
- return kt.enum(
139
- name,
140
- schema.enum?.map((x) =>
141
- kt.enumValue(toCasing(String(x), ctx.config.enumValueNameCasing), {
142
- annotations: [kt.annotation(kt.refs.jackson.jsonProperty(), [kt.argument(kt.string(String(x)))])],
143
- arguments: [kt.argument(kt.string(String(x)))],
144
- })
145
- ) ?? [],
146
- {
147
- doc: kt.doc(this.getSchemaDocDescription(ctx, { schema })),
148
- annotations: [schema.deprecated ? kt.annotation(kt.refs.deprecated(), [kt.argument(kt.string(''))]) : null],
149
- primaryConstructor: kt.constructor([
150
- kt.parameter.class(toCasing('value', ctx.config.propertyNameCasing), kt.refs.string(), {
151
- property: 'readonly',
152
- }),
153
- ]),
154
- companionObject: kt.object({
155
- members: [
156
- kt.function('fromValue', {
157
- parameters: [kt.parameter('value', kt.refs.string())],
158
- returnType: kt.reference(name, null, { nullable: true }),
159
- singleExpression: true,
160
- body: !schema.enum?.length ? 'null' : s`\nwhen(value) {${s.indent`${
161
- appendValueGroup([
162
- schema.enum.map((x) =>
163
- s`\n${kt.string(String(x))} -> ${toCasing(String(x), ctx.config.enumValueNameCasing)}`
164
- ),
165
- ])
166
- }
167
- else -> null`}
168
- }`,
169
- }),
170
- ],
171
- }),
172
- },
173
- );
174
- }
175
-
176
- protected getSchemaDocDescription(ctx: Context, args: Args.GetSchemaDocDescription): BasicAppendValue<Builder> {
177
- const docSegments = [args.schema.description?.trim()];
178
-
179
- if (ctx.config.includeSourceInDocs) {
180
- docSegments.push(getSourceDocLine(args.schema));
181
- }
182
-
183
- return docSegments.filter(notNullish).join('\n\n');
184
- }
185
-
186
- protected getType(ctx: Context, args: Args.GetType): kt.Reference<SourceBuilder> {
187
- let { schema, nullable } = args;
188
-
189
- if (schema.kind === 'oneOf' && schema.oneOf.length === 2 && schema.oneOf.some((x) => x.kind === 'null')) {
190
- const nonNullSchema = schema.oneOf.find((x) => x.kind !== 'null')!;
191
- if (nonNullSchema) {
192
- schema = nonNullSchema;
193
- nullable ??= true;
194
- }
195
- }
196
-
197
- const generatedType = this.getGeneratedType(ctx, { schema, nullable });
198
- if (generatedType) {
199
- return generatedType;
200
- }
201
-
202
- nullable ??= schema.nullable;
203
- switch (schema.kind) {
204
- case 'boolean':
205
- return kt.refs.boolean({ nullable });
206
- case 'integer':
207
- case 'number':
208
- switch (schema.format) {
209
- case 'int32':
210
- return kt.refs.int({ nullable });
211
- case 'int64':
212
- return kt.refs.long({ nullable });
213
- case 'float':
214
- return kt.refs.float({ nullable });
215
- case 'double':
216
- return kt.refs.double({ nullable });
217
- default:
218
- return schema.kind === 'integer' ? kt.refs.int({ nullable }) : kt.refs.double({ nullable });
219
- }
220
- case 'string':
221
- switch (schema.format) {
222
- case 'date-time':
223
- return kt.refs.java.offsetDateTime({ nullable });
224
- case 'time':
225
- return kt.refs.java.offsetTime({ nullable });
226
- case 'date':
227
- return kt.refs.java.localDate({ nullable });
228
- case 'local-date-time':
229
- return kt.refs.java.localDateTime({ nullable });
230
- case 'local-time':
231
- return kt.refs.java.localTime({ nullable });
232
- case 'uri':
233
- return kt.refs.java.uri({ nullable });
234
- default:
235
- return kt.refs.string({ nullable });
236
- }
237
- case 'null':
238
- return kt.refs.nothing({ nullable });
239
- case 'unknown':
240
- return kt.refs.any({ nullable });
241
- case 'array':
242
- return kt.refs.list(
243
- [schema.items ? this.getType(ctx, { schema: schema.items }) : kt.refs.any({ nullable: true })],
244
- { nullable },
245
- );
246
- case 'object':
247
- return schema.properties.size === 0 && schema.additionalProperties
248
- ? kt.refs.map([kt.refs.string(), this.getAdditionalPropertiesType(ctx, { schema })], { nullable })
249
- : kt.refs.any({ nullable });
250
- default:
251
- return kt.refs.any({ nullable });
252
- }
253
- }
254
-
255
- protected getGeneratedType(ctx: Context, args: Args.GetGeneratedType): kt.Reference<SourceBuilder> | null {
256
- const schema = getSchemaReference(args.schema, DEFAULT_IGNORED_SCHEMA_PROPERTIES);
257
- if (this.shouldGenerateTypeDeclaration(ctx, { schema })) {
258
- return kt.reference(this.getDeclarationTypeName(ctx, { schema }), this.getPackageName(ctx, { schema }), {
259
- nullable: args.nullable ?? schema.nullable,
260
- });
261
- }
262
- return null;
263
- }
264
-
265
- protected getAdditionalPropertiesType(
266
- ctx: Context,
267
- args: Args.GetAdditionalPropertiesType,
268
- ): kt.Reference<SourceBuilder> {
269
- const { schema } = args;
270
-
271
- return typeof schema.additionalProperties === 'object'
272
- ? this.getType(ctx, { schema: schema.additionalProperties })
273
- : kt.refs.any({ nullable: true });
274
- }
275
-
276
- protected getDefaultValue(ctx: Context, args: Args.GetDefaultValue): kt.Value<Builder> {
277
- const { schema } = args;
278
-
279
- if (schema.default === null || schema.default === undefined) {
280
- return 'null';
281
- } else {
282
- switch (schema.kind) {
283
- case 'boolean':
284
- return Boolean(schema.default) || String(schema.default).toLowerCase() === 'true' ? 'true' : 'false';
285
- case 'integer':
286
- case 'number':
287
- return String(schema.default);
288
- case 'string':
289
- return schema.enum && schema.enum.length > 0
290
- ? kt.call([this.getType(ctx, { schema }), toCasing(String(schema.default), ctx.config.enumValueNameCasing)])
291
- : kt.string(String(schema.default));
292
- case 'array':
293
- return kt.call(
294
- kt.refs.listOf.infer(),
295
- Array.isArray(schema.default) ? schema.default.map((x) => kt.toNode(x)) : [],
296
- );
297
- default:
298
- return 'null';
299
- }
300
- }
301
- }
302
-
303
- // #region Members
304
- protected getClassParameter(ctx: Context, args: Args.GetClassParameter): kt.Parameter<Builder> {
305
- const { schema, inheritedSchemas, property } = args;
306
-
307
- return kt.parameter.class(
308
- toCasing(property.name, ctx.config.propertyNameCasing),
309
- this.getType(ctx, { schema: property.schema, nullable: schema.required.has(property.name) ? undefined : true }),
310
- {
311
- description: property.schema.description?.trim(),
312
- annotations: [
313
- ...this.getJakartaValidationAnnotations(ctx, { schema, property }),
314
- this.getSwaggerSchemaAnnotation(ctx, { schema, property }),
315
- modify(this.getJacksonJsonPropertyAnnotation(ctx, { schema, property }), (x) => (x.target = 'param')),
316
- ...modifyEach(
317
- [
318
- this.getJacksonJsonPropertyAnnotation(ctx, { schema, property }),
319
- this.getJacksonJsonPropertyDescriptionAnnotation(ctx, { schema, property }),
320
- this.getJacksonJsonIncludeAnnotation(ctx, { schema, property }),
321
- ].filter(notNullish),
322
- (x) => (x.target = 'get'),
323
- ),
324
- property.schema.deprecated ? kt.annotation(kt.refs.deprecated(), [kt.argument(kt.string(''))]) : null,
325
- ].filter(notNullish),
326
- override: inheritedSchemas.some((schema) => this.hasProperty(ctx, { schema, propertyName: property.name })),
327
- property: 'readonly',
328
- default: property.schema.default !== undefined || !schema.required.has(property.name)
329
- ? this.getDefaultValue(ctx, { schema: property.schema })
330
- : null,
331
- },
332
- );
333
- }
334
-
335
- protected getInterfaceProperty(ctx: Context, args: Args.GetInterfaceProperty): kt.Property<Builder> {
336
- const { schema, property } = args;
337
-
338
- return kt.property(toCasing(property.name, ctx.config.propertyNameCasing), {
339
- doc: kt.doc(this.getSchemaDocDescription(ctx, { schema: property.schema })),
340
- annotations: modifyEach(
341
- [
342
- this.getJacksonJsonPropertyAnnotation(ctx, { schema, property }),
343
- this.getJacksonJsonPropertyDescriptionAnnotation(ctx, { schema, property }),
344
- this.getJacksonJsonIncludeAnnotation(ctx, { schema, property }),
345
- property.schema.deprecated ? kt.annotation(kt.refs.deprecated(), [kt.argument(kt.string(''))]) : null,
346
- ].filter(notNullish),
347
- (x) => (x.target = 'get'),
348
- ),
349
- type: this.getType(ctx, {
350
- schema: property.schema,
351
- nullable: schema.required.has(property.name) ? undefined : true,
352
- }),
353
- });
354
- }
355
-
356
- protected getAdditionalPropertiesProperty(
357
- ctx: Context,
358
- args: Args.GetAdditionalPropertiesProperty,
359
- ): kt.Property<Builder> {
360
- const { schema } = args;
361
-
362
- return kt.property(toCasing('additionalProperties', ctx.config.propertyNameCasing), {
363
- annotations: [kt.annotation(kt.refs.jackson.jsonIgnore())],
364
- type: kt.reference('MutableMap', null, {
365
- generics: ['String', this.getAdditionalPropertiesType(ctx, { schema })],
366
- }),
367
- default: 'mutableMapOf()',
368
- });
369
- }
370
-
371
- protected getAdditionalPropertiesSetter(
372
- ctx: Context,
373
- args: Args.GetAdditionalPropertiesSetter,
374
- ): kt.Function<Builder> {
375
- const { schema } = args;
376
-
377
- return kt.function(toCasing('set', ctx.config.functionNameCasing), {
378
- annotations: [kt.annotation(kt.refs.jackson.jsonAnySetter())],
379
- parameters: [
380
- kt.parameter(toCasing('name', ctx.config.parameterNameCasing), 'String'),
381
- kt.parameter(
382
- toCasing('value', ctx.config.parameterNameCasing),
383
- this.getAdditionalPropertiesType(ctx, { schema }),
384
- ),
385
- ],
386
- body: `this.${toCasing('additionalProperties', ctx.config.propertyNameCasing)}[name] = value`,
387
- });
388
- }
389
-
390
- protected getAdditionalPropertiesGetter(
391
- ctx: Context,
392
- args: Args.GetAdditionalPropertiesGetter,
393
- ): kt.Function<Builder> {
394
- const { schema } = args;
395
-
396
- return kt.function(toCasing('getMap', ctx.config.functionNameCasing), {
397
- annotations: [kt.annotation(kt.refs.jackson.jsonAnyGetter())],
398
- returnType: kt.refs.map([kt.refs.string(), this.getAdditionalPropertiesType(ctx, { schema })]),
399
- body: `return this.${toCasing('additionalProperties', ctx.config.propertyNameCasing)}`,
400
- });
401
- }
402
- // #endregion
403
-
404
- // #region Annotations
405
- protected getJacksonJsonTypeInfoAnnotation(
406
- ctx: Context,
407
- args: Args.GetJacksonJsonTypeInfoAnnotation,
408
- ): kt.Annotation<Builder> | null {
409
- const { schema } = args;
410
-
411
- return ctx.config.addJacksonAnnotations && schema.discriminator
412
- ? kt.annotation(kt.refs.jackson.jsonTypeInfo(), [
413
- kt.argument.named('use', 'JsonTypeInfo.Id.NAME'),
414
- kt.argument.named(
415
- 'include',
416
- 'properties' in schema && schema.properties.has(schema.discriminator.propertyName)
417
- ? 'JsonTypeInfo.As.EXISTING_PROPERTY'
418
- : 'JsonTypeInfo.As.PROPERTY',
419
- ),
420
- kt.argument.named('property', kt.string(schema.discriminator.propertyName)),
421
- kt.argument.named('visible', 'true'),
422
- ])
423
- : null;
424
- }
425
-
426
- protected getJacksonJsonSubTypesAnnotation(
427
- ctx: Context,
428
- args: Args.GetJacksonJsonSubTypesAnnotation,
429
- ): kt.Annotation<Builder> | null {
430
- const { schema } = args;
431
-
432
- if (!ctx.config.addJacksonAnnotations || !schema.discriminator) return null;
433
- const entries = Object.entries(schema.discriminator.mapping);
434
- return entries.length > 0
435
- ? kt.annotation(
436
- kt.refs.jackson.jsonSubTypes(),
437
- entries.map(([value, schema]) =>
438
- kt.argument(
439
- kt.call(
440
- [kt.refs.jackson.jsonSubTypes(), 'Type'],
441
- [
442
- kt.argument.named(
443
- 'value',
444
- modify(this.getType(ctx, { schema }), (x) => (x.classReference = true)),
445
- ),
446
- kt.argument.named('name', kt.string(value)),
447
- ],
448
- ),
449
- )
450
- ),
451
- )
452
- : null;
453
- }
454
-
455
- protected getJacksonJsonClassDescriptionAnnotation(
456
- ctx: Context,
457
- args: Args.GetJacksonJsonClassDescriptionAnnotation,
458
- ): kt.Annotation<Builder> | null {
459
- const { schema } = args;
460
-
461
- return ctx.config.addJacksonAnnotations && schema.description
462
- ? kt.annotation(kt.refs.jackson.jsonClassDescription(), [
463
- kt.argument(kt.string(schema.description)),
464
- ])
465
- : null;
466
- }
467
-
468
- protected getJacksonJsonPropertyAnnotation(
469
- ctx: Context,
470
- args: Args.GetJacksonJsonPropertyAnnotation,
471
- ): kt.Annotation<Builder> | null {
472
- const { schema, property } = args;
473
-
474
- return ctx.config.addJacksonAnnotations
475
- ? kt.annotation(kt.refs.jackson.jsonProperty(), [
476
- kt.argument(kt.string(property.name)),
477
- schema.required.has(property.name) ? kt.argument.named('required', 'true') : null,
478
- ])
479
- : null;
480
- }
481
-
482
- protected getJacksonJsonPropertyDescriptionAnnotation(
483
- ctx: Context,
484
- args: Args.GetJacksonJsonPropertyDescriptionAnnotation,
485
- ): kt.Annotation<Builder> | null {
486
- const { property } = args;
487
-
488
- return ctx.config.addJacksonAnnotations && property.schema.description
489
- ? kt.annotation(kt.refs.jackson.jsonPropertyDescription(), [
490
- kt.argument(kt.string(property.schema.description)),
491
- ])
492
- : null;
493
- }
494
-
495
- protected getJacksonJsonIncludeAnnotation(
496
- ctx: Context,
497
- args: Args.GetJacksonJsonIncludeAnnotation,
498
- ): kt.Annotation<Builder> | null {
499
- const { property } = args;
500
-
501
- return ctx.config.addJacksonAnnotations && property.schema.custom['exclude-when-null'] === true
502
- ? kt.annotation(kt.refs.jackson.jsonInclude(), [
503
- kt.argument(kt.call([kt.refs.jackson.jsonInclude(), 'Include', 'NON_NULL'])),
504
- ])
505
- : null;
506
- }
507
-
508
- protected getJakartaValidationAnnotations(
509
- ctx: Context,
510
- args: Args.GetJakartaValidationAnnotations,
511
- ): kt.Annotation<Builder>[] {
512
- const { property } = args;
513
- const annotations: kt.Annotation<Builder>[] = [];
514
- if (!ctx.config.addJakartaValidationAnnotations) {
515
- return annotations;
516
- }
517
-
518
- if (property.schema.kind === 'string') {
519
- if (property.schema.pattern) {
520
- annotations.push(
521
- kt.annotation(kt.refs.jakarta.pattern(), [kt.argument.named('regexp', kt.string(property.schema.pattern))], {
522
- target: 'get',
523
- }),
524
- );
525
- }
526
- if (property.schema.minLength === 1 && property.schema.maxLength === undefined) {
527
- annotations.push(kt.annotation(kt.refs.jakarta.notEmpty(), [], { target: 'get' }));
528
- } else if (property.schema.minLength !== undefined || property.schema.maxLength !== undefined) {
529
- annotations.push(kt.annotation(kt.refs.jakarta.size(), [
530
- property.schema.minLength !== undefined ? kt.argument.named('min', property.schema.minLength) : null,
531
- property.schema.maxLength !== undefined ? kt.argument.named('max', property.schema.maxLength) : null,
532
- ], { target: 'get' }));
533
- }
534
- } else if (property.schema.kind === 'number' || property.schema.kind === 'integer') {
535
- if (property.schema.minimum !== undefined) {
536
- annotations.push(
537
- kt.annotation(kt.refs.jakarta.min(), [kt.argument.named('value', property.schema.minimum)], {
538
- target: 'get',
539
- }),
540
- );
541
- }
542
- if (property.schema.maximum !== undefined) {
543
- annotations.push(
544
- kt.annotation(kt.refs.jakarta.max(), [kt.argument.named('value', property.schema.maximum)], {
545
- target: 'get',
546
- }),
547
- );
548
- }
549
- } else if (property.schema.kind === 'array') {
550
- if (property.schema.minItems !== undefined || property.schema.maxItems !== undefined) {
551
- annotations.push(kt.annotation(kt.refs.jakarta.size(), [
552
- property.schema.minItems !== undefined ? kt.argument.named('min', property.schema.minItems) : null,
553
- property.schema.maxItems !== undefined ? kt.argument.named('max', property.schema.maxItems) : null,
554
- ], { target: 'get' }));
555
- }
556
- }
557
-
558
- if (this.shouldGenerateTypeDeclaration(ctx, { schema: property.schema })) {
559
- annotations.push(kt.annotation(kt.refs.jakarta.valid(), [], { target: 'field' }));
560
- }
561
-
562
- return annotations;
563
- }
564
-
565
- protected getSwaggerSchemaAnnotation(
566
- ctx: Context,
567
- args: Args.GetSwaggerSchemaAnnotation,
568
- ): kt.Annotation<Builder> | null {
569
- const { schema, property } = args;
570
-
571
- return ctx.config.addSwaggerAnnotations
572
- ? kt.annotation(kt.refs.swagger.schema(), [
573
- property.schema.example !== undefined
574
- ? kt.argument.named('example', kt.string(String(property.schema.example)))
575
- : null,
576
- schema.required.has(property.name) ? kt.argument.named('required', 'true') : null,
577
- property.schema.description !== undefined
578
- ? kt.argument.named('description', kt.string(property.schema.description))
579
- : null,
580
- property.schema.deprecated ? kt.argument.named('deprecated', kt.toNode(property.schema.deprecated)) : null,
581
- ])
582
- : null;
583
- }
584
- // #endregion
585
-
586
- protected getPackageName(ctx: Context, args: Args.GetPackageName): string {
587
- const { schema } = args;
588
-
589
- const packageSuffix = typeof ctx.config.packageSuffix === 'string'
590
- ? ctx.config.packageSuffix
591
- : ctx.config.packageSuffix(schema);
592
- return ctx.config.packageName + packageSuffix;
593
- }
594
-
595
- protected shouldGenerateTypeDeclaration(ctx: Context, args: Args.ShouldGenerateTypeDeclaration): boolean {
596
- let { schema } = args;
597
-
598
- // All enum types should have its own type declaration
599
- if (schema.enum !== undefined && schema.enum.length > 0) {
600
- return true;
601
- }
602
-
603
- // All primitive types already exist and do not need its own type declaration
604
- if (
605
- schema.kind !== 'combined' &&
606
- schema.kind !== 'multi-type' &&
607
- schema.kind !== 'object' &&
608
- schema.kind !== 'oneOf'
609
- ) {
610
- return false;
611
- }
612
-
613
- // Too complex types cannot be represented in Kotlin, so they fallback to Any
614
- if (schema.kind === 'multi-type') {
615
- return false;
616
- }
617
- schema = this.normalizeSchema(ctx, { schema });
618
- if (schema.kind === 'combined' || schema.kind === 'oneOf') {
619
- return false;
620
- }
621
-
622
- // Schemas representable by a simple Map type do not need its own type declaration
623
- if (schema.kind === 'object' && schema.properties.size === 0 && schema.additionalProperties) {
624
- return false;
625
- }
626
-
627
- if (schema.kind === 'object' && ctx.config.emptyObjectTypeBehavior === 'use-any' && schema.properties.size === 0) {
628
- return false;
629
- }
630
-
631
- // Dynamically generated schemas do not have its own type declaration
632
- if (!ctx.data.schemas.some((x) => x.id === schema.id)) {
633
- return false;
634
- }
635
-
636
- // multipart schemas should not have its own type declaration
637
- if (schema.$src.path.endsWith('/requestBody/content/multipart/form-data/schema')) {
638
- return false;
639
- }
640
-
641
- return true;
642
- }
643
-
644
- protected getDeclarationTypeName(ctx: Context, args: Args.GetDeclarationTypeName): string {
645
- return toCasing(args.schema.name, ctx.config.typeNameCasing);
646
- }
647
-
648
- protected getInheritedSchemas(
649
- ctx: Context,
650
- args: Args.GetInheritedSchemas,
651
- ): (ApiSchema<ApiSchemaKind> & { discriminator: NonNullable<ApiSchema['discriminator']> })[] {
652
- return args.schema.inheritedSchemas
653
- .filter((schema) => this.shouldGenerateTypeDeclaration(ctx, { schema }) && !schema.isNameGenerated)
654
- .filter((item, index, self) => self.indexOf(item) === index);
655
- }
656
-
657
- protected getClassProperties(ctx: Context, args: Args.GetClassProperties): ApiSchemaProperty[] {
658
- const { schema } = args;
659
-
660
- const inheritedSchemas = this.getInheritedSchemas(ctx, { schema });
661
- const properties: ApiSchemaProperty[] = [];
662
- const appendedProperties: ApiSchemaProperty[] = [];
663
- for (const property of schema.properties.values()) {
664
- const discriminator = inheritedSchemas.find(
665
- (x) => x.discriminator?.propertyName === property.name,
666
- )?.discriminator;
667
- if (discriminator) {
668
- const schemaMappings = Object.entries(discriminator.mapping).filter(([_, v]) => v.id === schema.id);
669
- if (schemaMappings.length === 1) {
670
- const p = createOverwriteProxy(property);
671
- const s = createOverwriteProxy(p.schema);
672
- p.schema = s;
673
- s.default = schemaMappings[0][0];
674
- appendedProperties.push(p);
675
- continue;
676
- }
677
- }
678
-
679
- properties.push(property);
680
- }
681
-
682
- return [...this.sortProperties(ctx, { schema, properties }), ...appendedProperties];
683
- }
684
-
685
- protected sortProperties(_ctx: Context, args: Args.SortProperties): ApiSchemaProperty[] {
686
- return [...args.properties].sort((a, b) => classify(a) - classify(b));
687
-
688
- function classify(p: ApiSchemaProperty) {
689
- if (p.schema.default !== undefined) return 1;
690
- if (args.schema.required.has(p.name)) return 0;
691
- return 2;
692
- }
693
- }
694
-
695
- protected normalizeSchema(ctx: Context, args: Args.NormalizeSchema): ApiSchema {
696
- let { schema } = args;
697
-
698
- if (schema.kind === 'oneOf') {
699
- schema = ctx.config.oneOfBehavior === 'treat-as-any-of'
700
- // deno-lint-ignore no-explicit-any
701
- ? { ...(schema as any), kind: 'combined', anyOf: schema.oneOf, allOf: [], oneOf: undefined }
702
- // deno-lint-ignore no-explicit-any
703
- : { ...(schema as any), kind: 'combined', allOf: schema.oneOf, anyOf: [], oneOf: undefined };
704
- ctx.schema = schema;
705
- }
706
- if (schema.kind === 'object' || schema.kind === 'combined') {
707
- const mergedSchema = resolveAnyOfAndAllOf(schema, true);
708
- if (mergedSchema) {
709
- schema = mergedSchema;
710
- }
711
- }
712
-
713
- return schema;
714
- }
715
-
716
- protected hasProperty(ctx: Context, args: Args.HasProperty): boolean {
717
- const { schema, propertyName } = args;
718
-
719
- return (
720
- ('properties' in schema && schema.properties.has(propertyName)) ||
721
- ('anyOf' in schema && schema.anyOf.some((schema) => this.hasProperty(ctx, { schema, propertyName }))) ||
722
- ('allOf' in schema && schema.allOf.some((schema) => this.hasProperty(ctx, { schema, propertyName })))
723
- );
724
- }
725
- }