Skip to content
Kit

AST and node builders

The ast namespace from kubb/kit. Covers the node tree, schema types, and every helper group, each with what it returns and a sample call.

ast

ast from kubb/kit gives you the whole AST API in one namespace, like ts.factory for TypeScript. ast.factory builds nodes, and ast.node walks them. Each other group reads one subject, such as refs.

ast-namespace.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({
  schemas: [ast.factory.createSchema({ name: 'Pet', type: 'object', properties: [] })],
  operations: [],
})
Old top-level names, such as ast.narrowSchema or ast.transform, are deprecated aliases until Kubb v6. Their JSDoc names the replacement.

Node tree

An adapter returns one InputNode. Every node has a kind, such as 'Schema'. A schema also has a type. A ref schema points at a schema in schemas instead of copying it.

InputNodeschemas: SchemaNode[]operations:OperationNode[]meta: InputMetaparameters:ParameterNode[]requestBody:RequestBodyNoderesponses:ResponseNode[]content: ContentNode[]properties: PropertyNode[]schema: SchemaNode

A generator returns FileNodes, a second tree:

FileNodesources: SourceNode[]imports: ImportNode[]exports: ExportNode[]nodes: Text, Const, Type,Function, ArrowFunction,Jsx, Break

Schema node types

You narrow a SchemaNode by its type. ast.schema.types lists every value.

FamilyTypesNotes
Structuralobject, array, tuple, union, intersection, enum, not
Scalarstring, number, integer, bigint, boolean, null, any, unknown, void, neverinteger prints as number.
Specialref, date, datetime, time, uuid, email, url, ipv4, ipv6, blobblob is binary data

ast.factory

ast.factory builds typed nodes with the defaults filled in. Use it instead of object literals.

TreeFactories
InputcreateInput, createSchema, createOperation, createParameter, createProperty, createResponse, createRequestBody, createContent
FilecreateFile, createSource, createImport, createExport
Code nodescreateText, createConst, createType, createFunction, createArrowFunction, createJsx, createBreak
factory.ts
import { ast } from 'kubb/kit'

ast.factory.createSchema({ type: 'string', format: 'email' })
// { kind: 'Schema', type: 'string', primitive: 'string', format: 'email' }

ast.factory.createText('export const a = 1')
// { kind: 'Text', value: 'export const a = 1' }

ast.node

ast.node walks a tree with a visitor, which has a callback per kind: input, operation, schema, property, parameter, and response. In a plugin, use a macro instead of transform.

HelperReturns
ast.node.transformA new tree with the visitor's replacements
ast.node.collectThe visitor's non-null results, depth-first
ast.node.kindsEvery node kind, such as 'Schema'
ast.node.getTextCode node text, joined by newlines

Pass depth: 'shallow' to transform or collect to skip nested schemas.

node.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({ schemas: [], operations: [] })

const strict = ast.node.transform(root, {
  schema(node) {
    return node.type === 'object' && node.additionalProperties === undefined ? { ...node, additionalProperties: false } : node
  },
})

const mutations = ast.node.collect<ast.OperationNode>(root, {
  operation(node) {
    return node.method === 'POST' ? node : undefined
  },
})
// Array<OperationNode>

ast.node.kinds.schema // 'Schema'
ast.node.getText([ast.factory.createText('const a = 1'), ast.factory.createText('const b = 2')]) // 'const a = 1\nconst b = 2'

ast.file

HelperReturns
ast.file.inline{ files, virtualPaths, problems }, with virtual-file imports inlined
file.ts
import { ast } from 'kubb/kit'

// Array<FileNode>, Array<string>, Array<{ path: string, message: string }>
const {
  files: inlined,
  virtualPaths,
  problems,
} = ast.file.inline(files, {
  language: (file) => parsers.get(file.extname)?.inline,
})

ast.macro

A macro is a named transform that rewrites nodes before printing. Define one with defineMacro, as Macros shows.

HelperReturns
ast.macro.applyThe tree after running the macros
ast.macro.compareOrderSorts enforce values: 'pre' first, 'post' last
macro.ts
import { ast, defineMacro } from 'kubb/kit'

const macroUntagged = defineMacro({
  name: 'untagged',
  operation: (node) => (node.tags?.length ? undefined : { ...node, tags: ['untagged'] }),
})

ast.macro.apply(operation, [macroUntagged]).tags // ['untagged']
ast.macro.compareOrder('pre', 'post') // -2
ast.macro.compareOrder(undefined, 'post') // -1

kubb/kit also exports built-in macros. Call macroDiscriminatorEnum and macroEnumName with options to get the macro.

MacroPurpose
macroDedupeUnionDrops repeated union members, ignoring the source pointer
macroDiscriminatorEnumTurns a discriminator property into an enum of its values
macroEnumNameNames an inline enum from its parent and property

macroSimplifyUnion, the pre-5.16 name of macroDedupeUnion, is deprecated.

Macro options and callbacks

A macro has the callbacks of an ast.node visitor, a name, and optional enforce and match. Each callback gets the visitor context, with the node's parent, as this and as its second argument. It returns a replacement node, or undefined or null to keep the original.

Type definition
type Macro = {
  name: string
  enforce?: 'pre' | 'post'
  match?: (node: Node) => boolean
  schema?(node: SchemaNode, context): SchemaNode | null | undefined
  operation?(node: OperationNode, context): OperationNode | null | undefined
  // input, property, parameter, response
}

ast.json

Use ast.json to cache a parsed spec or to send one to another thread or process. A plain JSON.stringify(root) writes the whole target schema again at every ref. ast.json.stringify writes each target once.

HelperReturns
ast.json.stringifyJSON text for an InputNode, with every ref target written once
ast.json.parseThe InputNode from that text. Refs to one schema share one object again.
json.ts
import { ast } from 'kubb/kit'

const text = ast.json.stringify(root)

ast.json.parse(text) // InputNode, equal to root

A FileNode holds no refs, so plain JSON.stringify(file) and JSON.parse are enough for files.

ast.ref

HelperReturns
ast.ref.getNameThe target name, targetName first. Pass the node, not node.ref.
ast.ref.getSchemaThe schema a ref points at, or the node itself
ast.ref.isAliasWhether a ref adds nothing and prints as its target name
ast.ref.mergeSchemaThe ref merged with its schema, ref fields such as description winning

kubb/kit also exports the name builders childName and enumPropName.

ref.ts
import { ast } from 'kubb/kit'

ast.ref.getName('#/components/schemas/Pet') // 'Pet'
ast.ref.getSchema(petRef).type // 'object'
ast.ref.isAlias(petRef) // true
ast.ref.mergeSchema(petRef).description // 'The owner pet', from the ref

ast.graph

Use ast.graph to drop unused schemas or to wrap circular ones in a lazy getter.

HelperReturns
ast.graph.getRefNamesEvery schema name a node refers to, at any depth
ast.graph.getImportedNamesThe ref names a printed schema imports. { checks: true } adds refs in checks.
ast.graph.getUsedNamesThe schema names operations reach, also through other schemas
ast.graph.getCircularNamesThe schemas in a circular chain
graph.ts
import { ast } from 'kubb/kit'

ast.graph.getRefNames(ownerSchema) // Set { 'Pet' }
ast.graph.getImportedNames(petListSchema) // ['Pet']
ast.graph.getUsedNames(root.operations, root.schemas) // Set { 'Pet' }
ast.graph.getCircularNames([nodeSchema, tagSchema]) // Set { 'Node' }

ast.schema

HelperReturns
ast.schema.typesEvery schema type, such as 'string'
ast.schema.narrowThe schema typed as a given type, or null
ast.schema.findThe first matching schema. follow: ['ref'] also searches resolved refs.
ast.schema.applyOptionalityMarks the schema optional if not required, nullish if also nullable
ast.schema.findPropertiesThe named properties on an object, resolved ref, or intersection, not a union
ast.schema.getLiteralsThe literals an enum, resolved ref, or literal union allows
ast.schema.inferDiscriminatorThe property each member pins to its own literal
ast.schema.getEmbeddedJsonThe schema of JSON inside a string (contentMediaType with contentSchema)
ast.schema.isWhether a schema is binary, string, text, scalar, const, enumLike, or untyped
schema.ts
import { ast } from 'kubb/kit'

const root = ast.factory.createInput({ schemas: [], operations: [] })

const dateSchema = ast.schema.find(root, {
  follow: ['ref'],
  predicate: (schema) => schema.type === 'date',
})
schema-values.ts
ast.schema.types.string // 'string'
ast.schema.narrow(node, 'object')?.properties.length // number | undefined
ast.schema.applyOptionality(nullableName, false).nullish // true
ast.schema.findProperties({ node: petSchema, propertyName: 'id' }).map((property) => property.schema.type) // ['integer']
ast.schema.getLiterals(petKind) // ['cat', 'dog']
ast.schema.inferDiscriminator([catSchema, dogSchema]) // 'kind'
ast.schema.getEmbeddedJson(jsonStringSchema)?.name // 'Pet'
ast.schema.is(ast.factory.createSchema({ type: 'uuid' }), 'string') // true
ast.schema.is(uploadSchema, 'binary', { follow: ['ref', 'array'] }) // true for Blob or Blob[] behind refs

ast.schema.isString is deprecated. Use ast.schema.is(node, 'string'). followRefs: true on find is deprecated. Use follow: ['ref']. Both are removed in Kubb v6.

To reuse find results, see Schema search cache.

ast.mediaType

Each helper takes a media type string or a content entry.

HelperReturns
ast.mediaType.getBaseThe lowercase media type without parameters
ast.mediaType.isJsonWhether it is application/json, text/json, or +json
media-type.ts
ast.mediaType.getBase('Application/JSON; charset=utf-8') // 'application/json'
ast.mediaType.isJson('application/problem+json') // true

ast.http

HelperReturns
ast.http.isOperationWhether an operation is HTTP, narrowing it to have method and path
http.ts
import { ast } from 'kubb/kit'

if (ast.http.isOperation(node)) {
  node.method // 'GET'
}

Printers

kubb/kit exportReturns
createPrinterA factory from printer options to a Printer
defineMacroThe same macro object, typed as a Macro

A printer's overrides map replaces the handlers of single schema types. The printer.nodes option of @kubb/plugin-ts, @kubb/plugin-zod, and @kubb/plugin-faker fills it, as Printers shows.

Pass overrides through overrides. If you spread them into nodes, this.base cannot find the original handler.

Printer handlers and context

Key the map by schema type, such as 'string'. A type without a handler keeps the built-in one.

Type definition
type PrinterNodes = Partial<{
  [K in SchemaType]: (this: Context, node: SchemaNodeByType[K], ctx?: Context) => Output | null
}>

A handler gets the context as this and as its second argument, so an arrow function can read it as ctx, such as array: (node, ctx) => ctx!.transform(node.items[0]). The second argument is typed as optional, and its options as object, so handler types written for this alone keep compiling. Read typed options from this.options. The root print override gets the root context the same way.

this memberDoes
this.transform(node, options?)Prints a nested schema with every handler, overrides included
this.base(node, options?)Runs the replaced built-in handler, to wrap its output
this.optionsThe resolved printer options, such as arrayType on @kubb/plugin-ts
this.parentThe schema node whose handler called this.transform, undefined at the root
this.import(node)Declares an import, as an ast.factory.createImport() node

The options you pass to this.transform or this.base are merged over this.options for that child and what it prints, and leave the caller's options unchanged:

string(node) {
  const contentNode = ast.schema.getEmbeddedJson(node)
  return contentNode ? this.transform(contentNode, { direction: 'decode' }) : 'z.string()'
}
The built-in generators collect those imports. In your own generator, call printer.drainImports() after printing.

Architecture explains why the AST exists.

Less common cases

Schema search cache

When you call ast.schema.find across many schemas, reuse its answers with a cache. Keep one cache per predicate and follow value, so later calls skip what earlier ones searched.

find-cache.ts
import { ast } from 'kubb/kit'

const dateCache = new WeakMap<ast.SchemaNode, ast.SchemaNode | null>()
const hasDate = (schema: ast.SchemaNode) =>
  ast.schema.find(schema, { follow: ['ref'], cache: dateCache, predicate: (node) => node.type === 'date' }) !== undefined

AST helper details

Helper names are a verb plus what they return (getName) or a question (isJson).

HelperDetail
createPrinterImport a custom codec shows an overrides map in practice.
ast.schema.isfollow adds links on top of the node itself: 'ref' jumps to a resolved ref's target, and 'array' matches when some item matches. Following repeats and stops on a ref cycle.
ast.graph.getImportedNamesPass { checks: true } to include refs inside conditionals, contains, and content.
ast.macroA macro is a named transform that rewrites nodes before printing, with ordering through enforce and gating through match.