@kubb/ast 5.0.0-beta.63 → 5.0.0-beta.64

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 (69) hide show
  1. package/dist/{defineMacro-Shz8f6SG.js → defineMacro-B76LsJwO.js} +4 -4
  2. package/dist/{defineMacro-Shz8f6SG.js.map → defineMacro-B76LsJwO.js.map} +1 -1
  3. package/dist/{defineMacro-BATi7xoC.d.ts → defineMacro-B7qm3zTd.d.ts} +3 -3
  4. package/dist/factory-wJLzHeXT.d.ts +27 -0
  5. package/dist/factory.d.ts +3 -27
  6. package/dist/factory.js +2 -2
  7. package/dist/{index-B9cc8MBS.d.ts → index-BKD4drsX.d.ts} +2 -2
  8. package/dist/index.cjs +54 -2
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.ts +24 -21
  11. package/dist/index.js +54 -8
  12. package/dist/index.js.map +1 -1
  13. package/dist/macros.d.ts +2 -2
  14. package/dist/macros.js +4 -4
  15. package/dist/{operationParams-k5CKwSWZ.d.ts → operationParams-ByVfpYr7.d.ts} +3 -3
  16. package/dist/{refs-BjNDuCBD.js → refs-Dx6U5LoE.js} +3 -3
  17. package/dist/{refs-BjNDuCBD.js.map → refs-Dx6U5LoE.js.map} +1 -1
  18. package/dist/{schema-Cbnxmz4b.js → schema-YNbOtTCM.js} +2 -2
  19. package/dist/{schema-Cbnxmz4b.js.map → schema-YNbOtTCM.js.map} +1 -1
  20. package/dist/{types-BB_xgRJ3.d.ts → types-BP9BZoq-.d.ts} +8 -8
  21. package/dist/types.d.ts +5 -5
  22. package/dist/{utils-DaXkewb1.js → utils-BJi0y-xg.js} +4 -4
  23. package/dist/{utils-DaXkewb1.js.map → utils-BJi0y-xg.js.map} +1 -1
  24. package/dist/utils.d.ts +3 -3
  25. package/dist/utils.js +3 -3
  26. package/package.json +1 -2
  27. package/src/constants.ts +0 -150
  28. package/src/defineMacro.ts +0 -139
  29. package/src/defineNode.ts +0 -102
  30. package/src/definePrinter.ts +0 -258
  31. package/src/dialect.ts +0 -86
  32. package/src/factory.ts +0 -44
  33. package/src/guards.ts +0 -28
  34. package/src/index.ts +0 -13
  35. package/src/infer.ts +0 -132
  36. package/src/macros/index.ts +0 -3
  37. package/src/macros/macroDiscriminatorEnum.ts +0 -50
  38. package/src/macros/macroEnumName.ts +0 -33
  39. package/src/macros/macroSimplifyUnion.ts +0 -60
  40. package/src/nodes/base.ts +0 -49
  41. package/src/nodes/code.ts +0 -355
  42. package/src/nodes/content.ts +0 -51
  43. package/src/nodes/file.ts +0 -380
  44. package/src/nodes/function.ts +0 -283
  45. package/src/nodes/index.ts +0 -93
  46. package/src/nodes/input.ts +0 -144
  47. package/src/nodes/operation.ts +0 -168
  48. package/src/nodes/output.ts +0 -49
  49. package/src/nodes/parameter.ts +0 -71
  50. package/src/nodes/property.ts +0 -67
  51. package/src/nodes/requestBody.ts +0 -54
  52. package/src/nodes/response.ts +0 -173
  53. package/src/nodes/schema.ts +0 -732
  54. package/src/optionality.ts +0 -15
  55. package/src/registry.ts +0 -75
  56. package/src/signature.ts +0 -207
  57. package/src/types.ts +0 -8
  58. package/src/utils/codegen.ts +0 -103
  59. package/src/utils/extractStringsFromNodes.ts +0 -35
  60. package/src/utils/fileMerge.ts +0 -183
  61. package/src/utils/index.ts +0 -11
  62. package/src/utils/operationParams.ts +0 -353
  63. package/src/utils/refs.ts +0 -134
  64. package/src/utils/schemaGraph.ts +0 -177
  65. package/src/utils/schemaMerge.ts +0 -34
  66. package/src/utils/schemaTraversal.ts +0 -86
  67. package/src/utils/strings.ts +0 -139
  68. package/src/visitor.ts +0 -519
  69. /package/dist/{chunk-CNktS9qV.js → rolldown-runtime-CNktS9qV.js} +0 -0
@@ -1,353 +0,0 @@
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
- const caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>
7
- memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>
8
- params.map((param) => {
9
- const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name
10
- return { ...param, name: transformed }
11
- }),
12
- ),
13
- )
14
-
15
- /**
16
- * Applies casing rules to parameter names and returns a new array without mutating the input.
17
- *
18
- * Run it before handing parameters to schema builders so output property keys get the right casing
19
- * while `OperationNode.parameters` stays intact for other consumers. When `casing` is unset, the
20
- * original array is returned unchanged.
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({ target: groupName, key: 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
- // typeWrapper takes a type-name string, so only plain references are wrapped.
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
- }
package/src/utils/refs.ts DELETED
@@ -1,134 +0,0 @@
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
- * `extractRefName('#/components/schemas/Pet') // 'Pet'`
14
- */
15
- export function extractRefName(ref: string): string {
16
- return ref.split('/').at(-1) ?? ref
17
- }
18
-
19
- /**
20
- * Resolves the schema name of a ref node. Uses the last segment of `ref` when set, otherwise falls
21
- * back to `name` then nested `schema.name`.
22
- *
23
- * Returns `null` for non-ref nodes or when no name resolves.
24
- *
25
- * @example
26
- * `resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' }) // 'Pet'`
27
- */
28
- export function resolveRefName(node: SchemaNode | undefined): string | null {
29
- if (!node || node.type !== 'ref') return null
30
- if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null
31
-
32
- return node.name ?? node.schema?.name ?? null
33
- }
34
-
35
- /**
36
- * Builds a PascalCase child schema name by joining a parent name and property name.
37
- * Returns `null` when there is no parent to nest under.
38
- *
39
- * @example Nested under a parent
40
- * `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
41
- *
42
- * @example No parent
43
- * `childName(undefined, 'params') // null`
44
- */
45
- export function childName(parentName: string | null | undefined, propName: string): string | null {
46
- return parentName ? pascalCase([parentName, propName].join(' ')) : null
47
- }
48
-
49
- /**
50
- * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
51
- * empty parts.
52
- *
53
- * @example
54
- * `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
55
- */
56
- export function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {
57
- return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))
58
- }
59
-
60
- /**
61
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
62
- *
63
- * Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
64
- * same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
65
- * `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
66
- * nodes and refs without a resolved `schema` are returned unchanged.
67
- *
68
- * @example
69
- * ```ts
70
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
71
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
72
- * ```
73
- */
74
- export function syncSchemaRef(node: SchemaNode): SchemaNode {
75
- const ref = narrowSchema(node, 'ref')
76
-
77
- if (!ref) return node
78
- if (!ref.schema) return node
79
-
80
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref
81
-
82
- // Filter out undefined override values so they don't shadow the resolved schema's fields.
83
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
84
-
85
- return createSchema({ ...ref.schema, ...definedOverrides })
86
- }
87
-
88
- /**
89
- * Type guard that returns `true` when a schema emits as a plain `string` type.
90
- *
91
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
92
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
93
- */
94
- export function isStringType(node: SchemaNode): boolean {
95
- if (plainStringTypes.has(node.type)) {
96
- return true
97
- }
98
-
99
- const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')
100
- if (temporal) {
101
- return temporal.representation !== 'date'
102
- }
103
-
104
- return false
105
- }
106
-
107
- /**
108
- * Derives a {@link ParamGroupType} for a query or header group from the resolver.
109
- *
110
- * Returns `null` when there is no resolver, no params, or the group name equals the
111
- * individual param name (so there is no real group to emit).
112
- */
113
- export function resolveGroupType({
114
- node,
115
- params,
116
- group,
117
- resolver,
118
- }: {
119
- node: OperationNode
120
- params: Array<ParameterNode>
121
- group: 'query' | 'header'
122
- resolver: OperationParamsResolver | undefined
123
- }): ParamGroupType | null {
124
- if (!resolver || !params.length) {
125
- return null
126
- }
127
- const firstParam = params[0]!
128
- const groupMethod = group === 'query' ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName
129
- const groupName = groupMethod.call(resolver, node, firstParam)
130
- if (groupName === resolver.resolveParamName(node, firstParam)) {
131
- return null
132
- }
133
- return { type: groupName, optional: params.every((p) => !p.required) }
134
- }
@@ -1,177 +0,0 @@
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
- * Memoized inner pass that walks a single node and returns the names of every schema it references.
8
- */
9
- const collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {
10
- const refs = new Set<string>()
11
- collect<void>(node, {
12
- schema(child) {
13
- if (child.type === 'ref') {
14
- const name = resolveRefName(child)
15
- if (name) refs.add(name)
16
- }
17
- },
18
- })
19
- return refs
20
- })
21
-
22
- /**
23
- * Collects the names of every ref found anywhere inside a node's own subtree.
24
- *
25
- * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`
26
- * to accumulate names from several nodes into one set.
27
- *
28
- * @example Collect refs from a single schema
29
- * ```ts
30
- * const names = collectReferencedSchemaNames(petSchema)
31
- * // Set { 'Category', 'Tag' }
32
- * ```
33
- *
34
- * @example Accumulate refs from multiple schemas into one set
35
- * ```ts
36
- * const out = new Set<string>()
37
- * for (const schema of schemas) {
38
- * collectReferencedSchemaNames(schema, out)
39
- * }
40
- * ```
41
- */
42
- export function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {
43
- if (!node) return out
44
- for (const name of collectSchemaRefs(node)) out.add(name)
45
- return out
46
- }
47
-
48
- /**
49
- * Memoized two-level cache keyed first on the operations array, then on the schemas array.
50
- */
51
- const collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>
52
- memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),
53
- )
54
-
55
- function computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
56
- const schemaMap = new Map<string, SchemaNode>()
57
- for (const schema of schemas) {
58
- if (schema.name) schemaMap.set(schema.name, schema)
59
- }
60
-
61
- const result = new Set<string>()
62
-
63
- function visitSchema(schema: SchemaNode): void {
64
- const directRefs = collectReferencedSchemaNames(schema)
65
- for (const name of directRefs) {
66
- if (!result.has(name)) {
67
- result.add(name)
68
- const namedSchema = schemaMap.get(name)
69
- if (namedSchema) visitSchema(namedSchema)
70
- }
71
- }
72
- }
73
-
74
- for (const op of operations) {
75
- for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {
76
- visitSchema(schema)
77
- }
78
- }
79
-
80
- return result
81
- }
82
-
83
- /**
84
- * Collects the names of all top-level schemas transitively used by a set of operations.
85
- *
86
- * An operation uses a schema when its parameters, request body, or responses reference it, directly
87
- * or through other named schemas. Once a name is added to the result it is not revisited, so
88
- * reference cycles terminate.
89
- *
90
- * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
91
- *
92
- * @example Only generate schemas referenced by included operations
93
- * ```ts
94
- * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
95
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
96
- *
97
- * for (const schema of schemas) {
98
- * if (schema.name && !allowed.has(schema.name)) continue
99
- * // generate schema
100
- * }
101
- * ```
102
- */
103
- export function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
104
- return collectUsedSchemaNamesMemo(operations)(schemas)
105
- }
106
-
107
- const EMPTY_CIRCULAR_SET = new Set<string>()
108
-
109
- const findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {
110
- const graph = new Map<string, Set<string>>()
111
-
112
- for (const schema of schemas) {
113
- if (!schema.name) continue
114
- graph.set(schema.name, collectReferencedSchemaNames(schema))
115
- }
116
-
117
- const circular = new Set<string>()
118
- for (const start of graph.keys()) {
119
- const visited = new Set<string>()
120
- const stack: Array<string> = [...(graph.get(start) ?? [])]
121
- while (stack.length > 0) {
122
- const node = stack.pop()!
123
- if (node === start) {
124
- circular.add(start)
125
- break
126
- }
127
- if (visited.has(node)) continue
128
- visited.add(node)
129
-
130
- const next = graph.get(node)
131
- if (next) for (const r of next) stack.push(r)
132
- }
133
- }
134
-
135
- return circular
136
- })
137
-
138
- /**
139
- * Finds every schema that takes part in a circular dependency chain, including direct self-loops.
140
- *
141
- * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
142
- * the generated code does not recurse forever. Refs are followed by name only, so the walk stays
143
- * linear in the size of the schema graph.
144
- *
145
- * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
146
- */
147
- export function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {
148
- if (schemas.length === 0) return EMPTY_CIRCULAR_SET
149
- return findCircularSchemasMemo(schemas)
150
- }
151
-
152
- /**
153
- * Returns `true` when a schema, or anything nested inside it, references a circular schema.
154
- *
155
- * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
156
- * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
157
- *
158
- * @note Stops at the first matching circular ref.
159
- */
160
- export function containsCircularRef(
161
- node: SchemaNode | undefined,
162
- { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },
163
- ): boolean {
164
- if (!node || circularSchemas.size === 0) return false
165
-
166
- for (const _ of collectLazy<true>(node, {
167
- schema(child) {
168
- if (child.type !== 'ref') return null
169
- const name = resolveRefName(child)
170
- return name && name !== excludeName && circularSchemas.has(name) ? true : null
171
- },
172
- })) {
173
- return true
174
- }
175
-
176
- return false
177
- }
@@ -1,34 +0,0 @@
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 unchanged. The merge follows member order, so callers control which members
7
- * combine by where they place them in the sequence.
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
- }