@kubb/ast 5.0.0-beta.60 → 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 (61) hide show
  1. package/README.md +2 -1
  2. package/dist/defineMacro-BLIR6k-j.d.ts +475 -0
  3. package/dist/defineMacro-BTXvS8nI.js +106 -0
  4. package/dist/defineMacro-BTXvS8nI.js.map +1 -0
  5. package/dist/defineMacro-Bv9R_9a2.cjs +123 -0
  6. package/dist/defineMacro-Bv9R_9a2.cjs.map +1 -0
  7. package/dist/extractStringsFromNodes-Cja-xxx5.js +29 -0
  8. package/dist/extractStringsFromNodes-Cja-xxx5.js.map +1 -0
  9. package/dist/extractStringsFromNodes-DKgDjFO0.cjs +34 -0
  10. package/dist/extractStringsFromNodes-DKgDjFO0.cjs.map +1 -0
  11. package/dist/extractStringsFromNodes-p4mX1TQD.d.ts +14 -0
  12. package/dist/{factory-Du7nEP4B.js → factory-CZNOGI-N.js} +3 -2
  13. package/dist/{factory-Du7nEP4B.js.map → factory-CZNOGI-N.js.map} +1 -1
  14. package/dist/{factory-Cl8Z7mcc.cjs → factory-DG1CVkEb.cjs} +5 -4
  15. package/dist/{factory-Cl8Z7mcc.cjs.map → factory-DG1CVkEb.cjs.map} +1 -1
  16. package/dist/factory.cjs +2 -2
  17. package/dist/factory.js +2 -2
  18. package/dist/index.cjs +22 -20
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +18 -17
  21. package/dist/index.js +7 -4
  22. package/dist/index.js.map +1 -1
  23. package/dist/macros.cjs +117 -0
  24. package/dist/macros.cjs.map +1 -0
  25. package/dist/macros.d.ts +59 -0
  26. package/dist/macros.js +115 -0
  27. package/dist/macros.js.map +1 -0
  28. package/dist/{response-DKxTr522.js → response-KUdWiDWw.js} +36 -61
  29. package/dist/response-KUdWiDWw.js.map +1 -0
  30. package/dist/{response-DS5S3IG4.cjs → response-hnSw2NKE.cjs} +35 -66
  31. package/dist/response-hnSw2NKE.cjs.map +1 -0
  32. package/dist/{types-olVl9v5p.d.ts → types-DyDzizSf.d.ts} +3 -403
  33. package/dist/types.d.ts +4 -3
  34. package/dist/{utils-D83JA6Xx.cjs → utils-BLJwyza-.cjs} +18 -751
  35. package/dist/utils-BLJwyza-.cjs.map +1 -0
  36. package/dist/{utils-Dj_KoXMv.js → utils-CF_-Pn_c.js} +9 -628
  37. package/dist/utils-CF_-Pn_c.js.map +1 -0
  38. package/dist/utils.cjs +12 -10
  39. package/dist/utils.d.ts +28 -2
  40. package/dist/utils.js +4 -3
  41. package/dist/visitor-DJ6ZEJvq.js +548 -0
  42. package/dist/visitor-DJ6ZEJvq.js.map +1 -0
  43. package/dist/visitor-DpKZ9Tk0.cjs +654 -0
  44. package/dist/visitor-DpKZ9Tk0.cjs.map +1 -0
  45. package/package.json +5 -1
  46. package/src/defineMacro.ts +132 -0
  47. package/src/index.ts +3 -7
  48. package/src/macros/index.ts +3 -0
  49. package/src/macros/macroDiscriminatorEnum.ts +44 -0
  50. package/src/macros/macroEnumName.ts +25 -0
  51. package/src/macros/macroSimplifyUnion.ts +50 -0
  52. package/src/types.ts +2 -1
  53. package/src/utils/index.ts +2 -2
  54. package/src/utils/refs.ts +27 -1
  55. package/src/utils/schemaMerge.ts +34 -0
  56. package/dist/extractStringsFromNodes-WMYJ8nQL.d.ts +0 -82
  57. package/dist/response-DKxTr522.js.map +0 -1
  58. package/dist/response-DS5S3IG4.cjs.map +0 -1
  59. package/dist/utils-D83JA6Xx.cjs.map +0 -1
  60. package/dist/utils-Dj_KoXMv.js.map +0 -1
  61. package/src/transformers.ts +0 -191
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visitor-DpKZ9Tk0.cjs","names":["pascalCase","createSchema","inputDef","outputDef","operationDef","requestBodyDef","contentDef","responseDef","schemaDef","propertyDef","parameterDef","functionParameterDef","functionParametersDef","typeLiteralDef","indexedAccessTypeDef","objectBindingPatternDef","constDef","typeDef","functionDef","arrowFunctionDef","textDef","breakDef","jsxDef","importDef","exportDef","sourceDef","fileDef"],"sources":["../src/constants.ts","../src/guards.ts","../src/utils/refs.ts","../src/registry.ts","../src/visitor.ts"],"sourcesContent":["import type { HttpMethod } from './nodes/operation.ts'\nimport type { SchemaType } from './nodes/schema.ts'\n\n/**\n * Traversal depth for AST visitor utilities.\n *\n * - `'shallow'` visits only the immediate node, skipping children.\n * - `'deep'` recursively visits all descendant nodes.\n */\nexport type VisitorDepth = 'shallow' | 'deep'\n\nexport const visitorDepths = {\n shallow: 'shallow',\n deep: 'deep',\n} as const satisfies Record<VisitorDepth, VisitorDepth>\n\n/**\n * Schema type discriminators used by all AST schema nodes.\n *\n * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).\n * Call `isScalarPrimitive()` to check for the scalar types.\n */\nexport const schemaTypes = {\n /**\n * Text value.\n */\n string: 'string',\n /**\n * Floating-point number (`float`, `double`).\n */\n number: 'number',\n /**\n * Whole number (`int32`). Use `bigint` for `int64`.\n */\n integer: 'integer',\n /**\n * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.\n */\n bigint: 'bigint',\n /**\n * Boolean value.\n */\n boolean: 'boolean',\n /**\n * Explicit null value.\n */\n null: 'null',\n /**\n * Any value (no type restriction).\n */\n any: 'any',\n /**\n * Unknown value (must be narrowed before usage).\n */\n unknown: 'unknown',\n /**\n * No return value (`void`).\n */\n void: 'void',\n /**\n * Object with named properties.\n */\n object: 'object',\n /**\n * Sequential list of items.\n */\n array: 'array',\n /**\n * Fixed-length list with position-specific items.\n */\n tuple: 'tuple',\n /**\n * \"One of\" multiple schema members.\n */\n union: 'union',\n /**\n * \"All of\" multiple schema members.\n */\n intersection: 'intersection',\n /**\n * Enum schema.\n */\n enum: 'enum',\n /**\n * Reference to another schema.\n */\n ref: 'ref',\n /**\n * Calendar date (for example `2026-03-24`).\n */\n date: 'date',\n /**\n * Date-time value (for example `2026-03-24T09:00:00Z`).\n */\n datetime: 'datetime',\n /**\n * Time-only value (for example `09:00:00`).\n */\n time: 'time',\n /**\n * UUID value.\n */\n uuid: 'uuid',\n /**\n * Email address value.\n */\n email: 'email',\n /**\n * URL value.\n */\n url: 'url',\n /**\n * IPv4 address value.\n */\n ipv4: 'ipv4',\n /**\n * IPv6 address value.\n */\n ipv6: 'ipv6',\n /**\n * Binary/blob value.\n */\n blob: 'blob',\n /**\n * Impossible value (`never`).\n */\n never: 'never',\n} as const satisfies Record<SchemaType, SchemaType>\n\nexport type ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'boolean'\n\n/**\n * Scalar primitive schema types used for union simplification and type narrowing.\n */\nconst SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])\n\n/**\n * Returns `true` when `type` is a scalar primitive that can be assigned without wrapping\n * (for example `string | number | boolean`).\n */\nexport function isScalarPrimitive(type: string): type is ScalarPrimitive {\n return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)\n}\n\n/**\n * HTTP method identifiers used by operation nodes.\n */\nexport const httpMethods = {\n get: 'GET',\n post: 'POST',\n put: 'PUT',\n patch: 'PATCH',\n delete: 'DELETE',\n head: 'HEAD',\n options: 'OPTIONS',\n trace: 'TRACE',\n} as const satisfies Record<Lowercase<HttpMethod>, HttpMethod>\n\n/**\n * Default concurrency limit for the `walk()` traversal utility.\n *\n * Set to 30 to balance I/O-bound resolver parallelism against event-loop and memory pressure\n * during large spec traversals. Override it for different hardware constraints.\n *\n * @example\n * ```ts\n * import { walk, WALK_CONCURRENCY } from '@kubb/ast'\n *\n * walk(root, { concurrency: WALK_CONCURRENCY, root: () => {} })\n * ```\n */\nexport const WALK_CONCURRENCY = 30\n\n/**\n * Number of spaces in one indentation level when assembling multi-line code as strings.\n * Set to 2, 3, … to change the indent width used by `buildObject`/`buildList`.\n */\nconst INDENT_SIZE = 2\n\n/**\n * One indentation level, derived from {@link INDENT_SIZE}.\n */\nexport const INDENT = Array.from({ length: INDENT_SIZE }, () => ' ').join('')\n","import type { HttpOperationNode, OperationNode, SchemaNode, SchemaNodeByType } from './nodes/index.ts'\n\n/**\n * Narrows a `SchemaNode` to the variant that matches `type`.\n *\n * @example\n * ```ts\n * const schema = createSchema({ type: 'string' })\n * const stringNode = narrowSchema(schema, 'string') // StringSchemaNode | null\n * ```\n */\nexport function narrowSchema<T extends SchemaNode['type']>(node: SchemaNode | undefined, type: T): SchemaNodeByType[T] | null {\n return node?.type === type ? (node as SchemaNodeByType[T]) : null\n}\n\n/**\n * Narrows an `OperationNode` to an `HttpOperationNode` so `method` and `path` are present.\n *\n * @example\n * ```ts\n * if (isHttpOperationNode(node)) {\n * console.log(node.method, node.path)\n * }\n * ```\n */\nexport function isHttpOperationNode(node: OperationNode): node is HttpOperationNode {\n return node.protocol === 'http' || (node.method !== undefined && node.path !== undefined)\n}\n","import { pascalCase } from '@internals/utils'\nimport { narrowSchema } from '../guards.ts'\nimport type { OperationNode, ParameterNode, SchemaNode } from '../nodes/index.ts'\nimport { createSchema, type SchemaType } from '../nodes/schema.ts'\nimport type { OperationParamsResolver, ParamGroupType } from './operationParams.ts'\n\nconst plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)\n\n/**\n * Returns the last path segment of a reference string.\n *\n * @example\n * ```ts\n * extractRefName('#/components/schemas/Pet') // 'Pet'\n * ```\n */\nexport function extractRefName(ref: string): string {\n return ref.split('/').at(-1) ?? ref\n}\n\n/**\n * Resolves the schema name of a ref node, falling back through `ref` → `name` → nested `schema.name`.\n *\n * Returns `null` for non-ref nodes or when no name resolves.\n *\n * @example\n * ```ts\n * resolveRefName({ kind: 'Schema', type: 'ref', ref: '#/components/schemas/Pet' })\n * // => 'Pet'\n * ```\n */\nexport function resolveRefName(node: SchemaNode | undefined): string | null {\n if (!node || node.type !== 'ref') return null\n if (node.ref) return extractRefName(node.ref) ?? node.name ?? node.schema?.name ?? null\n\n return node.name ?? node.schema?.name ?? null\n}\n\n/**\n * Builds a PascalCase child schema name by joining a parent name and property name.\n * Returns `null` when there is no parent to nest under.\n *\n * @example\n * ```ts\n * childName('Order', 'shipping_address') // 'OrderShippingAddress'\n * childName(undefined, 'params') // null\n * ```\n */\nexport function childName(parentName: string | null | undefined, propName: string): string | null {\n return parentName ? pascalCase([parentName, propName].join(' ')) : null\n}\n\n/**\n * Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any\n * empty parts.\n *\n * @example\n * ```ts\n * enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'\n * ```\n */\nexport function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string {\n return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))\n}\n\n/**\n * Merges a ref node with its resolved schema, giving usage-site fields precedence.\n *\n * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override\n * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.\n *\n * @example\n * ```ts\n * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })\n * const merged = syncSchemaRef(ref) // merges with resolved Pet schema\n * ```\n */\nexport function syncSchemaRef(node: SchemaNode): SchemaNode {\n const ref = narrowSchema(node, 'ref')\n\n if (!ref) return node\n if (!ref.schema) return node\n\n const { kind: _kind, type: _type, name: _name, ref: _ref, schema: _schema, ...overrides } = ref\n\n // Filter out undefined override values so they don't shadow the resolved schema's fields.\n const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v !== undefined))\n\n return createSchema({ ...ref.schema, ...definedOverrides })\n}\n\n/**\n * Type guard that returns `true` when a schema emits as a plain `string` type.\n *\n * Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`\n * types, returns `true` only when `representation` is `'string'` rather than `'date'`.\n */\nexport function isStringType(node: SchemaNode): boolean {\n if (plainStringTypes.has(node.type)) {\n return true\n }\n\n const temporal = narrowSchema(node, 'date') ?? narrowSchema(node, 'time')\n if (temporal) {\n return temporal.representation !== 'date'\n }\n\n return false\n}\n\n/**\n * Derives a {@link ParamGroupType} for a query or header group from the resolver.\n *\n * Returns `null` when there is no resolver, no params, or the group name equals the\n * individual param name (so there is no real group to emit).\n */\nexport function resolveGroupType({\n node,\n params,\n group,\n resolver,\n}: {\n node: OperationNode\n params: Array<ParameterNode>\n group: 'query' | 'header'\n resolver: OperationParamsResolver | undefined\n}): ParamGroupType | null {\n if (!resolver || !params.length) {\n return null\n }\n const firstParam = params[0]!\n const groupMethod = group === 'query' ? resolver.resolveQueryParamsName : resolver.resolveHeaderParamsName\n const groupName = groupMethod.call(resolver, node, firstParam)\n if (groupName === resolver.resolveParamName(node, firstParam)) {\n return null\n }\n return { type: groupName, optional: params.every((p) => !p.required) }\n}\n","import type { NodeDef } from './node.ts'\nimport { arrowFunctionDef, breakDef, constDef, functionDef, jsxDef, textDef, typeDef } from './nodes/code.ts'\nimport { contentDef } from './nodes/content.ts'\nimport { exportDef, fileDef, importDef, sourceDef } from './nodes/file.ts'\nimport { functionParameterDef, functionParametersDef, indexedAccessTypeDef, objectBindingPatternDef, typeLiteralDef } from './nodes/function.ts'\nimport { inputDef } from './nodes/input.ts'\nimport { operationDef } from './nodes/operation.ts'\nimport { outputDef } from './nodes/output.ts'\nimport { parameterDef } from './nodes/parameter.ts'\nimport { propertyDef } from './nodes/property.ts'\nimport { requestBodyDef } from './nodes/requestBody.ts'\nimport { responseDef } from './nodes/response.ts'\nimport { schemaDef } from './nodes/schema.ts'\n\n// Surface every def from one place so the package barrel re-exports them with `export * from './registry.ts'`.\n// Adding a node means adding its `defineNode` to a `nodes/*.ts` file and listing it in `nodeDefs` below, nothing else.\nexport {\n arrowFunctionDef,\n breakDef,\n constDef,\n contentDef,\n exportDef,\n fileDef,\n functionDef,\n functionParameterDef,\n functionParametersDef,\n importDef,\n indexedAccessTypeDef,\n inputDef,\n jsxDef,\n objectBindingPatternDef,\n operationDef,\n outputDef,\n parameterDef,\n propertyDef,\n requestBodyDef,\n responseDef,\n schemaDef,\n sourceDef,\n textDef,\n typeDef,\n typeLiteralDef,\n}\n\n/**\n * Every node definition. Adding a node means adding its `defineNode` to one\n * `nodes/*.ts` file and listing it here. The visitor tables in `visitor.ts` derive from it.\n */\nexport const nodeDefs = [\n inputDef,\n outputDef,\n operationDef,\n requestBodyDef,\n contentDef,\n responseDef,\n schemaDef,\n propertyDef,\n parameterDef,\n functionParameterDef,\n functionParametersDef,\n typeLiteralDef,\n indexedAccessTypeDef,\n objectBindingPatternDef,\n constDef,\n typeDef,\n functionDef,\n arrowFunctionDef,\n textDef,\n breakDef,\n jsxDef,\n importDef,\n exportDef,\n sourceDef,\n fileDef,\n] satisfies ReadonlyArray<NodeDef>\n","import type { VisitorDepth } from './constants.ts'\nimport { visitorDepths, WALK_CONCURRENCY } from './constants.ts'\nimport type { NodeDef } from './node.ts'\nimport type {\n ContentNode,\n InputNode,\n Node,\n NodeKind,\n OperationNode,\n OutputNode,\n ParameterNode,\n PropertyNode,\n RequestBodyNode,\n ResponseNode,\n SchemaNode,\n} from './nodes/index.ts'\nimport { nodeDefs } from './registry.ts'\n\n/**\n * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).\n * Derived from each definition's `children`.\n */\nconst VISITOR_KEYS = Object.fromEntries(nodeDefs.flatMap((def) => (def.children ? [[def.kind, def.children] as const] : []))) as Partial<\n Record<NodeKind, ReadonlyArray<string>>\n>\n\n/**\n * Maps a node kind to the matching visitor callback name. Derived from each\n * definition's `visitorKey`.\n */\nconst VISITOR_KEY_BY_KIND = Object.fromEntries(nodeDefs.flatMap((def) => (def.visitorKey ? [[def.kind, def.visitorKey] as const] : []))) as Partial<\n Record<NodeKind, NonNullable<NodeDef['visitorKey']>>\n>\n\n/**\n * Per-kind builders rerun after children are rebuilt. Derived from each\n * definition's `rebuild` flag.\n */\nconst nodeRebuilders = Object.fromEntries(\n nodeDefs.flatMap((def) => (def.rebuild ? [[def.kind, def.create as unknown as (node: Node) => Node] as const] : [])),\n) as Partial<Record<NodeKind, (node: Node) => Node>>\n\n/**\n * Creates a small async concurrency limiter.\n *\n * At most `concurrency` tasks are in flight at once. Extra tasks are queued.\n *\n * @example\n * ```ts\n * const limit = createLimit(2)\n * for (const task of [taskA, taskB, taskC]) {\n * await limit(() => task())\n * }\n * // only 2 tasks run at the same time\n * ```\n */\nfunction createLimit(concurrency: number) {\n let active = 0\n const queue: Array<() => void> = []\n\n function next() {\n if (active < concurrency && queue.length > 0) {\n active++\n queue.shift()!()\n }\n }\n\n return function limit<T>(fn: () => Promise<T> | T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n queue.push(() => {\n Promise.resolve(fn())\n .then(resolve, reject)\n .finally(() => {\n active--\n next()\n })\n })\n next()\n })\n }\n}\n\ntype LimitFn = ReturnType<typeof createLimit>\n\n/**\n * Ordered mapping of `[NodeType, ParentType]` pairs.\n *\n * `ParentOf` uses this map to find parent types.\n */\ntype ParentNodeMap = [\n [InputNode, undefined],\n [OutputNode, undefined],\n [OperationNode, InputNode],\n [RequestBodyNode, OperationNode],\n [ContentNode, RequestBodyNode | ResponseNode],\n [SchemaNode, InputNode | ContentNode | SchemaNode | PropertyNode | ParameterNode],\n [PropertyNode, SchemaNode],\n [ParameterNode, OperationNode],\n [ResponseNode, OperationNode],\n]\n\n/**\n * Resolves the parent node type for a given AST node type.\n *\n * Visitor context relies on this so `ctx.parent` is typed for each callback.\n *\n * @example\n * ```ts\n * type InputParent = ParentOf<InputNode>\n * // undefined\n * ```\n *\n * @example\n * ```ts\n * type PropertyParent = ParentOf<PropertyNode>\n * // SchemaNode\n * ```\n *\n * @example\n * ```ts\n * type SchemaParent = ParentOf<SchemaNode>\n * // InputNode | OperationNode | SchemaNode | PropertyNode | ParameterNode | ResponseNode\n * ```\n */\nexport type ParentOf<T extends Node, TEntries extends ReadonlyArray<[Node, unknown]> = ParentNodeMap> = TEntries extends [\n infer TEntry extends [Node, unknown],\n ...infer TRest extends ReadonlyArray<[Node, unknown]>,\n]\n ? T extends TEntry[0]\n ? TEntry[1]\n : ParentOf<T, TRest>\n : Node\n\n/**\n * Traversal context passed as the second argument to every visitor callback.\n * `parent` is typed from the current node type.\n *\n * @example\n * ```ts\n * const visitor: Visitor = {\n * schema(node, { parent }) {\n * // parent type is narrowed by node kind\n * },\n * }\n * ```\n */\nexport type VisitorContext<T extends Node = Node> = {\n /**\n * Parent node of the currently visited node.\n * For `InputNode`, this is `undefined`.\n */\n parent?: ParentOf<T>\n}\n\n/**\n * Synchronous visitor consumed by `transform`. Each optional callback runs\n * for the matching node type. Return a new node to replace it, or `undefined`\n * to leave it untouched.\n *\n * Plugins typically expose `transformer` so users can supply a `Visitor` that\n * rewrites the AST before printing.\n *\n * @example Prefix every operationId\n * ```ts\n * const visitor: Visitor = {\n * operation(node) {\n * return { ...node, operationId: `api_${node.operationId}` }\n * },\n * }\n * ```\n *\n * @example Strip schema descriptions\n * ```ts\n * const visitor: Visitor = {\n * schema(node) {\n * return { ...node, description: undefined }\n * },\n * }\n * ```\n */\nexport type Visitor = {\n input?(node: InputNode, context: VisitorContext<InputNode>): undefined | null | InputNode\n output?(node: OutputNode, context: VisitorContext<OutputNode>): undefined | null | OutputNode\n operation?(node: OperationNode, context: VisitorContext<OperationNode>): undefined | null | OperationNode\n schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): undefined | null | SchemaNode\n property?(node: PropertyNode, context: VisitorContext<PropertyNode>): undefined | null | PropertyNode\n parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): undefined | null | ParameterNode\n response?(node: ResponseNode, context: VisitorContext<ResponseNode>): undefined | null | ResponseNode\n}\n\n/**\n * A visitor callback result that may be sync or async.\n */\ntype MaybePromise<T> = T | Promise<T>\n\n/**\n * Async visitor for `walk`. Synchronous `Visitor` objects are compatible.\n *\n * @example\n * ```ts\n * const visitor: AsyncVisitor = {\n * async operation(node) {\n * await Promise.resolve(node.operationId)\n * },\n * }\n * ```\n */\ntype AsyncVisitor = {\n input?(node: InputNode, context: VisitorContext<InputNode>): MaybePromise<undefined | null | InputNode>\n output?(node: OutputNode, context: VisitorContext<OutputNode>): MaybePromise<undefined | null | OutputNode>\n operation?(node: OperationNode, context: VisitorContext<OperationNode>): MaybePromise<undefined | null | OperationNode>\n schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): MaybePromise<undefined | null | SchemaNode>\n property?(node: PropertyNode, context: VisitorContext<PropertyNode>): MaybePromise<undefined | null | PropertyNode>\n parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): MaybePromise<undefined | null | ParameterNode>\n response?(node: ResponseNode, context: VisitorContext<ResponseNode>): MaybePromise<undefined | null | ResponseNode>\n}\n\n/**\n * Visitor used by `collect`.\n *\n * @example\n * ```ts\n * const visitor: CollectVisitor<string> = {\n * operation(node) {\n * return node.operationId\n * },\n * }\n * ```\n */\ntype CollectVisitor<T> = {\n input?(node: InputNode, context: VisitorContext<InputNode>): T | null | undefined\n output?(node: OutputNode, context: VisitorContext<OutputNode>): T | null | undefined\n operation?(node: OperationNode, context: VisitorContext<OperationNode>): T | null | undefined\n schema?(node: SchemaNode, context: VisitorContext<SchemaNode>): T | null | undefined\n property?(node: PropertyNode, context: VisitorContext<PropertyNode>): T | null | undefined\n parameter?(node: ParameterNode, context: VisitorContext<ParameterNode>): T | null | undefined\n response?(node: ResponseNode, context: VisitorContext<ResponseNode>): T | null | undefined\n}\n\n/**\n * Options for `transform`.\n *\n * @example\n * ```ts\n * const options: TransformOptions = { depth: 'deep', schema: (node) => node }\n * ```\n *\n * @example\n * ```ts\n * // Only transform the current node, not nested children\n * const options: TransformOptions = { depth: 'shallow', schema: (node) => node }\n * ```\n */\nexport type TransformOptions = Visitor & {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\n/**\n * Options for `walk`.\n *\n * @example\n * ```ts\n * const options: WalkOptions = { depth: 'deep', concurrency: 10, root: () => {} }\n * ```\n */\nexport type WalkOptions = AsyncVisitor & {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Maximum number of sibling nodes visited concurrently.\n * @default 30\n */\n concurrency?: number\n}\n\n/**\n * Options for `collect`.\n *\n * @example\n * ```ts\n * const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }\n * ```\n */\nexport type CollectOptions<T> = CollectVisitor<T> & {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\nconst visitorKeysByKind = VISITOR_KEYS as Record<string, ReadonlyArray<string> | undefined>\n\n/**\n * Returns `true` when `value` is an AST node (an object carrying a `kind`).\n */\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && 'kind' in value\n}\n\n/**\n * Returns the immediate traversable children of `node` based on {@link VISITOR_KEYS}.\n *\n * `Schema` children are only included when `recurse` is `true`. Shallow mode skips them.\n *\n * @example\n * ```ts\n * const children = getChildren(operationNode, true)\n * // returns parameters, the request body, and responses\n * ```\n */\nfunction* getChildren(node: Node, recurse: boolean): Generator<Node, void, undefined> {\n if (node.kind === 'Schema' && !recurse) return\n\n const keys = visitorKeysByKind[node.kind]\n if (!keys) return\n\n const record = node as unknown as Record<string, unknown>\n for (const key of keys) {\n const value = record[key]\n if (Array.isArray(value)) {\n for (const item of value) if (isNode(item)) yield item\n } else if (isNode(value)) {\n yield value\n }\n }\n}\n\n/**\n * Runs the visitor callback that matches `node.kind` with the traversal\n * context. The result is a replacement node, a collected value, or `undefined`\n * when no callback is registered for the kind.\n *\n * Shared by `walk`, `transform`, and `collectLazy` so node-kind dispatch lives\n * in one place. `TResult` is the caller's expected return: the same node type\n * for `transform`, the collected value type for `collectLazy`, ignored for `walk`.\n */\nfunction applyVisitor<TResult>(node: Node, visitor: Visitor | AsyncVisitor | CollectVisitor<unknown>, parent: Node | undefined): TResult | null | undefined {\n const key = VISITOR_KEY_BY_KIND[node.kind]\n if (!key) return undefined\n\n const fn = visitor[key] as ((node: Node, context: VisitorContext) => TResult | null | undefined) | undefined\n\n return fn?.(node, { parent })\n}\n\n/**\n * Async depth-first traversal for side effects. Visitor return values are\n * ignored. Use `transform` when you want to rewrite nodes.\n *\n * Sibling nodes at each depth run concurrently up to `options.concurrency`\n * (defaults to `WALK_CONCURRENCY`). Higher values overlap I/O-bound visitor\n * work. Lower values reduce memory pressure.\n *\n * @example Log every operation\n * ```ts\n * await walk(root, {\n * operation(node) {\n * console.log(node.operationId)\n * },\n * })\n * ```\n *\n * @example Only visit the root node\n * ```ts\n * await walk(root, { depth: 'shallow', input: () => {} })\n * ```\n */\nexport async function walk(node: Node, options: WalkOptions): Promise<void> {\n const recurse = (options.depth ?? visitorDepths.deep) === visitorDepths.deep\n const limit = createLimit(options.concurrency ?? WALK_CONCURRENCY)\n\n return _walk(node, options, recurse, limit, undefined)\n}\n\nasync function _walk(node: Node, visitor: AsyncVisitor, recurse: boolean, limit: LimitFn, parent: Node | undefined): Promise<void> {\n await limit(() => applyVisitor(node, visitor, parent))\n\n // Visit siblings concurrently and let the shared `limit` cap how many callbacks\n // run at once. Awaiting each child sequentially here would serialize the whole\n // traversal and make `concurrency` inert. Every visitor callback would run one\n // at a time regardless of the limit.\n const children = Array.from(getChildren(node, recurse))\n if (children.length === 0) return\n\n await Promise.all(children.map((child) => _walk(child, visitor, recurse, limit, node)))\n}\n\n/**\n * Synchronous depth-first transform. Each visitor callback can return a\n * replacement node. Returning `undefined` keeps the original.\n *\n * The original tree is never mutated, a new tree is returned. Pass\n * `depth: 'shallow'` to skip recursion into children.\n *\n * @example Prefix every operationId\n * ```ts\n * const next = transform(root, {\n * operation(node) {\n * return { ...node, operationId: `prefixed_${node.operationId}` }\n * },\n * })\n * ```\n *\n * @example Replace only the root node\n * ```ts\n * const next = transform(root, {\n * depth: 'shallow',\n * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),\n * })\n * ```\n */\nexport function transform(node: InputNode, options: TransformOptions): InputNode\nexport function transform(node: OutputNode, options: TransformOptions): OutputNode\nexport function transform(node: OperationNode, options: TransformOptions): OperationNode\nexport function transform(node: SchemaNode, options: TransformOptions): SchemaNode\nexport function transform(node: PropertyNode, options: TransformOptions): PropertyNode\nexport function transform(node: ParameterNode, options: TransformOptions): ParameterNode\nexport function transform(node: ResponseNode, options: TransformOptions): ResponseNode\nexport function transform(node: Node, options: TransformOptions): Node\nexport function transform(node: Node, options: TransformOptions): Node {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep\n\n const visited = applyVisitor<Node>(node, visitor, parent) ?? node\n const rebuilt = transformChildren(visited, options, recurse)\n\n // Structural sharing: when the visitor and child rebuild both left this node\n // untouched, return the original reference so callers can detect \"nothing\n // changed\" by identity and ancestors can avoid reallocating.\n if (rebuilt === node) return node\n\n const rebuild = nodeRebuilders[rebuilt.kind]\n return rebuild ? rebuild(rebuilt) : rebuilt\n}\n\n/**\n * Immutably rebuilds a node's children using {@link VISITOR_KEYS}, transforming\n * each child node and leaving non-node values (e.g. `additionalProperties: true`) intact.\n * `Schema` children are skipped in shallow mode.\n */\nfunction transformChildren(node: Node, options: TransformOptions, recurse: boolean): Node {\n if (node.kind === 'Schema' && !recurse) return node\n\n const keys = visitorKeysByKind[node.kind]\n if (!keys) return node\n\n const record = node as unknown as Record<string, unknown>\n const childOptions = { ...options, parent: node }\n let updates: Record<string, unknown> | undefined\n\n for (const key of keys) {\n if (!(key in record)) continue\n const value = record[key]\n if (Array.isArray(value)) {\n let changed = false\n const mapped = value.map((item) => {\n if (!isNode(item)) return item\n const next = transform(item, childOptions)\n if (next !== item) changed = true\n return next\n })\n if (changed) (updates ??= {})[key] = mapped\n } else if (isNode(value)) {\n const next = transform(value, childOptions)\n if (next !== value) (updates ??= {})[key] = next\n }\n }\n\n return updates ? ({ ...node, ...updates } as Node) : node\n}\n/**\n * Lazy depth-first collection pass. Yields every non-null value returned by\n * the visitor callbacks. Use `collect` for the eager array form.\n *\n * @example Collect every operationId\n * ```ts\n * const ids: string[] = []\n * for (const id of collectLazy<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })) {\n * ids.push(id)\n * }\n * ```\n */\nexport function* collectLazy<T>(node: Node, options: CollectOptions<T>): Generator<T, void, undefined> {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? visitorDepths.deep) === visitorDepths.deep\n\n const v = applyVisitor<T>(node, visitor, parent)\n if (v != null) yield v\n\n for (const child of getChildren(node, recurse)) {\n yield* collectLazy(child, { ...options, parent: node })\n }\n}\n\n/**\n * Eager depth-first collection pass. Gathers every non-null value the visitor\n * callbacks return into an array.\n *\n * @example Collect every operationId\n * ```ts\n * const ids = collect<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })\n * ```\n */\nexport function collect<T>(node: Node, options: CollectOptions<T>): Array<T> {\n return Array.from(collectLazy(node, options))\n}\n"],"mappings":";;AAWA,MAAa,gBAAgB;CAC3B,SAAS;CACT,MAAM;AACR;;;;;;;AAQA,MAAa,cAAc;;;;CAIzB,QAAQ;;;;CAIR,QAAQ;;;;CAIR,SAAS;;;;CAIT,QAAQ;;;;CAIR,SAAS;;;;CAIT,MAAM;;;;CAIN,KAAK;;;;CAIL,SAAS;;;;CAIT,MAAM;;;;CAIN,QAAQ;;;;CAIR,OAAO;;;;CAIP,OAAO;;;;CAIP,OAAO;;;;CAIP,cAAc;;;;CAId,MAAM;;;;CAIN,KAAK;;;;CAIL,MAAM;;;;CAIN,UAAU;;;;CAIV,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;;;;CAIP,KAAK;;;;CAIL,MAAM;;;;CAIN,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;AACT;;;;AAOA,MAAM,yBAAyB,IAAI,IAAqB;CAAC;CAAU;CAAU;CAAW;CAAU;AAAS,CAAC;;;;;AAM5G,SAAgB,kBAAkB,MAAuC;CACvE,OAAO,uBAAuB,IAAI,IAAuB;AAC3D;;;;AAKA,MAAa,cAAc;CACzB,KAAK;CACL,MAA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,eAAe;EAAE,GAAG;EAAS,QAAQ;CAAK;CAChD,IAAI;CAEJ,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,EAAE,OAAO,SAAS;EACtB,MAAM,QAAQ,OAAO;EACrB,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,IAAI,UAAU;GACd,MAAM,SAAS,MAAM,KAAK,SAAS;IACjC,IAAI,CAAC,OAAO,IAAI,GAAG,OAAO;IAC1B,MAAM,OAAO,UAAU,MAAM,YAAY;IACzC,IAAI,SAAS,MAAM,UAAU;IAC7B,OAAO;GACT,CAAC;GACD,IAAI,SAAS,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;EACvC,OAAO,IAAI,OAAO,KAAK,GAAG;GACxB,MAAM,OAAO,UAAU,OAAO,YAAY;GAC1C,IAAI,SAAS,OAAO,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;EAC9C;CACF;CAEA,OAAO,UAAW;EAAE,GAAG;EAAM,GAAG;CAAQ,IAAa;AACvD;;;;;;;;;;;;;;;;;AAiBA,UAAiB,YAAe,MAAY,SAA2D;CACrG,MAAM,EAAE,OAAO,QAAQ,GAAG,YAAY;CACtC,MAAM,WAAW,SAAS,cAAc,UAAU,cAAc;CAEhE,MAAM,IAAI,aAAgB,MAAM,SAAS,MAAM;CAC/C,IAAI,KAAK,MAAM,MAAM;CAErB,KAAK,MAAM,SAAS,YAAY,MAAM,OAAO,GAC3C,OAAO,YAAY,OAAO;EAAE,GAAG;EAAS,QAAQ;CAAK,CAAC;AAE1D;;;;;;;;;;;;;;AAeA,SAAgB,QAAW,MAAY,SAAsC;CAC3E,OAAO,MAAM,KAAK,YAAY,MAAM,OAAO,CAAC;AAC9C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/ast",
3
- "version": "5.0.0-beta.60",
3
+ "version": "5.0.0-beta.61",
4
4
  "description": "Spec-agnostic AST layer for Kubb. Defines the node tree, visitor pattern, factory functions, and type guards used across all code generation plugins.",
5
5
  "keywords": [
6
6
  "ast",
@@ -35,6 +35,10 @@
35
35
  "import": "./dist/factory.js",
36
36
  "require": "./dist/factory.cjs"
37
37
  },
38
+ "./macros": {
39
+ "import": "./dist/macros.js",
40
+ "require": "./dist/macros.cjs"
41
+ },
38
42
  "./types": {
39
43
  "import": "./dist/types.js",
40
44
  "require": "./dist/types.cjs"
@@ -0,0 +1,132 @@
1
+ import type { VisitorDepth } from './constants.ts'
2
+ import type { Node } from './nodes/index.ts'
3
+ import type { Visitor, VisitorContext } from './visitor.ts'
4
+ import { transform } from './visitor.ts'
5
+
6
+ /**
7
+ * Visitor callback names a macro can implement, one per traversable node kind.
8
+ * Mirrors the keys of {@link Visitor}.
9
+ */
10
+ const macroKeys = ['input', 'output', 'operation', 'schema', 'property', 'parameter', 'response'] as const
11
+
12
+ type MacroKey = (typeof macroKeys)[number]
13
+
14
+ /**
15
+ * Sort weight for an `enforce` hint. `pre` sorts before unmarked items and `post` after, so a plain
16
+ * list keeps its authored order.
17
+ */
18
+ function enforceWeight(enforce?: 'pre' | 'post'): number {
19
+ if (enforce === 'pre') return 0
20
+ if (enforce === 'post') return 2
21
+ return 1
22
+ }
23
+
24
+ /**
25
+ * A named, composable transform over the Kubb AST. It carries the same per-kind callbacks as a
26
+ * {@link Visitor} (`schema`, `operation`, …), plus a `name`, an optional `enforce` order, and an
27
+ * optional `when` gate. Macros run on the shared AST, so the same macro works across every adapter
28
+ * and output target. Exports follow the `macro<Name>` convention, mirroring plugins (`pluginTs`).
29
+ */
30
+ export type Macro = Visitor & {
31
+ /**
32
+ * Macro identifier, surfaced in diagnostics. Follows the `macro<Name>` convention.
33
+ */
34
+ name: string
35
+ /**
36
+ * Ordering hint. `pre` macros run before unmarked macros, `post` macros run after.
37
+ * Ordering within a bucket follows list order.
38
+ */
39
+ enforce?: 'pre' | 'post'
40
+ /**
41
+ * Gate checked against the current node before any callback runs. When it returns `false`
42
+ * the macro is skipped for that node.
43
+ */
44
+ when?: (node: Node) => boolean
45
+ }
46
+
47
+ /**
48
+ * Types a macro for inference and a single construction site, mirroring `definePlugin`.
49
+ * Adds no runtime behavior.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const macroUntagged = defineMacro({
54
+ * name: 'untagged',
55
+ * operation(node) {
56
+ * return node.tags?.length ? undefined : { ...node, tags: ['untagged'] }
57
+ * },
58
+ * })
59
+ * ```
60
+ */
61
+ export function defineMacro(macro: Macro): Macro {
62
+ return macro
63
+ }
64
+
65
+ type MacroCallback = (node: Node, context: VisitorContext) => Node | null | undefined
66
+
67
+ /**
68
+ * Runs every macro's callback for one node kind in order, chaining the result so each macro sees
69
+ * the previous macro's output. Returns `undefined` when nothing changed, so `transform` keeps the
70
+ * original reference (structural sharing).
71
+ */
72
+ function chain(macros: ReadonlyArray<Macro>, key: MacroKey, node: Node, context: VisitorContext): Node | undefined {
73
+ let current = node
74
+
75
+ for (const macro of macros) {
76
+ const callback = macro[key] as MacroCallback | undefined
77
+ if (!callback) continue
78
+ if (macro.when && !macro.when(current)) continue
79
+
80
+ const next = callback(current, context)
81
+ if (next != null) current = next
82
+ }
83
+
84
+ return current === node ? undefined : current
85
+ }
86
+
87
+ /**
88
+ * Folds an ordered list of macros into a single {@link Visitor} that `transform` (and the per-plugin
89
+ * transform layer in `@kubb/core`) can run. Macros are stable-sorted by `enforce`, then applied
90
+ * sequentially per node so later macros see earlier output. This differs from a plain visitor, which
91
+ * has no names, ordering, or composition.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * const visitor = composeMacros([macroSimplifyUnion, macroDiscriminatorEnum])
96
+ * const next = transform(root, visitor)
97
+ * ```
98
+ */
99
+ export function composeMacros(macros: ReadonlyArray<Macro>): Visitor {
100
+ const ordered = [...macros].sort((a, b) => enforceWeight(a.enforce) - enforceWeight(b.enforce))
101
+
102
+ const visitor: Visitor = {}
103
+ for (const key of macroKeys) {
104
+ if (!ordered.some((macro) => typeof macro[key] === 'function')) continue
105
+
106
+ const callback = (node: Node, context: VisitorContext) => chain(ordered, key, node, context)
107
+ ;(visitor as Record<MacroKey, MacroCallback>)[key] = callback
108
+ }
109
+
110
+ return visitor
111
+ }
112
+
113
+ /**
114
+ * Runs a list of macros over a node tree and returns the rewritten tree. Keeps `transform`'s
115
+ * structural sharing, so an empty or no-op macro list returns the same reference. Pass
116
+ * `depth: 'shallow'` to rewrite the root node only.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const next = applyMacros(root, [macroIntegerToString])
121
+ * ```
122
+ *
123
+ * @example Apply to the root node only
124
+ * ```ts
125
+ * const named = applyMacros(node, [macroEnumName({ parentName, propName, enumSuffix })], { depth: 'shallow' })
126
+ * ```
127
+ */
128
+ export function applyMacros<TNode extends Node>(root: TNode, macros: ReadonlyArray<Macro>, options?: { depth?: VisitorDepth }): TNode {
129
+ if (macros.length === 0) return root
130
+
131
+ return transform(root, { ...composeMacros(macros), depth: options?.depth }) as TNode
132
+ }
package/src/index.ts CHANGED
@@ -1,19 +1,15 @@
1
1
  export { httpMethods, schemaTypes } from './constants.ts'
2
2
  export { applyDedupe, buildDedupePlan } from './dedupe.ts'
3
3
  export { defineSchemaDialect } from './dialect.ts'
4
- // Node constructors, also published as the `@kubb/ast/factory` subpath, mirroring `ts.factory.createX`.
5
4
  export * as factory from './factory.ts'
6
5
  export { isHttpOperationNode, narrowSchema } from './guards.ts'
6
+ export { applyMacros, composeMacros, defineMacro } from './defineMacro.ts'
7
7
  export { defineNode } from './node.ts'
8
- export type { NodeDef } from './node.ts'
9
8
  export { syncOptionality } from './node.ts'
10
- // Every node def plus `nodeDefs` in one line, so adding a node never edits this barrel. The visitor
11
- // tables derived from `nodeDefs` stay internal to `visitor.ts`.
12
9
  export * from './registry.ts'
13
10
  export { createPrinterFactory, definePrinter } from './printer.ts'
14
11
  export { signatureOf } from './signature.ts'
15
- export { mergeAdjacentObjectsLazy, setDiscriminatorEnum, setEnumName, simplifyUnion } from './transformers.ts'
16
- export type * from './types.ts'
17
- // The node/AST helpers in ./utils/ live on the `@kubb/ast/utils` subpath, not the root barrel.
18
12
  export { extractStringsFromNodes } from './utils/extractStringsFromNodes.ts'
19
13
  export { collect, transform, walk } from './visitor.ts'
14
+
15
+ export type * from './types.ts'
@@ -0,0 +1,3 @@
1
+ export { macroDiscriminatorEnum } from './macroDiscriminatorEnum.ts'
2
+ export { macroEnumName } from './macroEnumName.ts'
3
+ export { macroSimplifyUnion } from './macroSimplifyUnion.ts'
@@ -0,0 +1,44 @@
1
+ import { defineMacro } from '../defineMacro.ts'
2
+ import { narrowSchema } from '../guards.ts'
3
+ import { createProperty } from '../nodes/property.ts'
4
+ import { createSchema } from '../nodes/schema.ts'
5
+
6
+ /**
7
+ * Builds a macro that replaces a discriminator property's schema with a string enum of the given
8
+ * values. Object schemas that lack the property are returned unchanged.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const macro = macroDiscriminatorEnum({ propertyName: 'type', values: ['dog', 'cat'] })
13
+ * const next = applyMacros(objectSchema, [macro], { depth: 'shallow' })
14
+ * ```
15
+ */
16
+ export function macroDiscriminatorEnum({ propertyName, values, enumName }: { propertyName: string; values: Array<string>; enumName?: string }) {
17
+ return defineMacro({
18
+ name: 'discriminator-enum',
19
+ schema(node) {
20
+ const objectNode = narrowSchema(node, 'object')
21
+ if (!objectNode?.properties?.length) return undefined
22
+ if (!objectNode.properties.some((prop) => prop.name === propertyName)) return undefined
23
+
24
+ return createSchema({
25
+ ...objectNode,
26
+ properties: objectNode.properties.map((prop) => {
27
+ if (prop.name !== propertyName) return prop
28
+
29
+ return createProperty({
30
+ ...prop,
31
+ schema: createSchema({
32
+ type: 'enum',
33
+ primitive: 'string',
34
+ enumValues: values,
35
+ name: enumName,
36
+ readOnly: prop.schema.readOnly,
37
+ writeOnly: prop.schema.writeOnly,
38
+ }),
39
+ })
40
+ }),
41
+ })
42
+ },
43
+ })
44
+ }
@@ -0,0 +1,25 @@
1
+ import { defineMacro } from '../defineMacro.ts'
2
+ import { narrowSchema } from '../guards.ts'
3
+ import { enumPropName } from '../utils/refs.ts'
4
+
5
+ /**
6
+ * Builds a macro that names an inline enum schema from its parent and property name. Boolean enums
7
+ * are left anonymous; non-enum nodes are returned unchanged.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const macro = macroEnumName({ parentName: 'Pet', propName: 'status', enumSuffix: 'enum' })
12
+ * const named = applyMacros(propSchema, [macro], { depth: 'shallow' })
13
+ * ```
14
+ */
15
+ export function macroEnumName({ parentName, propName, enumSuffix }: { parentName: string | null | undefined; propName: string; enumSuffix: string }) {
16
+ return defineMacro({
17
+ name: 'enum-name',
18
+ schema(node) {
19
+ const enumNode = narrowSchema(node, 'enum')
20
+ if (enumNode?.primitive === 'boolean') return { ...node, name: null }
21
+ if (enumNode) return { ...node, name: enumPropName(parentName, propName, enumSuffix) }
22
+ return undefined
23
+ },
24
+ })
25
+ }
@@ -0,0 +1,50 @@
1
+ import { isScalarPrimitive } from '../constants.ts'
2
+ import { defineMacro } from '../defineMacro.ts'
3
+ import { narrowSchema } from '../guards.ts'
4
+ import type { SchemaNode } from '../nodes/schema.ts'
5
+
6
+ /**
7
+ * Removes union members a broader scalar primitive already covers, such as a multi-value string enum
8
+ * sitting next to a plain `string`. Single-value enums are kept.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const next = applyMacros(unionSchema, [macroSimplifyUnion], { depth: 'shallow' })
13
+ * ```
14
+ */
15
+ export const macroSimplifyUnion = defineMacro({
16
+ name: 'simplify-union',
17
+ schema(node) {
18
+ const unionNode = narrowSchema(node, 'union')
19
+ if (!unionNode?.members?.length) return undefined
20
+
21
+ const simplified = simplifyUnionMembers(unionNode.members)
22
+ if (simplified.length === unionNode.members.length) return undefined
23
+
24
+ return { ...unionNode, members: simplified }
25
+ },
26
+ })
27
+
28
+ /**
29
+ * Filters union members, dropping enum members that a broader scalar primitive already covers.
30
+ */
31
+ function simplifyUnionMembers(members: Array<SchemaNode>): Array<SchemaNode> {
32
+ const scalarPrimitives = new Set(members.filter((member) => isScalarPrimitive(member.type)).map((m) => m.type))
33
+ if (!scalarPrimitives.size) return members
34
+
35
+ return members.filter((member) => {
36
+ const enumNode = narrowSchema(member, 'enum')
37
+ if (!enumNode) return true
38
+
39
+ const primitive = enumNode.primitive
40
+ if (!primitive) return true
41
+
42
+ const enumValueCount = enumNode.namedEnumValues?.length ?? enumNode.enumValues?.length ?? 0
43
+ if (enumValueCount <= 1) return true
44
+
45
+ if (scalarPrimitives.has(primitive)) return false
46
+ if ((primitive === 'integer' || primitive === 'number') && (scalarPrimitives.has('integer') || scalarPrimitives.has('number'))) return false
47
+
48
+ return true
49
+ })
50
+ }
package/src/types.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  export type { DedupeCanonical, DedupeLookups, DedupePlan } from './dedupe.ts'
2
2
  export type { SchemaDialect } from './dialect.ts'
3
- export type { DistributiveOmit } from './node.ts'
3
+ export type { DistributiveOmit, NodeDef } from './node.ts'
4
4
  export type { InferSchemaNode, ParserOptions } from './infer.ts'
5
5
  export type * from './nodes/index.ts'
6
6
  export type { ParentOf, Visitor, VisitorContext } from './visitor.ts'
7
7
  export type { Printer, PrinterFactoryOptions, PrinterPartial } from './printer.ts'
8
8
  export type { OperationParamsResolver } from './utils/operationParams.ts'
9
9
  export type { UserFileNode } from './factory.ts'
10
+ export type { Macro } from './defineMacro.ts'
@@ -1,8 +1,8 @@
1
1
  export { isValidVarName } from '@internals/utils'
2
2
  export { buildJSDoc, buildList, buildObject, objectKey } from './codegen.ts'
3
3
  export { extractStringsFromNodes } from './extractStringsFromNodes.ts'
4
- export { childName, enumPropName, extractRefName, isStringType, resolveGroupType, resolveRefName } from './refs.ts'
5
- export { syncSchemaRef } from '../transformers.ts'
4
+ export { childName, enumPropName, extractRefName, isStringType, resolveGroupType, resolveRefName, syncSchemaRef } from './refs.ts'
5
+ export { mergeAdjacentObjectsLazy } from './schemaMerge.ts'
6
6
  export { getNestedAccessor, jsStringEscape, stringify, stringifyObject, toRegExpString, trimQuotes } from './strings.ts'
7
7
  export { collectUsedSchemaNames, containsCircularRef, findCircularSchemas } from './schemaGraph.ts'
8
8
  export { lazyGetter, mapSchemaItems, mapSchemaMembers, mapSchemaProperties } from './schemaTraversal.ts'
package/src/utils/refs.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { pascalCase } from '@internals/utils'
2
2
  import { narrowSchema } from '../guards.ts'
3
3
  import type { OperationNode, ParameterNode, SchemaNode } from '../nodes/index.ts'
4
- import type { SchemaType } from '../nodes/schema.ts'
4
+ import { createSchema, type SchemaType } from '../nodes/schema.ts'
5
5
  import type { OperationParamsResolver, ParamGroupType } from './operationParams.ts'
6
6
 
7
7
  const plainStringTypes = new Set<SchemaType>(['string', 'uuid', 'email', 'url', 'datetime'] as const)
@@ -63,6 +63,32 @@ export function enumPropName(parentName: string | null | undefined, propName: st
63
63
  return pascalCase([parentName, propName, enumSuffix].filter(Boolean).join(' '))
64
64
  }
65
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
+
66
92
  /**
67
93
  * Type guard that returns `true` when a schema emits as a plain `string` type.
68
94
  *
@@ -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
+ }
@@ -1,82 +0,0 @@
1
- import { n as __name } from "./chunk-CNktS9qV.js";
2
- import { Pt as CodeNode, _t as SchemaNode } from "./index-BzjwdK2M.js";
3
-
4
- //#region src/transformers.d.ts
5
- /**
6
- * Replaces a discriminator property's schema with a string enum of allowed values.
7
- *
8
- * If `node` is not an object schema, or if the property does not exist, the input
9
- * node is returned as-is.
10
- *
11
- * @example
12
- * ```ts
13
- * const schema = createSchema({
14
- * type: 'object',
15
- * properties: [createProperty({ name: 'type', required: true, schema: createSchema({ type: 'string' }) })],
16
- * })
17
- * const result = setDiscriminatorEnum({ node: schema, propertyName: 'type', values: ['dog', 'cat'] })
18
- * ```
19
- */
20
- declare function setDiscriminatorEnum({
21
- node,
22
- propertyName,
23
- values,
24
- enumName
25
- }: {
26
- node: SchemaNode;
27
- propertyName: string;
28
- values: Array<string>;
29
- enumName?: string;
30
- }): SchemaNode;
31
- /**
32
- * Merges adjacent anonymous object members into a single anonymous object member.
33
- *
34
- * @example
35
- * ```ts
36
- * const merged = mergeAdjacentObjects([
37
- * createSchema({ type: 'object', properties: [createProperty({ name: 'a', schema: createSchema({ type: 'string' }) })] }),
38
- * createSchema({ type: 'object', properties: [createProperty({ name: 'b', schema: createSchema({ type: 'number' }) })] }),
39
- * ])
40
- * ```
41
- */
42
- declare function mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined>;
43
- /**
44
- * Removes enum members that are covered by broader scalar primitives in the same union.
45
- *
46
- * @example
47
- * ```ts
48
- * const simplified = simplifyUnion([
49
- * createSchema({ type: 'enum', primitive: 'string', enumValues: ['active'] }),
50
- * createSchema({ type: 'string' }),
51
- * ])
52
- * // keeps only string member
53
- * ```
54
- */
55
- declare function simplifyUnion(members: Array<SchemaNode>): Array<SchemaNode>;
56
- declare function setEnumName(propNode: SchemaNode, parentName: string | null | undefined, propName: string, enumSuffix: string): SchemaNode;
57
- /**
58
- * Merges a ref node with its resolved schema, giving usage-site fields precedence.
59
- *
60
- * Usage-site fields (`description`, `readOnly`, `nullable`, `deprecated`) on the ref node override
61
- * the same fields in the resolved `node.schema`. Non-ref nodes are returned unchanged.
62
- *
63
- * @example
64
- * ```ts
65
- * // Ref with description override
66
- * const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
67
- * const merged = syncSchemaRef(ref) // merges with resolved Pet schema
68
- * ```
69
- */
70
- declare function syncSchemaRef(node: SchemaNode): SchemaNode;
71
- //#endregion
72
- //#region src/utils/extractStringsFromNodes.d.ts
73
- /**
74
- * Extracts all string content from a `CodeNode` tree recursively.
75
- *
76
- * Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
77
- * and nested node content. Used to build the full source string for import filtering.
78
- */
79
- declare function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): string;
80
- //#endregion
81
- export { simplifyUnion as a, setEnumName as i, mergeAdjacentObjectsLazy as n, syncSchemaRef as o, setDiscriminatorEnum as r, extractStringsFromNodes as t };
82
- //# sourceMappingURL=extractStringsFromNodes-WMYJ8nQL.d.ts.map