@kubb/ast 5.0.0-beta.6 → 5.0.0-beta.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +17 -10
- package/README.md +51 -27
- package/dist/chunk-CNktS9qV.js +17 -0
- package/dist/defineMacro-BLIR6k-j.d.ts +475 -0
- package/dist/defineMacro-BTXvS8nI.js +106 -0
- package/dist/defineMacro-BTXvS8nI.js.map +1 -0
- package/dist/defineMacro-Bv9R_9a2.cjs +123 -0
- package/dist/defineMacro-Bv9R_9a2.cjs.map +1 -0
- package/dist/extractStringsFromNodes-Cja-xxx5.js +29 -0
- package/dist/extractStringsFromNodes-Cja-xxx5.js.map +1 -0
- package/dist/extractStringsFromNodes-DKgDjFO0.cjs +34 -0
- package/dist/extractStringsFromNodes-DKgDjFO0.cjs.map +1 -0
- package/dist/extractStringsFromNodes-p4mX1TQD.d.ts +14 -0
- package/dist/factory-CZNOGI-N.js +283 -0
- package/dist/factory-CZNOGI-N.js.map +1 -0
- package/dist/factory-DG1CVkEb.cjs +300 -0
- package/dist/factory-DG1CVkEb.cjs.map +1 -0
- package/dist/factory.cjs +29 -0
- package/dist/factory.d.ts +62 -0
- package/dist/factory.js +3 -0
- package/dist/index-BzjwdK2M.d.ts +2433 -0
- package/dist/index.cjs +444 -2180
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +94 -3408
- package/dist/index.js +395 -2101
- package/dist/index.js.map +1 -1
- package/dist/macros.cjs +117 -0
- package/dist/macros.cjs.map +1 -0
- package/dist/macros.d.ts +59 -0
- package/dist/macros.js +115 -0
- package/dist/macros.js.map +1 -0
- package/dist/operationParams-BZ07xDm0.d.ts +204 -0
- package/dist/response-KUdWiDWw.js +658 -0
- package/dist/response-KUdWiDWw.js.map +1 -0
- package/dist/response-hnSw2NKE.cjs +1027 -0
- package/dist/response-hnSw2NKE.cjs.map +1 -0
- package/dist/types-DyDzizSf.d.ts +364 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.ts +6 -0
- package/dist/types.js +1 -0
- package/dist/utils-BLJwyza-.cjs +912 -0
- package/dist/utils-BLJwyza-.cjs.map +1 -0
- package/dist/utils-CF_-Pn_c.js +770 -0
- package/dist/utils-CF_-Pn_c.js.map +1 -0
- package/dist/utils.cjs +36 -0
- package/dist/utils.d.ts +358 -0
- package/dist/utils.js +4 -0
- package/dist/visitor-DJ6ZEJvq.js +548 -0
- package/dist/visitor-DJ6ZEJvq.js.map +1 -0
- package/dist/visitor-DpKZ9Tk0.cjs +654 -0
- package/dist/visitor-DpKZ9Tk0.cjs.map +1 -0
- package/package.json +21 -6
- package/src/constants.ts +19 -64
- package/src/dedupe.ts +239 -0
- package/src/defineMacro.ts +132 -0
- package/src/dialect.ts +53 -0
- package/src/factory.ts +67 -678
- package/src/guards.ts +10 -92
- package/src/index.ts +13 -44
- package/src/infer.ts +16 -14
- package/src/macros/index.ts +3 -0
- package/src/macros/macroDiscriminatorEnum.ts +44 -0
- package/src/macros/macroEnumName.ts +25 -0
- package/src/macros/macroSimplifyUnion.ts +50 -0
- package/src/mocks.ts +7 -127
- package/src/node.ts +128 -0
- package/src/nodes/base.ts +5 -12
- package/src/nodes/code.ts +165 -74
- package/src/nodes/content.ts +56 -0
- package/src/nodes/file.ts +97 -36
- package/src/nodes/function.ts +216 -156
- package/src/nodes/http.ts +1 -35
- package/src/nodes/index.ts +23 -15
- package/src/nodes/input.ts +140 -0
- package/src/nodes/operation.ts +122 -68
- package/src/nodes/output.ts +23 -0
- package/src/nodes/parameter.ts +33 -3
- package/src/nodes/property.ts +36 -3
- package/src/nodes/requestBody.ts +61 -0
- package/src/nodes/response.ts +58 -13
- package/src/nodes/schema.ts +93 -17
- package/src/printer.ts +48 -42
- package/src/registry.ts +75 -0
- package/src/signature.ts +207 -0
- package/src/types.ts +8 -68
- package/src/utils/codegen.ts +104 -0
- package/src/utils/extractStringsFromNodes.ts +34 -0
- package/src/utils/fileMerge.ts +184 -0
- package/src/utils/index.ts +11 -0
- package/src/utils/operationParams.ts +353 -0
- package/src/utils/refs.ts +138 -0
- package/src/utils/schemaGraph.ts +169 -0
- package/src/utils/schemaMerge.ts +34 -0
- package/src/utils/schemaTraversal.ts +86 -0
- package/src/utils/strings.ts +139 -0
- package/src/visitor.ts +227 -289
- package/dist/chunk--u3MIqq1.js +0 -8
- package/src/nodes/root.ts +0 -64
- package/src/refs.ts +0 -67
- package/src/resolvers.ts +0 -45
- package/src/transformers.ts +0 -159
- package/src/utils.ts +0 -915
|
@@ -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;;;;CA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ACrG,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,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/ast",
|
|
3
|
-
"version": "5.0.0-beta.
|
|
4
|
-
"description": "Spec-agnostic AST layer for Kubb. Defines
|
|
3
|
+
"version": "5.0.0-beta.61",
|
|
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",
|
|
7
7
|
"codegen",
|
|
8
8
|
"kubb",
|
|
9
|
-
"openapi",
|
|
10
9
|
"typescript"
|
|
11
10
|
],
|
|
12
11
|
"license": "MIT",
|
|
@@ -24,7 +23,6 @@
|
|
|
24
23
|
"!/**/__snapshots__/**"
|
|
25
24
|
],
|
|
26
25
|
"type": "module",
|
|
27
|
-
"sideEffects": false,
|
|
28
26
|
"main": "./dist/index.cjs",
|
|
29
27
|
"module": "./dist/index.js",
|
|
30
28
|
"types": "./dist/index.d.ts",
|
|
@@ -33,6 +31,22 @@
|
|
|
33
31
|
"import": "./dist/index.js",
|
|
34
32
|
"require": "./dist/index.cjs"
|
|
35
33
|
},
|
|
34
|
+
"./factory": {
|
|
35
|
+
"import": "./dist/factory.js",
|
|
36
|
+
"require": "./dist/factory.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./macros": {
|
|
39
|
+
"import": "./dist/macros.js",
|
|
40
|
+
"require": "./dist/macros.cjs"
|
|
41
|
+
},
|
|
42
|
+
"./types": {
|
|
43
|
+
"import": "./dist/types.js",
|
|
44
|
+
"require": "./dist/types.cjs"
|
|
45
|
+
},
|
|
46
|
+
"./utils": {
|
|
47
|
+
"import": "./dist/utils.js",
|
|
48
|
+
"require": "./dist/utils.cjs"
|
|
49
|
+
},
|
|
36
50
|
"./package.json": "./package.json"
|
|
37
51
|
},
|
|
38
52
|
"publishConfig": {
|
|
@@ -40,7 +54,7 @@
|
|
|
40
54
|
"registry": "https://registry.npmjs.org/"
|
|
41
55
|
},
|
|
42
56
|
"devDependencies": {
|
|
43
|
-
"@types/node": "^22.19.
|
|
57
|
+
"@types/node": "^22.19.21",
|
|
44
58
|
"@internals/utils": "0.0.0"
|
|
45
59
|
},
|
|
46
60
|
"engines": {
|
|
@@ -48,11 +62,12 @@
|
|
|
48
62
|
},
|
|
49
63
|
"scripts": {
|
|
50
64
|
"build": "tsdown",
|
|
51
|
-
"clean": "
|
|
65
|
+
"clean": "node -e \"require('node:fs').rmSync('./dist', {recursive:true,force:true})\"",
|
|
52
66
|
"lint": "oxlint .",
|
|
53
67
|
"lint:fix": "oxlint --fix .",
|
|
54
68
|
"release": "pnpm publish --no-git-check",
|
|
55
69
|
"release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check",
|
|
70
|
+
"release:stage": "pnpm stage publish --no-git-check",
|
|
56
71
|
"start": "tsdown --watch",
|
|
57
72
|
"test": "vitest --passWithNoTests",
|
|
58
73
|
"typecheck": "tsc -p ./tsconfig.json --noEmit --emitDeclarationOnly false"
|
package/src/constants.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import type { NodeKind } from './nodes/base.ts'
|
|
2
|
-
import type { MediaType } from './nodes/http.ts'
|
|
3
1
|
import type { HttpMethod } from './nodes/operation.ts'
|
|
4
2
|
import type { SchemaType } from './nodes/schema.ts'
|
|
5
3
|
|
|
6
4
|
/**
|
|
7
5
|
* Traversal depth for AST visitor utilities.
|
|
8
6
|
*
|
|
9
|
-
* - `'shallow'`
|
|
10
|
-
* - `'deep'`
|
|
7
|
+
* - `'shallow'` visits only the immediate node, skipping children.
|
|
8
|
+
* - `'deep'` recursively visits all descendant nodes.
|
|
11
9
|
*/
|
|
12
10
|
export type VisitorDepth = 'shallow' | 'deep'
|
|
13
11
|
|
|
@@ -16,32 +14,11 @@ export const visitorDepths = {
|
|
|
16
14
|
deep: 'deep',
|
|
17
15
|
} as const satisfies Record<VisitorDepth, VisitorDepth>
|
|
18
16
|
|
|
19
|
-
export const nodeKinds = {
|
|
20
|
-
input: 'Input',
|
|
21
|
-
output: 'Output',
|
|
22
|
-
operation: 'Operation',
|
|
23
|
-
schema: 'Schema',
|
|
24
|
-
property: 'Property',
|
|
25
|
-
parameter: 'Parameter',
|
|
26
|
-
response: 'Response',
|
|
27
|
-
functionParameter: 'FunctionParameter',
|
|
28
|
-
parameterGroup: 'ParameterGroup',
|
|
29
|
-
functionParameters: 'FunctionParameters',
|
|
30
|
-
type: 'Type',
|
|
31
|
-
file: 'File',
|
|
32
|
-
import: 'Import',
|
|
33
|
-
export: 'Export',
|
|
34
|
-
source: 'Source',
|
|
35
|
-
text: 'Text',
|
|
36
|
-
break: 'Break',
|
|
37
|
-
} as const satisfies Record<string, NodeKind>
|
|
38
|
-
|
|
39
17
|
/**
|
|
40
18
|
* Schema type discriminators used by all AST schema nodes.
|
|
41
19
|
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* and format-specific types (`date`, `uuid`, `email`). Use `isScalarPrimitive()` to check for scalar types.
|
|
20
|
+
* Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).
|
|
21
|
+
* Call `isScalarPrimitive()` to check for the scalar types.
|
|
45
22
|
*/
|
|
46
23
|
export const schemaTypes = {
|
|
47
24
|
/**
|
|
@@ -61,7 +38,7 @@ export const schemaTypes = {
|
|
|
61
38
|
*/
|
|
62
39
|
bigint: 'bigint',
|
|
63
40
|
/**
|
|
64
|
-
* Boolean value
|
|
41
|
+
* Boolean value.
|
|
65
42
|
*/
|
|
66
43
|
boolean: 'boolean',
|
|
67
44
|
/**
|
|
@@ -154,15 +131,12 @@ export type ScalarPrimitive = 'string' | 'number' | 'integer' | 'bigint' | 'bool
|
|
|
154
131
|
|
|
155
132
|
/**
|
|
156
133
|
* Scalar primitive schema types used for union simplification and type narrowing.
|
|
157
|
-
*
|
|
158
|
-
* Use `isScalarPrimitive()` to safely check whether a type is a scalar primitive.
|
|
159
134
|
*/
|
|
160
|
-
|
|
135
|
+
const SCALAR_PRIMITIVE_TYPES = new Set<ScalarPrimitive>(['string', 'number', 'integer', 'bigint', 'boolean'])
|
|
161
136
|
|
|
162
137
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
* Use this to check if a schema type can be directly assigned without wrapping (e.g., `string | number | boolean`).
|
|
138
|
+
* Returns `true` when `type` is a scalar primitive that can be assigned without wrapping
|
|
139
|
+
* (for example `string | number | boolean`).
|
|
166
140
|
*/
|
|
167
141
|
export function isScalarPrimitive(type: string): type is ScalarPrimitive {
|
|
168
142
|
return SCALAR_PRIMITIVE_TYPES.has(type as ScalarPrimitive)
|
|
@@ -170,8 +144,6 @@ export function isScalarPrimitive(type: string): type is ScalarPrimitive {
|
|
|
170
144
|
|
|
171
145
|
/**
|
|
172
146
|
* HTTP method identifiers used by operation nodes.
|
|
173
|
-
*
|
|
174
|
-
* Includes all standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE).
|
|
175
147
|
*/
|
|
176
148
|
export const httpMethods = {
|
|
177
149
|
get: 'GET',
|
|
@@ -185,10 +157,10 @@ export const httpMethods = {
|
|
|
185
157
|
} as const satisfies Record<Lowercase<HttpMethod>, HttpMethod>
|
|
186
158
|
|
|
187
159
|
/**
|
|
188
|
-
* Default concurrency limit for `walk()` traversal utility.
|
|
160
|
+
* Default concurrency limit for the `walk()` traversal utility.
|
|
189
161
|
*
|
|
190
|
-
* Set to 30 to balance I/O-bound resolver parallelism against event
|
|
191
|
-
*
|
|
162
|
+
* Set to 30 to balance I/O-bound resolver parallelism against event-loop and memory pressure
|
|
163
|
+
* during large spec traversals. Override it for different hardware constraints.
|
|
192
164
|
*
|
|
193
165
|
* @example
|
|
194
166
|
* ```ts
|
|
@@ -200,29 +172,12 @@ export const httpMethods = {
|
|
|
200
172
|
export const WALK_CONCURRENCY = 30
|
|
201
173
|
|
|
202
174
|
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
|
|
206
|
-
|
|
175
|
+
* Number of spaces in one indentation level when assembling multi-line code as strings.
|
|
176
|
+
* Set to 2, 3, … to change the indent width used by `buildObject`/`buildList`.
|
|
177
|
+
*/
|
|
178
|
+
const INDENT_SIZE = 2
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* One indentation level, derived from {@link INDENT_SIZE}.
|
|
207
182
|
*/
|
|
208
|
-
export const
|
|
209
|
-
applicationJson: 'application/json',
|
|
210
|
-
applicationXml: 'application/xml',
|
|
211
|
-
applicationFormUrlEncoded: 'application/x-www-form-urlencoded',
|
|
212
|
-
applicationOctetStream: 'application/octet-stream',
|
|
213
|
-
applicationPdf: 'application/pdf',
|
|
214
|
-
applicationZip: 'application/zip',
|
|
215
|
-
applicationGraphql: 'application/graphql',
|
|
216
|
-
multipartFormData: 'multipart/form-data',
|
|
217
|
-
textPlain: 'text/plain',
|
|
218
|
-
textHtml: 'text/html',
|
|
219
|
-
textCsv: 'text/csv',
|
|
220
|
-
textXml: 'text/xml',
|
|
221
|
-
imagePng: 'image/png',
|
|
222
|
-
imageJpeg: 'image/jpeg',
|
|
223
|
-
imageGif: 'image/gif',
|
|
224
|
-
imageWebp: 'image/webp',
|
|
225
|
-
imageSvgXml: 'image/svg+xml',
|
|
226
|
-
audioMpeg: 'audio/mpeg',
|
|
227
|
-
videoMp4: 'video/mp4',
|
|
228
|
-
} as const satisfies Record<string, MediaType>
|
|
183
|
+
export const INDENT = Array.from({ length: INDENT_SIZE }, () => ' ').join('')
|
package/src/dedupe.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema-shape deduplication. `buildDedupePlan` finds top-level and inline schemas that share a
|
|
3
|
+
* structural signature, picks one canonical definition, and `applyDedupe` repoints every duplicate
|
|
4
|
+
* at it. This works on `SchemaNode` content, not on files.
|
|
5
|
+
*
|
|
6
|
+
* For merging a file's imports, exports, and source nodes, see `utils/fileMerge.ts`. Same idea of
|
|
7
|
+
* collapsing duplicates, but a different domain.
|
|
8
|
+
*/
|
|
9
|
+
import type { Node, OperationNode, SchemaNode } from './nodes/index.ts'
|
|
10
|
+
import { createSchema } from './nodes/schema.ts'
|
|
11
|
+
import { signatureOf } from './signature.ts'
|
|
12
|
+
import { extractRefName } from './utils/index.ts'
|
|
13
|
+
import { collectLazy, transform } from './visitor.ts'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A canonical destination for a deduplicated shape: the shared schema name and
|
|
17
|
+
* the synthetic `$ref` path that points at it.
|
|
18
|
+
*/
|
|
19
|
+
export type DedupeCanonical = {
|
|
20
|
+
/**
|
|
21
|
+
* Canonical schema name every duplicate occurrence refers to.
|
|
22
|
+
*/
|
|
23
|
+
name: string
|
|
24
|
+
/**
|
|
25
|
+
* `$ref` path stored on the generated `ref` nodes (for example `#/components/schemas/Status`).
|
|
26
|
+
*/
|
|
27
|
+
ref: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The result of {@link buildDedupePlan}: a lookup from structural signature to its
|
|
32
|
+
* canonical target, plus the freshly hoisted definitions that must be added to
|
|
33
|
+
* the schema list.
|
|
34
|
+
*/
|
|
35
|
+
export type DedupePlan = {
|
|
36
|
+
/**
|
|
37
|
+
* Maps a structural signature to the canonical schema that represents it.
|
|
38
|
+
*/
|
|
39
|
+
canonicalBySignature: Map<string, DedupeCanonical>
|
|
40
|
+
/**
|
|
41
|
+
* Maps the name of a top-level schema that duplicates a canonical one to that canonical, so
|
|
42
|
+
* references to the duplicate can be repointed at the first schema with the same content.
|
|
43
|
+
*/
|
|
44
|
+
aliasNames: Map<string, DedupeCanonical>
|
|
45
|
+
/**
|
|
46
|
+
* New top-level schema definitions created for inline shapes that had no existing
|
|
47
|
+
* named component. Nested duplicates inside each definition are already collapsed.
|
|
48
|
+
*/
|
|
49
|
+
hoisted: Array<SchemaNode>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The lookups {@link applyDedupe} needs from a {@link DedupePlan}.
|
|
54
|
+
*/
|
|
55
|
+
export type DedupeLookups = Pick<DedupePlan, 'canonicalBySignature' | 'aliasNames'>
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Options that inject the naming and candidate policy into {@link buildDedupePlan}.
|
|
59
|
+
* The mechanics (grouping, counting, rewriting) live here. The policy lives in the caller.
|
|
60
|
+
*/
|
|
61
|
+
export type BuildDedupePlanOptions = {
|
|
62
|
+
/**
|
|
63
|
+
* Returns `true` when a node should be deduplicated. This is the only gate, so it must
|
|
64
|
+
* reject both ineligible kinds (return `false` for anything other than, say, enums and
|
|
65
|
+
* objects) and unsafe shapes (e.g. nodes that reference a circular schema).
|
|
66
|
+
*/
|
|
67
|
+
isCandidate: (node: SchemaNode) => boolean
|
|
68
|
+
/**
|
|
69
|
+
* Produces the canonical name for an inline shape with no existing named component.
|
|
70
|
+
* Return `null` to leave the shape inline (for example when no contextual name exists).
|
|
71
|
+
*/
|
|
72
|
+
nameFor: (node: SchemaNode, signature: string) => string | null
|
|
73
|
+
/**
|
|
74
|
+
* Builds the `$ref` path for a canonical name.
|
|
75
|
+
*/
|
|
76
|
+
refFor: (name: string) => string
|
|
77
|
+
/**
|
|
78
|
+
* Minimum number of occurrences before a shape is deduplicated.
|
|
79
|
+
*
|
|
80
|
+
* @default 2
|
|
81
|
+
*/
|
|
82
|
+
minOccurrences?: number
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Builds the shared `ref` replacement for a duplicate occurrence, carrying the
|
|
87
|
+
* usage-slot and documentation fields that are not part of the canonical type.
|
|
88
|
+
*/
|
|
89
|
+
function createRefNode(node: SchemaNode, canonical: DedupeCanonical): SchemaNode {
|
|
90
|
+
return createSchema({
|
|
91
|
+
type: 'ref',
|
|
92
|
+
name: canonical.name,
|
|
93
|
+
ref: canonical.ref,
|
|
94
|
+
optional: node.optional,
|
|
95
|
+
nullish: node.nullish,
|
|
96
|
+
readOnly: node.readOnly,
|
|
97
|
+
writeOnly: node.writeOnly,
|
|
98
|
+
deprecated: node.deprecated,
|
|
99
|
+
description: node.description,
|
|
100
|
+
default: node.default,
|
|
101
|
+
example: node.example,
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Rewrites a node, replacing every candidate sub-schema whose signature has a canonical
|
|
107
|
+
* target with a `ref` to that target. Replacing a node with a `ref` prunes its subtree,
|
|
108
|
+
* so nested duplicates inside a replaced shape are not visited again. A `ref` that points
|
|
109
|
+
* at a duplicate top-level schema (see `aliasNames`) is repointed at the first schema with
|
|
110
|
+
* the same content.
|
|
111
|
+
*
|
|
112
|
+
* Pass `skipRootMatch` when rewriting a canonical definition so its own root is not
|
|
113
|
+
* turned into a reference to itself. Nested duplicates are still collapsed.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* const next = applyDedupe(operationNode, plan)
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
export function applyDedupe(node: SchemaNode, plan: DedupeLookups, skipRootMatch?: boolean): SchemaNode
|
|
121
|
+
export function applyDedupe(node: OperationNode, plan: DedupeLookups, skipRootMatch?: boolean): OperationNode
|
|
122
|
+
export function applyDedupe(node: Node, plan: DedupeLookups, skipRootMatch = false): Node {
|
|
123
|
+
const { canonicalBySignature, aliasNames } = plan
|
|
124
|
+
if (canonicalBySignature.size === 0 && aliasNames.size === 0) return node
|
|
125
|
+
|
|
126
|
+
const root = node
|
|
127
|
+
|
|
128
|
+
return transform(node, {
|
|
129
|
+
schema(schemaNode) {
|
|
130
|
+
if (schemaNode.type === 'ref') {
|
|
131
|
+
const target = schemaNode.ref ? extractRefName(schemaNode.ref) : schemaNode.name
|
|
132
|
+
const canonical = target ? aliasNames.get(target) : undefined
|
|
133
|
+
|
|
134
|
+
return canonical ? { ...schemaNode, name: canonical.name, ref: canonical.ref } : undefined
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const signature = signatureOf(schemaNode)
|
|
138
|
+
if (skipRootMatch && schemaNode === root) return undefined
|
|
139
|
+
|
|
140
|
+
const canonical = canonicalBySignature.get(signature)
|
|
141
|
+
if (!canonical) return undefined
|
|
142
|
+
|
|
143
|
+
return createRefNode(schemaNode, canonical)
|
|
144
|
+
},
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Strips usage-slot flags from a hoisted definition and applies its canonical name.
|
|
150
|
+
* A standalone definition is never optional, so `optional`/`nullish` are cleared.
|
|
151
|
+
*/
|
|
152
|
+
function cleanDefinition(node: SchemaNode, name: string): SchemaNode {
|
|
153
|
+
return { ...node, name, optional: undefined, nullish: undefined }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Scans a forest of schema and operation nodes and produces a {@link DedupePlan}.
|
|
158
|
+
*
|
|
159
|
+
* A shape that occurs at least `minOccurrences` times is deduplicated: if any occurrence
|
|
160
|
+
* is a named top-level schema, the first one becomes the canonical (so other top-level
|
|
161
|
+
* duplicates and inline copies turn into references to it). Every other top-level name with
|
|
162
|
+
* the same content is recorded in `aliasNames`, so refs to it can be repointed at the
|
|
163
|
+
* canonical. Otherwise a new definition is hoisted using `nameFor`. The plan is then applied
|
|
164
|
+
* per node with {@link applyDedupe}.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* const plan = buildDedupePlan([...schemaNodes, ...operationNodes], {
|
|
169
|
+
* isCandidate: (node) => node.type === 'enum' || node.type === 'object',
|
|
170
|
+
* nameFor: (node) => node.name ?? null,
|
|
171
|
+
* refFor: (name) => `#/components/schemas/${name}`,
|
|
172
|
+
* })
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
export function buildDedupePlan(roots: ReadonlyArray<Node>, options: BuildDedupePlanOptions): DedupePlan {
|
|
176
|
+
const { isCandidate, nameFor, refFor, minOccurrences = 2 } = options
|
|
177
|
+
|
|
178
|
+
const topLevelNodes = new Set<SchemaNode>()
|
|
179
|
+
|
|
180
|
+
type Group = {
|
|
181
|
+
count: number
|
|
182
|
+
representative: SchemaNode
|
|
183
|
+
topLevelNames: Array<string>
|
|
184
|
+
}
|
|
185
|
+
const groups = new Map<string, Group>()
|
|
186
|
+
|
|
187
|
+
function record(schemaNode: SchemaNode): void {
|
|
188
|
+
const signature = signatureOf(schemaNode)
|
|
189
|
+
if (!isCandidate(schemaNode)) return
|
|
190
|
+
|
|
191
|
+
const isTopLevel = topLevelNodes.has(schemaNode) && !!schemaNode.name
|
|
192
|
+
const group = groups.get(signature)
|
|
193
|
+
if (group) {
|
|
194
|
+
group.count++
|
|
195
|
+
if (isTopLevel) group.topLevelNames.push(schemaNode.name!)
|
|
196
|
+
} else {
|
|
197
|
+
groups.set(signature, { count: 1, representative: schemaNode, topLevelNames: isTopLevel ? [schemaNode.name!] : [] })
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
for (const root of roots) {
|
|
202
|
+
if (root.kind === 'Schema') topLevelNodes.add(root)
|
|
203
|
+
for (const schemaNode of collectLazy<SchemaNode>(root, { schema: (node) => node })) {
|
|
204
|
+
record(schemaNode)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const canonicalBySignature = new Map<string, DedupeCanonical>()
|
|
209
|
+
const aliasNames = new Map<string, DedupeCanonical>()
|
|
210
|
+
const pendingHoists: Array<{ name: string; representative: SchemaNode }> = []
|
|
211
|
+
|
|
212
|
+
for (const [signature, group] of groups) {
|
|
213
|
+
if (group.count < minOccurrences) continue
|
|
214
|
+
|
|
215
|
+
const [firstName, ...duplicateNames] = group.topLevelNames
|
|
216
|
+
if (firstName) {
|
|
217
|
+
const canonical: DedupeCanonical = { name: firstName, ref: refFor(firstName) }
|
|
218
|
+
canonicalBySignature.set(signature, canonical)
|
|
219
|
+
for (const duplicate of duplicateNames) {
|
|
220
|
+
aliasNames.set(duplicate, canonical)
|
|
221
|
+
}
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const name = nameFor(group.representative, signature)
|
|
226
|
+
if (!name) continue
|
|
227
|
+
|
|
228
|
+
canonicalBySignature.set(signature, { name, ref: refFor(name) })
|
|
229
|
+
pendingHoists.push({ name, representative: group.representative })
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Build hoisted definitions only after every canonical name is known, so nested
|
|
233
|
+
// duplicates inside a definition also resolve to refs.
|
|
234
|
+
const hoisted = pendingHoists.map(({ name, representative }) =>
|
|
235
|
+
cleanDefinition(applyDedupe(representative, { canonicalBySignature, aliasNames }, true), name),
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
return { canonicalBySignature, aliasNames, hoisted }
|
|
239
|
+
}
|
|
@@ -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
|
+
}
|