@kubb/core 5.0.0-beta.7 → 5.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts CHANGED
@@ -1,1305 +1,41 @@
1
- import type { AsyncEventEmitter, PossiblePromise } from '@internals/utils'
2
- import type { FileNode, HttpMethod, ImportNode, InputNode, Node, SchemaNode, UserFileNode, Visitor } from '@kubb/ast'
3
- import type { DEFAULT_STUDIO_URL, logLevel } from './constants.ts'
4
- import type { RendererFactory } from './createRenderer.ts'
5
- import type { Storage } from './createStorage.ts'
6
- import type { Generator } from './defineGenerator.ts'
7
- import type { Middleware } from './defineMiddleware.ts'
8
- import type { Parser } from './defineParser.ts'
9
- import type { Plugin } from './definePlugin.ts'
10
- import type { KubbHooks } from './Kubb.ts'
11
- import type { PluginDriver } from './PluginDriver.ts'
12
-
1
+ export type { DevtoolsOptions } from './devtools.ts'
2
+ export type { Adapter, AdapterFactoryOptions, AdapterSource } from './createAdapter.ts'
3
+ export type {
4
+ BuildOutput,
5
+ CLIOptions,
6
+ Config,
7
+ InputData,
8
+ InputPath,
9
+ Kubb,
10
+ KubbBuildEndContext,
11
+ KubbBuildStartContext,
12
+ KubbConfigEndContext,
13
+ KubbDebugContext,
14
+ KubbErrorContext,
15
+ KubbFileProcessingUpdateContext,
16
+ KubbFilesProcessingEndContext,
17
+ KubbFilesProcessingStartContext,
18
+ KubbGenerationEndContext,
19
+ KubbGenerationStartContext,
20
+ KubbGenerationSummaryContext,
21
+ KubbHookEndContext,
22
+ KubbHookStartContext,
23
+ KubbHooks,
24
+ KubbInfoContext,
25
+ KubbLifecycleStartContext,
26
+ KubbPluginsEndContext,
27
+ KubbSuccessContext,
28
+ KubbVersionNewContext,
29
+ KubbWarnContext,
30
+ PossibleConfig,
31
+ UserConfig,
32
+ } from './createKubb.ts'
13
33
  export type { Renderer, RendererFactory } from './createRenderer.ts'
14
-
15
- /**
16
- * Safely extracts a type from a registry, returning `{}` if the key doesn't exist.
17
- * Enables optional interface augmentation for `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`
18
- * without requiring changes to core.
19
- *
20
- * @internal
21
- */
22
- type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}
23
-
24
- /**
25
- * Reference to an input file to generate code from.
26
- *
27
- * Specify an absolute path or a path relative to the config file location.
28
- * The adapter will parse this file (e.g., OpenAPI YAML or JSON) into the universal AST.
29
- */
30
- export type InputPath = {
31
- /**
32
- * Path to your Swagger/OpenAPI file, absolute or relative to the config file location.
33
- *
34
- * @example
35
- * ```ts
36
- * { path: './petstore.yaml' }
37
- * { path: '/absolute/path/to/openapi.json' }
38
- * ```
39
- */
40
- path: string
41
- }
42
-
43
- /**
44
- * Inline input data to generate code from.
45
- *
46
- * Useful when you want to pass the specification directly instead of from a file.
47
- * Can be a string (YAML/JSON) or a parsed object.
48
- */
49
- export type InputData = {
50
- /**
51
- * Swagger/OpenAPI data as a string (YAML/JSON) or a parsed object.
52
- *
53
- * @example
54
- * ```ts
55
- * { data: fs.readFileSync('./openapi.yaml', 'utf8') }
56
- * { data: { openapi: '3.1.0', info: { ... } } }
57
- * ```
58
- */
59
- data: string | unknown
60
- }
61
-
62
- type Input = InputPath | InputData
63
-
64
- /**
65
- * Source data passed to an adapter's `parse` function.
66
- * Mirrors the config input shape with paths resolved to absolute.
67
- */
68
- export type AdapterSource = { type: 'path'; path: string } | { type: 'data'; data: string | unknown } | { type: 'paths'; paths: Array<string> }
69
-
70
- /**
71
- * Generic type parameters for an adapter definition.
72
- *
73
- * - `TName` — unique identifier (e.g. `'oas'`, `'asyncapi'`)
74
- * - `TOptions` — user-facing options passed to the adapter factory
75
- * - `TResolvedOptions` — options after defaults applied
76
- * - `TDocument` — type of the parsed source document
77
- */
78
- export type AdapterFactoryOptions<
79
- TName extends string = string,
80
- TOptions extends object = object,
81
- TResolvedOptions extends object = TOptions,
82
- TDocument = unknown,
83
- > = {
84
- name: TName
85
- options: TOptions
86
- resolvedOptions: TResolvedOptions
87
- document: TDocument
88
- }
89
-
90
- /**
91
- * Adapter that converts input files or data into an `InputNode`.
92
- *
93
- * Adapters parse different schema formats (OpenAPI, AsyncAPI, Drizzle, etc.) into Kubb's
94
- * universal intermediate representation that all plugins consume.
95
- *
96
- * @example
97
- * ```ts
98
- * import { adapterOas } from '@kubb/adapter-oas'
99
- *
100
- * export default defineConfig({
101
- * adapter: adapterOas(),
102
- * input: { path: './openapi.yaml' },
103
- * plugins: [pluginTs(), pluginZod()],
104
- * })
105
- * ```
106
- */
107
- export type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
108
- /**
109
- * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
110
- */
111
- name: TOptions['name']
112
- /**
113
- * Resolved adapter options after defaults have been applied.
114
- */
115
- options: TOptions['resolvedOptions']
116
- /**
117
- * Parsed source document after the first `parse()` call. `null` before parsing.
118
- */
119
- document: TOptions['document'] | null
120
- inputNode: InputNode | null
121
- /**
122
- * Parse the source into a universal `InputNode`.
123
- */
124
- parse: (source: AdapterSource) => PossiblePromise<InputNode>
125
- /**
126
- * Extract `ImportNode` entries for a schema tree.
127
- * Returns an empty array before the first `parse()` call.
128
- *
129
- * The `resolve` callback receives the collision-corrected schema name and must
130
- * return `{ name, path }` for the import, or `undefined` to skip it.
131
- */
132
- getImports: (node: SchemaNode, resolve: (schemaName: string) => { name: string; path: string }) => Array<ImportNode>
133
- /**
134
- * Validate the document at the given path or URL.
135
- */
136
- validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>
137
- }
138
-
139
- export type DevtoolsOptions = {
140
- /**
141
- * Open the AST inspector in Kubb Studio (`/ast`). Defaults to the main Studio page.
142
- * @default false
143
- */
144
- ast?: boolean
145
- }
146
-
147
- /**
148
- * Build configuration for Kubb code generation.
149
- *
150
- * The Config is the main entry point for customizing how Kubb generates code. It specifies:
151
- * - What to generate from (adapter + input)
152
- * - Where to output generated code (output)
153
- * - How to generate (plugins + middleware)
154
- * - Runtime details (parsers, storage, renderer)
155
- *
156
- * See `UserConfig` for a relaxed version with sensible defaults.
157
- *
158
- * @private
159
- */
160
- export type Config<TInput = Input> = {
161
- /**
162
- * Display name for this configuration in CLI output and logs.
163
- * Useful when running multiple builds with `defineConfig` arrays.
164
- *
165
- * @example
166
- * ```ts
167
- * name: 'api-client'
168
- * ```
169
- */
170
- name?: string
171
- /**
172
- * Project root directory, absolute or relative to the config file.
173
- * @default process.cwd()
174
- */
175
- root: string
176
- /**
177
- * Parsers that convert generated files to strings.
178
- * Each parser handles specific extensions (e.g. `.ts`, `.tsx`).
179
- * A fallback parser is appended for unhandled extensions.
180
- * When omitted, defaults to `parserTs` from `@kubb/parser-ts`.
181
- *
182
- * @default [parserTs] from `@kubb/parser-ts`
183
- * @example
184
- * ```ts
185
- * import { parserTs, tsxParser } from '@kubb/parser-ts'
186
- * export default defineConfig({
187
- * parsers: [parserTs, tsxParser],
188
- * })
189
- * ```
190
- */
191
- parsers: Array<Parser>
192
- /**
193
- * Adapter that parses input files into the universal `InputNode` representation.
194
- * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
195
- *
196
- * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
197
- * injected via `injectFile` are written, but no AST walk occurs and generator hooks
198
- * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
199
- *
200
- * @example
201
- * ```ts
202
- * import { adapterOas } from '@kubb/adapter-oas'
203
- * export default defineConfig({
204
- * adapter: adapterOas(),
205
- * input: { path: './petstore.yaml' },
206
- * })
207
- * ```
208
- */
209
- adapter?: Adapter
210
- /**
211
- * Source file or data to generate code from.
212
- * Use `input.path` for a file path or `input.data` for inline data.
213
- * Required when an adapter is configured; omit when running in plugin-only mode.
214
- */
215
- input?: TInput
216
- output: {
217
- /**
218
- * Output directory for generated files, absolute or relative to `root`.
219
- *
220
- * All generated files will be written under this directory. Subdirectories can be created
221
- * by plugins based on grouping strategy (by tag, path, etc.).
222
- *
223
- * @example
224
- * ```ts
225
- * output: {
226
- * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
227
- * }
228
- * ```
229
- */
230
- path: string
231
- /**
232
- * Remove all files from the output directory before starting the build.
233
- *
234
- * Useful to ensure old generated files aren't mixed with new ones.
235
- * Set to `true` for fresh builds, `false` to preserve manual edits in output dir.
236
- *
237
- * @default false
238
- * @example
239
- * ```ts
240
- * clean: true // wipes ./src/gen/* before generating
241
- * ```
242
- */
243
- clean?: boolean
244
- /**
245
- * Persists generated files to the file system.
246
- *
247
- * @default true
248
- * @deprecated Use `storage` option to control where files are written instead.
249
- */
250
- write?: boolean
251
- /**
252
- * Auto-format generated files after code generation completes.
253
- *
254
- * Applies a code formatter to all generated files. Use `'auto'` to detect which formatter
255
- * is available on your system. Pass `false` to skip formatting (useful for CI or specific workflows).
256
- *
257
- * @default false
258
- * @example
259
- * ```ts
260
- * format: 'auto' // auto-detect prettier, biome, or oxfmt
261
- * format: 'prettier' // force prettier
262
- * format: false // skip formatting
263
- * ```
264
- */
265
- format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false
266
- /**
267
- * Auto-lint generated files after code generation completes.
268
- *
269
- * Analyzes all generated files for style/correctness issues. Use `'auto'` to detect which linter
270
- * is available on your system. Pass `false` to skip linting.
271
- *
272
- * @default false
273
- * @example
274
- * ```ts
275
- * lint: 'auto' // auto-detect oxlint, biome, or eslint
276
- * lint: 'eslint' // force eslint
277
- * lint: false // skip linting
278
- * ```
279
- */
280
- lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false
281
- /**
282
- * Map file extensions to different output extensions.
283
- *
284
- * Useful when you want generated `.ts` imports to reference `.js` files or vice versa (e.g., for ESM dual packages).
285
- * Keys are the original extension, values are the output extension. Use empty string `''` to omit extension.
286
- *
287
- * @default { '.ts': '.ts' }
288
- * @example
289
- * ```ts
290
- * extension: { '.ts': '.js' } // generates import './api.js' instead of './api.ts'
291
- * extension: { '.ts': '', '.tsx': '.jsx' }
292
- * ```
293
- */
294
- extension?: Record<FileNode['extname'], FileNode['extname'] | ''>
295
- /**
296
- * Banner text prepended to every generated file.
297
- *
298
- * Useful for auto-generation notices or license headers. Choose a preset or write custom text.
299
- * Use `'simple'` for a basic Kubb banner, `'full'` for detailed metadata, or `false` to omit.
300
- *
301
- * @default 'simple'
302
- * @example
303
- * ```ts
304
- * defaultBanner: 'simple' // "This file was autogenerated by Kubb"
305
- * defaultBanner: 'full' // adds source, title, description, API version
306
- * defaultBanner: false // no banner
307
- * ```
308
- */
309
- defaultBanner?: 'simple' | 'full' | false
310
- /**
311
- * When `true`, overwrites existing files. When `false`, skips generated files that already exist.
312
- *
313
- * Individual plugins can override this setting. This is useful for preventing accidental data loss
314
- * when re-generating while you have local edits in the output folder.
315
- *
316
- * @default false
317
- * @example
318
- * ```ts
319
- * override: true // regenerate everything, even existing files
320
- * override: false // skip files that already exist
321
- * ```
322
- */
323
- override?: boolean
324
- } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>
325
- /**
326
- * Storage backend that controls where and how generated files are persisted.
327
- *
328
- * Defaults to `fsStorage()` which writes to the file system. Pass `memoryStorage()` to keep files in RAM,
329
- * or implement a custom `Storage` interface to write to cloud storage, databases, or other backends.
330
- *
331
- * @default fsStorage()
332
- * @example
333
- * ```ts
334
- * import { memoryStorage } from '@kubb/core'
335
- *
336
- * // Keep generated files in memory (useful for testing, CI pipelines)
337
- * storage: memoryStorage()
338
- *
339
- * // Use custom S3 storage
340
- * storage: myS3Storage()
341
- * ```
342
- *
343
- * @see {@link Storage} interface for implementing custom backends.
344
- */
345
- storage?: Storage
346
- /**
347
- * Plugins that execute during the build to generate code and transform the AST.
348
- *
349
- * Each plugin processes the AST produced by the adapter and can emit files for different
350
- * programming languages or formats (TypeScript, Zod schemas, Faker data, etc.).
351
- * Dependencies are enforced — an error is thrown if a plugin requires another plugin that isn't registered.
352
- *
353
- * Plugins can declare their own options via `PluginFactoryOptions`. See plugin documentation for details.
354
- *
355
- * @example
356
- * ```ts
357
- * import { pluginTs } from '@kubb/plugin-ts'
358
- * import { pluginZod } from '@kubb/plugin-zod'
359
- *
360
- * plugins: [
361
- * pluginTs({ output: { path: './src/gen' } }),
362
- * pluginZod({ output: { path: './src/gen' } }),
363
- * ]
364
- * ```
365
- */
366
- plugins: Array<Plugin>
367
- /**
368
- * Middleware instances that observe build events and post-process generated code.
369
- *
370
- * Middleware fires AFTER all plugins for each event. Perfect for tasks like:
371
- * - Auditing what was generated
372
- * - Adding barrel/index files
373
- * - Validating output
374
- * - Running custom transformations
375
- *
376
- * @example
377
- * ```ts
378
- * import { middlewareBarrel } from '@kubb/middleware-barrel'
379
- *
380
- * middleware: [middlewareBarrel()]
381
- * ```
382
- *
383
- * @see {@link defineMiddleware} to create custom middleware.
384
- */
385
- middleware?: Array<Middleware>
386
- /**
387
- * Default renderer factory used by all plugins and generators.
388
- * Resolution chain: `generator.renderer` → `plugin.renderer` → `config.renderer` → `undefined` (raw FileNode[] mode).
389
- *
390
- * @example
391
- * ```ts
392
- * import { jsxRenderer } from '@kubb/renderer-jsx'
393
- * export default defineConfig({
394
- * renderer: jsxRenderer,
395
- * plugins: [pluginTs(), pluginZod()],
396
- * })
397
- * ```
398
- */
399
- /**
400
- * Renderer that converts generated AST nodes to code strings.
401
- *
402
- * By default, Kubb uses the JSX renderer (`rendererJsx`). Pass a custom renderer to support
403
- * different output formats (template engines, code generation DSLs, etc.).
404
- *
405
- * @default rendererJsx() // from @kubb/renderer-jsx
406
- * @example
407
- * ```ts
408
- * import { rendererJsx } from '@kubb/renderer-jsx'
409
- * renderer: rendererJsx()
410
- * ```
411
- *
412
- * @see {@link Renderer} to implement a custom renderer.
413
- */
414
- renderer?: RendererFactory
415
- /**
416
- * Kubb Studio cloud integration settings.
417
- *
418
- * Kubb Studio (https://kubb.studio) is a web-based IDE for managing API specs and generated code.
419
- * Set to `true` to enable with default settings, or pass an object to customize the Studio URL.
420
- *
421
- * @default false // disabled by default
422
- * @example
423
- * ```ts
424
- * devtools: true // use default Kubb Studio
425
- * devtools: { studioUrl: 'https://my-studio.dev' } // custom Studio instance
426
- * ```
427
- */
428
- devtools?:
429
- | true
430
- | {
431
- /**
432
- * Override the Kubb Studio base URL.
433
- * @default 'https://kubb.studio'
434
- */
435
- studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {})
436
- }
437
- /**
438
- * Lifecycle hooks that execute during or after the build process.
439
- *
440
- * Hooks allow you to run external tools (prettier, eslint, custom scripts) based on build events.
441
- * Currently supports the `done` hook which fires after all plugins and middleware complete.
442
- *
443
- * @example
444
- * ```ts
445
- * hooks: {
446
- * done: 'prettier --write "./src/gen"', // auto-format generated files
447
- * // or multiple commands:
448
- * done: ['prettier --write "./src/gen"', 'eslint --fix "./src/gen"']
449
- * }
450
- * ```
451
- */
452
- hooks?: {
453
- /**
454
- * Command(s) to run after all plugins and middleware complete generation.
455
- *
456
- * Useful for post-processing: formatting, linting, copying files, or custom validation.
457
- * Pass a single command string or array of command strings to run sequentially.
458
- * Commands are executed relative to the `root` directory.
459
- *
460
- * @example
461
- * ```ts
462
- * done: 'prettier --write "./src/gen"'
463
- * done: ['prettier --write "./src/gen"', 'eslint --fix "./src/gen"']
464
- * ```
465
- */
466
- done?: string | Array<string>
467
- }
468
- }
469
-
470
- // plugin
471
-
472
- /**
473
- * Type/string pattern filter for include/exclude/override matching.
474
- */
475
- type PatternFilter = {
476
- type: string
477
- pattern: string | RegExp
478
- }
479
-
480
- /**
481
- * Pattern filter with partial option overrides applied when the pattern matches.
482
- */
483
- type PatternOverride<TOptions> = PatternFilter & {
484
- options: Omit<Partial<TOptions>, 'override'>
485
- }
486
-
487
- /**
488
- * Context for resolving filtered options for a given operation or schema node.
489
- *
490
- * @internal
491
- */
492
- export type ResolveOptionsContext<TOptions> = {
493
- options: TOptions
494
- exclude?: Array<PatternFilter>
495
- include?: Array<PatternFilter>
496
- override?: Array<PatternOverride<TOptions>>
497
- }
498
-
499
- /**
500
- * Base constraint for all plugin resolver objects.
501
- *
502
- * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`
503
- * are injected automatically by `defineResolver` — extend this type to add custom resolution methods.
504
- *
505
- * @example
506
- * ```ts
507
- * type MyResolver = Resolver & {
508
- * resolveName(node: SchemaNode): string
509
- * resolveTypedName(node: SchemaNode): string
510
- * }
511
- * ```
512
- */
513
- export type Resolver = {
514
- name: string
515
- pluginName: Plugin['name']
516
- default(name: string, type?: 'file' | 'function' | 'type' | 'const'): string
517
- resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null
518
- resolvePath(params: ResolverPathParams, context: ResolverContext): string
519
- resolveFile(params: ResolverFileParams, context: ResolverContext): FileNode
520
- resolveBanner(node: InputNode | null, context: ResolveBannerContext): string | undefined
521
- resolveFooter(node: InputNode | null, context: ResolveBannerContext): string | undefined
522
- }
523
-
524
- export type PluginFactoryOptions<
525
- /**
526
- * Unique plugin name.
527
- */
528
- TName extends string = string,
529
- /**
530
- * User-facing plugin options.
531
- */
532
- TOptions extends object = object,
533
- /**
534
- * Plugin options after defaults are applied.
535
- */
536
- TResolvedOptions extends object = TOptions,
537
- /**
538
- * Resolver that encapsulates naming and path-resolution helpers.
539
- * Define with `defineResolver` and export alongside the plugin.
540
- */
541
- TResolver extends Resolver = Resolver,
542
- > = {
543
- name: TName
544
- options: TOptions
545
- resolvedOptions: TResolvedOptions
546
- resolver: TResolver
547
- }
548
-
549
- /**
550
- * Normalized plugin after setup, with runtime fields populated.
551
- * For internal use only — plugins use the public `Plugin` type externally.
552
- *
553
- * @internal
554
- */
555
- export type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
556
- options: TOptions['resolvedOptions'] & {
557
- output: Output
558
- include?: Array<Include>
559
- exclude: Array<Exclude>
560
- override: Array<Override<TOptions['resolvedOptions']>>
561
- }
562
- resolver: TOptions['resolver']
563
- transformer?: Visitor
564
- renderer?: RendererFactory
565
- generators?: Array<Generator>
566
- apply?: (config: Config) => boolean
567
- version?: string
568
- }
569
-
570
- /**
571
- * Partial `Config` for user-facing entry points with sensible defaults.
572
- *
573
- * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
574
- * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
575
- * `storage`, `middleware`, `renderer`, `devtools`, and `hooks`.
576
- *
577
- * @example
578
- * ```ts
579
- * export default defineConfig({
580
- * input: { path: './petstore.yaml' },
581
- * output: { path: './src/gen' },
582
- * plugins: [pluginTs(), pluginZod()],
583
- * })
584
- * ```
585
- */
586
- export type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter'> & {
587
- /**
588
- * Project root directory, absolute or relative to the config file location.
589
- *
590
- * Used as the base path for `root`-relative paths (e.g., `output.path`, file paths in hooks).
591
- *
592
- * @default process.cwd()
593
- * @example
594
- * ```ts
595
- * root: '/home/user/my-project'
596
- * root: './my-project' // relative to config file
597
- * ```
598
- */
599
- root?: string
600
- /**
601
- * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
602
- *
603
- * Each parser handles a specific file type. By default, Kubb uses `parserTs` from `@kubb/parser-ts` for TypeScript files.
604
- * Pass custom parsers to support additional languages or custom formats.
605
- *
606
- * @default [parserTs] // from `@kubb/parser-ts`
607
- * @example
608
- * ```ts
609
- * import { parserTs } from '@kubb/parser-ts'
610
- * import { parserJsonSchema } from '@kubb/parser-json-schema'
611
- *
612
- * parsers: [parserTs(), parserJsonSchema()]
613
- * ```
614
- *
615
- * @see {@link Parser} to implement a custom parser.
616
- */
617
- parsers?: Array<Parser>
618
- /**
619
- * Adapter that parses your API specification (OpenAPI, GraphQL, AsyncAPI, etc.) into Kubb's universal AST.
620
- *
621
- * Pass an adapter to support different spec formats. When omitted, Kubb runs in plugin-only mode —
622
- * `kubb:plugin:setup` fires and `injectFile` works, but no AST walk occurs and generator hooks
623
- * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
624
- *
625
- * @example
626
- * ```ts
627
- * import { adapterOas } from '@kubb/adapter-oas'
628
- *
629
- * adapter: adapterOas()
630
- * ```
631
- *
632
- * @see {@link Adapter} to implement a custom adapter for GraphQL or other formats.
633
- */
634
- adapter?: Adapter
635
- /**
636
- * Plugins that execute during the build to generate code and transform the AST.
637
- *
638
- * Each plugin processes the AST produced by the adapter and can emit files for different
639
- * programming languages or formats (TypeScript, Zod schemas, Faker data, etc.).
640
- *
641
- * @default [] // no plugins (useful for setup/testing)
642
- * @example
643
- * ```ts
644
- * plugins: [
645
- * pluginTs({ output: { path: './src/gen' } }),
646
- * pluginZod({ output: { path: './src/gen' } }),
647
- * ]
648
- * ```
649
- *
650
- * @see {@link definePlugin} to create a custom plugin.
651
- */
652
- plugins?: Array<Plugin>
653
- }
654
-
655
- export type ResolveNameParams = {
656
- name: string
657
- pluginName?: string
658
- /**
659
- * Entity type being named.
660
- * - `'file'` — file name (camelCase)
661
- * - `'function'` — exported function name (camelCase)
662
- * - `'type'` — TypeScript type name (PascalCase)
663
- * - `'const'` — variable name (camelCase)
664
- */
665
- type?: 'file' | 'function' | 'type' | 'const'
666
- }
667
- /**
668
- * Context object passed to generator `schema`, `operation`, and `operations` methods.
669
- *
670
- * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks
671
- * are needed. `ctx.options` carries resolved per-node options after exclude/include/override
672
- * filtering for individual schema/operation calls, or plugin-level options for operations.
673
- */
674
- export type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
675
- config: Config
676
- /**
677
- * Absolute path to the current plugin's output directory.
678
- */
679
- root: string
680
- /**
681
- * Determine output mode based on the output config.
682
- * Returns `'single'` when `output.path` is a file, `'split'` for a directory.
683
- */
684
- getMode: (output: { path: string }) => 'single' | 'split'
685
- driver: PluginDriver
686
- /**
687
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
688
- */
689
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
690
- getPlugin(name: string): Plugin | undefined
691
- /**
692
- * Get a plugin by name, throws an error if not found.
693
- */
694
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>
695
- requirePlugin(name: string): Plugin
696
- /**
697
- * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
698
- */
699
- getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']
700
- getResolver(name: string): Resolver
701
- /**
702
- * Add files only if they don't exist.
703
- */
704
- addFile: (...file: Array<FileNode>) => Promise<void>
705
- /**
706
- * Merge sources into the same output file.
707
- */
708
- upsertFile: (...file: Array<FileNode>) => Promise<void>
709
- hooks: AsyncEventEmitter<KubbHooks>
710
- /**
711
- * The current plugin instance.
712
- */
713
- plugin: Plugin<TOptions>
714
- /**
715
- * The current plugin's resolver.
716
- */
717
- resolver: TOptions['resolver']
718
- /**
719
- * The current plugin's transformer.
720
- */
721
- transformer: Visitor | undefined
722
- /**
723
- * Emit a warning.
724
- */
725
- warn: (message: string) => void
726
- /**
727
- * Emit an error.
728
- */
729
- error: (error: string | Error) => void
730
- /**
731
- * Emit an info message.
732
- */
733
- info: (message: string) => void
734
- /**
735
- * Open the current input node in Kubb Studio.
736
- */
737
- openInStudio: (options?: DevtoolsOptions) => Promise<void>
738
- /**
739
- * The configured adapter instance.
740
- */
741
- adapter: Adapter
742
- /**
743
- * The universal `InputNode` produced by the adapter.
744
- */
745
- inputNode: InputNode
746
- /**
747
- * Resolved options after exclude/include/override filtering.
748
- */
749
- options: TOptions['resolvedOptions']
750
- }
751
- /**
752
- * Output configuration for generated files.
753
- */
754
- export type Output<_TOptions = unknown> = {
755
- /**
756
- * Output folder or file path for generated code.
757
- */
758
- path: string
759
- /**
760
- * Text or function prepended to every generated file.
761
- * When a function, receives the current `InputNode` and returns a string.
762
- */
763
- banner?: string | ((node?: InputNode) => string)
764
- /**
765
- * Text or function appended to every generated file.
766
- * When a function, receives the current `InputNode` and returns a string.
767
- */
768
- footer?: string | ((node?: InputNode) => string)
769
- /**
770
- * Whether to override existing external files if they already exist.
771
- * @default false
772
- */
773
- override?: boolean
774
- } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>
775
-
776
- export type Group = {
777
- /**
778
- * How to group files into subdirectories.
779
- * - `'tag'` — group by OpenAPI tags
780
- * - `'path'` — group by OpenAPI paths
781
- */
782
- type: 'tag' | 'path'
783
- /**
784
- * Function that returns the subdirectory name for a group value.
785
- * Defaults to `${camelCase(group)}Controller` for tags, first path segment for paths.
786
- */
787
- name?: (context: { group: string }) => string
788
- }
789
-
790
- export type LoggerOptions = {
791
- /**
792
- * Log level for output verbosity.
793
- * @default 3
794
- */
795
- logLevel: (typeof logLevel)[keyof typeof logLevel]
796
- }
797
-
798
- /**
799
- * Shared context passed to plugins, parsers, and other internals.
800
- */
801
- export type LoggerContext = AsyncEventEmitter<KubbHooks>
802
-
803
- export type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {
804
- name: string
805
- install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>
806
- }
807
-
808
- export type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>
809
-
810
34
  export type { Storage } from './createStorage.ts'
811
- export type { Generator } from './defineGenerator.ts'
35
+ export type { Generator, GeneratorContext } from './defineGenerator.ts'
36
+ export type { Logger, LoggerContext, LoggerOptions, UserLogger } from './defineLogger.ts'
812
37
  export type { Middleware } from './defineMiddleware.ts'
813
- export type { Plugin } from './definePlugin.ts'
814
- export type { Kubb, KubbHooks } from './Kubb.ts'
815
-
816
- /**
817
- * Context for hook-style plugin `kubb:plugin:setup` handler.
818
- * Provides methods to register generators, configure resolvers, transformers, and renderers.
819
- */
820
- export type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
821
- /**
822
- * Register a generator dynamically. Generators fire during the AST walk (schema/operation/operations)
823
- * just like generators declared statically on `createPlugin`.
824
- */
825
- addGenerator<TElement = unknown>(generator: Generator<TFactory, TElement>): void
826
- /**
827
- * Set or override the resolver for this plugin.
828
- * The resolver controls file naming and path resolution.
829
- */
830
- setResolver(resolver: Partial<TFactory['resolver']>): void
831
- /**
832
- * Set the AST transformer to pre-process nodes before they reach generators.
833
- */
834
- setTransformer(visitor: Visitor): void
835
- /**
836
- * Set the renderer factory to process JSX elements from generators.
837
- */
838
- setRenderer(renderer: RendererFactory): void
839
- /**
840
- * Set resolved options merged into the normalized plugin's `options`.
841
- * Call this in `kubb:plugin:setup` to provide options generators need.
842
- */
843
- setOptions(options: TFactory['resolvedOptions']): void
844
- /**
845
- * Inject a raw file into the build output, bypassing the generation pipeline.
846
- */
847
- injectFile(userFileNode: UserFileNode): void
848
- /**
849
- * Merge a partial config update into the current build configuration.
850
- */
851
- updateConfig(config: Partial<Config>): void
852
- /**
853
- * The resolved build configuration at setup time.
854
- */
855
- config: Config
856
- /**
857
- * The plugin's user-provided options.
858
- */
859
- options: TFactory['options']
860
- }
861
-
862
- /**
863
- * Context for hook-style plugin `kubb:build:start` handler.
864
- * Fires immediately before the plugin execution loop begins.
865
- */
866
- export type KubbBuildStartContext = {
867
- config: Config
868
- adapter: Adapter
869
- inputNode: InputNode
870
- /**
871
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
872
- */
873
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined
874
- getPlugin(name: string): Plugin | undefined
875
- /**
876
- * Get all files currently in the file manager.
877
- * Call this lazily (e.g. in `kubb:plugin:end`) to see files added by prior plugins.
878
- */
879
- readonly files: ReadonlyArray<FileNode>
880
- /**
881
- * Upsert one or more files into the file manager.
882
- * Files with the same path are merged; new files are appended.
883
- * Safe to call at any point during the plugin lifecycle, including inside `kubb:plugin:end`.
884
- */
885
- upsertFile: (...files: Array<FileNode>) => void
886
- }
887
-
888
- /**
889
- * Context for `kubb:plugins:end` handlers.
890
- * Fires after plugins run and per-plugin barrels are written, before final write to disk.
891
- * Middleware that needs final files (e.g. root barrel) use this event.
892
- */
893
- export type KubbPluginsEndContext = {
894
- config: Config
895
- /**
896
- * All files currently in the file manager (lazy snapshot).
897
- */
898
- readonly files: ReadonlyArray<FileNode>
899
- /**
900
- * Upsert files into the file manager.
901
- * Files added here are included in the write pass.
902
- */
903
- upsertFile: (...files: Array<FileNode>) => void
904
- }
905
-
906
- /**
907
- * Context for hook-style plugin `kubb:build:end` handler.
908
- * Fires after all files have been written to disk.
909
- */
910
- export type KubbBuildEndContext = {
911
- files: Array<FileNode>
912
- config: Config
913
- outputDir: string
914
- }
915
-
916
- export type KubbLifecycleStartContext = {
917
- version: string
918
- }
919
-
920
- export type KubbConfigEndContext = {
921
- configs: Array<Config>
922
- }
923
-
924
- export type KubbGenerationStartContext = {
925
- config: Config
926
- }
927
-
928
- export type KubbGenerationEndContext = {
929
- config: Config
930
- files: Array<FileNode>
931
- sources: Map<string, string>
932
- }
933
-
934
- export type KubbGenerationSummaryContext = {
935
- config: Config
936
- failedPlugins: Set<{ plugin: Plugin; error: Error }>
937
- status: 'success' | 'failed'
938
- hrStart: [number, number]
939
- filesCreated: number
940
- pluginTimings?: Map<Plugin['name'], number>
941
- }
942
-
943
- export type KubbVersionNewContext = {
944
- currentVersion: string
945
- latestVersion: string
946
- }
947
-
948
- export type KubbInfoContext = {
949
- message: string
950
- info?: string
951
- }
952
-
953
- export type KubbErrorContext = {
954
- error: Error
955
- meta?: Record<string, unknown>
956
- }
957
-
958
- export type KubbSuccessContext = {
959
- message: string
960
- info?: string
961
- }
962
-
963
- export type KubbWarnContext = {
964
- message: string
965
- info?: string
966
- }
967
-
968
- export type KubbDebugContext = {
969
- date: Date
970
- logs: Array<string>
971
- fileName?: string
972
- }
973
-
974
- export type KubbFilesProcessingStartContext = {
975
- files: Array<FileNode>
976
- }
977
-
978
- export type KubbFileProcessingUpdateContext = {
979
- /**
980
- * Number of files processed.
981
- */
982
- processed: number
983
- /**
984
- * Total files to process.
985
- */
986
- total: number
987
- /**
988
- * Processing percentage (0–100).
989
- */
990
- percentage: number
991
- /**
992
- * Optional source identifier.
993
- */
994
- source?: string
995
- /**
996
- * The file being processed.
997
- */
998
- file: FileNode
999
- /**
1000
- * The current build configuration.
1001
- */
1002
- config: Config
1003
- }
1004
-
1005
- export type KubbFilesProcessingEndContext = {
1006
- files: Array<FileNode>
1007
- }
1008
-
1009
- export type KubbPluginStartContext = {
1010
- plugin: NormalizedPlugin
1011
- }
1012
-
1013
- export type KubbPluginEndContext = {
1014
- plugin: NormalizedPlugin
1015
- duration: number
1016
- success: boolean
1017
- error?: Error
1018
- config: Config
1019
- /**
1020
- * Returns all files currently in the file manager (lazy snapshot).
1021
- * Includes files added by plugins that have already run.
1022
- */
1023
- readonly files: ReadonlyArray<FileNode>
1024
- /**
1025
- * Upsert one or more files into the file manager.
1026
- */
1027
- upsertFile: (...files: Array<FileNode>) => void
1028
- }
1029
-
1030
- export type KubbHookStartContext = {
1031
- id?: string
1032
- command: string
1033
- args?: readonly string[]
1034
- }
1035
-
1036
- export type KubbHookEndContext = {
1037
- id?: string
1038
- command: string
1039
- args?: readonly string[]
1040
- success: boolean
1041
- error: Error | null
1042
- }
1043
-
1044
- type ByTag = {
1045
- /**
1046
- * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
1047
- */
1048
- type: 'tag'
1049
- /**
1050
- * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
1051
- */
1052
- pattern: string | RegExp
1053
- }
1054
-
1055
- type ByOperationId = {
1056
- /**
1057
- * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
1058
- */
1059
- type: 'operationId'
1060
- /**
1061
- * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
1062
- */
1063
- pattern: string | RegExp
1064
- }
1065
-
1066
- type ByPath = {
1067
- /**
1068
- * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
1069
- */
1070
- type: 'path'
1071
- /**
1072
- * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
1073
- */
1074
- pattern: string | RegExp
1075
- }
1076
-
1077
- type ByMethod = {
1078
- /**
1079
- * Filter by HTTP method: `'get'`, `'post'`, `'put'`, `'delete'`, `'patch'`, `'head'`, `'options'`.
1080
- */
1081
- type: 'method'
1082
- /**
1083
- * HTTP method to match (case-insensitive when using string, or regex for dynamic matching).
1084
- */
1085
- pattern: HttpMethod | RegExp
1086
- }
1087
- // TODO implement as alternative for ByMethod
1088
- // type ByMethods = {
1089
- // type: 'methods'
1090
- // pattern: Array<HttpMethod>
1091
- // }
1092
-
1093
- type BySchemaName = {
1094
- /**
1095
- * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
1096
- */
1097
- type: 'schemaName'
1098
- /**
1099
- * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
1100
- */
1101
- pattern: string | RegExp
1102
- }
1103
-
1104
- type ByContentType = {
1105
- /**
1106
- * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
1107
- */
1108
- type: 'contentType'
1109
- /**
1110
- * Content type to match (case-sensitive). Can be a literal string or regex pattern.
1111
- */
1112
- pattern: string | RegExp
1113
- }
1114
-
1115
- /**
1116
- * A pattern filter that prevents matching nodes from being generated.
1117
- *
1118
- * Use to skip code generation for specific operations or schemas. For example, exclude deprecated endpoints
1119
- * or internal-only schemas. Can filter by tag, operationId, path, HTTP method, content type, or schema name.
1120
- *
1121
- * @example
1122
- * ```ts
1123
- * exclude: [
1124
- * { type: 'tag', pattern: 'internal' }, // skip "internal" tag
1125
- * { type: 'path', pattern: /^\/admin/ }, // skip all /admin endpoints
1126
- * { type: 'operationId', pattern: 'deprecated_*' } // skip operationIds matching pattern
1127
- * ]
1128
- * ```
1129
- */
1130
- export type Exclude = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName
1131
-
1132
- /**
1133
- * A pattern filter that restricts generation to only matching nodes.
1134
- *
1135
- * Use to generate code for a subset of operations or schemas. For example, only generate for a specific service
1136
- * tag or only for "production" endpoints. Can filter by tag, operationId, path, HTTP method, content type, or schema name.
1137
- *
1138
- * @example
1139
- * ```ts
1140
- * include: [
1141
- * { type: 'tag', pattern: 'public' }, // generate only "public" tag
1142
- * { type: 'path', pattern: /^\/api\/v1/ }, // generate only v1 endpoints
1143
- * ]
1144
- * ```
1145
- */
1146
- export type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName
1147
-
1148
- /**
1149
- * A pattern filter paired with partial option overrides applied when the pattern matches.
1150
- *
1151
- * Use to customize generation for specific operations or schemas. For example, apply different output paths
1152
- * for different tags, or use custom resolver functions per operation. Can filter by tag, operationId, path,
1153
- * HTTP method, schema name, or content type.
1154
- *
1155
- * @example
1156
- * ```ts
1157
- * override: [
1158
- * {
1159
- * type: 'tag',
1160
- * pattern: 'admin',
1161
- * options: { output: { path: './src/gen/admin' } } // admin APIs go to separate folder
1162
- * },
1163
- * {
1164
- * type: 'operationId',
1165
- * pattern: 'listPets',
1166
- * options: { exclude: true } // skip this specific operation
1167
- * }
1168
- * ]
1169
- * ```
1170
- */
1171
- export type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
1172
- //TODO should be options: Omit<Partial<TOptions>, 'override'>
1173
- options: Partial<TOptions>
1174
- }
1175
-
1176
- /**
1177
- * File-specific parameters for `Resolver.resolvePath`.
1178
- *
1179
- * Pass alongside a `ResolverContext` to identify which file to resolve.
1180
- * Provide `tag` for tag-based grouping or `path` for path-based grouping.
1181
- *
1182
- * @example
1183
- * ```ts
1184
- * resolver.resolvePath(
1185
- * { baseName: 'petTypes.ts', tag: 'pets' },
1186
- * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
1187
- * )
1188
- * // → '/src/types/petsController/petTypes.ts'
1189
- * ```
1190
- */
1191
- export type ResolverPathParams = {
1192
- baseName: FileNode['baseName']
1193
- pathMode?: 'single' | 'split'
1194
- /**
1195
- * Tag value used when `group.type === 'tag'`.
1196
- */
1197
- tag?: string
1198
- /**
1199
- * Path value used when `group.type === 'path'`.
1200
- */
1201
- path?: string
1202
- }
1203
-
1204
- /**
1205
- * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.
1206
- *
1207
- * Describes where on disk output is rooted, which output config is active, and the optional
1208
- * grouping strategy that controls subdirectory layout.
1209
- *
1210
- * @example
1211
- * ```ts
1212
- * const context: ResolverContext = {
1213
- * root: config.root,
1214
- * output,
1215
- * group,
1216
- * }
1217
- * ```
1218
- */
1219
- export type ResolverContext = {
1220
- root: string
1221
- output: Output
1222
- group?: Group
1223
- /**
1224
- * Plugin name used to populate `meta.pluginName` on the resolved file.
1225
- */
1226
- pluginName?: string
1227
- }
1228
-
1229
- /**
1230
- * File-specific parameters for `Resolver.resolveFile`.
1231
- *
1232
- * Pass alongside a `ResolverContext` to fully describe the file to resolve.
1233
- * `tag` and `path` are used only when a matching `group` is present in the context.
1234
- *
1235
- * @example
1236
- * ```ts
1237
- * resolver.resolveFile(
1238
- * { name: 'listPets', extname: '.ts', tag: 'pets' },
1239
- * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
1240
- * )
1241
- * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
1242
- * ```
1243
- */
1244
- export type ResolverFileParams = {
1245
- name: string
1246
- extname: FileNode['extname']
1247
- /**
1248
- * Tag value used when `group.type === 'tag'`.
1249
- */
1250
- tag?: string
1251
- /**
1252
- * Path value used when `group.type === 'path'`.
1253
- */
1254
- path?: string
1255
- }
1256
-
1257
- /**
1258
- * Context passed to `Resolver.resolveBanner` and `Resolver.resolveFooter`.
1259
- *
1260
- * `output` is optional — not every plugin configures a banner/footer.
1261
- * `config` carries the global Kubb config, used to derive the default Kubb banner.
1262
- *
1263
- * @example
1264
- * ```ts
1265
- * resolver.resolveBanner(inputNode, { output: { banner: '// generated' }, config })
1266
- * // → '// generated'
1267
- * ```
1268
- */
1269
- export type ResolveBannerContext = {
1270
- output?: Pick<Output, 'banner' | 'footer'>
1271
- config: Config
1272
- }
1273
-
1274
- /**
1275
- * CLI options derived from command-line flags.
1276
- */
1277
- export type CLIOptions = {
1278
- /**
1279
- * Path to `kubb.config.js`.
1280
- */
1281
- config?: string
1282
- /**
1283
- * Enable watch mode for input files.
1284
- */
1285
- watch?: boolean
1286
- /**
1287
- * Logging verbosity for CLI usage.
1288
- * @default 'silent'
1289
- */
1290
- logLevel?: 'silent' | 'info' | 'debug'
1291
- }
1292
-
1293
- /**
1294
- * All accepted forms of a Kubb configuration.
1295
- *
1296
- * Config is always `@kubb/core` {@link Config}.
1297
- * - `PossibleConfig` accepts `Config`/`Config[]`/promise or a no-arg config factory.
1298
- * - `PossibleConfig<TCliOptions>` accepts the same config forms or a config factory receiving `TCliOptions`.
1299
- */
1300
- export type PossibleConfig<TCliOptions = undefined> =
1301
- | PossiblePromise<Config | Config[]>
1302
- | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>)
1303
-
1304
- export type { BuildOutput } from './createKubb.ts'
1305
38
  export type { Parser } from './defineParser.ts'
39
+ export type { Exclude, Group, Include, Output, Override } from './definePlugin.ts'
40
+ export type { KubbPluginEndContext, KubbPluginSetupContext, KubbPluginStartContext, NormalizedPlugin, Plugin, PluginFactoryOptions } from './definePlugin.ts'
41
+ export type { ResolveBannerContext, ResolveOptionsContext, Resolver, ResolverContext, ResolverFileParams, ResolverPathParams } from './defineResolver.ts'