@goast/kotlin 0.5.12 → 0.5.13-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 (113) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +45 -45
  3. package/assets/client/okhttp3/ApiAbstractions.kt +30 -30
  4. package/assets/client/okhttp3/ApiClient.kt +252 -252
  5. package/assets/client/okhttp3/ApiResponse.kt +43 -43
  6. package/assets/client/okhttp3/Errors.kt +21 -21
  7. package/assets/client/okhttp3/PartConfig.kt +11 -11
  8. package/assets/client/okhttp3/RequestConfig.kt +18 -18
  9. package/assets/client/okhttp3/RequestMethod.kt +8 -8
  10. package/assets/client/okhttp3/ResponseExtensions.kt +24 -24
  11. package/assets/client/spring-reactive-web-clients/ApiRequestFile.kt +33 -33
  12. package/esm/src/generators/models/model-generator.d.ts.map +1 -1
  13. package/esm/src/generators/models/model-generator.js +12 -3
  14. package/esm/src/generators/services/okhttp3-clients/okhttp3-client-generator.d.ts.map +1 -1
  15. package/esm/src/generators/services/okhttp3-clients/okhttp3-client-generator.js +19 -12
  16. package/esm/src/generators/services/spring-controllers/spring-controller-generator.d.ts.map +1 -1
  17. package/esm/src/generators/services/spring-controllers/spring-controller-generator.js +30 -22
  18. package/esm/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.d.ts.map +1 -1
  19. package/esm/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.js +25 -16
  20. package/esm/src/utils.d.ts +3 -1
  21. package/esm/src/utils.d.ts.map +1 -1
  22. package/esm/src/utils.js +7 -0
  23. package/package.json +1 -1
  24. package/script/src/generators/models/model-generator.d.ts.map +1 -1
  25. package/script/src/generators/models/model-generator.js +11 -2
  26. package/script/src/generators/services/okhttp3-clients/okhttp3-client-generator.d.ts.map +1 -1
  27. package/script/src/generators/services/okhttp3-clients/okhttp3-client-generator.js +18 -11
  28. package/script/src/generators/services/spring-controllers/spring-controller-generator.d.ts.map +1 -1
  29. package/script/src/generators/services/spring-controllers/spring-controller-generator.js +29 -21
  30. package/script/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.d.ts.map +1 -1
  31. package/script/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.js +24 -15
  32. package/script/src/utils.d.ts +3 -1
  33. package/script/src/utils.d.ts.map +1 -1
  34. package/script/src/utils.js +9 -0
  35. package/src/mod.ts +0 -8
  36. package/src/src/assets.ts +0 -9
  37. package/src/src/ast/_index.ts +0 -66
  38. package/src/src/ast/common.ts +0 -1
  39. package/src/src/ast/index.ts +0 -1
  40. package/src/src/ast/node.ts +0 -10
  41. package/src/src/ast/nodes/annotation.ts +0 -79
  42. package/src/src/ast/nodes/argument.ts +0 -62
  43. package/src/src/ast/nodes/call.ts +0 -75
  44. package/src/src/ast/nodes/class.ts +0 -178
  45. package/src/src/ast/nodes/collection-literal.ts +0 -49
  46. package/src/src/ast/nodes/constructor.ts +0 -126
  47. package/src/src/ast/nodes/doc-tag.ts +0 -138
  48. package/src/src/ast/nodes/doc.ts +0 -111
  49. package/src/src/ast/nodes/enum-value.ts +0 -100
  50. package/src/src/ast/nodes/enum.ts +0 -163
  51. package/src/src/ast/nodes/function.ts +0 -178
  52. package/src/src/ast/nodes/generic-parameter.ts +0 -54
  53. package/src/src/ast/nodes/init-block.ts +0 -38
  54. package/src/src/ast/nodes/interface.ts +0 -133
  55. package/src/src/ast/nodes/lambda-type.ts +0 -73
  56. package/src/src/ast/nodes/lambda.ts +0 -74
  57. package/src/src/ast/nodes/object.ts +0 -102
  58. package/src/src/ast/nodes/parameter.ts +0 -118
  59. package/src/src/ast/nodes/property.ts +0 -225
  60. package/src/src/ast/nodes/reference.ts +0 -178
  61. package/src/src/ast/nodes/string.ts +0 -114
  62. package/src/src/ast/nodes/types.ts +0 -23
  63. package/src/src/ast/references/index.ts +0 -10
  64. package/src/src/ast/references/jackson.ts +0 -59
  65. package/src/src/ast/references/jakarta.ts +0 -14
  66. package/src/src/ast/references/java.ts +0 -27
  67. package/src/src/ast/references/kotlin.ts +0 -41
  68. package/src/src/ast/references/kotlinx.ts +0 -14
  69. package/src/src/ast/references/okhttp3.ts +0 -5
  70. package/src/src/ast/references/reactor.ts +0 -5
  71. package/src/src/ast/references/spring-reactive.ts +0 -37
  72. package/src/src/ast/references/spring.ts +0 -86
  73. package/src/src/ast/references/swagger.ts +0 -23
  74. package/src/src/ast/utils/get-kotlin-builder-options.ts +0 -19
  75. package/src/src/ast/utils/to-kt-node.ts +0 -31
  76. package/src/src/ast/utils/write-kt-annotations.ts +0 -15
  77. package/src/src/ast/utils/write-kt-arguments.ts +0 -45
  78. package/src/src/ast/utils/write-kt-enum-values.ts +0 -27
  79. package/src/src/ast/utils/write-kt-generic-parameters.ts +0 -12
  80. package/src/src/ast/utils/write-kt-members.ts +0 -25
  81. package/src/src/ast/utils/write-kt-node.ts +0 -37
  82. package/src/src/ast/utils/write-kt-parameters.ts +0 -25
  83. package/src/src/common-results.ts +0 -4
  84. package/src/src/config.ts +0 -61
  85. package/src/src/file-builder.ts +0 -112
  86. package/src/src/generators/file-generator.ts +0 -29
  87. package/src/src/generators/index.ts +0 -5
  88. package/src/src/generators/models/args.ts +0 -136
  89. package/src/src/generators/models/index.ts +0 -4
  90. package/src/src/generators/models/model-generator.ts +0 -725
  91. package/src/src/generators/models/models-generator.ts +0 -65
  92. package/src/src/generators/models/models.ts +0 -95
  93. package/src/src/generators/services/okhttp3-clients/args.ts +0 -90
  94. package/src/src/generators/services/okhttp3-clients/index.ts +0 -4
  95. package/src/src/generators/services/okhttp3-clients/models.ts +0 -73
  96. package/src/src/generators/services/okhttp3-clients/okhttp3-client-generator.ts +0 -613
  97. package/src/src/generators/services/okhttp3-clients/okhttp3-clients-generator.ts +0 -188
  98. package/src/src/generators/services/okhttp3-clients/refs.ts +0 -59
  99. package/src/src/generators/services/spring-controllers/args.ts +0 -95
  100. package/src/src/generators/services/spring-controllers/index.ts +0 -4
  101. package/src/src/generators/services/spring-controllers/models.ts +0 -76
  102. package/src/src/generators/services/spring-controllers/refs.ts +0 -17
  103. package/src/src/generators/services/spring-controllers/spring-controller-generator.ts +0 -1109
  104. package/src/src/generators/services/spring-controllers/spring-controllers-generator.ts +0 -140
  105. package/src/src/generators/services/spring-reactive-web-clients/args.ts +0 -112
  106. package/src/src/generators/services/spring-reactive-web-clients/index.ts +0 -4
  107. package/src/src/generators/services/spring-reactive-web-clients/models.ts +0 -78
  108. package/src/src/generators/services/spring-reactive-web-clients/refs.ts +0 -11
  109. package/src/src/generators/services/spring-reactive-web-clients/spring-reactive-web-client-generator.ts +0 -625
  110. package/src/src/generators/services/spring-reactive-web-clients/spring-reactive-web-clients-generator.ts +0 -125
  111. package/src/src/import-collection.ts +0 -98
  112. package/src/src/types.ts +0 -3
  113. package/src/src/utils.ts +0 -47
@@ -1,625 +0,0 @@
1
- import {
2
- type ApiParameter,
3
- type ApiSchema,
4
- type AppendValueGroup,
5
- appendValueGroup,
6
- type BasicAppendValue,
7
- builderTemplate as s,
8
- createOverwriteProxy,
9
- getSourceDisplayName,
10
- type MaybePromise,
11
- notNullish,
12
- resolveAnyOfAndAllOf,
13
- SourceBuilder,
14
- toCasing,
15
- } from '@goast/core';
16
-
17
- import { kt } from '../../../ast/index.js';
18
- import type { KtValue } from '../../../ast/nodes/types.js';
19
- import { KotlinFileBuilder } from '../../../file-builder.js';
20
- import type { ApiParameterWithMultipartInfo } from '../../../types.js';
21
- import { getSourceDocLine, modifyString } from '../../../utils.js';
22
- import { KotlinFileGenerator } from '../../file-generator.js';
23
- import type { DefaultKotlinSpringReactiveWebClientGeneratorArgs as Args } from './index.js';
24
- import type {
25
- KotlinSpringReactiveWebClientGeneratorContext,
26
- KotlinSpringReactiveWebClientGeneratorOutput,
27
- } from './models.js';
28
-
29
- type Context = KotlinSpringReactiveWebClientGeneratorContext;
30
- type Output = KotlinSpringReactiveWebClientGeneratorOutput;
31
- type Builder = KotlinFileBuilder;
32
-
33
- export interface KotlinSpringReactiveWebClientGenerator<TOutput extends Output = Output> {
34
- generate(ctx: Context): MaybePromise<TOutput>;
35
- }
36
-
37
- export class DefaultKotlinSpringReactiveWebClientGenerator extends KotlinFileGenerator<Context, Output>
38
- implements KotlinSpringReactiveWebClientGenerator {
39
- public generate(ctx: Context): MaybePromise<Output> {
40
- const typeName = this.getRequestsObjectName(ctx, {});
41
- const packageName = this.getPackageName(ctx, {});
42
- const filePath = this.getFilePath(ctx, { packageName });
43
-
44
- console.log(`Generating client for service ${ctx.service.name} to ${filePath}...`);
45
- ctx.service.endpoints.forEach((endpoint) => {
46
- console.log(
47
- ` ${getSourceDisplayName(ctx.data, endpoint)} [${toCasing(endpoint.name, ctx.config.functionNameCasing)}]`,
48
- );
49
- });
50
-
51
- const builder = new KotlinFileBuilder(packageName, ctx.config);
52
- builder.append(this.getClientFileContent(ctx, {}));
53
- builder.writeToFile(filePath);
54
-
55
- return { typeName, packageName };
56
- }
57
-
58
- // deno-lint-ignore no-unused-vars
59
- protected getClientFileContent(ctx: Context, args: Args.GetClientFileContent): AppendValueGroup<Builder> {
60
- return appendValueGroup([this.getRequestsObject(ctx, {})], '\n\n');
61
- }
62
-
63
- // deno-lint-ignore no-unused-vars
64
- protected getRequestsObject(ctx: Context, args: Args.GetRequestsObject): kt.Object<Builder> {
65
- return kt.object({
66
- name: this.getRequestsObjectName(ctx, {}),
67
- members: ctx.service.endpoints.flatMap((endpoint) =>
68
- this.getEndpointMembers(ctx, { endpoint, parameters: this.getAllParameters(ctx, { endpoint }) })
69
- ),
70
- });
71
- }
72
-
73
- protected getEndpointMembers(ctx: Context, args: Args.GetEndpointMembers): kt.ObjectMember<Builder>[] {
74
- const { endpoint, parameters } = args;
75
- const responseSchema = this.getResponseSchema(ctx, { endpoint });
76
-
77
- return [
78
- this.getEndpointFunction(ctx, { endpoint, parameters, responseSchema }),
79
- this.getEndpointFunctionWithHandler(ctx, { endpoint, parameters, responseSchema }),
80
- this.getEndpointUriFunction(ctx, { endpoint, parameters }),
81
- this.getEndpointRequestFunction(ctx, { endpoint, parameters, responseSchema }),
82
- ];
83
- }
84
-
85
- protected getEndpointFunctionName(ctx: Context, args: Args.GetEndpointFunctionName): string {
86
- const { endpoint } = args;
87
- return toCasing(endpoint.name, ctx.config.functionNameCasing);
88
- }
89
-
90
- protected getEndpointFunction(ctx: Context, args: Args.GetEndpointFunction): kt.Function<Builder> {
91
- const { endpoint, parameters, responseSchema } = args;
92
- const functionName = this.getEndpointFunctionName(ctx, { endpoint });
93
-
94
- return kt.function(functionName, {
95
- doc: kt.doc(this.getEndpointDocDescription(ctx, { endpoint })),
96
- suspend: true,
97
- receiverType: kt.refs.springReactive.webClient(),
98
- parameters: parameters.map((parameter) =>
99
- kt.parameter(
100
- toCasing(parameter.name, ctx.config.parameterNameCasing),
101
- this.getParameterType(ctx, { endpoint, parameter }),
102
- { default: this.getParameterDefaultValue(ctx, { endpoint, parameter }) },
103
- )
104
- ),
105
- returnType: this.getTypeUsage(ctx, { schema: responseSchema, fallback: kt.refs.unit() }),
106
- body: this.getEndpointFunctionBody(ctx, { endpoint, parameters, responseSchema }),
107
- });
108
- }
109
-
110
- protected getEndpointFunctionBody(ctx: Context, args: Args.GetEndpointFunctionBody): AppendValueGroup<Builder> {
111
- const { endpoint, parameters, responseSchema } = args;
112
- const result = appendValueGroup<Builder>([], '\n');
113
-
114
- const requestFunctionName = this.getEndpointRequestFunctionName(ctx, { endpoint });
115
- const parameterNames = parameters.map((p) => toCasing(p.name, ctx.config.parameterNameCasing));
116
- const call = kt.call([
117
- 'this',
118
- kt.call(requestFunctionName, parameterNames),
119
- kt.call('retrieve', []),
120
- responseSchema
121
- ? kt.call(
122
- kt.refs.springReactive.awaitBody([
123
- this.getTypeUsage(ctx, { schema: responseSchema, fallback: kt.refs.unit() }),
124
- ]),
125
- [],
126
- )
127
- : kt.call(kt.refs.springReactive.awaitBodilessEntity(), []),
128
- ]);
129
-
130
- if (responseSchema) {
131
- result.values.push(s`return ${call}`);
132
- } else {
133
- result.values.push(call);
134
- }
135
-
136
- return result;
137
- }
138
-
139
- protected getEndpointFunctionWithHandler(
140
- ctx: Context,
141
- args: Args.GetEndpointFunctionWithHandler,
142
- ): kt.Function<Builder> {
143
- const { endpoint, parameters, responseSchema } = args;
144
- const functionName = this.getEndpointFunctionName(ctx, { endpoint });
145
-
146
- return kt.function(functionName, {
147
- doc: kt.doc(this.getEndpointDocDescription(ctx, { endpoint })),
148
- suspend: true,
149
- // Spring 7's `WebClient.awaitExchange` is `<V : Any>`, so the `<T>` overloads need an `Any` bound to infer.
150
- generics: [
151
- kt.genericParameter('T', ctx.config.springBootVersion === 4 ? { constraint: kt.refs.any() } : undefined),
152
- ],
153
- receiverType: kt.refs.springReactive.webClient(),
154
- parameters: [
155
- ...parameters.map((parameter) =>
156
- kt.parameter(
157
- toCasing(parameter.name, ctx.config.parameterNameCasing),
158
- this.getParameterType(ctx, { endpoint, parameter }),
159
- { default: this.getParameterDefaultValue(ctx, { endpoint, parameter }) },
160
- )
161
- ),
162
- kt.parameter(
163
- 'responseHandler',
164
- kt.lambdaType([kt.refs.springReactive.clientResponse()], 'T', { suspend: true }),
165
- ),
166
- ],
167
- returnType: 'T',
168
- body: this.getEndpointFunctionWithHandlerBody(ctx, { endpoint, parameters, responseSchema }),
169
- });
170
- }
171
-
172
- protected getEndpointFunctionWithHandlerBody(
173
- ctx: Context,
174
- args: Args.GetEndpointFunctionWithHandlerBody,
175
- ): AppendValueGroup<Builder> {
176
- const { endpoint, parameters } = args;
177
- const result = appendValueGroup<Builder>([], '\n');
178
-
179
- const requestFunctionName = this.getEndpointRequestFunctionName(ctx, { endpoint });
180
- const parameterNames = parameters.map((p) => toCasing(p.name, ctx.config.parameterNameCasing));
181
-
182
- result.values.push(s`return ${
183
- kt.call([
184
- kt.call(['this', requestFunctionName], parameterNames),
185
- kt.call([kt.refs.springReactive.awaitExchange()], ['responseHandler']),
186
- ])
187
- }`);
188
-
189
- return result;
190
- }
191
-
192
- protected getEndpointRequestFunctionName(ctx: Context, args: Args.GetEndpointRequestFunctionName): string {
193
- const { endpoint } = args;
194
- return toCasing(`${this.getEndpointFunctionName(ctx, { endpoint })}_request`, ctx.config.functionNameCasing);
195
- }
196
-
197
- protected getEndpointRequestFunction(ctx: Context, args: Args.GetEndpointRequestFunction): kt.Function<Builder> {
198
- const { endpoint, parameters, responseSchema } = args;
199
- const functionName = this.getEndpointRequestFunctionName(ctx, { endpoint });
200
-
201
- return kt.function(functionName, {
202
- doc: kt.doc(this.getEndpointDocDescription(ctx, { endpoint })),
203
- receiverType: kt.refs.springReactive.webClient(),
204
- parameters: parameters.map((parameter) =>
205
- kt.parameter(
206
- toCasing(parameter.name, ctx.config.parameterNameCasing),
207
- this.getParameterType(ctx, { endpoint, parameter }),
208
- { default: this.getParameterDefaultValue(ctx, { endpoint, parameter }) },
209
- )
210
- ),
211
- returnType: kt.refs.springReactive.requestHeadersSpec(['*']),
212
- body: this.getEndpointRequestFunctionBody(ctx, { endpoint, parameters, responseSchema }),
213
- });
214
- }
215
-
216
- protected getEndpointRequestFunctionBody(
217
- ctx: Context,
218
- args: Args.GetEndpointRequestFunctionBody,
219
- ): AppendValueGroup<Builder> {
220
- const { endpoint, parameters, responseSchema } = args;
221
- const result = appendValueGroup<Builder>([], '\n');
222
-
223
- const callChain: KtValue<Builder>[] = [];
224
- callChain.push(
225
- s`return this.method(${kt.refs.spring.httpMethod()}.${endpoint.method.toUpperCase()})`,
226
- this.getEndpointUriCall(ctx, { endpoint, parameters }),
227
- );
228
-
229
- if (responseSchema) {
230
- callChain.push(s`accept(${kt.refs.spring.mediaType()}.APPLICATION_JSON)`);
231
- }
232
-
233
- if (endpoint.requestBody?.content[0] !== undefined) {
234
- callChain.push(
235
- s`contentType(${kt.refs.spring.mediaType()}.parseMediaType(${
236
- kt.string(endpoint.requestBody.content[0].type)
237
- }))`,
238
- );
239
- }
240
-
241
- if (endpoint.requestBody?.content[0]) {
242
- if (endpoint.requestBody.content[0].type === 'multipart/form-data') {
243
- callChain.push(
244
- kt.call('body', [
245
- kt.call([kt.refs.springReactive.bodyInserters(), 'fromMultipartData'], [
246
- kt.call([
247
- kt.call(kt.refs.spring.multipartBodyBuilder(), []),
248
- kt.call('apply', [
249
- kt.lambda(
250
- [],
251
- appendValueGroup(
252
- parameters.filter((x) => x.multipart).map((p) => {
253
- const parameterName = toCasing(p.name, ctx.config.parameterNameCasing);
254
- if (p.multipart?.isFile) {
255
- return kt.call([
256
- p.required && !p.schema?.nullable ? parameterName : `${parameterName}?`,
257
- 'addToBuilder',
258
- ], ['this']);
259
- } else {
260
- const call = kt.call([
261
- kt.call('part', [kt.string(p.multipart!.name), parameterName]),
262
- kt.call('contentType', [
263
- kt.call([
264
- kt.refs.spring.mediaType(),
265
- 'APPLICATION_JSON',
266
- ]),
267
- ]),
268
- ]);
269
- return p.required && !p.schema?.nullable ? call : kt.call([`${parameterName}?`, 'also'], [
270
- kt.lambda([parameterName], call, { singleline: true }),
271
- ]);
272
- }
273
- }),
274
- '\n',
275
- ),
276
- ),
277
- ]),
278
- 'build',
279
- ], []),
280
- ]),
281
- ]),
282
- );
283
- } else {
284
- const bodySchema = endpoint.requestBody.content[0].schema;
285
- const parameterName = this.getRequestBodyParamName(ctx, { endpoint });
286
- const call = kt.call('bodyValue', [
287
- toCasing(parameterName, ctx.config.parameterNameCasing),
288
- ]);
289
- callChain.push(
290
- endpoint.requestBody.required && !bodySchema?.nullable ? call : kt.call('apply', [
291
- kt.lambda(
292
- [],
293
- kt.call([`${parameterName}?`, 'also'], [kt.lambda([parameterName], call, { singleline: true })]),
294
- { singleline: true },
295
- ),
296
- ]),
297
- );
298
- }
299
- }
300
-
301
- if (parameters.some((x) => x.target === 'header')) {
302
- callChain.push(
303
- kt.call('headers', [
304
- kt.lambda(
305
- ['headers'],
306
- appendValueGroup(
307
- parameters.filter((x) => x.target === 'header').map((p) => {
308
- const parameterName = toCasing(p.name, ctx.config.parameterNameCasing);
309
- const toString = this.getParameterToString(ctx, { endpoint, parameter: p });
310
- return p.required && !p.schema?.nullable
311
- ? kt.call(['headers', 'add'], [kt.string(p.name), parameterName + toString])
312
- : kt.call([`${parameterName}?`, 'also'], [
313
- kt.lambda([], kt.call(['headers', 'add'], [kt.string(p.name), 'it' + toString]), {
314
- singleline: true,
315
- }),
316
- ]);
317
- }),
318
- '\n',
319
- ),
320
- ),
321
- ]),
322
- );
323
- }
324
-
325
- result.values.push(kt.call(callChain));
326
- return result;
327
- }
328
-
329
- /**
330
- * Emits the `uri(...)` call of the request function. If `preserveUriTemplate` is enabled, the URI template is
331
- * passed to `WebClient` verbatim, so Spring can record it (`ClientRequestObservationContext.uriTemplate`) and tag
332
- * `http.client.requests` with the route instead of the expanded path.
333
- */
334
- protected getEndpointUriCall(ctx: Context, args: Args.GetEndpointUriCall): kt.Value<Builder> {
335
- const { endpoint, parameters } = args;
336
-
337
- if (!ctx.config.preserveUriTemplate) {
338
- return kt.call('uri', [kt.call(
339
- [this.getEndpointUriFunctionName(ctx, { endpoint })],
340
- parameters.filter((p) => p.target === 'path' || p.target === 'query').map((p) =>
341
- toCasing(p.name, ctx.config.parameterNameCasing)
342
- ),
343
- )]);
344
- }
345
-
346
- const uriTemplate = kt.string(this.getEndpointPath(ctx, { endpoint }));
347
- const pathVariables = this.getUriPathVariablesValue(ctx, { endpoint });
348
- const queryParameterCalls = this.getUriQueryParameterCalls(ctx, { endpoint });
349
-
350
- // Without query parameters the template and its variables can be handed to `uri` directly.
351
- if (!queryParameterCalls) {
352
- return kt.call('uri', [uriTemplate, pathVariables]);
353
- }
354
-
355
- // Query parameters need a `UriBuilder`, which the `uri(String, Function<UriBuilder, URI>)` overload provides
356
- // while still recording the template.
357
- return kt.call('uri', [
358
- uriTemplate,
359
- kt.lambda(
360
- ['uriBuilder'],
361
- kt.call([
362
- 'uriBuilder',
363
- kt.call('apply', [kt.lambda([], queryParameterCalls)]),
364
- kt.call('build', [pathVariables]),
365
- ]),
366
- ),
367
- ]);
368
- }
369
-
370
- protected getUriPathVariablesValue(ctx: Context, args: Args.GetUriPathVariablesValue): kt.Value<Builder> | null {
371
- const { endpoint } = args;
372
- const pathParameters = endpoint.parameters.filter((p) => p.target === 'path');
373
- if (pathParameters.length === 0) return null;
374
-
375
- return kt.call(
376
- [kt.refs.mapOf.infer()],
377
- pathParameters.map((p) =>
378
- s`${kt.string(p.name)} to ${toCasing(p.name, ctx.config.parameterNameCasing)}${
379
- this.getParameterToString(ctx, { endpoint, parameter: p })
380
- }`
381
- ),
382
- );
383
- }
384
-
385
- protected getUriQueryParameterCalls(
386
- ctx: Context,
387
- args: Args.GetUriQueryParameterCalls,
388
- ): AppendValueGroup<Builder> | null {
389
- const { endpoint } = args;
390
- const queryParameters = endpoint.parameters.filter((p) => p.target === 'query');
391
- if (queryParameters.length === 0) return null;
392
-
393
- return appendValueGroup(
394
- queryParameters.map((p) => {
395
- const parameterName = toCasing(p.name, ctx.config.parameterNameCasing);
396
- const toString = this.getParameterToString(ctx, { endpoint, parameter: p });
397
- return p.required && !p.schema?.nullable
398
- ? kt.call('queryParam', [kt.string(p.name), parameterName + toString])
399
- : kt.call([`${parameterName}?`, 'also'], [
400
- kt.lambda([], kt.call('queryParam', [kt.string(p.name), 'it' + toString]), { singleline: true }),
401
- ]);
402
- }),
403
- '\n',
404
- );
405
- }
406
-
407
- protected getEndpointUriFunctionName(ctx: Context, args: Args.GetEndpointUriFunctionName): string {
408
- const { endpoint } = args;
409
- return toCasing(`${this.getEndpointFunctionName(ctx, { endpoint })}_uri`, ctx.config.functionNameCasing);
410
- }
411
-
412
- protected getEndpointUriFunction(ctx: Context, args: Args.GetEndpointUriFunction): kt.Function<Builder> {
413
- const { endpoint, parameters } = args;
414
- const functionName = this.getEndpointUriFunctionName(ctx, { endpoint });
415
-
416
- return kt.function(functionName, {
417
- parameters: parameters.filter((p) => p.target === 'path' || p.target === 'query').map((parameter) =>
418
- kt.parameter(
419
- toCasing(parameter.name, ctx.config.parameterNameCasing),
420
- this.getParameterType(ctx, { endpoint, parameter }),
421
- { default: this.getParameterDefaultValue(ctx, { endpoint, parameter }) },
422
- )
423
- ),
424
- returnType: kt.refs.string(),
425
- body: this.getEndpointUriFunctionBody(ctx, { endpoint, parameters }),
426
- });
427
- }
428
-
429
- protected getEndpointUriFunctionBody(ctx: Context, args: Args.GetEndpointUriFunctionBody): AppendValueGroup<Builder> {
430
- const { endpoint } = args;
431
- const result = appendValueGroup<Builder>([], '\n');
432
-
433
- const callChain: KtValue<Builder>[] = [];
434
- callChain.push(
435
- s`${kt.refs.spring.uriComponentsBuilder()}.fromPath(${kt.string(this.getEndpointPath(ctx, { endpoint }))})`,
436
- );
437
-
438
- const queryParameterCalls = this.getUriQueryParameterCalls(ctx, { endpoint });
439
- if (queryParameterCalls) {
440
- callChain.push(kt.call('apply', [kt.lambda([], queryParameterCalls)]));
441
- }
442
-
443
- const pathVariables = this.getUriPathVariablesValue(ctx, { endpoint });
444
- callChain.push(pathVariables ? kt.call('buildAndExpand', [pathVariables]) : kt.call('build', []));
445
-
446
- callChain.push('toUriString');
447
- result.values.push(s`return ${kt.call(callChain, [])}`);
448
- return result;
449
- }
450
-
451
- protected getParameterToString(ctx: Context, args: Args.GetParameterToString): kt.Value<Builder> {
452
- const { parameter } = args;
453
- if (parameter.schema?.kind === 'array') {
454
- return '.joinToString()';
455
- } else if (
456
- parameter.schema?.kind === 'string' && parameter.schema.enum?.length &&
457
- this.getSchemaType(ctx, { schema: parameter.schema })
458
- ) {
459
- return '.value';
460
- } else {
461
- return '.toString()';
462
- }
463
- }
464
-
465
- protected getParameterType(ctx: Context, args: Args.GetParameterType): kt.Type<Builder> {
466
- const { parameter } = args;
467
- if (parameter.multipart?.isFile) {
468
- return ctx.refs.apiRequestFile();
469
- }
470
- return this.getTypeUsage(ctx, {
471
- schema: parameter.schema,
472
- nullable: !parameter.required,
473
- });
474
- }
475
-
476
- protected getParameterDefaultValue(ctx: Context, args: Args.GetParameterDefaultValue): kt.Value<Builder> | null {
477
- const { parameter } = args;
478
-
479
- return !parameter.required
480
- ? parameter.schema?.kind === 'string' && parameter.schema.enum && parameter.schema.default
481
- ? s`${this.getTypeUsage(ctx, { schema: parameter.schema, nullable: false })}.${
482
- toCasing(String(parameter.schema.default), ctx.config.enumValueNameCasing)
483
- }`
484
- : kt.toNode(parameter.schema?.default)
485
- : null;
486
- }
487
-
488
- protected getTypeUsage(ctx: Context, args: Args.GetTypeUsage<Builder>): kt.Type<Builder> {
489
- const { schema, nullable, fallback } = args;
490
- const type = this.getSchemaType(ctx, { schema });
491
- return type
492
- ? createOverwriteProxy(type, { nullable: nullable ?? type.nullable })
493
- : (fallback ?? kt.refs.any({ nullable }));
494
- }
495
-
496
- // deno-lint-ignore no-unused-vars
497
- protected getPackageName(ctx: Context, args: Args.GetPackageName): string {
498
- const packageSuffix = typeof ctx.config.packageSuffix === 'string'
499
- ? ctx.config.packageSuffix
500
- : ctx.config.packageSuffix(ctx.service);
501
- return ctx.config.packageName + packageSuffix;
502
- }
503
-
504
- protected getResponseSchema(_ctx: Context, args: Args.GetResponseSchema): ApiSchema | undefined {
505
- const { endpoint } = args;
506
- return endpoint.responses.find((x) => !x.statusCode || (x.statusCode >= 200 && x.statusCode < 300))
507
- ?.contentOptions[0]?.schema;
508
- }
509
-
510
- protected getSchemaType(ctx: Context, args: Args.GetSchemaType): kt.Reference<SourceBuilder> | undefined {
511
- const { schema } = args;
512
- return schema && ctx.input.kotlin.models[schema.id].type;
513
- }
514
-
515
- protected getAllParameters(ctx: Context, args: Args.GetAllParameters): ApiParameterWithMultipartInfo[] {
516
- const { endpoint } = args;
517
- const parameters = endpoint.parameters.filter(
518
- (parameter) => parameter.target === 'query' || parameter.target === 'path' || parameter.target === 'header',
519
- );
520
- if (endpoint.requestBody) {
521
- const content = endpoint.requestBody.content[0];
522
- let schema = content.schema;
523
-
524
- if (content.type === 'multipart/form-data') {
525
- if (schema && schema.kind === 'object') {
526
- schema = resolveAnyOfAndAllOf(schema, true) ?? schema;
527
- const properties = schema.properties ?? {};
528
- for (const [name, property] of properties.entries()) {
529
- parameters.push(
530
- Object.assign(
531
- this.createApiParameter({
532
- id: `multipart-${name}`,
533
- name,
534
- target: 'body',
535
- schema: property.schema,
536
- required: schema.required.has(name),
537
- description: property.schema.description,
538
- }),
539
- {
540
- multipart: {
541
- name,
542
- isFile: property.schema.kind === 'string' && property.schema.format === 'binary',
543
- },
544
- },
545
- ),
546
- );
547
- }
548
- }
549
- } else {
550
- parameters.push(
551
- this.createApiParameter({
552
- id: 'body',
553
- name: this.getRequestBodyParamName(ctx, { endpoint }),
554
- target: 'body',
555
- schema,
556
- required: endpoint.requestBody.required,
557
- description: endpoint.requestBody.description,
558
- }),
559
- );
560
- }
561
- }
562
-
563
- return parameters.sort((a, b) => (a.required === b.required ? 0 : a.required ? -1 : 1));
564
- }
565
-
566
- protected getRequestBodyParamName(ctx: Context, args: Args.GetRequestBodyParamName): string {
567
- const { endpoint } = args;
568
- const schema = endpoint.requestBody?.content[0].schema;
569
- const schemaInfo = this.getSchemaType(ctx, { schema });
570
- return toCasing(
571
- schemaInfo && schemaInfo.name !== 'Any' ? SourceBuilder.build((b) => kt.reference.write(b, schemaInfo)) : 'body',
572
- ctx.config.parameterNameCasing,
573
- );
574
- }
575
-
576
- protected getEndpointDocDescription(ctx: Context, args: Args.GetEndpointDocDescription): BasicAppendValue<Builder> {
577
- const docSegments = [args.endpoint.description?.trim()];
578
-
579
- if (ctx.config.includeSourceInDocs) {
580
- docSegments.push(getSourceDocLine(args.endpoint));
581
- }
582
-
583
- return docSegments.filter(notNullish).join('\n\n');
584
- }
585
-
586
- protected getBasePath(ctx: Context, _args: Args.GetBasePath): string {
587
- return modifyString(
588
- (ctx.service.$src ?? ctx.service.endpoints[0]?.$src)?.document.servers?.[0]?.url ?? '/',
589
- ctx.config.basePath,
590
- ctx.service,
591
- );
592
- }
593
-
594
- protected getEndpointPath(ctx: Context, args: Args.GetEndpointPath): string {
595
- const { endpoint } = args;
596
- return modifyString(endpoint.path.replace(/^\/*/, ''), ctx.config.pathModifier, endpoint);
597
- }
598
-
599
- protected getFilePath(ctx: Context, args: Args.GetFilePath): string {
600
- const { packageName } = args;
601
- return `${ctx.config.outputDir}/${packageName.replace(/\./g, '/')}/${this.getRequestsObjectName(ctx, {})}.kt`;
602
- }
603
-
604
- // deno-lint-ignore no-unused-vars
605
- protected getRequestsObjectName(ctx: Context, args: Args.GetRequestsObjectName): string {
606
- return toCasing(`${ctx.service.name}_Requests`, ctx.config.typeNameCasing);
607
- }
608
-
609
- private createApiParameter(data: Partial<ApiParameter> & Pick<ApiParameter, 'id' | 'name' | 'target'>): ApiParameter {
610
- return {
611
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
612
- $src: undefined!,
613
- $ref: undefined,
614
- schema: undefined,
615
- required: false,
616
- description: undefined,
617
- allowEmptyValue: undefined,
618
- allowReserved: undefined,
619
- deprecated: false,
620
- explode: undefined,
621
- style: undefined,
622
- ...data,
623
- };
624
- }
625
- }