@kubb/core 5.0.0-alpha.4 → 5.0.0-alpha.41

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.
Files changed (71) hide show
  1. package/dist/PluginDriver-BQwm8hDd.cjs +1729 -0
  2. package/dist/PluginDriver-BQwm8hDd.cjs.map +1 -0
  3. package/dist/PluginDriver-CgXFtmNP.js +1617 -0
  4. package/dist/PluginDriver-CgXFtmNP.js.map +1 -0
  5. package/dist/index.cjs +915 -1901
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +268 -264
  8. package/dist/index.js +894 -1863
  9. package/dist/index.js.map +1 -1
  10. package/dist/mocks.cjs +164 -0
  11. package/dist/mocks.cjs.map +1 -0
  12. package/dist/mocks.d.ts +74 -0
  13. package/dist/mocks.js +159 -0
  14. package/dist/mocks.js.map +1 -0
  15. package/dist/types-C6NCtNqM.d.ts +2151 -0
  16. package/package.json +11 -14
  17. package/src/FileManager.ts +131 -0
  18. package/src/FileProcessor.ts +84 -0
  19. package/src/Kubb.ts +174 -85
  20. package/src/PluginDriver.ts +941 -0
  21. package/src/constants.ts +33 -43
  22. package/src/createAdapter.ts +25 -0
  23. package/src/createKubb.ts +605 -0
  24. package/src/createPlugin.ts +31 -0
  25. package/src/createRenderer.ts +57 -0
  26. package/src/createStorage.ts +58 -0
  27. package/src/defineGenerator.ts +88 -100
  28. package/src/defineLogger.ts +13 -3
  29. package/src/defineParser.ts +45 -0
  30. package/src/definePlugin.ts +90 -7
  31. package/src/defineResolver.ts +453 -0
  32. package/src/devtools.ts +14 -14
  33. package/src/index.ts +12 -17
  34. package/src/mocks.ts +234 -0
  35. package/src/renderNode.ts +35 -0
  36. package/src/storages/fsStorage.ts +29 -9
  37. package/src/storages/memoryStorage.ts +2 -2
  38. package/src/types.ts +821 -152
  39. package/src/utils/TreeNode.ts +47 -9
  40. package/src/utils/diagnostics.ts +4 -1
  41. package/src/utils/executeStrategies.ts +16 -13
  42. package/src/utils/getBarrelFiles.ts +88 -15
  43. package/src/utils/isInputPath.ts +10 -0
  44. package/src/utils/packageJSON.ts +75 -0
  45. package/dist/chunk-ByKO4r7w.cjs +0 -38
  46. package/dist/hooks.cjs +0 -50
  47. package/dist/hooks.cjs.map +0 -1
  48. package/dist/hooks.d.ts +0 -49
  49. package/dist/hooks.js +0 -46
  50. package/dist/hooks.js.map +0 -1
  51. package/dist/types-Bbh1o0yW.d.ts +0 -1057
  52. package/src/BarrelManager.ts +0 -74
  53. package/src/PackageManager.ts +0 -180
  54. package/src/PluginManager.ts +0 -668
  55. package/src/PromiseManager.ts +0 -40
  56. package/src/build.ts +0 -420
  57. package/src/config.ts +0 -56
  58. package/src/defineAdapter.ts +0 -22
  59. package/src/defineStorage.ts +0 -56
  60. package/src/errors.ts +0 -1
  61. package/src/hooks/index.ts +0 -8
  62. package/src/hooks/useKubb.ts +0 -22
  63. package/src/hooks/useMode.ts +0 -11
  64. package/src/hooks/usePlugin.ts +0 -11
  65. package/src/hooks/usePluginManager.ts +0 -11
  66. package/src/utils/FunctionParams.ts +0 -155
  67. package/src/utils/formatters.ts +0 -56
  68. package/src/utils/getConfigs.ts +0 -30
  69. package/src/utils/getPlugins.ts +0 -23
  70. package/src/utils/linters.ts +0 -25
  71. package/src/utils/resolveOptions.ts +0 -93
@@ -0,0 +1,2151 @@
1
+ import { t as __name } from "./chunk--u3MIqq1.js";
2
+ import { FileNode, HttpMethod, ImportNode, InputNode, Node, OperationNode, SchemaNode, Visitor } from "@kubb/ast";
3
+
4
+ //#region ../../internals/utils/src/asyncEventEmitter.d.ts
5
+ /**
6
+ * A function that can be registered as an event listener, synchronous or async.
7
+ */
8
+ type AsyncListener<TArgs extends unknown[]> = (...args: TArgs) => void | Promise<void>;
9
+ /**
10
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
11
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
16
+ * emitter.on('build', async (name) => { console.log(name) })
17
+ * await emitter.emit('build', 'petstore') // all listeners awaited
18
+ * ```
19
+ */
20
+ declare class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[] }> {
21
+ #private;
22
+ /**
23
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
24
+ * @default 10
25
+ */
26
+ constructor(maxListener?: number);
27
+ /**
28
+ * Emits `eventName` and awaits all registered listeners sequentially.
29
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * await emitter.emit('build', 'petstore')
34
+ * ```
35
+ */
36
+ emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void>;
37
+ /**
38
+ * Registers a persistent listener for `eventName`.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * emitter.on('build', async (name) => { console.log(name) })
43
+ * ```
44
+ */
45
+ on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
46
+ /**
47
+ * Registers a one-shot listener that removes itself after the first invocation.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * emitter.onOnce('build', async (name) => { console.log(name) })
52
+ * ```
53
+ */
54
+ onOnce<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
55
+ /**
56
+ * Removes a previously registered listener.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * emitter.off('build', handler)
61
+ * ```
62
+ */
63
+ off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
64
+ /**
65
+ * Returns the number of listeners registered for `eventName`.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * emitter.on('build', handler)
70
+ * emitter.listenerCount('build') // 1
71
+ * ```
72
+ */
73
+ listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number;
74
+ /**
75
+ * Removes all listeners from every event channel.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * emitter.removeAll()
80
+ * ```
81
+ */
82
+ removeAll(): void;
83
+ }
84
+ //#endregion
85
+ //#region ../../internals/utils/src/promise.d.ts
86
+ /** A value that may already be resolved or still pending.
87
+ *
88
+ * @example
89
+ * ```ts
90
+ * function load(id: string): PossiblePromise<string> {
91
+ * return cache.get(id) ?? fetchRemote(id)
92
+ * }
93
+ * ```
94
+ */
95
+ type PossiblePromise<T> = Promise<T> | T;
96
+ //#endregion
97
+ //#region src/constants.d.ts
98
+ /**
99
+ * Base URL for the Kubb Studio web app.
100
+ */
101
+ declare const DEFAULT_STUDIO_URL: "https://studio.kubb.dev";
102
+ /**
103
+ * Numeric log-level thresholds used internally to compare verbosity.
104
+ *
105
+ * Higher numbers are more verbose.
106
+ */
107
+ declare const logLevel: {
108
+ readonly silent: number;
109
+ readonly error: 0;
110
+ readonly warn: 1;
111
+ readonly info: 3;
112
+ readonly verbose: 4;
113
+ readonly debug: 5;
114
+ };
115
+ //#endregion
116
+ //#region src/createRenderer.d.ts
117
+ /**
118
+ * Minimal interface any Kubb renderer must satisfy.
119
+ *
120
+ * The generic `TElement` is the type of the element the renderer accepts —
121
+ * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for
122
+ * your own renderer. Defaults to `unknown` so that generators which do not
123
+ * care about the element type continue to work without specifying it.
124
+ *
125
+ * This allows core to drive rendering without a hard dependency on
126
+ * `@kubb/renderer-jsx` or any specific renderer implementation.
127
+ */
128
+ type Renderer<TElement = unknown> = {
129
+ render(element: TElement): Promise<void>;
130
+ unmount(error?: Error | number | null): void;
131
+ readonly files: Array<FileNode>;
132
+ };
133
+ /**
134
+ * A factory function that produces a fresh {@link Renderer} per render.
135
+ *
136
+ * Generators use this to declare which renderer handles their output.
137
+ */
138
+ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
139
+ /**
140
+ * Creates a renderer factory for use in generator definitions.
141
+ *
142
+ * Wrap your renderer factory function with this helper to register it as the
143
+ * renderer for a generator. Core will call this factory once per render cycle
144
+ * to obtain a fresh renderer instance.
145
+ *
146
+ * @example
147
+ * ```ts
148
+ * // packages/renderer-jsx/src/index.ts
149
+ * export const jsxRenderer = createRenderer(() => {
150
+ * const runtime = new Runtime()
151
+ * return {
152
+ * async render(element) { await runtime.render(element) },
153
+ * get files() { return runtime.nodes },
154
+ * unmount(error) { runtime.unmount(error) },
155
+ * }
156
+ * })
157
+ *
158
+ * // packages/plugin-zod/src/generators/zodGenerator.tsx
159
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
160
+ * export const zodGenerator = defineGenerator<PluginZod>({
161
+ * name: 'zod',
162
+ * renderer: jsxRenderer,
163
+ * schema(node, options) { return <File ...>...</File> },
164
+ * })
165
+ * ```
166
+ */
167
+ declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
168
+ //#endregion
169
+ //#region src/createStorage.d.ts
170
+ type Storage = {
171
+ /**
172
+ * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).
173
+ */
174
+ readonly name: string;
175
+ /**
176
+ * Returns `true` when an entry for `key` exists in storage.
177
+ */
178
+ hasItem(key: string): Promise<boolean>;
179
+ /**
180
+ * Returns the stored string value, or `null` when `key` does not exist.
181
+ */
182
+ getItem(key: string): Promise<string | null>;
183
+ /**
184
+ * Persists `value` under `key`, creating any required structure.
185
+ */
186
+ setItem(key: string, value: string): Promise<void>;
187
+ /**
188
+ * Removes the entry for `key`. No-ops when the key does not exist.
189
+ */
190
+ removeItem(key: string): Promise<void>;
191
+ /**
192
+ * Returns all keys, optionally filtered to those starting with `base`.
193
+ */
194
+ getKeys(base?: string): Promise<Array<string>>;
195
+ /**
196
+ * Removes all entries, optionally scoped to those starting with `base`.
197
+ */
198
+ clear(base?: string): Promise<void>;
199
+ /**
200
+ * Optional teardown hook called after the build completes.
201
+ */
202
+ dispose?(): Promise<void>;
203
+ };
204
+ /**
205
+ * Creates a storage factory. Call the returned function with optional options to get the storage instance.
206
+ *
207
+ * @example
208
+ * export const memoryStorage = createStorage(() => {
209
+ * const store = new Map<string, string>()
210
+ * return {
211
+ * name: 'memory',
212
+ * async hasItem(key) { return store.has(key) },
213
+ * async getItem(key) { return store.get(key) ?? null },
214
+ * async setItem(key, value) { store.set(key, value) },
215
+ * async removeItem(key) { store.delete(key) },
216
+ * async getKeys(base) {
217
+ * const keys = [...store.keys()]
218
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
219
+ * },
220
+ * async clear(base) { if (!base) store.clear() },
221
+ * }
222
+ * })
223
+ */
224
+ declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
225
+ //#endregion
226
+ //#region src/defineGenerator.d.ts
227
+ /**
228
+ * A generator is a named object with optional `schema`, `operation`, and `operations`
229
+ * methods. Each method receives the AST node as the first argument and a typed
230
+ * `ctx` object as the second, giving access to `ctx.config`, `ctx.resolver`,
231
+ * `ctx.adapter`, `ctx.options`, `ctx.upsertFile`, etc.
232
+ *
233
+ * Generators that return renderer elements (e.g. JSX) must declare a `renderer`
234
+ * factory so that core knows how to process the output without coupling core
235
+ * to any specific renderer package.
236
+ *
237
+ * Return a renderer element, an array of `FileNode`, or `void` to handle file
238
+ * writing manually via `ctx.upsertFile`.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
243
+ *
244
+ * export const typeGenerator = defineGenerator<PluginTs>({
245
+ * name: 'typescript',
246
+ * renderer: jsxRenderer,
247
+ * schema(node, ctx) {
248
+ * const { adapter, resolver, root, options } = ctx
249
+ * return <File ...><Type node={node} resolver={resolver} /></File>
250
+ * },
251
+ * operation(node, ctx) {
252
+ * const { options } = ctx
253
+ * return <File ...><OperationType node={node} /></File>
254
+ * },
255
+ * })
256
+ * ```
257
+ */
258
+ type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
259
+ /**
260
+ * Used in diagnostic messages and debug output.
261
+ */
262
+ name: string;
263
+ /**
264
+ * Optional renderer factory that produces a {@link Renderer} for each render cycle.
265
+ *
266
+ * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
267
+ * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
268
+ *
269
+ * Generators that only return `Array<FileNode>` or `void` do not need to set this.
270
+ *
271
+ * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin
272
+ * declares a `renderer` (overrides the plugin-level fallback).
273
+ *
274
+ * @example
275
+ * ```ts
276
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
277
+ * export const myGenerator = defineGenerator<PluginTs>({
278
+ * renderer: jsxRenderer,
279
+ * schema(node, ctx) { return <File ...>...</File> },
280
+ * })
281
+ * ```
282
+ */
283
+ renderer?: RendererFactory<TElement> | null;
284
+ /**
285
+ * Called for each schema node in the AST walk.
286
+ * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
287
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
288
+ */
289
+ schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
290
+ /**
291
+ * Called for each operation node in the AST walk.
292
+ * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
293
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
294
+ */
295
+ operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
296
+ /**
297
+ * Called once after all operations have been walked.
298
+ * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
299
+ * plus `ctx.options` with the plugin-level options for the batch call.
300
+ */
301
+ operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
302
+ };
303
+ /**
304
+ * Defines a generator. Returns the object as-is with correct `this` typings.
305
+ * `applyHookResult` handles renderer elements and `File[]` uniformly using
306
+ * the generator's declared `renderer` factory.
307
+ */
308
+ declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
309
+ //#endregion
310
+ //#region src/defineParser.d.ts
311
+ type PrintOptions = {
312
+ extname?: FileNode['extname'];
313
+ };
314
+ type Parser<TMeta extends object = any> = {
315
+ name: string;
316
+ /**
317
+ * File extensions this parser handles.
318
+ * Use `undefined` to create a catch-all fallback parser.
319
+ *
320
+ * @example Handled extensions
321
+ * `['.ts', '.js']`
322
+ */
323
+ extNames: Array<FileNode['extname']> | undefined;
324
+ /**
325
+ * Convert a resolved file to a string.
326
+ */
327
+ parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string;
328
+ };
329
+ /**
330
+ * Defines a parser with type safety.
331
+ *
332
+ * Use this function to create parsers that transform generated files to strings
333
+ * based on their extension.
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * import { defineParser } from '@kubb/core'
338
+ *
339
+ * export const jsonParser = defineParser({
340
+ * name: 'json',
341
+ * extNames: ['.json'],
342
+ * parse(file) {
343
+ * const { extractStringsFromNodes } = await import('@kubb/ast')
344
+ * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
345
+ * },
346
+ * })
347
+ * ```
348
+ */
349
+ declare function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta>;
350
+ //#endregion
351
+ //#region src/FileManager.d.ts
352
+ /**
353
+ * In-memory file store for generated files.
354
+ *
355
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
356
+ * The `files` getter returns all stored files sorted by path length (shortest first).
357
+ *
358
+ * @example
359
+ * ```ts
360
+ * import { FileManager } from '@kubb/core'
361
+ *
362
+ * const manager = new FileManager()
363
+ * manager.upsert(myFile)
364
+ * console.log(manager.files) // all stored files
365
+ * ```
366
+ */
367
+ declare class FileManager {
368
+ #private;
369
+ /**
370
+ * Adds one or more files. Files with the same path are merged — sources, imports,
371
+ * and exports from all calls with the same path are concatenated together.
372
+ */
373
+ add(...files: Array<FileNode>): Array<FileNode>;
374
+ /**
375
+ * Adds or merges one or more files.
376
+ * If a file with the same path already exists, its sources/imports/exports are merged together.
377
+ */
378
+ upsert(...files: Array<FileNode>): Array<FileNode>;
379
+ getByPath(path: string): FileNode | null;
380
+ deleteByPath(path: string): void;
381
+ clear(): void;
382
+ /**
383
+ * All stored files, sorted by path length (shorter paths first).
384
+ * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
385
+ */
386
+ get files(): Array<FileNode>;
387
+ }
388
+ //#endregion
389
+ //#region src/PluginDriver.d.ts
390
+ type RequiredPluginLifecycle = Required<PluginLifecycle>;
391
+ /**
392
+ * Hook dispatch strategy used by the `PluginDriver`.
393
+ *
394
+ * - `hookFirst` — stops at the first non-null result.
395
+ * - `hookForPlugin` — calls only the matching plugin.
396
+ * - `hookParallel` — calls all plugins concurrently.
397
+ * - `hookSeq` — calls all plugins in order, threading the result.
398
+ */
399
+ type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq';
400
+ type ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H];
401
+ type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
402
+ result: Result;
403
+ plugin: Plugin;
404
+ };
405
+ type Options = {
406
+ hooks?: AsyncEventEmitter<KubbHooks>;
407
+ /**
408
+ * @default Number.POSITIVE_INFINITY
409
+ */
410
+ concurrency?: number;
411
+ };
412
+ /**
413
+ * Parameters accepted by `PluginDriver.getFile` to resolve a generated file descriptor.
414
+ */
415
+ type GetFileOptions<TOptions = object> = {
416
+ name: string;
417
+ mode?: 'single' | 'split';
418
+ extname: FileNode['extname'];
419
+ pluginName: string;
420
+ options?: TOptions;
421
+ };
422
+ declare class PluginDriver {
423
+ #private;
424
+ readonly config: Config;
425
+ readonly options: Options;
426
+ /**
427
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * PluginDriver.getMode('src/gen/types.ts') // 'single'
432
+ * PluginDriver.getMode('src/gen/types') // 'split'
433
+ * ```
434
+ */
435
+ static getMode(fileOrFolder: string | undefined | null): 'single' | 'split';
436
+ /**
437
+ * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
438
+ * the build pipeline after the adapter's `parse()` resolves.
439
+ */
440
+ inputNode: InputNode | undefined;
441
+ adapter: Adapter | undefined;
442
+ /**
443
+ * Central file store for all generated files.
444
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
445
+ * add files; this property gives direct read/write access when needed.
446
+ */
447
+ readonly fileManager: FileManager;
448
+ readonly plugins: Map<string, Plugin>;
449
+ constructor(config: Config, options: Options);
450
+ get hooks(): AsyncEventEmitter<KubbHooks>;
451
+ /**
452
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
453
+ *
454
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
455
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
456
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
457
+ *
458
+ * All other hooks are iterated and registered directly as pass-through listeners.
459
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
460
+ *
461
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
462
+ * the plugin lifecycle without modifying plugin behavior.
463
+ */
464
+ registerPluginHooks(hookPlugin: HookStylePlugin, normalizedPlugin: Plugin): void;
465
+ /**
466
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
467
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
468
+ *
469
+ * Call this once from `safeBuild` before the plugin execution loop begins.
470
+ */
471
+ emitSetupHooks(): Promise<void>;
472
+ /**
473
+ * Registers a generator for the given plugin on the shared event emitter.
474
+ *
475
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
476
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
477
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
478
+ * so that generators from different plugins do not cross-fire.
479
+ *
480
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
481
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
482
+ * declares a renderer.
483
+ *
484
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
485
+ */
486
+ registerGenerator(pluginName: string, gen: Generator): void;
487
+ /**
488
+ * Returns `true` when at least one generator was registered for the given plugin
489
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
490
+ *
491
+ * Used by the build loop to decide whether to walk the AST and emit generator events
492
+ * for a plugin that has no static `plugin.generators`.
493
+ */
494
+ hasRegisteredGenerators(pluginName: string): boolean;
495
+ dispose(): void;
496
+ setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
497
+ getResolver(pluginName: string): Resolver;
498
+ getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown>;
499
+ /**
500
+ * @deprecated use resolvers context instead
501
+ */
502
+ getFile<TOptions = object>({
503
+ name,
504
+ mode,
505
+ extname,
506
+ pluginName,
507
+ options
508
+ }: GetFileOptions<TOptions>): FileNode<{
509
+ pluginName: string;
510
+ }>;
511
+ /**
512
+ * @deprecated use resolvers context instead
513
+ */
514
+ resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => string;
515
+ /**
516
+ * @deprecated use resolvers context instead
517
+ */
518
+ resolveName: (params: ResolveNameParams) => string;
519
+ /**
520
+ * Run a specific hookName for plugin x.
521
+ */
522
+ hookForPlugin<H extends PluginLifecycleHooks>({
523
+ pluginName,
524
+ hookName,
525
+ parameters
526
+ }: {
527
+ pluginName: string;
528
+ hookName: H;
529
+ parameters: PluginParameter<H>;
530
+ }): Promise<Array<ReturnType<ParseResult<H>> | null>>;
531
+ /**
532
+ * Run a specific hookName for plugin x.
533
+ */
534
+ hookForPluginSync<H extends PluginLifecycleHooks>({
535
+ pluginName,
536
+ hookName,
537
+ parameters
538
+ }: {
539
+ pluginName: string;
540
+ hookName: H;
541
+ parameters: PluginParameter<H>;
542
+ }): Array<ReturnType<ParseResult<H>>> | null;
543
+ /**
544
+ * Returns the first non-null result.
545
+ */
546
+ hookFirst<H extends PluginLifecycleHooks>({
547
+ hookName,
548
+ parameters,
549
+ skipped
550
+ }: {
551
+ hookName: H;
552
+ parameters: PluginParameter<H>;
553
+ skipped?: ReadonlySet<Plugin> | null;
554
+ }): Promise<SafeParseResult<H>>;
555
+ /**
556
+ * Returns the first non-null result.
557
+ */
558
+ hookFirstSync<H extends PluginLifecycleHooks>({
559
+ hookName,
560
+ parameters,
561
+ skipped
562
+ }: {
563
+ hookName: H;
564
+ parameters: PluginParameter<H>;
565
+ skipped?: ReadonlySet<Plugin> | null;
566
+ }): SafeParseResult<H> | null;
567
+ /**
568
+ * Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
569
+ */
570
+ hookParallel<H extends PluginLifecycleHooks, TOutput = void>({
571
+ hookName,
572
+ parameters
573
+ }: {
574
+ hookName: H;
575
+ parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
576
+ }): Promise<Awaited<TOutput>[]>;
577
+ /**
578
+ * Execute a lifecycle hook sequentially for all plugins that implement it.
579
+ */
580
+ hookSeq<H extends PluginLifecycleHooks>({
581
+ hookName,
582
+ parameters
583
+ }: {
584
+ hookName: H;
585
+ parameters?: PluginParameter<H>;
586
+ }): Promise<void>;
587
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
588
+ getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
589
+ /**
590
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
591
+ */
592
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>;
593
+ requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
594
+ }
595
+ //#endregion
596
+ //#region src/createKubb.d.ts
597
+ /**
598
+ * Full output produced by a successful or failed build.
599
+ */
600
+ type BuildOutput = {
601
+ /**
602
+ * Plugins that threw during installation, paired with the caught error.
603
+ */
604
+ failedPlugins: Set<{
605
+ plugin: Plugin;
606
+ error: Error;
607
+ }>;
608
+ files: Array<FileNode>;
609
+ driver: PluginDriver;
610
+ /**
611
+ * Elapsed time in milliseconds for each plugin, keyed by plugin name.
612
+ */
613
+ pluginTimings: Map<string, number>;
614
+ error?: Error;
615
+ /**
616
+ * Raw generated source, keyed by absolute file path.
617
+ */
618
+ sources: Map<string, string>;
619
+ };
620
+ type CreateKubbOptions = {
621
+ hooks?: AsyncEventEmitter<KubbHooks>;
622
+ };
623
+ /**
624
+ * Creates a Kubb instance bound to a single config entry.
625
+ *
626
+ * Accepts a user-facing config shape and resolves it to a full {@link Config} during
627
+ * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
628
+ * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
629
+ * calling `setup()` or `build()`.
630
+ *
631
+ * @example
632
+ * ```ts
633
+ * const kubb = createKubb(userConfig)
634
+ *
635
+ * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {
636
+ * console.log(`${plugin.name} completed in ${duration}ms`)
637
+ * })
638
+ *
639
+ * const { files, failedPlugins } = await kubb.safeBuild()
640
+ * ```
641
+ */
642
+ declare function createKubb(userConfig: UserConfig, options?: CreateKubbOptions): Kubb$1;
643
+ //#endregion
644
+ //#region src/Kubb.d.ts
645
+ type DebugInfo = {
646
+ date: Date;
647
+ logs: Array<string>;
648
+ fileName?: string;
649
+ };
650
+ type HookProgress<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
651
+ hookName: H;
652
+ plugins: Array<Plugin>;
653
+ };
654
+ type HookExecution<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
655
+ strategy: Strategy;
656
+ hookName: H;
657
+ plugin: Plugin;
658
+ parameters?: Array<unknown>;
659
+ output?: unknown;
660
+ };
661
+ type HookResult<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
662
+ duration: number;
663
+ strategy: Strategy;
664
+ hookName: H;
665
+ plugin: Plugin;
666
+ parameters?: Array<unknown>;
667
+ output?: unknown;
668
+ };
669
+ /**
670
+ * The instance returned by {@link createKubb}.
671
+ */
672
+ type Kubb$1 = {
673
+ /**
674
+ * The shared event emitter. Attach listeners here before calling `setup()` or `build()`.
675
+ */
676
+ readonly hooks: AsyncEventEmitter<KubbHooks>;
677
+ /**
678
+ * Raw generated source, keyed by absolute file path.
679
+ * Populated after a successful `build()` or `safeBuild()` call.
680
+ */
681
+ readonly sources: Map<string, string>;
682
+ /**
683
+ * The plugin driver. Available after `setup()` has been called.
684
+ */
685
+ readonly driver: PluginDriver | undefined;
686
+ /**
687
+ * The resolved config with applied defaults. Available after `setup()` has been called.
688
+ */
689
+ readonly config: Config | undefined;
690
+ /**
691
+ * Initializes all Kubb infrastructure: validates input, applies config defaults,
692
+ * runs the adapter, and creates the PluginDriver.
693
+ *
694
+ * Calling `build()` or `safeBuild()` without calling `setup()` first will
695
+ * automatically invoke `setup()` before proceeding.
696
+ */
697
+ setup(): Promise<void>;
698
+ /**
699
+ * Runs a full Kubb build and throws on any error or plugin failure.
700
+ * Automatically calls `setup()` if it has not been called yet.
701
+ */
702
+ build(): Promise<BuildOutput>;
703
+ /**
704
+ * Runs a full Kubb build and captures errors instead of throwing.
705
+ * Automatically calls `setup()` if it has not been called yet.
706
+ */
707
+ safeBuild(): Promise<BuildOutput>;
708
+ };
709
+ /**
710
+ * Events emitted during the Kubb code generation lifecycle.
711
+ * These events can be listened to for logging, progress tracking, and custom integrations.
712
+ *
713
+ * @example
714
+ * ```typescript
715
+ * import type { AsyncEventEmitter } from '@internals/utils'
716
+ * import type { KubbHooks } from '@kubb/core'
717
+ *
718
+ * const hooks: AsyncEventEmitter<KubbHooks> = new AsyncEventEmitter()
719
+ *
720
+ * hooks.on('kubb:lifecycle:start', () => {
721
+ * console.log('Starting Kubb generation')
722
+ * })
723
+ *
724
+ * hooks.on('kubb:plugin:end', (plugin, { duration }) => {
725
+ * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)
726
+ * })
727
+ * ```
728
+ */
729
+ interface KubbHooks {
730
+ /**
731
+ * Emitted at the beginning of the Kubb lifecycle, before any code generation starts.
732
+ */
733
+ 'kubb:lifecycle:start': [version: string];
734
+ /**
735
+ * Emitted at the end of the Kubb lifecycle, after all code generation is complete.
736
+ */
737
+ 'kubb:lifecycle:end': [];
738
+ /**
739
+ * Emitted when configuration loading starts.
740
+ */
741
+ 'kubb:config:start': [];
742
+ /**
743
+ * Emitted when configuration loading is complete.
744
+ */
745
+ 'kubb:config:end': [configs: Array<Config>];
746
+ /**
747
+ * Emitted when code generation phase starts.
748
+ */
749
+ 'kubb:generation:start': [config: Config];
750
+ /**
751
+ * Emitted when code generation phase completes.
752
+ */
753
+ 'kubb:generation:end': [config: Config, files: Array<FileNode>, sources: Map<string, string>];
754
+ /**
755
+ * Emitted with a summary of the generation results.
756
+ * Contains summary lines, title, and success status.
757
+ */
758
+ 'kubb:generation:summary': [config: Config, {
759
+ failedPlugins: Set<{
760
+ plugin: Plugin;
761
+ error: Error;
762
+ }>;
763
+ status: 'success' | 'failed';
764
+ hrStart: [number, number];
765
+ filesCreated: number;
766
+ pluginTimings?: Map<Plugin['name'], number>;
767
+ }];
768
+ /**
769
+ * Emitted when code formatting starts (e.g., running Biome or Prettier).
770
+ */
771
+ 'kubb:format:start': [];
772
+ /**
773
+ * Emitted when code formatting completes.
774
+ */
775
+ 'kubb:format:end': [];
776
+ /**
777
+ * Emitted when linting starts.
778
+ */
779
+ 'kubb:lint:start': [];
780
+ /**
781
+ * Emitted when linting completes.
782
+ */
783
+ 'kubb:lint:end': [];
784
+ /**
785
+ * Emitted when plugin hooks execution starts.
786
+ */
787
+ 'kubb:hooks:start': [];
788
+ /**
789
+ * Emitted when plugin hooks execution completes.
790
+ */
791
+ 'kubb:hooks:end': [];
792
+ /**
793
+ * Emitted when a single hook execution starts (e.g., format or lint).
794
+ * The callback should be invoked when the command completes.
795
+ */
796
+ 'kubb:hook:start': [{
797
+ id?: string;
798
+ command: string;
799
+ args?: readonly string[];
800
+ }];
801
+ /**
802
+ * Emitted when a single hook execution completes.
803
+ */
804
+ 'kubb:hook:end': [{
805
+ id?: string;
806
+ command: string;
807
+ args?: readonly string[];
808
+ success: boolean;
809
+ error: Error | null;
810
+ }];
811
+ /**
812
+ * Emitted when a new version of Kubb is available.
813
+ */
814
+ 'kubb:version:new': [currentVersion: string, latestVersion: string];
815
+ /**
816
+ * Informational message event.
817
+ */
818
+ 'kubb:info': [message: string, info?: string];
819
+ /**
820
+ * Error event. Emitted when an error occurs during code generation.
821
+ */
822
+ 'kubb:error': [error: Error, meta?: Record<string, unknown>];
823
+ /**
824
+ * Success message event.
825
+ */
826
+ 'kubb:success': [message: string, info?: string];
827
+ /**
828
+ * Warning message event.
829
+ */
830
+ 'kubb:warn': [message: string, info?: string];
831
+ /**
832
+ * Debug event for detailed logging.
833
+ * Contains timestamp, log messages, and optional filename.
834
+ */
835
+ 'kubb:debug': [info: DebugInfo];
836
+ /**
837
+ * Emitted when file processing starts.
838
+ * Contains the list of files to be processed.
839
+ */
840
+ 'kubb:files:processing:start': [files: Array<FileNode>];
841
+ /**
842
+ * Emitted for each file being processed, providing progress updates.
843
+ * Contains processed count, total count, percentage, and file details.
844
+ */
845
+ 'kubb:file:processing:update': [{
846
+ /**
847
+ * Number of files processed so far.
848
+ */
849
+ processed: number;
850
+ /**
851
+ * Total number of files to process.
852
+ */
853
+ total: number;
854
+ /**
855
+ * Processing percentage (0–100).
856
+ */
857
+ percentage: number;
858
+ /**
859
+ * Optional source identifier.
860
+ */
861
+ source?: string;
862
+ /**
863
+ * The file being processed.
864
+ */
865
+ file: FileNode;
866
+ /**
867
+ * Kubb configuration
868
+ * Provides access to the current config during file processing.
869
+ */
870
+ config: Config;
871
+ }];
872
+ /**
873
+ * Emitted when file processing completes.
874
+ * Contains the list of processed files.
875
+ */
876
+ 'kubb:files:processing:end': [files: Array<FileNode>];
877
+ /**
878
+ * Emitted when a plugin starts executing.
879
+ */
880
+ 'kubb:plugin:start': [plugin: Plugin];
881
+ /**
882
+ * Emitted when a plugin completes execution.
883
+ * Duration in ms.
884
+ */
885
+ 'kubb:plugin:end': [plugin: Plugin, result: {
886
+ duration: number;
887
+ success: boolean;
888
+ error?: Error;
889
+ }];
890
+ /**
891
+ * Emitted when plugin hook progress tracking starts.
892
+ * Contains the hook name and list of plugins to execute.
893
+ */
894
+ 'kubb:plugins:hook:progress:start': [progress: HookProgress];
895
+ /**
896
+ * Emitted when plugin hook progress tracking ends.
897
+ * Contains the hook name that completed.
898
+ */
899
+ 'kubb:plugins:hook:progress:end': [{
900
+ hookName: PluginLifecycleHooks;
901
+ }];
902
+ /**
903
+ * Emitted when a plugin hook starts processing.
904
+ * Contains strategy, hook name, plugin, parameters, and output.
905
+ */
906
+ 'kubb:plugins:hook:processing:start': [execution: HookExecution];
907
+ /**
908
+ * Emitted when a plugin hook completes processing.
909
+ * Contains duration, strategy, hook name, plugin, parameters, and output.
910
+ */
911
+ 'kubb:plugins:hook:processing:end': [result: HookResult];
912
+ /**
913
+ * Fired once — before any plugin's `buildStart` runs — so that hook-style plugins
914
+ * can register generators, configure resolvers/transformers/renderers, or inject
915
+ * extra files. All `kubb:plugin:setup` handlers registered via `definePlugin` receive
916
+ * a plugin-specific context (with the correct `addGenerator` closure).
917
+ * External tooling can observe this event via `hooks.on('kubb:plugin:setup', …)`.
918
+ */
919
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
920
+ /**
921
+ * Fired immediately before the plugin execution loop begins.
922
+ * The adapter has already parsed the source and `inputNode` is available.
923
+ */
924
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
925
+ /**
926
+ * Fired after all files have been written to disk.
927
+ */
928
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
929
+ /**
930
+ * Emitted for each schema node during the AST walk.
931
+ * Generator listeners registered via `addGenerator()` in `kubb:plugin:setup` respond to this event.
932
+ * The `ctx.plugin.name` identifies which plugin is driving the current walk.
933
+ * `ctx.options` carries the per-node resolved options (after exclude/include/override).
934
+ */
935
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
936
+ /**
937
+ * Emitted for each operation node during the AST walk.
938
+ * Generator listeners registered via `addGenerator()` in `kubb:plugin:setup` respond to this event.
939
+ * The `ctx.plugin.name` identifies which plugin is driving the current walk.
940
+ * `ctx.options` carries the per-node resolved options (after exclude/include/override).
941
+ */
942
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
943
+ /**
944
+ * Emitted once after all operations have been walked, with the full collected array.
945
+ * Generator listeners with an `operations()` method respond to this event.
946
+ * The `ctx.plugin.name` identifies which plugin is driving the current walk.
947
+ * `ctx.options` carries the plugin-level resolved options for the batch call.
948
+ */
949
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
950
+ }
951
+ declare global {
952
+ namespace Kubb {
953
+ interface PluginContext {}
954
+ /**
955
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
956
+ * Augment this interface in each plugin's `types.ts` to enable automatic
957
+ * typing for `getPlugin` and `requirePlugin`.
958
+ *
959
+ * @example
960
+ * ```ts
961
+ * // packages/plugin-ts/src/types.ts
962
+ * declare global {
963
+ * namespace Kubb {
964
+ * interface PluginRegistry {
965
+ * 'plugin-ts': PluginTs
966
+ * }
967
+ * }
968
+ * }
969
+ * ```
970
+ */
971
+ interface PluginRegistry {}
972
+ }
973
+ }
974
+ //#endregion
975
+ //#region src/definePlugin.d.ts
976
+ /**
977
+ * Base hook handlers for all events except `kubb:plugin:setup`.
978
+ * These handlers have identical signatures regardless of the plugin's
979
+ * `PluginFactoryOptions` generic — they are split out so that the
980
+ * interface below only needs to override the one event that depends on
981
+ * the plugin type.
982
+ */
983
+ type PluginHooksBase = { [K in Exclude<keyof KubbHooks, 'kubb:plugin:setup'>]?: (...args: KubbHooks[K]) => void | Promise<void> };
984
+ /**
985
+ * Plugin hook handlers.
986
+ *
987
+ * `kubb:plugin:setup` is typed with the plugin's own `PluginFactoryOptions` so
988
+ * `ctx.setResolver`, `ctx.setOptions`, `ctx.options` etc. use the correct types.
989
+ *
990
+ * Uses interface + method shorthand for `kubb:plugin:setup`
991
+ * checking, allowing `PluginHooks<PluginTs>` to be assignable to `PluginHooks`.
992
+ *
993
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
994
+ */
995
+ interface PluginHooks<TFactory extends PluginFactoryOptions = PluginFactoryOptions> extends PluginHooksBase {
996
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
997
+ }
998
+ /**
999
+ * A hook-style plugin object produced by `definePlugin`.
1000
+ * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property
1001
+ * (matching Astro's integration naming convention).
1002
+ *
1003
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
1004
+ */
1005
+ type HookStylePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1006
+ /**
1007
+ * Unique name for the plugin, following the same naming convention as `createPlugin`.
1008
+ */
1009
+ name: string;
1010
+ /**
1011
+ * Plugins that must be registered before this plugin executes.
1012
+ * An error is thrown at startup when any listed dependency is missing.
1013
+ */
1014
+ dependencies?: Array<string>;
1015
+ /**
1016
+ * The options passed by the user when calling the plugin factory.
1017
+ */
1018
+ options?: TFactory['options'];
1019
+ /**
1020
+ * Lifecycle event handlers for this plugin.
1021
+ * Any event from the global `KubbHooks` map can be subscribed to here.
1022
+ */
1023
+ hooks: PluginHooks<TFactory>;
1024
+ };
1025
+ /**
1026
+ * Creates a plugin factory using the new hook-style (`hooks:`) API.
1027
+ *
1028
+ * The returned factory is called with optional options and produces a `HookStylePlugin`
1029
+ * that coexists with plugins created via the legacy `createPlugin` API in the same
1030
+ * `kubb.config.ts`.
1031
+ *
1032
+ * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
1033
+ * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
1034
+ *
1035
+ * @example
1036
+ * ```ts
1037
+ * // With PluginFactoryOptions (recommended for real plugins)
1038
+ * export const pluginTs = definePlugin<PluginTs>((options) => ({
1039
+ * name: 'plugin-ts',
1040
+ * hooks: {
1041
+ * 'kubb:plugin:setup'(ctx) {
1042
+ * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
1043
+ * },
1044
+ * },
1045
+ * }))
1046
+ * ```
1047
+ */
1048
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => HookStylePlugin<TFactory>): (options?: TFactory['options']) => HookStylePlugin<TFactory>;
1049
+ //#endregion
1050
+ //#region src/utils/getBarrelFiles.d.ts
1051
+ type FileMetaBase = {
1052
+ pluginName?: string;
1053
+ };
1054
+ //#endregion
1055
+ //#region src/types.d.ts
1056
+ type InputPath = {
1057
+ /**
1058
+ * Specify your Swagger/OpenAPI file, either as an absolute path or a path relative to the root.
1059
+ */
1060
+ path: string;
1061
+ };
1062
+ type InputData = {
1063
+ /**
1064
+ * A `string` or `object` that contains your Swagger/OpenAPI data.
1065
+ */
1066
+ data: string | unknown;
1067
+ };
1068
+ type Input = InputPath | InputData;
1069
+ /**
1070
+ * The raw source passed to an adapter's `parse` function.
1071
+ * Mirrors the shape of `Config['input']` with paths already resolved to absolute.
1072
+ */
1073
+ type AdapterSource = {
1074
+ type: 'path';
1075
+ path: string;
1076
+ } | {
1077
+ type: 'data';
1078
+ data: string | unknown;
1079
+ } | {
1080
+ type: 'paths';
1081
+ paths: Array<string>;
1082
+ };
1083
+ /**
1084
+ * Type parameters for an adapter definition.
1085
+ *
1086
+ * Mirrors `PluginFactoryOptions` but scoped to the adapter lifecycle:
1087
+ * - `TName` — unique string identifier (e.g. `'oas'`, `'asyncapi'`)
1088
+ * - `TOptions` — raw user-facing options passed to the adapter factory
1089
+ * - `TResolvedOptions` — defaults applied; what the adapter stores as `options`
1090
+ * - `TDocument` — type of the raw source document exposed by the adapter after `parse()`
1091
+ */
1092
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
1093
+ name: TName;
1094
+ options: TOptions;
1095
+ resolvedOptions: TResolvedOptions;
1096
+ document: TDocument;
1097
+ };
1098
+ /**
1099
+ * An adapter converts a source file or data into a `@kubb/ast` `InputNode`.
1100
+ *
1101
+ * Adapters are the single entry-point for different schema formats
1102
+ * (OpenAPI, AsyncAPI, Drizzle, …) and produce the universal `InputNode`
1103
+ * that all Kubb plugins consume.
1104
+ *
1105
+ * @example
1106
+ * ```ts
1107
+ * import { oasAdapter } from '@kubb/adapter-oas'
1108
+ *
1109
+ * export default defineConfig({
1110
+ * adapter: adapterOas(), // default — OpenAPI / Swagger
1111
+ * input: { path: './openapi.yaml' },
1112
+ * plugins: [pluginTs(), pluginZod()],
1113
+ * })
1114
+ * ```
1115
+ */
1116
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
1117
+ /**
1118
+ * Human-readable identifier, e.g. `'oas'`, `'drizzle'`, `'asyncapi'`.
1119
+ */
1120
+ name: TOptions['name'];
1121
+ /**
1122
+ * Resolved options (after defaults have been applied).
1123
+ */
1124
+ options: TOptions['resolvedOptions'];
1125
+ /**
1126
+ * The raw source document produced after the first `parse()` call.
1127
+ * `undefined` before parsing; typed by the adapter's `TDocument` generic.
1128
+ */
1129
+ document: TOptions['document'] | null;
1130
+ inputNode: InputNode | null;
1131
+ /**
1132
+ * Convert the raw source into a universal `InputNode`.
1133
+ */
1134
+ parse: (source: AdapterSource) => PossiblePromise<InputNode>;
1135
+ /**
1136
+ * Extracts `ImportNode` entries needed by a `SchemaNode` tree.
1137
+ * Populated after the first `parse()` call. Returns an empty array before that.
1138
+ *
1139
+ * The `resolve` callback receives the collision-corrected schema name and must
1140
+ * return the `{ name, path }` pair for the import, or `undefined` to skip it.
1141
+ */
1142
+ getImports: (node: SchemaNode, resolve: (schemaName: string) => {
1143
+ name: string;
1144
+ path: string;
1145
+ }) => Array<ImportNode>;
1146
+ };
1147
+ /**
1148
+ * Controls how `index.ts` barrel files are generated.
1149
+ * - `'all'` — exports every generated symbol from every file.
1150
+ * - `'named'` — exports only explicitly named exports.
1151
+ * - `'propagate'` — propagates re-exports from nested barrel files upward.
1152
+ */
1153
+ type BarrelType = 'all' | 'named' | 'propagate';
1154
+ type DevtoolsOptions = {
1155
+ /**
1156
+ * Open the AST inspector view (`/ast`) in Kubb Studio.
1157
+ * When `false`, opens the main Studio page instead.
1158
+ * @default false
1159
+ */
1160
+ ast?: boolean;
1161
+ };
1162
+ /**
1163
+ * @private
1164
+ */
1165
+ type Config<TInput = Input> = {
1166
+ /**
1167
+ * The name to display in the CLI output.
1168
+ */
1169
+ name?: string;
1170
+ /**
1171
+ * The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
1172
+ * @default process.cwd()
1173
+ */
1174
+ root: string;
1175
+ /**
1176
+ * An array of parsers used to convert generated files to strings.
1177
+ * Each parser handles specific file extensions (e.g. `.ts`, `.tsx`).
1178
+ *
1179
+ * A catch-all fallback parser is always appended last for any unhandled extension.
1180
+ *
1181
+ * When omitted, `parserTs` from `@kubb/parser-ts` is used automatically as the
1182
+ * default (requires `@kubb/parser-ts` to be installed as an optional dependency).
1183
+ * @default [parserTs] — from `@kubb/parser-ts`
1184
+ * @example
1185
+ * ```ts
1186
+ * import { parserTs, tsxParser } from '@kubb/parser-ts'
1187
+ * export default defineConfig({
1188
+ * parsers: [parserTs, tsxParser],
1189
+ * })
1190
+ * ```
1191
+ */
1192
+ parsers: Array<Parser>;
1193
+ /**
1194
+ * Adapter that converts the input file into a `@kubb/ast` `InputNode` — the universal
1195
+ * intermediate representation consumed by all Kubb plugins.
1196
+ *
1197
+ * - Use `@kubb/adapter-oas` for OpenAPI / Swagger.
1198
+ * - Use `@kubb/adapter-drizzle` or `@kubb/adapter-asyncapi` for other formats.
1199
+ *
1200
+ * @example
1201
+ * ```ts
1202
+ * import { adapterOas } from '@kubb/adapter-oas'
1203
+ * export default defineConfig({
1204
+ * adapter: adapterOas(),
1205
+ * input: { path: './petStore.yaml' },
1206
+ * })
1207
+ * ```
1208
+ */
1209
+ adapter: Adapter;
1210
+ /**
1211
+ * Source file or data to generate code from.
1212
+ * Use `input.path` for a file on disk or `input.data` for an inline string or object.
1213
+ */
1214
+ input: TInput;
1215
+ output: {
1216
+ /**
1217
+ * Output directory for generated files.
1218
+ * Accepts an absolute path or a path relative to `root`.
1219
+ */
1220
+ path: string;
1221
+ /**
1222
+ * Clean the output directory before each build.
1223
+ */
1224
+ clean?: boolean;
1225
+ /**
1226
+ * Save files to the file system.
1227
+ * @default true
1228
+ * @deprecated Use `storage` to control where files are written.
1229
+ */
1230
+ write?: boolean;
1231
+ /**
1232
+ * Storage backend for generated files.
1233
+ * Defaults to `fsStorage()` — the built-in filesystem driver.
1234
+ * Accepts any object implementing the {@link Storage} interface.
1235
+ * Keys are root-relative paths (e.g. `src/gen/api/getPets.ts`).
1236
+ * @default fsStorage()
1237
+ * @example
1238
+ * ```ts
1239
+ * import { memoryStorage } from '@kubb/core'
1240
+ * storage: memoryStorage()
1241
+ * ```
1242
+ */
1243
+ storage?: Storage;
1244
+ /**
1245
+ * Specifies the formatting tool to be used.
1246
+ * - 'auto' automatically detects and uses biome or prettier (in that order of preference).
1247
+ * - 'prettier' uses Prettier for code formatting.
1248
+ * - 'biome' uses Biome for code formatting.
1249
+ * - 'oxfmt' uses Oxfmt for code formatting.
1250
+ * - false disables code formatting.
1251
+ * @default 'prettier'
1252
+ */
1253
+ format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
1254
+ /**
1255
+ * Specifies the linter that should be used to analyze the code.
1256
+ * - 'auto' automatically detects and uses biome, oxlint, or eslint (in that order of preference).
1257
+ * - 'eslint' uses ESLint for linting.
1258
+ * - 'biome' uses Biome for linting.
1259
+ * - 'oxlint' uses Oxlint for linting.
1260
+ * - false disables linting.
1261
+ * @default 'auto'
1262
+ */
1263
+ lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
1264
+ /**
1265
+ * Overrides the extension for generated imports and exports. By default, each plugin adds an extension.
1266
+ * @default { '.ts': '.ts'}
1267
+ */
1268
+ extension?: Record<FileNode['extname'], FileNode['extname'] | ''>;
1269
+ /**
1270
+ * Configures how `index.ts` files are created, including disabling barrel file generation. Each plugin has its own `barrelType` option; this setting controls the root barrel file (e.g., `src/gen/index.ts`).
1271
+ * @default 'named'
1272
+ */
1273
+ barrelType?: 'all' | 'named' | false;
1274
+ /**
1275
+ * Adds a default banner to the start of every generated file indicating it was generated by Kubb.
1276
+ * - 'simple' adds banner with link to Kubb.
1277
+ * - 'full' adds source, title, description, and OpenAPI version.
1278
+ * - false disables banner generation.
1279
+ * @default 'simple'
1280
+ */
1281
+ defaultBanner?: 'simple' | 'full' | false;
1282
+ /**
1283
+ * Whether to override existing external files if they already exist.
1284
+ * When setting the option in the global configuration, all plugins inherit the same behavior by default.
1285
+ * However, all plugins also have an `output.override` option, which can be used to override the behavior for a specific plugin.
1286
+ * @default false
1287
+ */
1288
+ override?: boolean;
1289
+ };
1290
+ /**
1291
+ * An array of Kubb plugins used for code generation.
1292
+ * Each plugin may declare additional configurable options.
1293
+ * If a plugin depends on another, an error is thrown when the dependency is missing.
1294
+ * Use `dependencies` on the plugin to declare execution order.
1295
+ */
1296
+ plugins: Array<Plugin>;
1297
+ /**
1298
+ * Project-wide renderer factory. All plugins and generators that do not declare their own
1299
+ * `renderer` ultimately fall back to this value.
1300
+ *
1301
+ * The resolution chain is: `generator.renderer` → `plugin.renderer` → `config.renderer` → `undefined` (raw `FileNode[]` mode).
1302
+ *
1303
+ * @example
1304
+ * ```ts
1305
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1306
+ * export default defineConfig({
1307
+ * renderer: jsxRenderer,
1308
+ * plugins: [pluginTs(), pluginZod()],
1309
+ * })
1310
+ * ```
1311
+ */
1312
+ renderer?: RendererFactory;
1313
+ /**
1314
+ * Devtools configuration for Kubb Studio integration.
1315
+ */
1316
+ devtools?: true | {
1317
+ /**
1318
+ * Override the Kubb Studio base URL.
1319
+ * @default 'https://studio.kubb.dev'
1320
+ */
1321
+ studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {});
1322
+ };
1323
+ /**
1324
+ * Hooks triggered when a specific action occurs in Kubb.
1325
+ */
1326
+ hooks?: {
1327
+ /**
1328
+ * Hook that triggers at the end of all executions.
1329
+ * Useful for running Prettier or ESLint to format/lint your code.
1330
+ */
1331
+ done?: string | Array<string>;
1332
+ };
1333
+ };
1334
+ /**
1335
+ * A type/string-pattern filter used for `include`, `exclude`, and `override` matching.
1336
+ */
1337
+ type PatternFilter = {
1338
+ type: string;
1339
+ pattern: string | RegExp;
1340
+ };
1341
+ /**
1342
+ * A pattern filter paired with partial option overrides to apply when the pattern matches.
1343
+ */
1344
+ type PatternOverride<TOptions> = PatternFilter & {
1345
+ options: Omit<Partial<TOptions>, 'override'>;
1346
+ };
1347
+ /**
1348
+ * Context passed to `resolver.resolveOptions` to apply include/exclude/override filtering
1349
+ * for a given operation or schema node.
1350
+ */
1351
+ type ResolveOptionsContext<TOptions> = {
1352
+ options: TOptions;
1353
+ exclude?: Array<PatternFilter>;
1354
+ include?: Array<PatternFilter>;
1355
+ override?: Array<PatternOverride<TOptions>>;
1356
+ };
1357
+ /**
1358
+ * Base constraint for all plugin resolver objects.
1359
+ *
1360
+ * `default`, `resolveOptions`, `resolvePath`, and `resolveFile` are injected automatically
1361
+ * by `defineResolver` — plugin authors may override them but never need to implement them
1362
+ * from scratch.
1363
+ *
1364
+ * @example
1365
+ * ```ts
1366
+ * type MyResolver = Resolver & {
1367
+ * resolveName(node: SchemaNode): string
1368
+ * resolveTypedName(node: SchemaNode): string
1369
+ * }
1370
+ * ```
1371
+ */
1372
+ type Resolver = {
1373
+ name: string;
1374
+ pluginName: Plugin['name'];
1375
+ default(name: ResolveNameParams['name'], type?: ResolveNameParams['type']): string;
1376
+ resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
1377
+ resolvePath(params: ResolverPathParams, context: ResolverContext): string;
1378
+ resolveFile(params: ResolverFileParams, context: ResolverContext): FileNode;
1379
+ resolveBanner(node: InputNode | null, context: ResolveBannerContext): string | undefined;
1380
+ resolveFooter(node: InputNode | null, context: ResolveBannerContext): string | undefined;
1381
+ };
1382
+ type PluginFactoryOptions<
1383
+ /**
1384
+ * Name to be used for the plugin.
1385
+ */
1386
+ TName extends string = string,
1387
+ /**
1388
+ * Options of the plugin.
1389
+ */
1390
+ TOptions extends object = object,
1391
+ /**
1392
+ * Options of the plugin that can be used later on, see `options` inside your plugin config.
1393
+ */
1394
+ TResolvedOptions extends object = TOptions,
1395
+ /**
1396
+ * Context that you want to expose to other plugins.
1397
+ */
1398
+ TContext = unknown,
1399
+ /**
1400
+ * When calling `resolvePath` you can specify better types.
1401
+ */
1402
+ TResolvePathOptions extends object = object,
1403
+ /**
1404
+ * Resolver object that encapsulates the naming and path-resolution helpers used by this plugin.
1405
+ * Use `defineResolver` to define the resolver object and export it alongside the plugin.
1406
+ */
1407
+ TResolver extends Resolver = Resolver> = {
1408
+ name: TName;
1409
+ options: TOptions;
1410
+ resolvedOptions: TResolvedOptions;
1411
+ context: TContext;
1412
+ resolvePathOptions: TResolvePathOptions;
1413
+ resolver: TResolver;
1414
+ };
1415
+ /**
1416
+ * @deprecated
1417
+ */
1418
+ type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1419
+ /**
1420
+ * Unique name used for the plugin.
1421
+ * The name follows the format `scope:foo-bar` or `foo-bar` — adding a scope avoids conflicts with other plugins.
1422
+ *
1423
+ * @example Plugin name
1424
+ * `'@kubb/typescript'`
1425
+ */
1426
+ name: TOptions['name'];
1427
+ /**
1428
+ * Resolved options merged with output/include/exclude/override defaults for the current plugin.
1429
+ */
1430
+ options: TOptions['resolvedOptions'] & {
1431
+ output: Output;
1432
+ include?: Array<Include>;
1433
+ exclude: Array<Exclude$1>;
1434
+ override: Array<Override<TOptions['resolvedOptions']>>;
1435
+ };
1436
+ /**
1437
+ * The resolver for this plugin.
1438
+ * Set via `setResolver()` in `kubb:plugin:setup` or passed as a user option.
1439
+ */
1440
+ resolver?: TOptions['resolver'];
1441
+ /**
1442
+ * The composed transformer for this plugin.
1443
+ * Set via `setTransformer()` in `kubb:plugin:setup` or passed as a user option.
1444
+ */
1445
+ transformer?: Visitor;
1446
+ /**
1447
+ * Plugin-level renderer factory. All generators that do not declare their own `renderer`
1448
+ * inherit this value. A generator can explicitly opt out by setting `renderer: null`.
1449
+ *
1450
+ * @example
1451
+ * ```ts
1452
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1453
+ * createPlugin((options) => ({
1454
+ * name: 'my-plugin',
1455
+ * renderer: jsxRenderer,
1456
+ * generators: [
1457
+ * { name: 'types', schema(node) { return <File>...</File> } }, // inherits jsxRenderer
1458
+ * { name: 'raw', renderer: null, schema(node) { return [...] } }, // explicit opt-out
1459
+ * ],
1460
+ * }))
1461
+ * ```
1462
+ */
1463
+ renderer?: RendererFactory;
1464
+ /**
1465
+ * Generators declared directly on the plugin. Each generator's `renderer` takes precedence
1466
+ * over `plugin.renderer`; set `renderer: null` on a generator to opt out of rendering even
1467
+ * when the plugin declares a renderer.
1468
+ */
1469
+ generators?: Array<Generator>;
1470
+ /**
1471
+ * Specifies the plugins that the current plugin depends on. The current plugin is executed after all listed plugins.
1472
+ * An error is returned if any required dependency plugin is missing.
1473
+ */
1474
+ dependencies?: Array<string>;
1475
+ /**
1476
+ * When `apply` is defined, the plugin is only activated when `apply(config)` returns `true`.
1477
+ * Inspired by Vite's `apply` option.
1478
+ *
1479
+ * @example
1480
+ * ```ts
1481
+ * apply: (config) => config.output.path !== 'disabled'
1482
+ * ```
1483
+ */
1484
+ apply?: (config: Config) => boolean;
1485
+ /**
1486
+ * Expose shared helpers or data to all other plugins via `PluginContext`.
1487
+ * The object returned is merged into the context that every plugin receives.
1488
+ * Use the `declare global { namespace Kubb { interface PluginContext { … } } }` pattern
1489
+ * to make the injected properties type-safe.
1490
+ *
1491
+ * @example
1492
+ * ```ts
1493
+ * inject() {
1494
+ * return { getOas: () => parseSpec(this.config) }
1495
+ * }
1496
+ * // Other plugins can then call `this.getOas()` inside buildStart()
1497
+ * ```
1498
+ */
1499
+ inject?: (this: PluginContext<TOptions>) => TOptions['context'];
1500
+ };
1501
+ /**
1502
+ * @deprecated
1503
+ */
1504
+ type UserPluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = UserPlugin<TOptions> & PluginLifecycle<TOptions>;
1505
+ /**
1506
+ * Partial version of {@link Config} intended for user-facing config entry points.
1507
+ *
1508
+ * Fields that have sensible defaults (`root`, `plugins`, `parsers`, `adapter`) are optional.
1509
+ */
1510
+ type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter'> & {
1511
+ /**
1512
+ * The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
1513
+ * @default process.cwd()
1514
+ */
1515
+ root?: string;
1516
+ /**
1517
+ * An array of parsers used to convert generated files to strings.
1518
+ * Each parser handles specific file extensions (e.g. `.ts`, `.tsx`).
1519
+ *
1520
+ * A catch-all fallback parser is always appended last for any unhandled extension.
1521
+ */
1522
+ parsers?: Array<Parser>;
1523
+ /**
1524
+ * Adapter that converts the input file into a `@kubb/ast` `InputNode`.
1525
+ */
1526
+ adapter?: Adapter;
1527
+ /**
1528
+ * User-facing plugins can be either legacy createPlugin instances or hook-style plugins.
1529
+ */
1530
+ plugins?: Array<Omit<UserPlugin, 'inject'> | HookStylePlugin>;
1531
+ };
1532
+ /**
1533
+ * Handler for a single schema node. Used by the `schema` hook on a plugin.
1534
+ */
1535
+ type SchemaHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: SchemaNode, options: TOptions['resolvedOptions']) => PossiblePromise<unknown | Array<FileNode> | void>;
1536
+ /**
1537
+ * Handler for a single operation node. Used by the `operation` hook on a plugin.
1538
+ */
1539
+ type OperationHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: OperationNode, options: TOptions['resolvedOptions']) => PossiblePromise<unknown | Array<FileNode> | void>;
1540
+ /**
1541
+ * Handler for all collected operation nodes. Used by the `operations` hook on a plugin.
1542
+ */
1543
+ type OperationsHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, nodes: Array<OperationNode>, options: TOptions['resolvedOptions']) => PossiblePromise<unknown | Array<FileNode> | void>;
1544
+ /**
1545
+ * @deprecated will be replaced with HookStylePlugin
1546
+ */
1547
+ type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1548
+ /**
1549
+ * Unique name used for the plugin.
1550
+ *
1551
+ * @example Plugin name
1552
+ * `'@kubb/typescript'`
1553
+ */
1554
+ name: TOptions['name'];
1555
+ /**
1556
+ * Specifies the plugins that the current plugin depends on. The current plugin is executed after all listed plugins.
1557
+ * An error is returned if any required dependency plugin is missing.
1558
+ */
1559
+ dependencies?: Array<string>;
1560
+ /**
1561
+ * Options set for a specific plugin(see kubb.config.js), passthrough of options.
1562
+ */
1563
+ options: TOptions['resolvedOptions'] & {
1564
+ output: Output;
1565
+ include?: Array<Include>;
1566
+ exclude: Array<Exclude$1>;
1567
+ override: Array<Override<TOptions['resolvedOptions']>>;
1568
+ };
1569
+ /**
1570
+ * The resolver for this plugin.
1571
+ * Set via `setResolver()` in `kubb:plugin:setup` or passed as a user option.
1572
+ */
1573
+ resolver: TOptions['resolver'];
1574
+ /**
1575
+ * The composed transformer for this plugin.
1576
+ * Set via `setTransformer()` in `kubb:plugin:setup` or passed as a user option.
1577
+ */
1578
+ transformer?: Visitor;
1579
+ /**
1580
+ * When `apply` is defined, the plugin is only activated when `apply(config)` returns `true`.
1581
+ * Inspired by Vite's `apply` option.
1582
+ */
1583
+ apply?: (config: Config) => boolean;
1584
+ /**
1585
+ * Optional semver version string for this plugin, e.g. `"1.2.3"`.
1586
+ * Used in diagnostic messages and version-conflict detection.
1587
+ */
1588
+ version?: string;
1589
+ /**
1590
+ * Plugin-level renderer factory. All generators that do not declare their own `renderer`
1591
+ * inherit this value. A generator can explicitly opt out by setting `renderer: null`.
1592
+ */
1593
+ renderer?: RendererFactory;
1594
+ /**
1595
+ * Generators declared directly on the plugin. Each generator's `renderer` takes precedence
1596
+ * over `plugin.renderer`; set `renderer: null` on a generator to opt out of rendering even
1597
+ * when the plugin declares a renderer.
1598
+ */
1599
+ generators?: Array<Generator>;
1600
+ buildStart: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1601
+ /**
1602
+ * Called once per plugin after all files have been written to disk.
1603
+ * Use this for post-processing, copying assets, or generating summary reports.
1604
+ */
1605
+ buildEnd: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1606
+ /**
1607
+ * Called for each schema node during the AST walk.
1608
+ * Return a React element, an array of `FileNode`, or `void` for manual handling.
1609
+ * Nodes matching `exclude`/`include` filters are skipped automatically.
1610
+ *
1611
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1612
+ */
1613
+ schema?: SchemaHook<TOptions>;
1614
+ /**
1615
+ * Called for each operation node during the AST walk.
1616
+ * Return a React element, an array of `FileNode`, or `void` for manual handling.
1617
+ *
1618
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1619
+ */
1620
+ operation?: OperationHook<TOptions>;
1621
+ /**
1622
+ * Called once after all operations have been walked, with the full collected set.
1623
+ *
1624
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1625
+ */
1626
+ operations?: OperationsHook<TOptions>;
1627
+ /**
1628
+ * Expose shared helpers or data to all other plugins via `PluginContext`.
1629
+ * The returned object is merged into the context received by every plugin.
1630
+ */
1631
+ inject: (this: PluginContext<TOptions>) => TOptions['context'];
1632
+ };
1633
+ /**
1634
+ * @deprecated
1635
+ */
1636
+ type PluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & PluginLifecycle<TOptions>;
1637
+ /**
1638
+ * @deprecated
1639
+ */
1640
+ type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1641
+ /**
1642
+ * Called once per plugin at the start of its processing phase, before schema/operation/operations hooks run.
1643
+ * Use this to set up shared state, fetch remote data, or perform any async initialization.
1644
+ */
1645
+ buildStart?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1646
+ /**
1647
+ * Called once per plugin after all files have been written to disk.
1648
+ * Use this for post-processing, copying assets, or generating summary reports.
1649
+ */
1650
+ buildEnd?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1651
+ /**
1652
+ * Called for each schema node during the AST walk.
1653
+ * Return a React element (`<File>...</File>`), an array of `FileNode` objects,
1654
+ * or `void` to handle file writing manually via `this.upsertFile`.
1655
+ * Nodes matching `exclude` / `include` filters are skipped automatically.
1656
+ *
1657
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1658
+ */
1659
+ schema?: SchemaHook<TOptions>;
1660
+ /**
1661
+ * Called for each operation node during the AST walk.
1662
+ * Return a React element (`<File>...</File>`), an array of `FileNode` objects,
1663
+ * or `void` to handle file writing manually via `this.upsertFile`.
1664
+ *
1665
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1666
+ */
1667
+ operation?: OperationHook<TOptions>;
1668
+ /**
1669
+ * Called once after all operation nodes have been walked, with the full collection.
1670
+ * Useful for generating index/barrel files per group or aggregate operation handlers.
1671
+ *
1672
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1673
+ */
1674
+ operations?: OperationsHook<TOptions>;
1675
+ /**
1676
+ * Resolves a path from a baseName and directory.
1677
+ * Options can also be included.
1678
+ *
1679
+ * @example
1680
+ * `('./Pet.ts', './src/gen/') => '/src/gen/Pet.ts'`
1681
+ *
1682
+ * @deprecated Use resolvers instead.
1683
+ */
1684
+ resolvePath?: (this: PluginContext<TOptions>, baseName: FileNode['baseName'], mode?: 'single' | 'split', options?: TOptions['resolvePathOptions']) => string;
1685
+ /**
1686
+ * Resolves a display name from a raw string.
1687
+ * Useful when converting to PascalCase or camelCase.
1688
+ *
1689
+ * @example
1690
+ * `('pet') => 'Pet'`
1691
+ *
1692
+ * @deprecated Use resolvers instead.
1693
+ */
1694
+ resolveName?: (this: PluginContext<TOptions>, name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
1695
+ };
1696
+ /**
1697
+ * @deprecated
1698
+ */
1699
+ type PluginLifecycleHooks = keyof PluginLifecycle;
1700
+ type PluginParameter<H extends PluginLifecycleHooks> = Parameters<Required<PluginLifecycle>[H]>;
1701
+ type ResolvePathParams<TOptions = object> = {
1702
+ pluginName?: string;
1703
+ baseName: FileNode['baseName'];
1704
+ mode?: 'single' | 'split';
1705
+ /**
1706
+ * Options passed as the third argument to `resolvePath`.
1707
+ */
1708
+ options?: TOptions;
1709
+ };
1710
+ type ResolveNameParams = {
1711
+ name: string;
1712
+ pluginName?: string;
1713
+ /**
1714
+ * Specifies the type of entity being named.
1715
+ * - `'file'` — customizes the name of the created file (camelCase).
1716
+ * - `'function'` — customizes the exported function names (camelCase).
1717
+ * - `'type'` — customizes TypeScript type names (PascalCase).
1718
+ * - `'const'` — customizes variable names (camelCase).
1719
+ */
1720
+ type?: 'file' | 'function' | 'type' | 'const';
1721
+ };
1722
+ /**
1723
+ * @deprecated
1724
+ */
1725
+ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1726
+ config: Config;
1727
+ /**
1728
+ * Absolute path to the output directory for the current plugin.
1729
+ * Shorthand for `path.resolve(config.root, config.output.path)`.
1730
+ */
1731
+ root: string;
1732
+ /**
1733
+ * Returns the output mode for the given output config.
1734
+ * Returns `'single'` when `output.path` has a file extension, `'split'` otherwise.
1735
+ * Shorthand for `PluginDriver.getMode(path.resolve(this.root, output.path))`.
1736
+ */
1737
+ getMode: (output: {
1738
+ path: string;
1739
+ }) => 'single' | 'split';
1740
+ driver: PluginDriver;
1741
+ /**
1742
+ * Get a plugin by name. Returns the plugin typed via `Kubb.PluginRegistry` when
1743
+ * the name is a registered key, otherwise returns the generic `Plugin`.
1744
+ */
1745
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1746
+ getPlugin(name: string): Plugin | undefined;
1747
+ /**
1748
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1749
+ * Useful for enforcing dependencies inside `buildStart()`.
1750
+ */
1751
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1752
+ requirePlugin(name: string): Plugin;
1753
+ /**
1754
+ * Add files only when they do not exist yet.
1755
+ */
1756
+ addFile: (...file: Array<FileNode>) => Promise<void>;
1757
+ /**
1758
+ * Merge multiple sources into the same output file.
1759
+ */
1760
+ upsertFile: (...file: Array<FileNode>) => Promise<void>;
1761
+ hooks: AsyncEventEmitter<KubbHooks>;
1762
+ /**
1763
+ * The current plugin.
1764
+ */
1765
+ plugin: Plugin<TOptions>;
1766
+ /**
1767
+ * Resolver for the current plugin. Shorthand for `plugin.resolver`.
1768
+ */
1769
+ resolver: TOptions['resolver'];
1770
+ /**
1771
+ * Composed transformer for the current plugin. Shorthand for `plugin.transformer`.
1772
+ * Apply with `transform(node, context.transformer)` to pre-process AST nodes before printing.
1773
+ */
1774
+ transformer: Visitor | undefined;
1775
+ /**
1776
+ * Emit a warning via the build event system.
1777
+ * Shorthand for `this.hooks.emit('kubb:warn', message)`.
1778
+ */
1779
+ warn: (message: string) => void;
1780
+ /**
1781
+ * Emit an error via the build event system.
1782
+ * Shorthand for `this.hooks.emit('kubb:error', error)`.
1783
+ */
1784
+ error: (error: string | Error) => void;
1785
+ /**
1786
+ * Emit an info message via the build event system.
1787
+ * Shorthand for `this.hooks.emit('kubb:info', message)`.
1788
+ */
1789
+ info: (message: string) => void;
1790
+ /**
1791
+ * Opens the Kubb Studio URL for the current `inputNode` in the default browser.
1792
+ * Falls back to printing the URL if the browser cannot be launched.
1793
+ * No-ops silently when no adapter has set an `inputNode`.
1794
+ */
1795
+ openInStudio: (options?: DevtoolsOptions) => Promise<void>;
1796
+ } & ({
1797
+ /**
1798
+ * Returns the universal `@kubb/ast` `InputNode` produced by the configured adapter.
1799
+ * Returns `undefined` when no adapter was set (legacy OAS-only usage).
1800
+ */
1801
+ inputNode: InputNode;
1802
+ /**
1803
+ * The adapter from `@kubb/ast`.
1804
+ */
1805
+ adapter: Adapter;
1806
+ } | {
1807
+ inputNode?: never;
1808
+ adapter?: never;
1809
+ }) & Kubb.PluginContext;
1810
+ /**
1811
+ * Context object passed as the second argument to generator `schema`, `operation`, and
1812
+ * `operations` methods.
1813
+ *
1814
+ * Generators are only invoked from `runPluginAstHooks`, which already guards against a
1815
+ * missing adapter. This type reflects that guarantee — `ctx.adapter` and `ctx.inputNode`
1816
+ * are always defined, so no runtime checks or casts are needed inside generator bodies.
1817
+ *
1818
+ * `ctx.options` carries the per-node resolved options for `schema`/`operation` calls
1819
+ * (after exclude/include/override filtering) and the plugin-level options for `operations`.
1820
+ */
1821
+ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Omit<PluginContext<TOptions>, 'adapter' | 'inputNode'> & {
1822
+ adapter: Adapter;
1823
+ inputNode: InputNode;
1824
+ options: TOptions['resolvedOptions'];
1825
+ };
1826
+ /**
1827
+ * Configure generated file output location and behavior.
1828
+ */
1829
+ type Output<_TOptions = unknown> = {
1830
+ /**
1831
+ * Path to the output folder or file that will contain generated code.
1832
+ */
1833
+ path: string;
1834
+ /**
1835
+ * Define what needs to be exported, here you can also disable the export of barrel files
1836
+ * @default 'named'
1837
+ */
1838
+ barrelType?: BarrelType | false;
1839
+ /**
1840
+ * Text or function appended at the start of every generated file.
1841
+ * When a function, receives the current `InputNode` and must return a string.
1842
+ */
1843
+ banner?: string | ((node?: InputNode) => string);
1844
+ /**
1845
+ * Text or function appended at the end of every generated file.
1846
+ * When a function, receives the current `InputNode` and must return a string.
1847
+ */
1848
+ footer?: string | ((node?: InputNode) => string);
1849
+ /**
1850
+ * Whether to override existing external files if they already exist.
1851
+ * @default false
1852
+ */
1853
+ override?: boolean;
1854
+ };
1855
+ type UserGroup = {
1856
+ /**
1857
+ * Determines how files are grouped into subdirectories.
1858
+ * - `'tag'` groups files by OpenAPI tags.
1859
+ * - `'path'` groups files by OpenAPI paths.
1860
+ */
1861
+ type: 'tag' | 'path';
1862
+ /**
1863
+ * Returns the subdirectory name for a given group value.
1864
+ * Defaults to `${camelCase(group)}Controller` for tags and the first path segment for paths.
1865
+ */
1866
+ name?: (context: {
1867
+ group: string;
1868
+ }) => string;
1869
+ };
1870
+ type Group = {
1871
+ /**
1872
+ * Determines how files are grouped into subdirectories.
1873
+ * - `'tag'` groups files by OpenAPI tags.
1874
+ * - `'path'` groups files by OpenAPI paths.
1875
+ */
1876
+ type: 'tag' | 'path';
1877
+ /**
1878
+ * Returns the subdirectory name for a given group value.
1879
+ */
1880
+ name: (context: {
1881
+ group: string;
1882
+ }) => string;
1883
+ };
1884
+ type LoggerOptions = {
1885
+ /**
1886
+ * @default 3
1887
+ */
1888
+ logLevel: (typeof logLevel)[keyof typeof logLevel];
1889
+ };
1890
+ /**
1891
+ * Shared context passed to all plugins, parsers, and other internals.
1892
+ */
1893
+ type LoggerContext = AsyncEventEmitter<KubbHooks>;
1894
+ type Logger<TOptions extends LoggerOptions = LoggerOptions> = {
1895
+ name: string;
1896
+ install: (context: LoggerContext, options?: TOptions) => void | Promise<void>;
1897
+ };
1898
+ type UserLogger<TOptions extends LoggerOptions = LoggerOptions> = Logger<TOptions>;
1899
+ /**
1900
+ * Compatibility preset for code generation tools.
1901
+ * - `'default'` – no compatibility adjustments (default behavior).
1902
+ * - `'kubbV4'` – align generated names and structures with Kubb v4 output.
1903
+ */
1904
+ type CompatibilityPreset = 'default' | 'kubbV4';
1905
+ /**
1906
+ * Context passed to a hook-style plugin's `kubb:plugin:setup` handler.
1907
+ * Provides methods to register generators, configure the resolver, transformer,
1908
+ * and renderer, as well as access to the current build configuration.
1909
+ */
1910
+ type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1911
+ /**
1912
+ * Register a generator on this plugin. Generators are invoked during the AST walk
1913
+ * (schema/operation/operations) exactly like generators declared statically on `createPlugin`.
1914
+ */
1915
+ addGenerator<TElement = unknown>(generator: Generator<TFactory, TElement>): void;
1916
+ /**
1917
+ * Set or partially override the resolver for this plugin.
1918
+ * The resolver controls file naming and path resolution for generated files.
1919
+ *
1920
+ * When `TFactory` is a concrete `PluginFactoryOptions` (e.g. `PluginClient`),
1921
+ * the resolver parameter is typed to the plugin's own resolver type (e.g. `ResolverClient`).
1922
+ */
1923
+ setResolver(resolver: Partial<TFactory['resolver']>): void;
1924
+ /**
1925
+ * Set the AST transformer (visitor) for this plugin.
1926
+ * The transformer pre-processes nodes before they reach the generators.
1927
+ */
1928
+ setTransformer(visitor: Visitor): void;
1929
+ /**
1930
+ * Set the renderer factory for this plugin.
1931
+ * Used to process JSX elements returned by generators.
1932
+ */
1933
+ setRenderer(renderer: RendererFactory): void;
1934
+ /**
1935
+ * Set the resolved options for the build loop. These options are merged into the
1936
+ * normalized plugin's `options` object (which includes `output`, `exclude`, `override`).
1937
+ *
1938
+ * Call this in `kubb:plugin:setup` to provide the resolved options that generators
1939
+ * and the build loop need (e.g., `enumType`, `optionalType`, `group`).
1940
+ */
1941
+ setOptions(options: TFactory['resolvedOptions']): void;
1942
+ /**
1943
+ * Inject a raw file into the build output, bypassing the normal generation pipeline.
1944
+ */
1945
+ injectFile(file: Pick<FileNode, 'baseName' | 'path'> & {
1946
+ sources?: FileNode['sources'];
1947
+ }): void;
1948
+ /**
1949
+ * Merge a partial config update into the current build configuration.
1950
+ */
1951
+ updateConfig(config: Partial<Config>): void;
1952
+ /**
1953
+ * The resolved build configuration at the time of setup.
1954
+ */
1955
+ config: Config;
1956
+ /**
1957
+ * The plugin's own options as passed by the user.
1958
+ */
1959
+ options: TFactory['options'];
1960
+ };
1961
+ /**
1962
+ * Context passed to a hook-style plugin's `kubb:build:start` handler.
1963
+ * Fires immediately before the plugin execution loop begins.
1964
+ */
1965
+ type KubbBuildStartContext = {
1966
+ config: Config;
1967
+ adapter: Adapter;
1968
+ inputNode: InputNode;
1969
+ getPlugin(name: string): Plugin | undefined;
1970
+ };
1971
+ /**
1972
+ * Context passed to a hook-style plugin's `kubb:build:end` handler.
1973
+ * Fires after all files have been written to disk.
1974
+ */
1975
+ type KubbBuildEndContext = {
1976
+ files: Array<FileNode>;
1977
+ config: Config;
1978
+ outputDir: string;
1979
+ };
1980
+ type ByTag = {
1981
+ type: 'tag';
1982
+ pattern: string | RegExp;
1983
+ };
1984
+ type ByOperationId = {
1985
+ type: 'operationId';
1986
+ pattern: string | RegExp;
1987
+ };
1988
+ type ByPath = {
1989
+ type: 'path';
1990
+ pattern: string | RegExp;
1991
+ };
1992
+ type ByMethod = {
1993
+ type: 'method';
1994
+ pattern: HttpMethod | RegExp;
1995
+ };
1996
+ type BySchemaName = {
1997
+ type: 'schemaName';
1998
+ pattern: string | RegExp;
1999
+ };
2000
+ type ByContentType = {
2001
+ type: 'contentType';
2002
+ pattern: string | RegExp;
2003
+ };
2004
+ /**
2005
+ * A pattern filter that prevents matching nodes from being generated.
2006
+ * Match by `tag`, `operationId`, `path`, `method`, `contentType`, or `schemaName`.
2007
+ */
2008
+ type Exclude$1 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
2009
+ /**
2010
+ * A pattern filter that restricts generation to only matching nodes.
2011
+ * Match by `tag`, `operationId`, `path`, `method`, `contentType`, or `schemaName`.
2012
+ */
2013
+ type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
2014
+ /**
2015
+ * A pattern filter paired with partial option overrides applied when the pattern matches.
2016
+ * Match by `tag`, `operationId`, `path`, `method`, `schemaName`, or `contentType`.
2017
+ */
2018
+ type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
2019
+ options: Partial<TOptions>;
2020
+ };
2021
+ type ResolvePathOptions = {
2022
+ pluginName?: string;
2023
+ group?: {
2024
+ tag?: string;
2025
+ path?: string;
2026
+ };
2027
+ type?: ResolveNameParams['type'];
2028
+ };
2029
+ /**
2030
+ * File-specific parameters for `Resolver.resolvePath`.
2031
+ *
2032
+ * Pass alongside a `ResolverContext` to identify which file to resolve.
2033
+ * Provide `tag` for tag-based grouping or `path` for path-based grouping.
2034
+ *
2035
+ * @example
2036
+ * ```ts
2037
+ * resolver.resolvePath(
2038
+ * { baseName: 'petTypes.ts', tag: 'pets' },
2039
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
2040
+ * )
2041
+ * // → '/src/types/petsController/petTypes.ts'
2042
+ * ```
2043
+ */
2044
+ type ResolverPathParams = {
2045
+ baseName: FileNode['baseName'];
2046
+ pathMode?: 'single' | 'split';
2047
+ /**
2048
+ * Tag value used when `group.type === 'tag'`.
2049
+ */
2050
+ tag?: string;
2051
+ /**
2052
+ * Path value used when `group.type === 'path'`.
2053
+ */
2054
+ path?: string;
2055
+ };
2056
+ /**
2057
+ * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.
2058
+ *
2059
+ * Describes where on disk output is rooted, which output config is active, and the optional
2060
+ * grouping strategy that controls subdirectory layout.
2061
+ *
2062
+ * @example
2063
+ * ```ts
2064
+ * const context: ResolverContext = {
2065
+ * root: config.root,
2066
+ * output,
2067
+ * group,
2068
+ * }
2069
+ * ```
2070
+ */
2071
+ type ResolverContext = {
2072
+ root: string;
2073
+ output: Output;
2074
+ group?: Group;
2075
+ /**
2076
+ * Plugin name used to populate `meta.pluginName` on the resolved file.
2077
+ */
2078
+ pluginName?: string;
2079
+ };
2080
+ /**
2081
+ * File-specific parameters for `Resolver.resolveFile`.
2082
+ *
2083
+ * Pass alongside a `ResolverContext` to fully describe the file to resolve.
2084
+ * `tag` and `path` are used only when a matching `group` is present in the context.
2085
+ *
2086
+ * @example
2087
+ * ```ts
2088
+ * resolver.resolveFile(
2089
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
2090
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
2091
+ * )
2092
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
2093
+ * ```
2094
+ */
2095
+ type ResolverFileParams = {
2096
+ name: string;
2097
+ extname: FileNode['extname'];
2098
+ /**
2099
+ * Tag value used when `group.type === 'tag'`.
2100
+ */
2101
+ tag?: string;
2102
+ /**
2103
+ * Path value used when `group.type === 'path'`.
2104
+ */
2105
+ path?: string;
2106
+ };
2107
+ /**
2108
+ * Context passed to `Resolver.resolveBanner` and `Resolver.resolveFooter`.
2109
+ *
2110
+ * `output` is optional — not every plugin configures a banner/footer.
2111
+ * `config` carries the global Kubb config, used to derive the default Kubb banner.
2112
+ *
2113
+ * @example
2114
+ * ```ts
2115
+ * resolver.resolveBanner(inputNode, { output: { banner: '// generated' }, config })
2116
+ * // → '// generated'
2117
+ * ```
2118
+ */
2119
+ type ResolveBannerContext = {
2120
+ output?: Pick<Output, 'banner' | 'footer'>;
2121
+ config: Config;
2122
+ };
2123
+ /**
2124
+ * CLI options derived from command-line flags.
2125
+ */
2126
+ type CLIOptions = {
2127
+ /**
2128
+ * Path to `kubb.config.js`.
2129
+ */
2130
+ config?: string;
2131
+ /**
2132
+ * Enable watch mode for input files.
2133
+ */
2134
+ watch?: boolean;
2135
+ /**
2136
+ * Logging verbosity for CLI usage.
2137
+ * @default 'silent'
2138
+ */
2139
+ logLevel?: 'silent' | 'info' | 'debug';
2140
+ };
2141
+ /**
2142
+ * All accepted forms of a Kubb configuration.
2143
+ *
2144
+ * Config is always `@kubb/core` {@link Config}.
2145
+ * - `PossibleConfig` accepts `Config`/`Config[]`/promise or a no-arg config factory.
2146
+ * - `PossibleConfig<TCliOptions>` accepts the same config forms or a config factory receiving `TCliOptions`.
2147
+ */
2148
+ type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Config[]> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>);
2149
+ //#endregion
2150
+ export { KubbHooks as $, PluginParameter as A, ResolverFileParams as B, Output as C, PluginFactoryOptions as D, PluginContext as E, ResolveOptionsContext as F, UserLogger as G, SchemaHook as H, ResolvePathOptions as I, FileMetaBase as J, UserPlugin as K, ResolvePathParams as L, PossibleConfig as M, ResolveBannerContext as N, PluginLifecycle as O, ResolveNameParams as P, Kubb$1 as Q, Resolver as R, OperationsHook as S, Plugin as T, UserConfig as U, ResolverPathParams as V, UserGroup as W, PluginHooks as X, HookStylePlugin as Y, definePlugin as Z, KubbPluginSetupContext as _, CLIOptions as a, defineParser as at, LoggerOptions as b, DevtoolsOptions as c, Storage as ct, Group as d, RendererFactory as dt, BuildOutput as et, Include as f, createRenderer as ft, KubbBuildStartContext as g, KubbBuildEndContext as h, BarrelType as i, Parser as it, PluginWithLifeCycle as j, PluginLifecycleHooks as k, Exclude$1 as l, createStorage as lt, InputPath as m, AsyncEventEmitter as mt, AdapterFactoryOptions as n, PluginDriver as nt, CompatibilityPreset as o, Generator as ot, InputData as p, logLevel as pt, UserPluginWithLifeCycle as q, AdapterSource as r, FileManager as rt, Config as s, defineGenerator as st, Adapter as t, createKubb as tt, GeneratorContext as u, Renderer as ut, Logger as v, Override as w, OperationHook as x, LoggerContext as y, ResolverContext as z };
2151
+ //# sourceMappingURL=types-C6NCtNqM.d.ts.map