Kubb Documentation

repository·main·Indexed 23 days ago

https://github.com/kubb-labs/kubb

Kubb is a code generation tool that produces TypeScript types, API clients, hooks, and validators from OpenAPI specifications. It features a CLI for project scaffolding, generation, and validation, as well as an MCP server for AI-assisted workflows. The ecosystem includes @kubb/adapter-oas for parsing Swagger 2.0 and OpenAPI 3.0/3.1, a spec-agnostic Abstract Syntax Tree (AST) layer via @kubb/ast, and a plugin authoring toolkit provided through kubb/kit.

Tokens
38.1K
Snippets
129
Records
201
Agent score
78%

What's inside Kubb

  1. Overview of @kubb/kit tools and helpers

    main

    The @kubb/kit package provides the following core abstractions for plugin development:

    Definition Wrappers

    • definePlugin: Wraps a plugin into the expected build engine shape.
    • defineGenerator: Wraps a generator.
    • defineResolver: Wraps a resolver.
    • defineParser: Wraps a parser.

    Factories

    • createAdapter: Factory for custom spec adapters.
    • createRenderer: Factory for output renderers.
    • createStorage: Factory for custom storage backends.

    AST and Macros

    • ast & factory: Node builders used by generators to construct files, schemas, and operation nodes.
    • ast.applyMacros / setMacros: Used with built-in macro presets like macroDiscriminatorEnum, macroEnumName, macroRenameSchema, and macroSimplifyUnion. Use ast.defineMacro to build custom macros.

    Schema and Graph Helpers

    • Schema helpers: childName, enumPropName, extractRefName, isStringType, mergeAdjacentObjectsLazy, syncSchemaRef, and containsCircularRef.
    • Graph helpers (on ast): resolveRefName, findCircularSchemas, and collectUsedSchemaNames.
  2. Overview of Kubb Claude Code plugin features

    main

    The Kubb Claude Code plugin extends Claude's capabilities for code generation using the Kubb meta-framework. It includes several specialized intelligence layers:

    • config skill: Teaches Claude how to write kubb.config.ts and select appropriate @kubb/plugin-* packages.
    • output skill: Teaches Claude how to import and utilize the generated artifacts (types, clients, hooks, schemas, and mocks).
    • kubb-expert agent: An agent capable of handling end-to-end tasks, such as "add Kubb to my project," from the initial specification to the final generated code.
    • Kubb MCP server integration: Wires in the Kubb MCP server (kubb mcp) to allow for conversational code generation via chat rather than just CLI commands.
  3. What is @kubb/core?

    main

    The @kubb/core package is the core engine for Kubb's plugin-based code generation system. It provides the fundamental building blocks used by every Kubb plugin, including:

    • The plugin driver
    • The file manager
    • defineConfig for configuration
    • definePlugin for plugin definition
    • defineMiddleware for middleware definition
    • The build orchestration layer
  4. Understand the @kubb/ast architecture

    main

    The @kubb/ast package provides a spec-agnostic Abstract Syntax Tree (AST) layer used by all Kubb code generation plugins. It defines the node tree, visitor patterns, factory functions, and type guards.

    Important Integration Note: While the examples below use direct imports from @kubb/ast, most Kubb plugins and generators should access the AST via the ast namespace provided by kubb/kit. This allows plugins to interact with the AST without a direct dependency on the @kubb/ast package. For example, ast.factory.createSchema is the standard way to access constructors when using kubb/kit.

  5. How @kubb/plugin-barrel works

    main

    The plugin operates as a post-generation step. After every other plugin finishes generating files, @kubb/plugin-barrel walks the output tree and:

    1. Creates an index.ts in each directory, re-exporting everything inside.
    2. Creates a root index.ts at the top of the output path that re-exports from all plugin directories.

    It uses enforce: 'post' to ensure it always runs after all regular plugins have completed, allowing it to access the full set of generated files.

  6. Understand @kubb/plugin-barrel export types

    main

    The type option determines how the generated index.ts files re-export content:

    • 'all': Uses wildcard re-exports (export * from './...').
    • 'named': Uses named re-exports (export { ... } from './...'). This is the default and is tree-shaking friendly.
    • 'propagate': Uses wildcard re-exports (export * from './...') on index files only, propagating up through directories.
  7. Select and combine Kubb generator plugins

    main

    Kubb uses a plugin-based architecture. Plugins have specific dependencies that must be met for them to work correctly:

    • pluginTs is the required base for almost everything.
    • Client plugins (pluginAxios, pluginFetch) require pluginTs.
    • Framework plugins (pluginReactQuery, pluginVueQuery, pluginSwr) require both pluginTs and a client plugin.
    • pluginMsw requires both pluginTs and pluginFaker.

    Plugin Reference Table

    NeedPackageImport
    TypeScript types (recommended base)@kubb/plugin-tspluginTs
    Axios client@kubb/plugin-axiospluginAxios
    Fetch client@kubb/plugin-fetchpluginFetch
    TanStack React Query hooks@kubb/plugin-react-querypluginReactQuery
    Vue Query hooks@kubb/plugin-vue-querypluginVueQuery
    SWR hooks@kubb/plugin-swrpluginSwr
    Zod schemas@kubb/plugin-zodpluginZod
    Faker.js mock factories@kubb/plugin-fakerpluginFaker
    MSW request handlers@kubb/plugin-mswpluginMsw
    Cypress fixtures@kubb/plugin-cypresspluginCypress
    MCP server from the spec@kubb/plugin-mcppluginMcp
    ReDoc documentation@kubb/plugin-redocpluginRedoc

    Common Plugin Combinations

    • Types only: pluginTs()
    • Typed data fetching: Add pluginAxios() or pluginFetch(), or a framework plugin (pluginReactQuery, pluginVueQuery, or pluginSwr).
    • Runtime validation: Add pluginZod() and point the client at it.
    • Testing and mocks: Add pluginFaker() and pluginMsw().
  8. Discovering generated exports and plugin options

    main

    Because export names (derived from operationId and schema names) and casing/grouping are configurable, you should not assume exact names. Use these methods to find the correct identifiers:

    1. Inspect the filesystem: List the contents of your output.path to see the actual file and export names.
    2. Check Plugin Options: To understand how a plugin behaves or what its defaults are, inspect the plugin's Options type. You can find this in:
      • node_modules/@kubb/plugin-<name>/src/types.ts
      • The published type declarations in your IDE.
    3. Consult Documentation: Visit https://kubb.dev/plugins/plugin-<name> for the official documentation and dependency requirements for a specific plugin.
  9. Integrate unplugin-kubb with build tools

    main

    The unplugin-kubb package provides specific entry points for different build tools and frameworks. Import the corresponding entry point to add Kubb to your configuration.

    // Vite
    import kubb from 'unplugin-kubb/vite'
    export default defineConfig({
      plugins: [kubb({/* options */})],
    })
    
    // Rollup
    import kubb from 'unplugin-kubb/rollup'
    export default {
      plugins: [kubb({/* options */})],
    }
    
    // Webpack
    module.exports = {
      /* ... */
      plugins: [require('unplugin-kubb/webpack')({/* options */})],
    }
    
    // Nuxt
    export default defineNuxtConfig({
      modules: [['unplugin-kubb/nuxt', {/* options */}]],
    })
    
    // esbuild
    import { build } from 'esbuild'
    import kubb from 'unplugin-kubb/esbuild'
    build({
      plugins: [kubb()],
    })
  10. How to use and maintain Kubb generated code

    main

    Kubb generates code (types, clients, hooks, schemas, mocks) based on an OpenAPI/Swagger specification. This code is intended to be consumed by your application or test code, but should never be edited manually.

    Key Rules for Using Generated Code

    • Do not edit files in the output directory: Generated files contain a Do not edit manually banner. If you need to change the code, modify the source specification or the kubb.config.ts and run kubb generate again.
    • Import, don't copy: Always import the generated entities to ensure that subsequent regenerations keep your application in sync with the spec.
    • Configure the runtime client once: The generated client functions and framework hooks share a single runtime client configuration.
    • Typecheck after regeneration: Always run your typechecker after running kubb generate to catch any breaking changes introduced by specification updates.

    Locating Generated Files

    1. Check kubb.config.ts for the top-level output.path (e.g., ./src/gen).
    2. Check individual plugin configurations for their specific output.path sub-folders (e.g., models, clients, hooks).
    3. Importing: If the output.barrel option is enabled, you can import from the folder's index.ts. Otherwise, import the specific file directly.
  11. Scaffold a new project with `kubb init`

    main

    Use kubb init to set up a new project. This command scaffolds a kubb.config.ts file and installs necessary plugins for code generation from an OpenAPI specification.

    Interactive Mode

    Run the command without flags to start an interactive wizard that prompts for your OpenAPI spec path, output directory, and desired plugins.

    npx kubb init

    Non-Interactive Mode

    Pass flags to skip prompts for automated setups.

    • --yes, -y: Skip all prompts and use defaults.
    • --input <path>, -i: Path to the OpenAPI specification (default: ./openapi.yaml).
    • --output <path>, -o: Output directory for generated files (default: ./src/gen).
    • --plugins <list>: Comma-separated list of plugins to install.

    Available plugins for --plugins: plugin-ts, plugin-axios, plugin-fetch, plugin-react-query, plugin-vue-query, plugin-zod, plugin-faker, plugin-msw, plugin-cypress, plugin-mcp, plugin-redoc.

    Examples

    # Accept all defaults
    npx kubb init --yes
    
    # Fully non-interactive setup
    npx kubb init --input ./openapi.yaml --output ./src/gen --plugins plugin-ts,plugin-zod
    
    # Select specific plugins only
    npx kubb init --plugins plugin-ts,plugin-axios,plugin-react-query
    npx kubb init