Skip to content
Kit

Resolvers

createResolver builds the Resolver that names a plugin's symbols, files, and imports. Covers built-in members, name reservations, and merging.

createResolver

A resolver names every symbol and file your plugin generates, and decides where imports point. Build one with createResolver, which requires pluginName. Other plugins read it through ctx.getResolver(name) in a template, or getResolver(name) from kubb/kit in any plugin hook. getResolver reads the memo of the running hook; pass the memo as a second argument to read it outside a hook. Without a stored resolver, getResolver stores and returns the default one for that plugin.

resolver.ts
import { createResolver } from 'kubb/kit'
import type { PluginType, Resolver } from 'kubb/kit'

// Extend the base Resolver with plugin-specific naming namespaces.
type MyResolver = Resolver & {
  schema: {
    name(node: { name: string }): string
  }
}

type MyPlugin = PluginType<'plugin-example', object, object, MyResolver>

export const resolver = createResolver<MyPlugin>({
  pluginName: 'plugin-example',
  name(name) {
    return `${name.charAt(0).toUpperCase()}${name.slice(1)}`
  },
  schema: {
    name(node) {
      return this.name(node.name)
    },
  },
})

Built-in members

Every resolver has these members. name and file follow your overrides, and default always holds Kubb's built-ins.

MemberDoes
name(name)The identifier casing. Falls back to default.name.
file(options)Builds a FileNode from file.baseName and file.path, or default.path.
imports(options)One import per $ref. See resolver.imports.
memo(key, compute)Caches a value for the rest of the build.
resolveName(), reserveNames()Allocate names that do not collide. See Name reservations.
groupDir(group, value)The folder a group puts a file in.
default.nameKubb's camelCase.
default.optionsApplies the exclude, include, and override filters.
default.pathResolves to output.path. With mode: 'directory' it adds the base name, inside a tag or path folder when group is set.
default.fileBuilds a FileNode. The built-in base name camelCases each dotted segment, so pet.petId becomes pet/petId.
default.bannerReturns output.banner, or the "Generated by Kubb" header. null when output.defaultBanner is false.
default.footerReturns output.footer, or null.

resolver.imports

resolver.imports returns one import per $ref in a schema tree. It names each import from the ref's targetName, or else the last segment of its pointer. Names and paths go through name and file, and extname defaults to .ts.

imports.ts
const imports = resolver.imports({ node, root, output })
// → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
OptionEffect
nameTurns a referenced schema name into the imported identifier, for example (schemaName) => \${resolver.name(schemaName)}Type``.
checkstrue also imports refs inside conditionals, contains, and a string's content. See Ref imports in checks.

Name reservations

resolver.resolveName({ key, name }) keeps the preferred name when it is free and adds 2, 3, and so on when it is taken. Use the same key for a declaration and its references.

Kubb reserves component names itself, and resolver.name only applies casing. Reserve other identifiers, such as enum type aliases, with resolver.reserveNames first.

reserve-names.ts
resolver.reserveNames(['CreateContainerBody', 'CreateContainerBody2'])
const name = resolver.resolveName({
  key: ['operation', 'POST', '/containers', 'body'],
  name: 'CreateContainerBody',
})
// 'CreateContainerBody3'

Resolver.merge

Resolver.merge(base, ...patches) layers the patches over base in order and returns a new resolver. A top-level name replaces. file and each namespace merge per member, so overriding query.name keeps the base query.keyName.

merge.ts
const patched = Resolver.merge(resolver, {
  name(name) {
    return `Custom${this.default.name(name)}`
  },
})
Type a patch with ResolverPatch<T> to check this and the namespace shapes against the target resolver.

Reusable resolver parts

A resolver part is a partial resolver, such as one namespace or a file rule, that any plugin can merge in. Define one with defineResolver. It types this as the full resolver plus the part and adds no runtime behavior, like defineMacro. Name exports resolver<Name>.

resolverHook.ts
import { defineResolver } from 'kubb/kit'

export const resolverHook = defineResolver({
  hook: {
    optionsName(): string {
      return this.resolveName({ key: ['hook', 'options'], name: 'HookOptions' })
    },
  },
})

Spread parts into createResolver, or pass a list to setResolver. The list merges left to right, so a later part wins per method:

plugin.ts
setResolver([resolverReactQuery, resolverHook])

kubb/kit ships the parts the official plugins share:

PartAdds
resolverOperationParamsparam.name, param.path, param.query, param.headers, param.cookies
resolverOperationResponseresponse.status, response.headers, response.body, response.responses, response.response
resolverCasedFile(caseLast)file.baseName that nests dotted names and cases the file name with caseLast
resolverTs.ts
import { casing, createResolver, resolverCasedFile, resolverOperationParams, resolverOperationResponse } from 'kubb/kit'

export const resolverTs = createResolver<PluginTs>({
  pluginName: 'plugin-ts',
  name: (name) => casing.pascal(name),
  ...resolverOperationParams,
  ...resolverOperationResponse,
  ...resolverCasedFile(casing.pascal),
})

Every name a part builds goes through the plugin's top-level name, so the part follows that plugin's casing. Build your own keys with operationKey(node, ...scope) so two declarations of one operation never share a name.

Resolver overrides

name changes identifier casing, file.name, file.baseName and file.path control files, and plugin namespaces control specific symbols. Users pass the same shape to a plugin's resolver option.

Type definition
type ResolverPatch = {
  name?: (name: string) => string
  file?: {
    name?: (node: SchemaNode | OperationNode, exportName?: string) => string | undefined
    baseName?: (params: { name: string; extname: string }) => string
    path?: (params: { baseName: string; output: Output }) => string
  }
  imports?: Resolver['imports']
  // plugin-specific namespaces, such as query.keyName or schema.typeName
}
  • Write methods as regular functions, not arrow functions, so this is the merged resolver.
  • file.name names a node's file before casing. Return undefined to keep the default: the operationId or the schema name.
  • exportName is the name another plugin imports with from. A plugin that writes several files per node uses it to say which file holds that name.
  • file() and from() both read file.name, so the files a plugin writes match the imports other plugins point at.
  • Kit adds Operation to an operation file that would land on a schema file, but only for a plugin with a Schema template.
  • Kubb resolves the path file.path returns against the root output.path, and the result must stay inside it. The output argument is the plugin's own output.
  • file.baseName and file.path must return the same result for the same arguments, because resolver.imports keeps each import path for the rest of the build.
  • this.default.name(name) always applies camelCase. For other casing, call casing from kubb/kit.
  • From a namespaced method, this.name(name) calls the active top-level name, including a user override. Inside the top-level name it recurses, so wrap an exported preset, such as resolverTs.name, instead.
  • this.memo(key, compute) computes each value once per build. See Memo caches.

Less common cases

Ref imports in checks

When your plugin prints checks such as conditionals, contains, or a string's content, pass checks: true to resolver.imports. It then also imports the refs inside them.

Checks that cannot fail stay out: a contains with min: 0 and no max, and content that is not JSON or is encoded.