@kubb/ast 5.0.0-beta.57 → 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.
Files changed (69) hide show
  1. package/README.md +21 -7
  2. package/dist/casing-BE2R1RXg.cjs +88 -0
  3. package/dist/casing-BE2R1RXg.cjs.map +1 -0
  4. package/dist/chunk-CNktS9qV.js +17 -0
  5. package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +82 -0
  6. package/dist/factory-BmcGBdeg.cjs +1251 -0
  7. package/dist/factory-BmcGBdeg.cjs.map +1 -0
  8. package/dist/factory-Du7nEP4B.js +282 -0
  9. package/dist/factory-Du7nEP4B.js.map +1 -0
  10. package/dist/factory.cjs +28 -0
  11. package/dist/factory.d.ts +62 -0
  12. package/dist/factory.js +3 -0
  13. package/dist/{types-C5aVnRE1.d.ts → index-BzjwdK2M.d.ts} +94 -1146
  14. package/dist/index.cjs +220 -1481
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +96 -58
  17. package/dist/index.js +182 -1920
  18. package/dist/index.js.map +1 -1
  19. package/dist/operationParams-BZ07xDm0.d.ts +204 -0
  20. package/dist/response-DKxTr522.js +683 -0
  21. package/dist/response-DKxTr522.js.map +1 -0
  22. package/dist/types-olVl9v5p.d.ts +764 -0
  23. package/dist/types.d.ts +5 -2
  24. package/dist/utils-BCtRXfhI.cjs +275 -0
  25. package/dist/utils-BCtRXfhI.cjs.map +1 -0
  26. package/dist/utils-SdZU0F3H.js +1336 -0
  27. package/dist/utils-SdZU0F3H.js.map +1 -0
  28. package/dist/utils.cjs +129 -13
  29. package/dist/utils.d.ts +127 -76
  30. package/dist/utils.js +3 -2
  31. package/package.json +5 -1
  32. package/src/constants.ts +8 -14
  33. package/src/dedupe.ts +8 -0
  34. package/src/factory.ts +18 -1
  35. package/src/guards.ts +1 -1
  36. package/src/index.ts +7 -50
  37. package/src/node.ts +1 -1
  38. package/src/nodes/base.ts +0 -10
  39. package/src/nodes/code.ts +29 -47
  40. package/src/nodes/content.ts +2 -2
  41. package/src/nodes/file.ts +28 -23
  42. package/src/nodes/function.ts +2 -17
  43. package/src/nodes/index.ts +1 -1
  44. package/src/nodes/input.ts +20 -19
  45. package/src/nodes/operation.ts +1 -1
  46. package/src/nodes/parameter.ts +0 -3
  47. package/src/nodes/property.ts +0 -3
  48. package/src/nodes/requestBody.ts +3 -6
  49. package/src/nodes/schema.ts +3 -2
  50. package/src/printer.ts +4 -4
  51. package/src/registry.ts +31 -26
  52. package/src/signature.ts +3 -3
  53. package/src/transformers.ts +28 -1
  54. package/src/types.ts +2 -53
  55. package/src/utils/codegen.ts +104 -0
  56. package/src/utils/extractStringsFromNodes.ts +34 -0
  57. package/src/utils/fileMerge.ts +184 -0
  58. package/src/utils/index.ts +8 -296
  59. package/src/utils/operationParams.ts +353 -0
  60. package/src/utils/refs.ts +112 -0
  61. package/src/utils/schemaGraph.ts +169 -0
  62. package/src/utils/strings.ts +139 -0
  63. package/src/visitor.ts +43 -19
  64. package/dist/chunk-C0LytTxp.js +0 -8
  65. package/dist/utils-0p8ZO287.js +0 -570
  66. package/dist/utils-0p8ZO287.js.map +0 -1
  67. package/dist/utils-cdQ6Pzyi.cjs +0 -726
  68. package/dist/utils-cdQ6Pzyi.cjs.map +0 -1
  69. package/src/utils/ast.ts +0 -879
package/src/utils/ast.ts DELETED
@@ -1,879 +0,0 @@
1
- import { camelCase, isValidVarName, memoize } from '@internals/utils'
2
-
3
- import { narrowSchema } from '../guards.ts'
4
- import { createFunctionParameter, createFunctionParameters, createIndexedAccessType, createTypeLiteral } from '../nodes/function.ts'
5
- import { createProperty } from '../nodes/property.ts'
6
- import { createSchema } from '../nodes/schema.ts'
7
- import type {
8
- CodeNode,
9
- ExportNode,
10
- FunctionParameterNode,
11
- FunctionParametersNode,
12
- ImportNode,
13
- OperationNode,
14
- ParameterNode,
15
- SchemaNode,
16
- SourceNode,
17
- TypeExpression,
18
- TypeLiteralNode,
19
- } from '../nodes/index.ts'
20
- import type { SchemaType } from '../nodes/schema.ts'
21
- import { extractRefName } from './index.ts'
22
- import { collect, collectLazy } from '../visitor.ts'
23
-
24
- const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)
25
-
26
- /**
27
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
28
- *
29
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node
30
- * override the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
31
- *
32
- * @example
33
- * ```ts
34
- * // Ref with description override
35
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
36
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
37
- * ```
38
- */
39
- export function syncSchemaRef(node: SchemaNode): SchemaNode {
40
- const ref = narrowSchema(node, 'ref')
41
-
42
- if (!ref) return node
43
- if (!ref.schema) return node
44
-
45
- const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref
46
-
47
- // Filter out undefined override values so they don't shadow the resolved schema's fields.
48
- const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))
49
-
50
- return createSchema({ ...ref.schema, ...definedOverrides })
51
- }
52
-
53
- /**
54
- * Type guard that returns `true` when a schema emits as a plain `string` type.
55
- *
56
- * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
57
- * types, returns `true` only when `representation` is `'string'` rather than `'date'`.
58
- */
59
- export function isStringType(node: SchemaNode): boolean {
60
- if (plainStringTypes.has(node.type)) {
61
- return true
62
- }
63
-
64
- const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')
65
- if (temporal) {
66
- return temporal.representation !== 'date'
67
- }
68
-
69
- return false
70
- }
71
-
72
- /**
73
- * Applies casing rules to parameter names and returns a new parameter array.
74
- *
75
- * Use this before passing parameters to schema builders so output property keys match
76
- * the desired casing while preserving `OperationNode.parameters` for other consumers.
77
- * The input array is not mutated. When `casing` is not set, the original array is returned unchanged.
78
- */
79
- const caseParamsMemo = memoize(new WeakMap<Array<ParameterNode>, (casing: string) => Array<ParameterNode>>(), (params) =>
80
- memoize(new Map<string, Array<ParameterNode>>(), (casing: string) =>
81
- params.map((param) => {
82
- const transformed = casing === 'camelcase' || !isValidVarName(param.name) ? camelCase(param.name) : param.name
83
- return { ...param, name: transformed }
84
- }),
85
- ),
86
- )
87
-
88
- export function caseParams(params: Array<ParameterNode>, casing: 'camelcase' | undefined): Array<ParameterNode> {
89
- if (!casing) return params
90
- return caseParamsMemo(params)(casing)
91
- }
92
-
93
- /**
94
- * Creates a single-property object schema used as a discriminator literal.
95
- *
96
- * @example
97
- * ```ts
98
- * createDiscriminantNode({ propertyName: 'type', value: 'dog' })
99
- * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
100
- * ```
101
- */
102
- export function createDiscriminantNode({ propertyName, value }: { propertyName: string; value: string }): SchemaNode {
103
- return createSchema({
104
- type: 'object',
105
- primitive: 'object',
106
- properties: [
107
- createProperty({
108
- name: propertyName,
109
- schema: createSchema({
110
- type: 'enum',
111
- primitive: 'string',
112
- enumValues: [value],
113
- }),
114
- required: true,
115
- }),
116
- ],
117
- })
118
- }
119
-
120
- /**
121
- * Named type for a group of parameters (query or header) emitted as a single typed parameter.
122
- */
123
- type ParamGroupType = {
124
- /**
125
- * Type expression for the group, a plain group-name reference.
126
- */
127
- type: TypeExpression
128
- /**
129
- * Whether the parameter group is optional.
130
- */
131
- optional: boolean
132
- }
133
-
134
- /**
135
- * A single member of a destructured parameter group, fed to `createFunctionParameter({ properties })`.
136
- */
137
- type GroupProperty = {
138
- name: string
139
- type: TypeExpression
140
- optional?: boolean
141
- }
142
-
143
- /**
144
- * Resolver interface for {@link createOperationParams}.
145
- *
146
- * `ResolverTs` from `@kubb/plugin-ts` satisfies this interface and can be passed directly.
147
- */
148
- export type OperationParamsResolver = {
149
- /**
150
- * Resolves the type name for an individual parameter.
151
- *
152
- * @example Individual path parameter name
153
- * `resolver.resolveParamName(node, param) // → 'DeletePetPathPetId'`
154
- */
155
- resolveParamName(node: OperationNode, param: ParameterNode): string
156
- /**
157
- * Resolves the request body type name.
158
- *
159
- * @example Request body type name
160
- * `resolver.resolveDataName(node) // → 'CreatePetData'`
161
- */
162
- resolveDataName(node: OperationNode): string
163
- /**
164
- * Resolves the grouped path parameters type name.
165
- * When the return value equals `resolveParamName`, no indexed access is emitted.
166
- *
167
- * @example Grouped path params type name
168
- * `resolver.resolvePathParamsName(node, param) // → 'DeletePetPathParams'`
169
- */
170
- resolvePathParamsName(node: OperationNode, param: ParameterNode): string
171
- /**
172
- * Resolves the grouped query parameters type name.
173
- * When the return value equals `resolveParamName`, an inline struct type is emitted instead.
174
- *
175
- * @example Grouped query params type name
176
- * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
177
- */
178
- resolveQueryParamsName(node: OperationNode, param: ParameterNode): string
179
- /**
180
- * Resolves the grouped header parameters type name.
181
- * When the return value equals `resolveParamName`, an inline struct type is emitted instead.
182
- *
183
- * @example Grouped header params type name
184
- * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
185
- */
186
- resolveHeaderParamsName(node: OperationNode, param: ParameterNode): string
187
- }
188
-
189
- /**
190
- * Options for {@link createOperationParams}.
191
- */
192
- export type CreateOperationParamsOptions = {
193
- /**
194
- * How all operation parameters are grouped in the function signature.
195
- * - `'object'` wraps all params into a single destructured object `{ petId, data, params }`
196
- * - `'inline'` emits each param category as a separate top-level parameter
197
- */
198
- paramsType: 'object' | 'inline'
199
- /**
200
- * How path parameters are emitted when `paramsType` is `'inline'`.
201
- * - `'object'` groups them as `{ petId, storeId }: PathParams`
202
- * - `'inline'` spreads them as individual parameters `petId: string, storeId: string`
203
- * - `'inlineSpread'` emits a single rest parameter `...pathParams: PathParams`
204
- */
205
- pathParamsType: 'object' | 'inline' | 'inlineSpread'
206
- /**
207
- * Converts parameter names to camelCase before output.
208
- */
209
- paramsCasing?: 'camelcase'
210
- /**
211
- * Resolver for parameter and request body type names.
212
- * Pass `ResolverTs` from `@kubb/plugin-ts` directly.
213
- * When omitted, falls back to the schema primitive or `'unknown'`.
214
- */
215
- resolver?: OperationParamsResolver
216
- /**
217
- * Default value for the path parameters binding when `pathParamsType` is `'object'`.
218
- * Falls back to `'{}'` when all path params are optional.
219
- */
220
- pathParamsDefault?: string
221
- /**
222
- * Extra parameters appended after the standard operation parameters.
223
- *
224
- * @example Plugin-specific trailing parameter
225
- * ```ts
226
- * extraParams: [createFunctionParameter({ name: 'options', type: 'Partial<RequestOptions>', default: '{}' })]
227
- * ```
228
- */
229
- extraParams?: Array<FunctionParameterNode>
230
- /**
231
- * Override the default parameter names used for body, query, header, and rest-path groups.
232
- *
233
- * Useful when targeting languages or frameworks with different naming conventions.
234
- *
235
- * @default { data: 'data', params: 'params', headers: 'headers', path: 'pathParams' }
236
- */
237
- paramNames?: {
238
- /**
239
- * Name for the request body parameter.
240
- * @default 'data'
241
- */
242
- data?: string
243
- /**
244
- * Name for the query parameters group parameter.
245
- * @default 'params'
246
- */
247
- params?: string
248
- /**
249
- * Name for the header parameters group parameter.
250
- * @default 'headers'
251
- */
252
- headers?: string
253
- /**
254
- * Name for the rest path-parameters parameter when `pathParamsType` is `'inlineSpread'`.
255
- * @default 'pathParams'
256
- */
257
- path?: string
258
- }
259
- /**
260
- * Applies a uniform transformation to every resolved type name before it is used
261
- * in a parameter node. Use this for framework-level type wrappers.
262
- *
263
- * @example Vue Query, wrap every parameter type with `MaybeRefOrGetter`
264
- * `typeWrapper: (t) => \`MaybeRefOrGetter<${t}>\``
265
- */
266
- typeWrapper?: (type: string) => string
267
- }
268
-
269
- /**
270
- * Resolves the {@link TypeExpression} for an individual parameter.
271
- *
272
- * Without a resolver, falls back to the schema primitive (a plain type-name string).
273
- * When the parameter belongs to a named group, emits an {@link IndexedAccessTypeNode}
274
- * (`GroupParams['petId']`); otherwise the resolved individual name as a plain string.
275
- */
276
- export function resolveParamType({
277
- node,
278
- param,
279
- resolver,
280
- }: {
281
- node: OperationNode
282
- param: ParameterNode
283
- resolver: OperationParamsResolver | undefined
284
- }): TypeExpression {
285
- if (!resolver) {
286
- return param.schema.primitive ?? 'unknown'
287
- }
288
-
289
- const individualName = resolver.resolveParamName(node, param)
290
-
291
- const groupLocation = param.in === 'path' || param.in === 'query' || param.in === 'header' ? param.in : undefined
292
-
293
- const groupResolvers = {
294
- path: resolver.resolvePathParamsName,
295
- query: resolver.resolveQueryParamsName,
296
- header: resolver.resolveHeaderParamsName,
297
- } as const
298
-
299
- const groupName = groupLocation ? groupResolvers[groupLocation].call(resolver, node, param) : undefined
300
-
301
- if (groupName && groupName !== individualName) {
302
- return createIndexedAccessType({ objectType: groupName, indexType: param.name })
303
- }
304
-
305
- return individualName
306
- }
307
-
308
- /**
309
- * Converts an `OperationNode` into function parameters for code generation.
310
- *
311
- * Centralizes parameter grouping logic for all plugins. `paramsType` chooses between one
312
- * destructured object parameter (`object`) and separate top-level parameters (`inline`), while
313
- * `pathParamsType` controls how path params render in inline mode. Provide a `resolver` for type
314
- * name resolution and `extraParams` for plugin-specific trailing parameters such as an `options` object.
315
- */
316
- export function createOperationParams(node: OperationNode, options: CreateOperationParamsOptions): FunctionParametersNode {
317
- const { paramsType, pathParamsType, paramsCasing, resolver, pathParamsDefault, extraParams = [], paramNames, typeWrapper } = options
318
-
319
- const dataName = paramNames?.data ?? 'data'
320
- const paramsName = paramNames?.params ?? 'params'
321
- const headersName = paramNames?.headers ?? 'headers'
322
- const pathName = paramNames?.path ?? 'pathParams'
323
-
324
- const wrapType = (type: string): string => (typeWrapper ? typeWrapper(type) : type)
325
- // Only plain type-name references are wrapped, they need casing applied.
326
- // TypeLiteral and IndexedAccessType expressions are pre-resolved and pass through unchanged.
327
- const wrapTypeExpression = (type: TypeExpression): TypeExpression => (typeof type === 'string' ? wrapType(type) : type)
328
-
329
- const casedParams = caseParams(node.parameters, paramsCasing)
330
- const pathParams = casedParams.filter((p) => p.in === 'path')
331
- const queryParams = casedParams.filter((p) => p.in === 'query')
332
- const headerParams = casedParams.filter((p) => p.in === 'header')
333
-
334
- const toProperty = (param: ParameterNode): GroupProperty => ({
335
- name: param.name,
336
- type: wrapTypeExpression(resolveParamType({ node, param, resolver })),
337
- optional: !param.required,
338
- })
339
- const emptyObjectDefault = (props: Array<GroupProperty>): string | undefined => (props.every((p) => p.optional) ? '{}' : undefined)
340
-
341
- const bodyType = node.requestBody?.content?.[0]?.schema ? wrapType(resolver?.resolveDataName(node) ?? 'unknown') : undefined
342
- const bodyProperty: Array<GroupProperty> = bodyType ? [{ name: dataName, type: bodyType, optional: !(node.requestBody?.required ?? false) }] : []
343
-
344
- const trailingGroups: Array<BuildGroupArgs> = [
345
- { name: paramsName, node, params: queryParams, groupType: resolveGroupType({ node, params: queryParams, group: 'query', resolver }), resolver, wrapType },
346
- {
347
- name: headersName,
348
- node,
349
- params: headerParams,
350
- groupType: resolveGroupType({ node, params: headerParams, group: 'header', resolver }),
351
- resolver,
352
- wrapType,
353
- },
354
- ]
355
-
356
- const params: Array<FunctionParameterNode> = []
357
-
358
- if (paramsType === 'object') {
359
- const children = [...pathParams.map(toProperty), ...bodyProperty, ...trailingGroups.flatMap(buildGroupProperty)]
360
- if (children.length) {
361
- params.push(createFunctionParameter({ properties: children, default: emptyObjectDefault(children) }))
362
- }
363
- } else {
364
- if (pathParamsType === 'inlineSpread' && pathParams.length) {
365
- const spreadType = resolver?.resolvePathParamsName(node, pathParams[0]!)
366
- params.push(createFunctionParameter({ name: pathName, type: spreadType ? wrapType(spreadType) : undefined, rest: true }))
367
- } else if (pathParamsType === 'inline') {
368
- params.push(...pathParams.map((p) => createFunctionParameter(toProperty(p))))
369
- } else if (pathParams.length) {
370
- const pathChildren = pathParams.map(toProperty)
371
- params.push(createFunctionParameter({ properties: pathChildren, default: pathParamsDefault ?? emptyObjectDefault(pathChildren) }))
372
- }
373
-
374
- params.push(...bodyProperty.map((p) => createFunctionParameter(p)))
375
- params.push(...trailingGroups.flatMap(buildGroupParam))
376
- }
377
-
378
- params.push(...extraParams)
379
-
380
- return createFunctionParameters({ params })
381
- }
382
-
383
- /**
384
- * Shared arguments for building a query or header parameter group.
385
- */
386
- type BuildGroupArgs = {
387
- name: string
388
- node: OperationNode
389
- params: Array<ParameterNode>
390
- groupType: ParamGroupType | null
391
- resolver: OperationParamsResolver | undefined
392
- wrapType: (type: string) => string
393
- }
394
-
395
- /**
396
- * Builds the property descriptor for a query or header group.
397
- * Returns an empty array when there are no params to emit.
398
- *
399
- * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
400
- * {@link TypeLiteralNode} from the individual params.
401
- */
402
- function buildGroupProperty({ name, node, params, groupType, resolver, wrapType }: BuildGroupArgs): Array<GroupProperty> {
403
- if (groupType) {
404
- const type = typeof groupType.type === 'string' ? wrapType(groupType.type) : groupType.type
405
- return [{ name, type, optional: groupType.optional }]
406
- }
407
- if (params.length) {
408
- return [{ name, type: buildTypeLiteral({ node, params, resolver }), optional: params.every((p) => !p.required) }]
409
- }
410
- return []
411
- }
412
-
413
- /**
414
- * Builds a single {@link FunctionParameterNode} for a query or header group.
415
- * Returns an empty array when there are no params to emit.
416
- *
417
- * A pre-resolved `groupType` emits `name: GroupType`. Otherwise it builds an inline
418
- * {@link TypeLiteralNode} from the individual params.
419
- */
420
- export function buildGroupParam(args: BuildGroupArgs): Array<FunctionParameterNode> {
421
- return buildGroupProperty(args).map((p) => createFunctionParameter(p))
422
- }
423
-
424
- /**
425
- * Derives a {@link ParamGroupType} for a query or header group from the resolver.
426
- *
427
- * Returns `null` when there is no resolver, no params, or the group name equals the
428
- * individual param name (so there is no real group to emit).
429
- */
430
- export function resolveGroupType({
431
- node,
432
- params,
433
- group,
434
- resolver,
435
- }: {
436
- node: OperationNode
437
- params: Array<ParameterNode>
438
- group: 'query' | 'header'
439
- resolver: OperationParamsResolver | undefined
440
- }): ParamGroupType | null {
441
- if (!resolver || !params.length) {
442
- return null
443
- }
444
- const firstParam = params[0]!
445
- const groupMethod = group === 'query' ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName
446
- const groupName = groupMethod.call(resolver, node, firstParam)
447
- if (groupName === resolver.resolveParamName(node, firstParam)) {
448
- return null
449
- }
450
- return { type: groupName, optional: params.every((p) => !p.required) }
451
- }
452
-
453
- /**
454
- * Builds a {@link TypeLiteralNode} for an inline anonymous type grouping named fields.
455
- *
456
- * Used when query or header parameters have no dedicated group type name.
457
- * Each language printer renders this appropriately (TypeScript: `{ petId: string; name?: string }`).
458
- */
459
- export function buildTypeLiteral({
460
- node,
461
- params,
462
- resolver,
463
- }: {
464
- node: OperationNode
465
- params: Array<ParameterNode>
466
- resolver: OperationParamsResolver | undefined
467
- }): TypeLiteralNode {
468
- return createTypeLiteral({
469
- members: params.map((p) => ({
470
- name: p.name,
471
- type: resolveParamType({ node, param: p, resolver }),
472
- optional: !p.required,
473
- })),
474
- })
475
- }
476
-
477
- function sourceKey(source: SourceNode): string {
478
- const nameKey = source.name ?? extractStringsFromNodes(source.nodes)
479
- return `${nameKey}:${source.isExportable ?? false}:${source.isTypeOnly ?? false}`
480
- }
481
-
482
- function pathTypeKey(path: string, isTypeOnly: boolean | null | undefined): string {
483
- return `${path}:${isTypeOnly ?? false}`
484
- }
485
-
486
- function exportKey(path: string, name: string | null | undefined, isTypeOnly: boolean | null | undefined, asAlias: boolean | null | undefined): string {
487
- return `${path}:${name ?? ''}:${isTypeOnly ?? false}:${asAlias ?? ''}`
488
- }
489
-
490
- function importKey(path: string, name: string | null | undefined, isTypeOnly: boolean | null | undefined): string {
491
- return `${path}:${name ?? ''}:${isTypeOnly ?? false}`
492
- }
493
-
494
- /**
495
- * Computes a multi-level sort key for exports and imports:
496
- * non-array names first (wildcards/namespace aliases). Type-only before value. Alphabetical path. Unnamed before named.
497
- */
498
- function sortKey(node: { name?: string | Array<unknown> | null; isTypeOnly?: boolean | null; path: string }): string {
499
- const isArray = Array.isArray(node.name) ? '1' : '0'
500
- const typeOnly = node.isTypeOnly ? '0' : '1'
501
- const hasName = node.name != null ? '1' : '0'
502
- const name = Array.isArray(node.name) ? node.name.toSorted().join('\0') : (node.name ?? '')
503
- return `${isArray}:${typeOnly}:${node.path}:${hasName}:${name}`
504
- }
505
-
506
- /**
507
- * Deduplicates and merges `SourceNode` objects by `name + isExportable + isTypeOnly`.
508
- *
509
- * Unnamed sources are deduplicated by object reference. Returns a deduplicated array in original order.
510
- */
511
- export function combineSources(sources: Array<SourceNode>): Array<SourceNode> {
512
- const seen = new Map<string, SourceNode>()
513
- for (const source of sources) {
514
- const key = sourceKey(source)
515
- if (!seen.has(key)) seen.set(key, source)
516
- }
517
- return [...seen.values()]
518
- }
519
-
520
- /**
521
- * Merges `incoming` names into `existing`, preserving order and dropping duplicates.
522
- *
523
- * Shared by `combineExports` and `combineImports` for the same-path name-merge case.
524
- */
525
- function mergeNameArrays<TName>(existing: Array<TName>, incoming: Array<TName>): Array<TName> {
526
- const merged = new Set(existing)
527
- for (const name of incoming) merged.add(name)
528
- return [...merged]
529
- }
530
-
531
- /**
532
- * Deduplicates and merges `ExportNode` objects by path and type.
533
- *
534
- * Named exports with the same path and `isTypeOnly` flag have their names merged into a single export.
535
- * Non-array exports are deduplicated by exact identity. Returns a sorted, deduplicated array.
536
- */
537
- export function combineExports(exports: Array<ExportNode>): Array<ExportNode> {
538
- const result: Array<ExportNode> = []
539
- // Accumulates array-named exports keyed by `path:isTypeOnly` for name-merging
540
- const namedByPath = new Map<string, ExportNode>()
541
- // Deduplicates non-array exports by their exact identity
542
- const seen = new Set<string>()
543
-
544
- // Precompute sort keys once, avoids recomputing per comparison.
545
- const keyed = exports.map((node) => ({ node, key: sortKey(node) }))
546
- keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
547
-
548
- for (const { node: curr } of keyed) {
549
- const { name, path, isTypeOnly, asAlias } = curr
550
-
551
- if (Array.isArray(name)) {
552
- if (!name.length) continue
553
-
554
- const key = pathTypeKey(path, isTypeOnly)
555
- const existing = namedByPath.get(key)
556
-
557
- if (existing && Array.isArray(existing.name)) {
558
- existing.name = mergeNameArrays(existing.name, name)
559
- } else {
560
- const newItem: ExportNode = { ...curr, name: [...new Set(name)] }
561
- result.push(newItem)
562
- namedByPath.set(key, newItem)
563
- }
564
- } else {
565
- const key = exportKey(path, name, isTypeOnly, asAlias)
566
- if (!seen.has(key)) {
567
- result.push(curr)
568
- seen.add(key)
569
- }
570
- }
571
- }
572
-
573
- return result
574
- }
575
-
576
- /**
577
- * Deduplicates and merges `ImportNode` objects, filtering out unused imports.
578
- *
579
- * Retains imports that are referenced in `source` or re-exported. Imports with the same path and
580
- * `isTypeOnly` flag have their names merged. Returns a sorted, deduplicated, filtered array.
581
- *
582
- * @note Use this when combining imports from multiple files to avoid duplicate declarations.
583
- */
584
- export function combineImports(imports: Array<ImportNode>, exports: Array<ExportNode>, source?: string): Array<ImportNode> {
585
- // Build a lookup of all exported names to retain imports that are re-exported
586
- const exportedNames = new Set(exports.flatMap((e) => (Array.isArray(e.name) ? e.name : e.name ? [e.name] : [])))
587
- const isUsed = (importName: string): boolean => !source || source.includes(importName) || exportedNames.has(importName)
588
-
589
- // Memoize object import names so the same logical (propertyName, name) pair always
590
- // reuses the same object reference. Set-based deduplication then works correctly.
591
- const importNameMemo = new Map<string, { propertyName: string; name?: string }>()
592
- const canonicalizeName = (n: string | { propertyName: string; name?: string }): string | { propertyName: string; name?: string } => {
593
- if (typeof n === 'string') return n
594
- const key = `${n.propertyName}:${n.name ?? ''}`
595
- if (!importNameMemo.has(key)) importNameMemo.set(key, n)
596
- return importNameMemo.get(key)!
597
- }
598
-
599
- // Paths that keep at least one used named import. A default import from such a path is retained
600
- // even when its binding can't be found in `source` e.g. a generated `client` default import
601
- // alongside `import type { Client } from <same path>`, where merged grouped output omits the body.
602
- const pathsWithUsedNamedImport = new Set<string>()
603
- for (const node of imports) {
604
- if (!Array.isArray(node.name)) continue
605
- if (node.name.some((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.name ?? item.propertyName)))) {
606
- pathsWithUsedNamedImport.add(node.path)
607
- }
608
- }
609
-
610
- const result: Array<ImportNode> = []
611
- // Accumulates array-named imports keyed by `path:isTypeOnly` for name-merging
612
- const namedByPath = new Map<string, ImportNode>()
613
- // Deduplicates non-array imports by their exact identity
614
- const seen = new Set<string>()
615
-
616
- // Precompute sort keys once, avoids recomputing per comparison.
617
- const keyed = imports.map((node) => ({ node, key: sortKey(node) }))
618
- keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
619
-
620
- for (const { node: curr } of keyed) {
621
- if (curr.path === curr.root) continue
622
-
623
- const { path, isTypeOnly } = curr
624
- let { name } = curr
625
-
626
- if (Array.isArray(name)) {
627
- name = [...new Set(name.map(canonicalizeName))].filter((item) => (typeof item === 'string' ? isUsed(item) : isUsed(item.name ?? item.propertyName)))
628
- if (!name.length) continue
629
-
630
- const key = pathTypeKey(path, isTypeOnly)
631
- const existing = namedByPath.get(key)
632
-
633
- if (existing && Array.isArray(existing.name)) {
634
- existing.name = mergeNameArrays(existing.name, name)
635
- } else {
636
- const newItem: ImportNode = { ...curr, name }
637
- result.push(newItem)
638
- namedByPath.set(key, newItem)
639
- }
640
- } else {
641
- if (name && !isUsed(name) && !pathsWithUsedNamedImport.has(path)) continue
642
-
643
- const key = importKey(path, name, isTypeOnly)
644
- if (!seen.has(key)) {
645
- result.push(curr)
646
- seen.add(key)
647
- }
648
- }
649
- }
650
-
651
- return result
652
- }
653
-
654
- /**
655
- * Extracts all string content from a `CodeNode` tree recursively.
656
- *
657
- * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
658
- * and nested node content. Used internally to build the full source string for import filtering.
659
- */
660
- export function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): string {
661
- if (!nodes?.length) return ''
662
- return nodes
663
- .map((node) => {
664
- // Backward-compat: compiled plugins may still pass bare strings at runtime
665
- if (typeof node === 'string') return node as string
666
- if (node.kind === 'Text') return node.value
667
- if (node.kind === 'Break') return ''
668
- if (node.kind === 'Jsx') return node.value
669
-
670
- const parts: Array<string> = []
671
-
672
- if ('params' in node && node.params) parts.push(node.params)
673
- if ('generics' in node && node.generics) parts.push(Array.isArray(node.generics) ? node.generics.join(', ') : node.generics)
674
- if ('returnType' in node && node.returnType) parts.push(node.returnType)
675
- if ('type' in node && typeof node.type === 'string') parts.push(node.type)
676
-
677
- const nested = extractStringsFromNodes(node.nodes)
678
-
679
- if (nested) parts.push(nested)
680
-
681
- return parts.join('\n')
682
- })
683
- .filter(Boolean)
684
- .join('\n')
685
- }
686
-
687
- /**
688
- * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.
689
- *
690
- * Returns `null` for non-ref nodes or when no name can be resolved. Use this to get a schema's
691
- * identifier for type definitions or error messages.
692
- *
693
- * @example
694
- * ```ts
695
- * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })
696
- * // => 'Pet'
697
- * ```
698
- */
699
- export function resolveRefName(node: SchemaNode | undefined): string | null {
700
- if (!node || node.type !== 'ref') return null
701
- if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null
702
-
703
- return node.name ?? node.schema?.name ?? null
704
- }
705
-
706
- /**
707
- * Collects every named schema referenced (transitively) from a node via ref edges.
708
- *
709
- * Refs are followed by name only, the resolved `node.schema` is not traversed inline.
710
- * Use this to determine schema dependencies, build reference graphs, or detect what schemas need to be emitted.
711
- *
712
- * @example Collect refs from a single schema
713
- * ```ts
714
- * const names = collectReferencedSchemaNames(petSchema)
715
- * // → Set { 'Category', 'Tag' }
716
- * ```
717
- *
718
- * @example Accumulate refs from multiple schemas into one set
719
- * ```ts
720
- * const out = new Set<string>()
721
- * for (const schema of schemas) {
722
- * collectReferencedSchemaNames(schema, out)
723
- * }
724
- * ```
725
- */
726
- const collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {
727
- const refs = new Set<string>()
728
- collect<void>(node, {
729
- schema(child) {
730
- if (child.type === 'ref') {
731
- const name = resolveRefName(child)
732
- if (name) refs.add(name)
733
- }
734
- },
735
- })
736
- return refs
737
- })
738
-
739
- export function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {
740
- if (!node) return out
741
- for (const name of collectSchemaRefs(node)) out.add(name)
742
- return out
743
- }
744
-
745
- /**
746
- * Collects the names of all top-level schemas transitively used by a set of operations.
747
- *
748
- * An operation uses a schema when any of its parameters, request body content, or responses
749
- * reference it, directly or indirectly through other named schemas.
750
- * The walk is iterative and safe against reference cycles.
751
- *
752
- * Use this together with `include` filters to determine which schemas from `components/schemas`
753
- * are reachable from the allowed operations, so that schemas used only by excluded operations
754
- * are not generated.
755
- *
756
- * @example Only generate schemas referenced by included operations
757
- * ```ts
758
- * const includedOps = operations.filter(op => resolver.resolveOptions(op, { options, include }) !== null)
759
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
760
- *
761
- * for (const schema of schemas) {
762
- * if (schema.name && !allowed.has(schema.name)) continue
763
- * // … generate schema
764
- * }
765
- * ```
766
- *
767
- * @example Check whether a specific schema is needed
768
- * ```ts
769
- * const allowed = collectUsedSchemaNames(includedOps, schemas)
770
- * allowed.has('OrderStatus') // false when no included operation references OrderStatus
771
- * ```
772
- */
773
- const collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>
774
- memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),
775
- )
776
-
777
- function computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
778
- const schemaMap = new Map<string, SchemaNode>()
779
- for (const schema of schemas) {
780
- if (schema.name) schemaMap.set(schema.name, schema)
781
- }
782
-
783
- const result = new Set<string>()
784
-
785
- function visitSchema(schema: SchemaNode): void {
786
- const directRefs = collectReferencedSchemaNames(schema)
787
- for (const name of directRefs) {
788
- if (!result.has(name)) {
789
- result.add(name)
790
- const namedSchema = schemaMap.get(name)
791
- if (namedSchema) visitSchema(namedSchema)
792
- }
793
- }
794
- }
795
-
796
- for (const op of operations) {
797
- for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {
798
- visitSchema(schema)
799
- }
800
- }
801
-
802
- return result
803
- }
804
-
805
- export function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {
806
- return collectUsedSchemaNamesMemo(operations)(schemas)
807
- }
808
-
809
- const EMPTY_CIRCULAR_SET = new Set<string>()
810
-
811
- const findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {
812
- const graph = new Map<string, Set<string>>()
813
-
814
- for (const schema of schemas) {
815
- if (!schema.name) continue
816
- graph.set(schema.name, collectReferencedSchemaNames(schema))
817
- }
818
-
819
- const circular = new Set<string>()
820
- for (const start of graph.keys()) {
821
- const visited = new Set<string>()
822
- const stack: Array<string> = [...(graph.get(start) ?? [])]
823
- while (stack.length > 0) {
824
- const node = stack.pop()!
825
- if (node === start) {
826
- circular.add(start)
827
- break
828
- }
829
- if (visited.has(node)) continue
830
- visited.add(node)
831
-
832
- const next = graph.get(node)
833
- if (next) for (const r of next) stack.push(r)
834
- }
835
- }
836
-
837
- return circular
838
- })
839
-
840
- /**
841
- * Identifies all schemas that participate in circular dependency chains, including direct self-loops.
842
- *
843
- * Returns a Set of schema names with circular dependencies. Use this to wrap recursive schema positions
844
- * in deferred constructs (lazy getter, `z.lazy(() => …)`) to prevent infinite recursion when generated code runs.
845
- * Refs are followed by name only, keeping the algorithm linear in the schema graph size.
846
- *
847
- * @note Call this once on the full schema graph, then use `containsCircularRef()` to check individual schemas.
848
- */
849
- export function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {
850
- if (schemas.length === 0) return EMPTY_CIRCULAR_SET
851
- return findCircularSchemasMemo(schemas)
852
- }
853
-
854
- /**
855
- * Type guard returning `true` when a schema or anything nested within it contains a ref to a circular schema.
856
- *
857
- * Use `excludeName` to ignore refs to specific schemas (useful when self-references are handled separately).
858
- * Commonly used with `findCircularSchemas()` to detect where lazy wrappers are needed in code generation.
859
- *
860
- * @note Returns `true` for the first matching circular ref found. Use for fast dependency checks.
861
- */
862
- export function containsCircularRef(
863
- node: SchemaNode | undefined,
864
- { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },
865
- ): boolean {
866
- if (!node || circularSchemas.size === 0) return false
867
-
868
- for (const _ of collectLazy<true>(node, {
869
- schema(child) {
870
- if (child.type !== 'ref') return null
871
- const name = resolveRefName(child)
872
- return name && name !== excludeName && circularSchemas.has(name) ? true : null
873
- },
874
- })) {
875
- return true
876
- }
877
-
878
- return false
879
- }