Skip to content
Kit

Plugins

Define a Kubb plugin with defineExtension and kind plugin: meta, dependencies, setup, and the setup context that registers generators.

A plugin generates code from the AST. Define one with defineExtension and kind: 'plugin'. Its setup registers generators, a resolver, and macros, then returns the options generators read as ctx.options. meta and the factory statics work as for every extension.

plugin-example.ts
import { defineExtension, type PluginType } from 'kubb/kit'

type PluginExample = PluginType<'plugin-example', { prefix?: string }, { prefix: string }>

export const pluginExample = defineExtension<PluginExample>({
  kind: 'plugin',
  meta: { name: 'plugin-example', version: '1.0.0' },
  dependencies: { 'plugin-ts': {} },
  setup(options, kubb) {
    // Register resolvers, generators, and macros on `kubb`.
    return { prefix: options.prefix ?? '' }
  },
})

PluginType<TName, TOptions, TResolvedOptions, TResolver, TPrinter> from kubb/kit types the plugin. TOptions is what users pass, and TResolvedOptions is what setup returns. TResolver types ctx.resolver and defaults to Resolver. TPrinter types ctx.printer. Core's PluginType from @kubb/core takes only the first three.

FieldTypeDescription
setup(options, kubb: KitSetupContext) => TResolvedOptionsRuns once per build, before kubb:plugin:setup. Can be async.
dependenciesExtensionDependenciesPlugins this one builds on.
enforce'pre' | 'post'Runs the plugin before or after the others. Dependencies still run first.
hooks{ [hook]: handler }Handlers for any lifecycle hook.

Setup context

setup and the kubb:plugin:setup hook register resolvers, generators, macros and printers with the composables from kubb/kit: setResolver, addGenerator, addMacro, setMacros, setPrinter and provide. Composables take no context argument, so helpers that setup calls can use them too.

import { addGenerator, createResolver, defineExtension, defineGenerator, requirePlugin, setResolver } from 'kubb/kit'

const resolver = createResolver({ pluginName: 'plugin-example' })
const generator = defineGenerator({ name: 'example', operation: () => [] })

export const pluginExample = defineExtension({
  kind: 'plugin',
  meta: { name: 'plugin-example' },
  setup(options) {
    requirePlugin('plugin-ts')
    setResolver(resolver)
    addGenerator(generator)
    return options
  },
})

The setup context has the same composables as methods, so you can also write kubb.setResolver(...). Both styles register the same, and kubb is typed as KitSetupContext:

export const pluginExample = defineExtension({
  kind: 'plugin',
  meta: { name: 'plugin-example' },
  setup(options, kubb) {
    kubb.setResolver(resolver)
    kubb.addGenerator(generator)
    return options
  },
})
The composables and the methods work only in a plugin defined with defineExtension from kubb/kit.

The setup context, the kubb argument of setup (ctx in the hook), holds these members:

MemberSignaturePurpose
setOptions(options: ResolvedOptions) => voidSets the resolved options. In setup, return them instead.
injectFile(file: UserFileNode) => voidAdds a file outside generation. Set copy to an absolute path to copy a template.
requirePlugin(name: string) => PluginReturns another plugin, or fails with KUBB_PLUGIN_NOT_FOUND.
memo(key: string, compute: () => T) => TComputes a value once per build, shared by every plugin. memo.get(key), memo.set(key, value) and memo.has(key) read and replace a value directly.
plugin{ name: string, meta: ExtensionMeta }The name and meta of the plugin being set up.
configConfigThe resolved build configuration. Composable: useConfig().
optionsTOptionsThe options the user passed. Composable: useOptions().
addGenerator, setResolver, addMacro, setMacros, setPrinter, provideSame as the composablesKit's setup composables, as methods.

Methods have a composable of the same name, such as requirePlugin(). useKubb() returns the whole context, and tryUseKubb() returns undefined outside setup instead of throwing.

The setup context is also this in setup and kubb:plugin:setup, so this, ctx and useKubb() are the same object. setOptions(), useOptions() and injectFile() run only in setup, and throw KUBB_NO_CONTEXT anywhere else.

To run your own code with a context, see withContext.

useKubb(), useConfig() and memo() work in setup, kubb:plugin:setup, the hooks in your hooks map with visit hooks, and generators. useKubb() returns the context of the hook that runs. setOptions(), useOptions() and injectFile() work only in setup and kubb:plugin:setup. Anywhere else, composables throw KUBB_NO_CONTEXT.

To cache outside a build, see Memo caches.

Printer

setPrinter(factory) registers the printer your generators use. Kit calls the factory with the printer context, as its argument, this and useKubb(), once per build, and once more for each override that matches a node. Generators get the result as ctx.printer, and pass per-node options with printer.with(...). Type a factory you export with PrinterFactory<PluginType>, so its ctx (a PrinterContext) is inferred.

import { addGenerator, createPrinter, defineExtension, defineGenerator, type PluginType, type Resolver, setPrinter } from 'kubb/kit'

const printerExample = createPrinter((options: { name?: string }) => ({ name: 'example', options, nodes: { string: () => 'string' } }))

type PluginExample = PluginType<'plugin-example', object, object, Resolver, ReturnType<typeof printerExample>>

const generator = defineGenerator<PluginExample>({
  name: 'example',
  schema(node, ctx) {
    ctx.info(`${node.name}: ${ctx.printer.with({ name: node.name }).print(node)}`)
    return null
  },
})

export const pluginExample = defineExtension<PluginExample>({
  kind: 'plugin',
  meta: { name: 'plugin-example' },
  setup(options) {
    setPrinter<PluginExample>(() => printerExample())
    addGenerator(generator)
    return options
  },
})

Shared option types

PluginOptions and ResolvedPluginOptions type the options every generator plugin shares: output, group, include, exclude, and override. Intersect them into your own types and add the plugin's keys. The type argument is the options object an override entry can set.

types.ts
import type { PluginOptions, PluginType, ResolvedPluginOptions } from 'kubb/kit'

export type Options = PluginOptions<ResolvedOptions> & {
  prefix?: string
}

export type ResolvedOptions = ResolvedPluginOptions<ResolvedOptions> & {
  prefix: string
}

export type PluginExample = PluginType<'plugin-example', Options, ResolvedOptions>
TypeKeys
PluginOptionsWhat users pass: optional output, group, exclude, include, and override.
ResolvedPluginOptionsWhat setup returns: output, exclude, include or undefined, override, group or null.

Plugin naming

SurfacePatternExample
npm package@<scope>/plugin-<name> or kubb-plugin-<name>@kubb/plugin-zod
meta.nameplugin-<name>'plugin-zod'
Factory exportplugin<Name>pluginZod
Name constantplugin<Name>NamepluginZodName
PluginType aliasPlugin<Name>PluginZod

Type the name constant with satisfies: export const pluginZodName = 'plugin-zod' satisfies PluginZod['name'].

Less common cases

Provide

provide(name, factory, { priority }) offers a resolver under a shared name, such as 'types'. A generator reads it with from(name), without naming the plugin behind it.

  • The provider with the highest priority wins. On a tie, the first one stays. priority defaults to 0.
  • Kit calls factory once, the first time a generator asks for the name, so factory can call getResolver.
  • A name that a plugin in the config already uses is refused, since it would replace that plugin's resolver.
  • getResolver(name) returns the provider's resolver as it is, for code that needs plain names without imports.
import { defineExtension, getResolver, provide, type PluginType } from 'kubb/kit'

type PluginTypes = PluginType<'plugin-types', object, object, ResolverTypes>

export const pluginTypes = defineExtension<PluginTypes>({
  kind: 'plugin',
  meta: { name: 'plugin-types' },
  setup(options) {
    provide('types', () => getResolver('plugin-types'))
    return options
  },
})

Add the plugin to Kubb.PluginRegistry and each provided name to Kubb.ProvideRegistry, so getResolver and from(name) are typed:

declare global {
  namespace Kubb {
    interface PluginRegistry {
      'plugin-types': PluginTypes
    }
    interface ProvideRegistry {
      types: ResolverTypes
    }
  }
}

Memo caches

When your plugin computes the same value many times, cache it with memo.

CallCache
this.memo(key, compute) in a resolverComputes each value once per build.
memo(store, key, compute)Caches in a store you own, outside a build: a Map, a WeakMap, or memo.create().
  • memo.create({ weak: true }) frees an entry with its key.
  • memo.create({ max }) empties the store when it is full.
  • To type a this.memo value, register the key's prefix: and its value type in Kubb.MemoRegistry.
patterns.ts
import { memo } from 'kubb/kit'

const patterns = memo.create<string, RegExp>({ max: 1000 })

export const toRegExp = (pattern: string) => memo(patterns, pattern, () => new RegExp(pattern))

Setup composables

When your plugin's setup awaits something before it calls a composable, the composable still reads the context of the plugin whose setup is running.

Context lists which composables work in which hook.