@kubb/ast 5.0.0-beta.58 → 5.0.0-beta.59
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/README.md +10 -0
- package/dist/casing-BE2R1RXg.cjs +88 -0
- package/dist/casing-BE2R1RXg.cjs.map +1 -0
- package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
- package/dist/factory-BmcGBdeg.cjs +1251 -0
- package/dist/factory-BmcGBdeg.cjs.map +1 -0
- package/dist/factory-Du7nEP4B.js +282 -0
- package/dist/factory-Du7nEP4B.js.map +1 -0
- package/dist/factory.cjs +25 -28
- package/dist/factory.d.ts +3 -3
- package/dist/factory.js +3 -3
- package/dist/{ast-ClnJg9BN.d.ts → index-BzjwdK2M.d.ts} +74 -372
- package/dist/index.cjs +445 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +94 -59
- package/dist/index.js +7 -113
- package/dist/index.js.map +1 -1
- package/dist/operationParams-BZ07xDm0.d.ts +204 -0
- package/dist/response-DKxTr522.js +683 -0
- package/dist/response-DKxTr522.js.map +1 -0
- package/dist/{types-CB2oY8Dw.d.ts → types-olVl9v5p.d.ts} +222 -227
- package/dist/types.d.ts +4 -3
- package/dist/utils-BCtRXfhI.cjs +275 -0
- package/dist/utils-BCtRXfhI.cjs.map +1 -0
- package/dist/{utils-DN4XLVqz.js → utils-SdZU0F3H.js} +472 -1235
- package/dist/utils-SdZU0F3H.js.map +1 -0
- package/dist/utils.cjs +127 -22
- package/dist/utils.d.ts +112 -80
- package/dist/utils.js +3 -2
- package/package.json +1 -1
- package/src/constants.ts +8 -14
- package/src/dedupe.ts +8 -0
- package/src/factory.ts +1 -2
- package/src/guards.ts +1 -1
- package/src/index.ts +4 -13
- package/src/nodes/code.ts +29 -47
- package/src/nodes/content.ts +2 -2
- package/src/nodes/file.ts +28 -23
- package/src/nodes/function.ts +0 -15
- package/src/nodes/input.ts +6 -6
- package/src/nodes/operation.ts +1 -1
- package/src/nodes/parameter.ts +0 -3
- package/src/nodes/property.ts +0 -3
- package/src/nodes/requestBody.ts +3 -6
- package/src/nodes/schema.ts +3 -2
- package/src/printer.ts +1 -1
- package/src/registry.ts +31 -26
- package/src/signature.ts +3 -3
- package/src/transformers.ts +28 -1
- package/src/types.ts +2 -53
- package/src/utils/codegen.ts +104 -0
- package/src/utils/fileMerge.ts +184 -0
- package/src/utils/index.ts +7 -339
- package/src/utils/operationParams.ts +353 -0
- package/src/utils/refs.ts +112 -0
- package/src/utils/schemaGraph.ts +169 -0
- package/src/utils/strings.ts +139 -0
- package/src/visitor.ts +43 -19
- package/dist/extractStringsFromNodes-Bn9cOos9.d.ts +0 -14
- package/dist/factory-C5gHvtLU.js +0 -138
- package/dist/factory-C5gHvtLU.js.map +0 -1
- package/dist/factory-JN-Ylfl6.cjs +0 -155
- package/dist/factory-JN-Ylfl6.cjs.map +0 -1
- package/dist/utils-C8bWAzhv.cjs +0 -2696
- package/dist/utils-C8bWAzhv.cjs.map +0 -1
- package/dist/utils-DN4XLVqz.js.map +0 -1
- package/src/utils/ast.ts +0 -816
package/src/utils/index.ts
CHANGED
|
@@ -1,341 +1,9 @@
|
|
|
1
|
-
import { isIdentifier, pascalCase, singleQuote } from '@internals/utils'
|
|
2
|
-
import { INDENT } from '../constants.ts'
|
|
3
|
-
import type { OperationNode, ParameterNode } from '../nodes/index.ts'
|
|
4
|
-
import type { OperationParamsResolver, ParamGroupType } from './ast.ts'
|
|
5
|
-
|
|
6
1
|
export { isValidVarName } from '@internals/utils'
|
|
2
|
+
export { buildJSDoc, buildList, buildObject, objectKey } from './codegen.ts'
|
|
7
3
|
export { extractStringsFromNodes } from './extractStringsFromNodes.ts'
|
|
8
|
-
export {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
findCircularSchemas,
|
|
15
|
-
isStringType,
|
|
16
|
-
resolveParamType,
|
|
17
|
-
syncSchemaRef,
|
|
18
|
-
} from './ast.ts'
|
|
19
|
-
export type { BuildGroupArgs, ParamGroupType } from './ast.ts'
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
23
|
-
* Returns the string unchanged when no balanced quote pair is found.
|
|
24
|
-
*
|
|
25
|
-
* @example
|
|
26
|
-
* ```ts
|
|
27
|
-
* trimQuotes('"hello"') // 'hello'
|
|
28
|
-
* trimQuotes('hello') // 'hello'
|
|
29
|
-
* ```
|
|
30
|
-
*/
|
|
31
|
-
export function trimQuotes(text: string): string {
|
|
32
|
-
if (text.length >= 2) {
|
|
33
|
-
const first = text[0]
|
|
34
|
-
const last = text[text.length - 1]
|
|
35
|
-
if ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '`' && last === '`')) {
|
|
36
|
-
return text.slice(1, -1)
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return text
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Serializes a primitive value to a single-quoted string literal, stripping any surrounding quote
|
|
44
|
-
* characters first. Escaping comes from `JSON.stringify`, then the quote style switches to single
|
|
45
|
-
* quotes so generated code matches the repo style without a formatter.
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* ```ts
|
|
49
|
-
* stringify('hello') // "'hello'"
|
|
50
|
-
* stringify('"hello"') // "'hello'"
|
|
51
|
-
* ```
|
|
52
|
-
*/
|
|
53
|
-
export function stringify(value: string | number | boolean | undefined): string {
|
|
54
|
-
if (value === undefined || value === null) return "''"
|
|
55
|
-
const json = JSON.stringify(trimQuotes(value.toString()))
|
|
56
|
-
const inner = json.slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'")
|
|
57
|
-
return `'${inner}'`
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
|
|
62
|
-
* and the Unicode line terminators U+2028 and U+2029.
|
|
63
|
-
*
|
|
64
|
-
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
65
|
-
*
|
|
66
|
-
* @example
|
|
67
|
-
* ```ts
|
|
68
|
-
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
69
|
-
* ```
|
|
70
|
-
*/
|
|
71
|
-
export function jsStringEscape(input: unknown): string {
|
|
72
|
-
return `${input}`.replace(/["'\\\n\r\u2028\u2029]/g, (character) => {
|
|
73
|
-
switch (character) {
|
|
74
|
-
case '"':
|
|
75
|
-
case "'":
|
|
76
|
-
case '\\':
|
|
77
|
-
return `\\${character}`
|
|
78
|
-
case '\n':
|
|
79
|
-
return '\\n'
|
|
80
|
-
case '\r':
|
|
81
|
-
return '\\r'
|
|
82
|
-
case '\u2028':
|
|
83
|
-
return '\\u2028'
|
|
84
|
-
case '\u2029':
|
|
85
|
-
return '\\u2029'
|
|
86
|
-
default:
|
|
87
|
-
return ''
|
|
88
|
-
}
|
|
89
|
-
})
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
|
|
94
|
-
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
|
|
95
|
-
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
|
|
96
|
-
*
|
|
97
|
-
* @example
|
|
98
|
-
* ```ts
|
|
99
|
-
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
100
|
-
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
101
|
-
* ```
|
|
102
|
-
*/
|
|
103
|
-
export function toRegExpString(text: string, func: string | null = 'RegExp'): string {
|
|
104
|
-
const raw = trimQuotes(text)
|
|
105
|
-
|
|
106
|
-
const match = raw.match(/^\^(\(\?([igmsuy]+)\))/i)
|
|
107
|
-
const replacementTarget = match?.[1] ?? ''
|
|
108
|
-
const matchedFlags = match?.[2]
|
|
109
|
-
const cleaned = raw
|
|
110
|
-
.replace(/^\\?\//, '')
|
|
111
|
-
.replace(/\\?\/$/, '')
|
|
112
|
-
.replace(replacementTarget, '')
|
|
113
|
-
|
|
114
|
-
const { source, flags } = new RegExp(cleaned, matchedFlags)
|
|
115
|
-
|
|
116
|
-
if (func === null) return `/${source}/${flags}`
|
|
117
|
-
|
|
118
|
-
return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ''})`
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
|
|
123
|
-
* objects recurse with fixed indentation, so the result drops straight into an object literal
|
|
124
|
-
* without re-parsing.
|
|
125
|
-
*
|
|
126
|
-
* @example
|
|
127
|
-
* ```ts
|
|
128
|
-
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
|
|
129
|
-
* // 'foo: bar,\nnested: {\n a: 1\n }'
|
|
130
|
-
* ```
|
|
131
|
-
*/
|
|
132
|
-
export function stringifyObject(value: Record<string, unknown>): string {
|
|
133
|
-
const items = Object.entries(value)
|
|
134
|
-
.map(([key, val]) => {
|
|
135
|
-
if (val !== null && typeof val === 'object') {
|
|
136
|
-
return `${key}: {\n ${stringifyObject(val as Record<string, unknown>)}\n }`
|
|
137
|
-
}
|
|
138
|
-
return `${key}: ${val}`
|
|
139
|
-
})
|
|
140
|
-
.filter(Boolean)
|
|
141
|
-
return items.join(',\n')
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
|
|
146
|
-
* `accessor`. Returns `null` for an empty path.
|
|
147
|
-
*
|
|
148
|
-
* @example
|
|
149
|
-
* ```ts
|
|
150
|
-
* getNestedAccessor('pagination.next.id', 'lastPage')
|
|
151
|
-
* // "lastPage?.['pagination']?.['next']?.['id']"
|
|
152
|
-
* ```
|
|
153
|
-
*/
|
|
154
|
-
export function getNestedAccessor(param: string | Array<string>, accessor: string): string | null {
|
|
155
|
-
const parts = Array.isArray(param) ? param : param.split('.')
|
|
156
|
-
if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) return null
|
|
157
|
-
return `${accessor}?.['${`${parts.join("']?.['")}']`}`
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Builds a JSDoc comment block from an array of lines, returning `fallback` when there are no
|
|
162
|
-
* comments so callers always get a usable string.
|
|
163
|
-
*
|
|
164
|
-
* @example
|
|
165
|
-
* ```ts
|
|
166
|
-
* buildJSDoc(['@type string', '@example hello'])
|
|
167
|
-
* // '/**\n * @type string\n * @example hello\n *\/\n '
|
|
168
|
-
* ```
|
|
169
|
-
*/
|
|
170
|
-
export function buildJSDoc(
|
|
171
|
-
comments: Array<string>,
|
|
172
|
-
options: {
|
|
173
|
-
/**
|
|
174
|
-
* String used to indent each comment line.
|
|
175
|
-
* @default ' * '
|
|
176
|
-
*/
|
|
177
|
-
indent?: string
|
|
178
|
-
/**
|
|
179
|
-
* String appended after the closing tag.
|
|
180
|
-
* @default '\n '
|
|
181
|
-
*/
|
|
182
|
-
suffix?: string
|
|
183
|
-
/**
|
|
184
|
-
* Returned as-is when `comments` is empty.
|
|
185
|
-
* @default ' '
|
|
186
|
-
*/
|
|
187
|
-
fallback?: string
|
|
188
|
-
} = {},
|
|
189
|
-
): string {
|
|
190
|
-
const { indent = ' * ', suffix = '\n ', fallback = ' ' } = options
|
|
191
|
-
|
|
192
|
-
if (comments.length === 0) return fallback
|
|
193
|
-
|
|
194
|
-
return `/**\n${comments.map((c) => `${indent}${c}`).join('\n')}\n */${suffix}`
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* Indents every non-empty line of `text` by one indent level, leaving blank lines empty.
|
|
199
|
-
*/
|
|
200
|
-
function indentLines(text: string): string {
|
|
201
|
-
if (!text) return ''
|
|
202
|
-
return text
|
|
203
|
-
.split('\n')
|
|
204
|
-
.map((line) => (line.trim() ? `${INDENT}${line}` : ''))
|
|
205
|
-
.join('\n')
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
|
|
210
|
-
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
|
|
211
|
-
*
|
|
212
|
-
* @example
|
|
213
|
-
* ```ts
|
|
214
|
-
* objectKey('name') // 'name'
|
|
215
|
-
* objectKey('x-total') // "'x-total'"
|
|
216
|
-
* ```
|
|
217
|
-
*/
|
|
218
|
-
export function objectKey(name: string): string {
|
|
219
|
-
return isIdentifier(name) ? name : singleQuote(name)
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
224
|
-
* level and closing the brace at column zero. Nested objects built the same way indent cumulatively,
|
|
225
|
-
* so callers never re-parse the generated code. A trailing comma is added per entry to match the
|
|
226
|
-
* formatter's multi-line style.
|
|
227
|
-
*
|
|
228
|
-
* @example
|
|
229
|
-
* ```ts
|
|
230
|
-
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
231
|
-
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
232
|
-
* ```
|
|
233
|
-
*/
|
|
234
|
-
export function buildObject(entries: Array<string>): string {
|
|
235
|
-
if (entries.length === 0) return '{}'
|
|
236
|
-
const body = entries.map((entry) => `${indentLines(entry)},`).join('\n')
|
|
237
|
-
|
|
238
|
-
return `{\n${body}\n}`
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
243
|
-
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
244
|
-
* one level with a trailing comma and the closing bracket at column zero. Use it for `z.union([…])`,
|
|
245
|
-
* `z.array([…])`, and similar member lists so objects inside them nest correctly.
|
|
246
|
-
*
|
|
247
|
-
* @example
|
|
248
|
-
* ```ts
|
|
249
|
-
* buildList(['z.string()', 'z.number()'])
|
|
250
|
-
* // '[z.string(), z.number()]'
|
|
251
|
-
* ```
|
|
252
|
-
*/
|
|
253
|
-
export function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {
|
|
254
|
-
const [open, close] = brackets
|
|
255
|
-
if (items.length === 0) return `${open}${close}`
|
|
256
|
-
if (!items.some((item) => item.includes('\n'))) return `${open}${items.join(', ')}${close}`
|
|
257
|
-
const body = items.map((item) => `${indentLines(item)},`).join('\n')
|
|
258
|
-
|
|
259
|
-
return `${open}\n${body}\n${close}`
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* Returns the last path segment of a reference string.
|
|
264
|
-
*
|
|
265
|
-
* @example
|
|
266
|
-
* ```ts
|
|
267
|
-
* extractRefName('#/components/schemas/Pet') // 'Pet'
|
|
268
|
-
* ```
|
|
269
|
-
*/
|
|
270
|
-
export function extractRefName(ref: string): string {
|
|
271
|
-
return ref.split('/').at(-1) ?? ref
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/**
|
|
275
|
-
* Builds a PascalCase child schema name by joining a parent name and property name.
|
|
276
|
-
* Returns `null` when there is no parent to nest under.
|
|
277
|
-
*
|
|
278
|
-
* @example
|
|
279
|
-
* ```ts
|
|
280
|
-
* childName('Order', 'shipping_address') // 'OrderShippingAddress'
|
|
281
|
-
* childName(undefined, 'params') // null
|
|
282
|
-
* ```
|
|
283
|
-
*/
|
|
284
|
-
export function childName(parentName: string | null | undefined, propName: string): string | null {
|
|
285
|
-
return parentName ? pascalCase([parentName, propName].join(' ')) : null
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
|
|
290
|
-
* empty parts.
|
|
291
|
-
*
|
|
292
|
-
* @example
|
|
293
|
-
* ```ts
|
|
294
|
-
* enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
|
|
295
|
-
* ```
|
|
296
|
-
*/
|
|
297
|
-
export function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {
|
|
298
|
-
return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Returns the discriminator key whose mapping value matches `ref`, or `null` when there is no match.
|
|
303
|
-
*
|
|
304
|
-
* @example
|
|
305
|
-
* ```ts
|
|
306
|
-
* findDiscriminator({ dog: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // 'dog'
|
|
307
|
-
* ```
|
|
308
|
-
*/
|
|
309
|
-
export function findDiscriminator(mapping: Record<string, string> | undefined, ref: string | undefined): string | null {
|
|
310
|
-
if (!mapping || !ref) return null
|
|
311
|
-
return Object.entries(mapping).find(([, value]) => value === ref)?.[0] ?? null
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* Derives a {@link ParamGroupType} for a query or header group from the resolver.
|
|
316
|
-
*
|
|
317
|
-
* Returns `null` when there is no resolver, no params, or the group name equals the
|
|
318
|
-
* individual param name (so there is no real group to emit).
|
|
319
|
-
*/
|
|
320
|
-
export function resolveGroupType({
|
|
321
|
-
node,
|
|
322
|
-
params,
|
|
323
|
-
group,
|
|
324
|
-
resolver,
|
|
325
|
-
}: {
|
|
326
|
-
node: OperationNode
|
|
327
|
-
params: Array<ParameterNode>
|
|
328
|
-
group: 'query' | 'header'
|
|
329
|
-
resolver: OperationParamsResolver | undefined
|
|
330
|
-
}): ParamGroupType | null {
|
|
331
|
-
if (!resolver || !params.length) {
|
|
332
|
-
return null
|
|
333
|
-
}
|
|
334
|
-
const firstParam = params[0]!
|
|
335
|
-
const groupMethod = group === 'query' ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName
|
|
336
|
-
const groupName = groupMethod.call(resolver, node, firstParam)
|
|
337
|
-
if (groupName === resolver.resolveParamName(node, firstParam)) {
|
|
338
|
-
return null
|
|
339
|
-
}
|
|
340
|
-
return { type: groupName, optional: params.every((p) => !p.required) }
|
|
341
|
-
}
|
|
4
|
+
export { childName, enumPropName, extractRefName, isStringType, resolveGroupType } from './refs.ts'
|
|
5
|
+
export { syncSchemaRef } from '../transformers.ts'
|
|
6
|
+
export { getNestedAccessor, jsStringEscape, stringify, stringifyObject, toRegExpString, trimQuotes } from './strings.ts'
|
|
7
|
+
export { collectUsedSchemaNames, containsCircularRef, findCircularSchemas } from './schemaGraph.ts'
|
|
8
|
+
export { buildGroupParam, buildTypeLiteral, caseParams, createOperationParams, resolveParamType } from './operationParams.ts'
|
|
9
|
+
export type { BuildGroupArgs, ParamGroupType } from './operationParams.ts'
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { camelCase, isValidVarName, memoize } from '@internals/utils'
|
|
2
|
+
import { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'
|
|
3
|
+
import type { FunctionParameterNode, FunctionParametersNode, OperationNode, ParameterNode, TypeExpression, TypeLiteralNode } from '../nodes/index.ts'
|
|
4
|
+
import { resolveGroupType } from './refs.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Applies casing rules to parameter names and returns a new array without mutating the input.
|
|
8
|
+
*
|
|
9
|
+
* Run it before handing parameters to schema builders so output property keys get the right casing
|
|
10
|
+
* while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
|
|
11
|
+
* original array is returned unchanged.
|
|
12
|
+
*/
|
|
13
|
+
const caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>
|
|
14
|
+
memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>
|
|
15
|
+
params.map((param) => {
|
|
16
|
+
const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name
|
|
17
|
+
return { ...param, name: transformed }
|
|
18
|
+
}),
|
|
19
|
+
),
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
export function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {
|
|
23
|
+
if (!casing) return params
|
|
24
|
+
return caseParamsMemo(params)(casing)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Named type for a group of parameters (query or header) emitted as a single typed parameter.
|
|
29
|
+
*/
|
|
30
|
+
export type ParamGroupType = {
|
|
31
|
+
/**
|
|
32
|
+
* Type expression for the group, a plain group-name reference.
|
|
33
|
+
*/
|
|
34
|
+
type: TypeExpression
|
|
35
|
+
/**
|
|
36
|
+
* Whether the parameter group is optional.
|
|
37
|
+
*/
|
|
38
|
+
optional: boolean
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.
|
|
43
|
+
*/
|
|
44
|
+
type GroupProperty = {
|
|
45
|
+
name: string
|
|
46
|
+
type: TypeExpression
|
|
47
|
+
optional?: boolean
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Resolver interface for {@link createOperationParams}.
|
|
52
|
+
*
|
|
53
|
+
* `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.
|
|
54
|
+
*/
|
|
55
|
+
export type OperationParamsResolver = {
|
|
56
|
+
/**
|
|
57
|
+
* Resolves the type name for an individual parameter.
|
|
58
|
+
*
|
|
59
|
+
* @example Individual path parameter name
|
|
60
|
+
* `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`
|
|
61
|
+
*/
|
|
62
|
+
resolveParamName(node: OperationNode, param: ParameterNode): string
|
|
63
|
+
/**
|
|
64
|
+
* Resolves the request body type name.
|
|
65
|
+
*
|
|
66
|
+
* @example Request body type name
|
|
67
|
+
* `resolver.resolveDataName(node) // → 'CreatePetData'`
|
|
68
|
+
*/
|
|
69
|
+
resolveDataName(node: OperationNode): string
|
|
70
|
+
/**
|
|
71
|
+
* Resolves the grouped path parameters type name.
|
|
72
|
+
* When the return value equals `resolveParamName`, no indexed access is emitted.
|
|
73
|
+
*
|
|
74
|
+
* @example Grouped path params type name
|
|
75
|
+
* `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`
|
|
76
|
+
*/
|
|
77
|
+
resolvePathParamsName(node: OperationNode, param: ParameterNode): string
|
|
78
|
+
/**
|
|
79
|
+
* Resolves the grouped query parameters type name.
|
|
80
|
+
* When the return value equals `resolveParamName`, an inline struct type is emitted instead.
|
|
81
|
+
*
|
|
82
|
+
* @example Grouped query params type name
|
|
83
|
+
* `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
|
|
84
|
+
*/
|
|
85
|
+
resolveQueryParamsName(node: OperationNode, param: ParameterNode): string
|
|
86
|
+
/**
|
|
87
|
+
* Resolves the grouped header parameters type name.
|
|
88
|
+
* When the return value equals `resolveParamName`, an inline struct type is emitted instead.
|
|
89
|
+
*
|
|
90
|
+
* @example Grouped header params type name
|
|
91
|
+
* `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
|
|
92
|
+
*/
|
|
93
|
+
resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Options for {@link createOperationParams}.
|
|
98
|
+
*/
|
|
99
|
+
export type CreateOperationParamsOptions = {
|
|
100
|
+
/**
|
|
101
|
+
* How all operation parameters are grouped in the function signature.
|
|
102
|
+
* - `'object'` wraps all params into a single destructured object `{ petId, data, params }`
|
|
103
|
+
* - `'inline'` emits each param category as a separate top-level parameter
|
|
104
|
+
*/
|
|
105
|
+
paramsType: 'object' | 'inline'
|
|
106
|
+
/**
|
|
107
|
+
* How path parameters are emitted when `paramsType` is `'inline'`.
|
|
108
|
+
* - `'object'` groups them as `{ petId, storeId }: PathParams`
|
|
109
|
+
* - `'inline'` spreads them as individual parameters `petId: string, storeId: string`
|
|
110
|
+
* - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`
|
|
111
|
+
*/
|
|
112
|
+
pathParamsType: 'object' | 'inline' | 'inlineSpread'
|
|
113
|
+
/**
|
|
114
|
+
* Converts parameter names to camelCase before output.
|
|
115
|
+
*/
|
|
116
|
+
paramsCasing?: 'camelcase'
|
|
117
|
+
/**
|
|
118
|
+
* Resolver for parameter and request body type names.
|
|
119
|
+
* Pass `ResolverTs` from `@kubb/plugin-ts` directly.
|
|
120
|
+
* When omitted, falls back to the schema primitive or `'unknown'`.
|
|
121
|
+
*/
|
|
122
|
+
resolver?: OperationParamsResolver
|
|
123
|
+
/**
|
|
124
|
+
* Default value for the path parameters binding when `pathParamsType` is `'object'`.
|
|
125
|
+
* Falls back to `'{}'` when all path params are optional.
|
|
126
|
+
*/
|
|
127
|
+
pathParamsDefault?: string
|
|
128
|
+
/**
|
|
129
|
+
* Extra parameters appended after the standard operation parameters.
|
|
130
|
+
*
|
|
131
|
+
* @example Plugin-specific trailing parameter
|
|
132
|
+
* ```ts
|
|
133
|
+
* extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
extraParams?: Array<FunctionParameterNode>
|
|
137
|
+
/**
|
|
138
|
+
* Override the default parameter names used for body, query, header, and rest-path groups.
|
|
139
|
+
*
|
|
140
|
+
* Useful when targeting languages or frameworks with different naming conventions.
|
|
141
|
+
*
|
|
142
|
+
* @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }
|
|
143
|
+
*/
|
|
144
|
+
paramNames?: {
|
|
145
|
+
/**
|
|
146
|
+
* Name for the request body parameter.
|
|
147
|
+
* @default 'data'
|
|
148
|
+
*/
|
|
149
|
+
data?: string
|
|
150
|
+
/**
|
|
151
|
+
* Name for the query parameters group parameter.
|
|
152
|
+
* @default 'params'
|
|
153
|
+
*/
|
|
154
|
+
params?: string
|
|
155
|
+
/**
|
|
156
|
+
* Name for the header parameters group parameter.
|
|
157
|
+
* @default 'headers'
|
|
158
|
+
*/
|
|
159
|
+
headers?: string
|
|
160
|
+
/**
|
|
161
|
+
* Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.
|
|
162
|
+
* @default 'pathParams'
|
|
163
|
+
*/
|
|
164
|
+
path?: string
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Transforms every resolved type name before it lands in a parameter node, for framework-level
|
|
168
|
+
* type wrappers.
|
|
169
|
+
*
|
|
170
|
+
* @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`
|
|
171
|
+
* `typeWrapper: (t) => \`MaybeRefOrGetter<${t}>\``
|
|
172
|
+
*/
|
|
173
|
+
typeWrapper?: (type: string) => string
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Resolves the {@link TypeExpression} for an individual parameter.
|
|
178
|
+
*
|
|
179
|
+
* Without a resolver, it falls back to the schema primitive (a plain type-name string). When the
|
|
180
|
+
* parameter belongs to a named group, it emits an {@link IndexedAccessTypeNode} like
|
|
181
|
+
* `GroupParams['petId']`, otherwise the resolved individual name.
|
|
182
|
+
*/
|
|
183
|
+
export function resolveParamType({
|
|
184
|
+
node,
|
|
185
|
+
param,
|
|
186
|
+
resolver,
|
|
187
|
+
}: {
|
|
188
|
+
node: OperationNode
|
|
189
|
+
param: ParameterNode
|
|
190
|
+
resolver: OperationParamsResolver | undefined
|
|
191
|
+
}): TypeExpression {
|
|
192
|
+
if (!resolver) {
|
|
193
|
+
return param.schema.primitive ?? 'unknown'
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const individualName = resolver.resolveParamName(node, param)
|
|
197
|
+
|
|
198
|
+
const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined
|
|
199
|
+
|
|
200
|
+
const groupResolvers = {
|
|
201
|
+
path: resolver.resolvePathParamsName,
|
|
202
|
+
query: resolver.resolveQueryParamsName,
|
|
203
|
+
header: resolver.resolveHeaderParamsName,
|
|
204
|
+
} as const
|
|
205
|
+
|
|
206
|
+
const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined
|
|
207
|
+
|
|
208
|
+
if (groupName && groupName !== individualName) {
|
|
209
|
+
return createIndexedAccessType({ objectType: groupName, indexType: param.name })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return individualName
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Converts an `OperationNode` into function parameters for code generation.
|
|
217
|
+
*
|
|
218
|
+
* Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
|
|
219
|
+
* destructured object parameter (`object`) and separate top-level parameters (`inline`), while
|
|
220
|
+
* `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
|
|
221
|
+
* name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
|
|
222
|
+
*/
|
|
223
|
+
export function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {
|
|
224
|
+
const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options
|
|
225
|
+
|
|
226
|
+
const dataName = paramNames?.data ?? 'data'
|
|
227
|
+
const paramsName = paramNames?.params ?? 'params'
|
|
228
|
+
const headersName = paramNames?.headers ?? 'headers'
|
|
229
|
+
const pathName = paramNames?.path ?? 'pathParams'
|
|
230
|
+
|
|
231
|
+
const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)
|
|
232
|
+
// Only plain type-name references are wrapped, they need casing applied.
|
|
233
|
+
// TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.
|
|
234
|
+
const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)
|
|
235
|
+
|
|
236
|
+
const casedParams = caseParams(node.parameters, paramsCasing)
|
|
237
|
+
const pathParams = casedParams.filter((p) => p.in === 'path')
|
|
238
|
+
const queryParams = casedParams.filter((p) => p.in === 'query')
|
|
239
|
+
const headerParams = casedParams.filter((p) => p.in === 'header')
|
|
240
|
+
|
|
241
|
+
const toProperty = (param: ParameterNode): GroupProperty => ({
|
|
242
|
+
name: param.name,
|
|
243
|
+
type: wrapTypeExpression(resolveParamType({ node, param, resolver })),
|
|
244
|
+
optional: !param.required,
|
|
245
|
+
})
|
|
246
|
+
const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)
|
|
247
|
+
|
|
248
|
+
const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined
|
|
249
|
+
const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []
|
|
250
|
+
|
|
251
|
+
const trailingGroups: Array<BuildGroupArgs> = [
|
|
252
|
+
{ name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },
|
|
253
|
+
{
|
|
254
|
+
name: headersName,
|
|
255
|
+
node,
|
|
256
|
+
params: headerParams,
|
|
257
|
+
groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),
|
|
258
|
+
resolver,
|
|
259
|
+
wrapType,
|
|
260
|
+
},
|
|
261
|
+
]
|
|
262
|
+
|
|
263
|
+
const params: Array<FunctionParameterNode> = []
|
|
264
|
+
|
|
265
|
+
if (paramsType === 'object') {
|
|
266
|
+
const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]
|
|
267
|
+
if (children.length) {
|
|
268
|
+
params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))
|
|
269
|
+
}
|
|
270
|
+
} else {
|
|
271
|
+
if (pathParamsType === 'inlineSpread' && pathParams.length) {
|
|
272
|
+
const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)
|
|
273
|
+
params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))
|
|
274
|
+
} else if (pathParamsType === 'inline') {
|
|
275
|
+
params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))
|
|
276
|
+
} else if (pathParams.length) {
|
|
277
|
+
const pathChildren = pathParams.map(toProperty)
|
|
278
|
+
params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
params.push(...bodyProperty.map((p) => createFunctionParameter(p)))
|
|
282
|
+
params.push(...trailingGroups.flatMap(buildGroupParam))
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
params.push(...extraParams)
|
|
286
|
+
|
|
287
|
+
return createFunctionParameters({ params })
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Shared arguments for building a query or header parameter group.
|
|
292
|
+
*/
|
|
293
|
+
export type BuildGroupArgs = {
|
|
294
|
+
name: string
|
|
295
|
+
node: OperationNode
|
|
296
|
+
params: Array<ParameterNode>
|
|
297
|
+
groupType: ParamGroupType | null
|
|
298
|
+
resolver: OperationParamsResolver | undefined
|
|
299
|
+
wrapType: (type: string) => string
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Builds the property descriptor for a query or header group.
|
|
304
|
+
* Returns an empty array when there are no params to emit.
|
|
305
|
+
*
|
|
306
|
+
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
307
|
+
* {@link TypeLiteralNode} from the individual params.
|
|
308
|
+
*/
|
|
309
|
+
function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {
|
|
310
|
+
if (groupType) {
|
|
311
|
+
const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type
|
|
312
|
+
return [{ name, type, optional: groupType.optional }]
|
|
313
|
+
}
|
|
314
|
+
if (params.length) {
|
|
315
|
+
return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]
|
|
316
|
+
}
|
|
317
|
+
return []
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Builds a single {@link FunctionParameterNode} for a query or header group.
|
|
322
|
+
* Returns an empty array when there are no params to emit.
|
|
323
|
+
*
|
|
324
|
+
* A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
|
|
325
|
+
* {@link TypeLiteralNode} from the individual params.
|
|
326
|
+
*/
|
|
327
|
+
export function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {
|
|
328
|
+
return buildGroupProperty(args).map((p) => createFunctionParameter(p))
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
|
|
333
|
+
*
|
|
334
|
+
* Used when query or header parameters have no dedicated group type name.
|
|
335
|
+
* Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
|
|
336
|
+
*/
|
|
337
|
+
export function buildTypeLiteral({
|
|
338
|
+
node,
|
|
339
|
+
params,
|
|
340
|
+
resolver,
|
|
341
|
+
}: {
|
|
342
|
+
node: OperationNode
|
|
343
|
+
params: Array<ParameterNode>
|
|
344
|
+
resolver: OperationParamsResolver | undefined
|
|
345
|
+
}): TypeLiteralNode {
|
|
346
|
+
return createTypeLiteral({
|
|
347
|
+
members: params.map((p) => ({
|
|
348
|
+
name: p.name,
|
|
349
|
+
type: resolveParamType({ node, param: p, resolver }),
|
|
350
|
+
optional: !p.required,
|
|
351
|
+
})),
|
|
352
|
+
})
|
|
353
|
+
}
|