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> types the plugin. TOptions is what users pass, and TResolvedOptions is what setup returns.

FieldTypeDescription
setup(options, kubb: KubbPluginSetupContext) => 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 everything through the setup context: the kubb argument (ctx in the hook) or a composable from kubb/kit. Composables take no argument, so helpers that setup calls can use them too.

import { createResolver, defineExtension, defineGenerator } 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, kubb) {
    kubb.requirePlugin('plugin-ts')
    kubb.setResolver(resolver)
    kubb.addGenerator(generator)
    return options
  },
})
MemberSignaturePurpose
addGenerator(...generators: Array<Generator>) => voidRegisters generators.
setResolver(resolver: ResolverPatch<Resolver> | Resolver) => voidSets the resolver. A patch merges over the defaults.
addMacro(macro: Macro) => voidAdds a macro that rewrites nodes before generators run.
setMacros(macros: ReadonlyArray<Macro>) => voidReplaces this plugin's macros.
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.
configConfigThe resolved build configuration. Composable: useConfig().
optionsTOptionsThe options the user passed. Composable: useOptions().

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

Composables work only in setup and kubb:plugin:setup. In generators and anywhere else, they throw KUBB_NO_CONTEXT.

To cache outside a build, see Memo caches.

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

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.

Outside setup and kubb:plugin:setup, including in generators, composables throw KUBB_NO_CONTEXT.