@kubb/ast 5.0.0-beta.6 → 5.0.0-beta.61

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 (102) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +51 -27
  3. package/dist/chunk-CNktS9qV.js +17 -0
  4. package/dist/defineMacro-BLIR6k-j.d.ts +475 -0
  5. package/dist/defineMacro-BTXvS8nI.js +106 -0
  6. package/dist/defineMacro-BTXvS8nI.js.map +1 -0
  7. package/dist/defineMacro-Bv9R_9a2.cjs +123 -0
  8. package/dist/defineMacro-Bv9R_9a2.cjs.map +1 -0
  9. package/dist/extractStringsFromNodes-Cja-xxx5.js +29 -0
  10. package/dist/extractStringsFromNodes-Cja-xxx5.js.map +1 -0
  11. package/dist/extractStringsFromNodes-DKgDjFO0.cjs +34 -0
  12. package/dist/extractStringsFromNodes-DKgDjFO0.cjs.map +1 -0
  13. package/dist/extractStringsFromNodes-p4mX1TQD.d.ts +14 -0
  14. package/dist/factory-CZNOGI-N.js +283 -0
  15. package/dist/factory-CZNOGI-N.js.map +1 -0
  16. package/dist/factory-DG1CVkEb.cjs +300 -0
  17. package/dist/factory-DG1CVkEb.cjs.map +1 -0
  18. package/dist/factory.cjs +29 -0
  19. package/dist/factory.d.ts +62 -0
  20. package/dist/factory.js +3 -0
  21. package/dist/index-BzjwdK2M.d.ts +2433 -0
  22. package/dist/index.cjs +444 -2180
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +94 -3408
  25. package/dist/index.js +395 -2101
  26. package/dist/index.js.map +1 -1
  27. package/dist/macros.cjs +117 -0
  28. package/dist/macros.cjs.map +1 -0
  29. package/dist/macros.d.ts +59 -0
  30. package/dist/macros.js +115 -0
  31. package/dist/macros.js.map +1 -0
  32. package/dist/operationParams-BZ07xDm0.d.ts +204 -0
  33. package/dist/response-KUdWiDWw.js +658 -0
  34. package/dist/response-KUdWiDWw.js.map +1 -0
  35. package/dist/response-hnSw2NKE.cjs +1027 -0
  36. package/dist/response-hnSw2NKE.cjs.map +1 -0
  37. package/dist/types-DyDzizSf.d.ts +364 -0
  38. package/dist/types.cjs +0 -0
  39. package/dist/types.d.ts +6 -0
  40. package/dist/types.js +1 -0
  41. package/dist/utils-BLJwyza-.cjs +912 -0
  42. package/dist/utils-BLJwyza-.cjs.map +1 -0
  43. package/dist/utils-CF_-Pn_c.js +770 -0
  44. package/dist/utils-CF_-Pn_c.js.map +1 -0
  45. package/dist/utils.cjs +36 -0
  46. package/dist/utils.d.ts +358 -0
  47. package/dist/utils.js +4 -0
  48. package/dist/visitor-DJ6ZEJvq.js +548 -0
  49. package/dist/visitor-DJ6ZEJvq.js.map +1 -0
  50. package/dist/visitor-DpKZ9Tk0.cjs +654 -0
  51. package/dist/visitor-DpKZ9Tk0.cjs.map +1 -0
  52. package/package.json +21 -6
  53. package/src/constants.ts +19 -64
  54. package/src/dedupe.ts +239 -0
  55. package/src/defineMacro.ts +132 -0
  56. package/src/dialect.ts +53 -0
  57. package/src/factory.ts +67 -678
  58. package/src/guards.ts +10 -92
  59. package/src/index.ts +13 -44
  60. package/src/infer.ts +16 -14
  61. package/src/macros/index.ts +3 -0
  62. package/src/macros/macroDiscriminatorEnum.ts +44 -0
  63. package/src/macros/macroEnumName.ts +25 -0
  64. package/src/macros/macroSimplifyUnion.ts +50 -0
  65. package/src/mocks.ts +7 -127
  66. package/src/node.ts +128 -0
  67. package/src/nodes/base.ts +5 -12
  68. package/src/nodes/code.ts +165 -74
  69. package/src/nodes/content.ts +56 -0
  70. package/src/nodes/file.ts +97 -36
  71. package/src/nodes/function.ts +216 -156
  72. package/src/nodes/http.ts +1 -35
  73. package/src/nodes/index.ts +23 -15
  74. package/src/nodes/input.ts +140 -0
  75. package/src/nodes/operation.ts +122 -68
  76. package/src/nodes/output.ts +23 -0
  77. package/src/nodes/parameter.ts +33 -3
  78. package/src/nodes/property.ts +36 -3
  79. package/src/nodes/requestBody.ts +61 -0
  80. package/src/nodes/response.ts +58 -13
  81. package/src/nodes/schema.ts +93 -17
  82. package/src/printer.ts +48 -42
  83. package/src/registry.ts +75 -0
  84. package/src/signature.ts +207 -0
  85. package/src/types.ts +8 -68
  86. package/src/utils/codegen.ts +104 -0
  87. package/src/utils/extractStringsFromNodes.ts +34 -0
  88. package/src/utils/fileMerge.ts +184 -0
  89. package/src/utils/index.ts +11 -0
  90. package/src/utils/operationParams.ts +353 -0
  91. package/src/utils/refs.ts +138 -0
  92. package/src/utils/schemaGraph.ts +169 -0
  93. package/src/utils/schemaMerge.ts +34 -0
  94. package/src/utils/schemaTraversal.ts +86 -0
  95. package/src/utils/strings.ts +139 -0
  96. package/src/visitor.ts +227 -289
  97. package/dist/chunk--u3MIqq1.js +0 -8
  98. package/src/nodes/root.ts +0 -64
  99. package/src/refs.ts +0 -67
  100. package/src/resolvers.ts +0 -45
  101. package/src/transformers.ts +0 -159
  102. package/src/utils.ts +0 -915
@@ -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
+ }
@@ -0,0 +1,138 @@
1
+ import { pascalCase } from '@internals/utils'
2
+ import { narrowSchema } from '../guards.ts'
3
+ import type { OperationNode, ParameterNode, SchemaNode } from '../nodes/index.ts'
4
+ import { createSchema, type SchemaType } from '../nodes/schema.ts'
5
+ import type { OperationParamsResolver, ParamGroupType } from './operationParams.ts'
6
+
7
+ const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)
8
+
9
+ /**
10
+ * Returns the last path segment of a reference string.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * extractRefName('#/components/schemas/Pet') // 'Pet'
15
+ * ```
16
+ */
17
+ export function extractRefName(ref: string): string {
18
+ return ref.split('/').at(-1) ?? ref
19
+ }
20
+
21
+ /**
22
+ * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
23
+ *
24
+ * Returns `null` for non-ref nodes or when no name resolves.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
29
+ * // => 'Pet'
30
+ * ```
31
+ */
32
+ export function resolveRefName(node: SchemaNode | undefined): string | null {
33
+ if (!node || node.type !== 'ref') return null
34
+ if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null
35
+
36
+ return node.name ?? node.schema?.name ?? null
37
+ }
38
+
39
+ /**
40
+ * Builds a PascalCase child schema name by joining a parent name and property name.
41
+ * Returns `null` when there is no parent to nest under.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * childName('Order', 'shipping_address') // 'OrderShippingAddress'
46
+ * childName(undefined, 'params') // null
47
+ * ```
48
+ */
49
+ export function childName(parentName: string | null | undefined, propName: string): string | null {
50
+ return parentName ? pascalCase([parentName, propName].join(' ')) : null
51
+ }
52
+
53
+ /**
54
+ * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
55
+ * empty parts.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'
60
+ * ```
61
+ */
62
+ export function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {
63
+ return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))
64
+ }
65
+
66
+ /**
67
+ * Merges a ref node with its resolved schema, giving usage-site fields precedence.
68
+ *
69
+ * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
70
+ * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
75
+ * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
76
+ * ```
77
+ */
78
+ export function syncSchemaRef(node: SchemaNode): SchemaNode {
79
+ const ref = narrowSchema(node, 'ref')
80
+
81
+ if (!ref) return node
82
+ if (!ref.schema) return node
83
+
84
+ const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref
85
+
86
+ // Filter out undefined override values so they don't shadow the resolved schema's fields.
87
+ const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
88
+
89
+ return createSchema({ ...ref.schema, ...definedOverrides })
90
+ }
91
+
92
+ /**
93
+ * Type guard that returns `true` when a schema emits as a plain `string` type.
94
+ *
95
+ * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
96
+ * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
97
+ */
98
+ export function isStringType(node: SchemaNode): boolean {
99
+ if (plainStringTypes.has(node.type)) {
100
+ return true
101
+ }
102
+
103
+ const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')
104
+ if (temporal) {
105
+ return temporal.representation !== 'date'
106
+ }
107
+
108
+ return false
109
+ }
110
+
111
+ /**
112
+ * Derives a {@link ParamGroupType} for a query or header group from the resolver.
113
+ *
114
+ * Returns `null` when there is no resolver, no params, or the group name equals the
115
+ * individual param name (so there is no real group to emit).
116
+ */
117
+ export function resolveGroupType({
118
+ node,
119
+ params,
120
+ group,
121
+ resolver,
122
+ }: {
123
+ node: OperationNode
124
+ params: Array<ParameterNode>
125
+ group: 'query' | 'header'
126
+ resolver: OperationParamsResolver | undefined
127
+ }): ParamGroupType | null {
128
+ if (!resolver || !params.length) {
129
+ return null
130
+ }
131
+ const firstParam = params[0]!
132
+ const groupMethod = group === 'query' ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName
133
+ const groupName = groupMethod.call(resolver, node, firstParam)
134
+ if (groupName === resolver.resolveParamName(node, firstParam)) {
135
+ return null
136
+ }
137
+ return { type: groupName, optional: params.every((p) => !p.required) }
138
+ }
@@ -0,0 +1,169 @@
1
+ import { memoize } from '@internals/utils'
2
+ import type { OperationNode, SchemaNode } from '../nodes/index.ts'
3
+ import { collect, collectLazy } from '../visitor.ts'
4
+ import { resolveRefName } from './refs.ts'
5
+
6
+ /**
7
+ * Collects every named schema referenced transitively from a node through its ref edges.
8
+ *
9
+ * Refs are followed by name only, so the resolved `node.schema` is never traversed inline.
10
+ *
11
+ * @example Collect refs from a single schema
12
+ * ```ts
13
+ * const names = collectReferencedSchemaNames(petSchema)
14
+ * // → Set { 'Category', 'Tag' }
15
+ * ```
16
+ *
17
+ * @example Accumulate refs from multiple schemas into one set
18
+ * ```ts
19
+ * const out = new Set<string>()
20
+ * for (const schema of schemas) {
21
+ * collectReferencedSchemaNames(schema, out)
22
+ * }
23
+ * ```
24
+ */
25
+ const collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {
26
+ const refs = new Set<string>()
27
+ collect<void>(node, {
28
+ schema(child) {
29
+ if (child.type === 'ref') {
30
+ const name = resolveRefName(child)
31
+ if (name) refs.add(name)
32
+ }
33
+ },
34
+ })
35
+ return refs
36
+ })
37
+
38
+ export function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {
39
+ if (!node) return out
40
+ for (const name of collectSchemaRefs(node)) out.add(name)
41
+ return out
42
+ }
43
+
44
+ /**
45
+ * Collects the names of all top-level schemas transitively used by a set of operations.
46
+ *
47
+ * An operation uses a schema when its parameters, request body, or responses reference it, directly
48
+ * or through other named schemas. The walk is iterative, so reference cycles are safe.
49
+ *
50
+ * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
51
+ *
52
+ * @example Only generate schemas referenced by included operations
53
+ * ```ts
54
+ * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
55
+ * const allowed = collectUsedSchemaNames(includedOps, schemas)
56
+ *
57
+ * for (const schema of schemas) {
58
+ * if (schema.name && !allowed.has(schema.name)) continue
59
+ * // … generate schema
60
+ * }
61
+ * ```
62
+ */
63
+ const collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>
64
+ memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),
65
+ )
66
+
67
+ function computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
68
+ const schemaMap = new Map<string, SchemaNode>()
69
+ for (const schema of schemas) {
70
+ if (schema.name) schemaMap.set(schema.name, schema)
71
+ }
72
+
73
+ const result = new Set<string>()
74
+
75
+ function visitSchema(schema: SchemaNode): void {
76
+ const directRefs = collectReferencedSchemaNames(schema)
77
+ for (const name of directRefs) {
78
+ if (!result.has(name)) {
79
+ result.add(name)
80
+ const namedSchema = schemaMap.get(name)
81
+ if (namedSchema) visitSchema(namedSchema)
82
+ }
83
+ }
84
+ }
85
+
86
+ for (const op of operations) {
87
+ for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {
88
+ visitSchema(schema)
89
+ }
90
+ }
91
+
92
+ return result
93
+ }
94
+
95
+ export function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
96
+ return collectUsedSchemaNamesMemo(operations)(schemas)
97
+ }
98
+
99
+ const EMPTY_CIRCULAR_SET = new Set<string>()
100
+
101
+ const findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {
102
+ const graph = new Map<string, Set<string>>()
103
+
104
+ for (const schema of schemas) {
105
+ if (!schema.name) continue
106
+ graph.set(schema.name, collectReferencedSchemaNames(schema))
107
+ }
108
+
109
+ const circular = new Set<string>()
110
+ for (const start of graph.keys()) {
111
+ const visited = new Set<string>()
112
+ const stack: Array<string> = [...(graph.get(start) ?? [])]
113
+ while (stack.length > 0) {
114
+ const node = stack.pop()!
115
+ if (node === start) {
116
+ circular.add(start)
117
+ break
118
+ }
119
+ if (visited.has(node)) continue
120
+ visited.add(node)
121
+
122
+ const next = graph.get(node)
123
+ if (next) for (const r of next) stack.push(r)
124
+ }
125
+ }
126
+
127
+ return circular
128
+ })
129
+
130
+ /**
131
+ * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
132
+ *
133
+ * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
134
+ * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
135
+ * linear in the size of the schema graph.
136
+ *
137
+ * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
138
+ */
139
+ export function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {
140
+ if (schemas.length === 0) return EMPTY_CIRCULAR_SET
141
+ return findCircularSchemasMemo(schemas)
142
+ }
143
+
144
+ /**
145
+ * Returns `true` when a schema, or anything nested inside it, references a circular schema.
146
+ *
147
+ * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
148
+ * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
149
+ *
150
+ * @note Stops at the first matching circular ref.
151
+ */
152
+ export function containsCircularRef(
153
+ node: SchemaNode | undefined,
154
+ { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },
155
+ ): boolean {
156
+ if (!node || circularSchemas.size === 0) return false
157
+
158
+ for (const _ of collectLazy<true>(node, {
159
+ schema(child) {
160
+ if (child.type !== 'ref') return null
161
+ const name = resolveRefName(child)
162
+ return name && name !== excludeName && circularSchemas.has(name) ? true : null
163
+ },
164
+ })) {
165
+ return true
166
+ }
167
+
168
+ return false
169
+ }
@@ -0,0 +1,34 @@
1
+ import { narrowSchema } from '../guards.ts'
2
+ import { createSchema, type SchemaNode } from '../nodes/schema.ts'
3
+
4
+ /**
5
+ * Merges a run of adjacent anonymous object members into one. Named or non-object members break the
6
+ * run and pass through. Stays a construction-time helper, not a macro, so callers keep control of the
7
+ * member boundaries (such as keeping synthetic discriminant objects out of a run).
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
12
+ * ```
13
+ */
14
+ export function* mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined> {
15
+ let acc: SchemaNode | undefined
16
+
17
+ for (const member of members) {
18
+ const objectMember = narrowSchema(member, 'object')
19
+ if (objectMember && !objectMember.name && acc !== undefined) {
20
+ const accObject = narrowSchema(acc, 'object')
21
+ if (accObject && !accObject.name) {
22
+ acc = createSchema({
23
+ ...accObject,
24
+ properties: [...(accObject.properties ?? []), ...(objectMember.properties ?? [])],
25
+ })
26
+ continue
27
+ }
28
+ }
29
+ if (acc !== undefined) yield acc
30
+ acc = member
31
+ }
32
+
33
+ if (acc !== undefined) yield acc
34
+ }