@kubb/core 5.0.0-alpha.33 → 5.0.0-alpha.35

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.
@@ -1,7 +1,6 @@
1
1
  import { t as __name } from "./chunk--u3MIqq1.js";
2
- import { FileNode, ImportNode, InputNode, Node, OperationNode, Printer, Printer as Printer$1, PrinterFactoryOptions, PrinterPartial, SchemaNode, Visitor } from "@kubb/ast/types";
2
+ import { FileNode, ImportNode, InputNode, Node, OperationNode, SchemaNode, Visitor } from "@kubb/ast";
3
3
  import { HttpMethod } from "@kubb/oas";
4
- import { KubbReactNode } from "@kubb/renderer-jsx/types";
5
4
 
6
5
  //#region ../../internals/utils/src/asyncEventEmitter.d.ts
7
6
  /**
@@ -63,6 +62,16 @@ declare class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[
63
62
  * ```
64
63
  */
65
64
  off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
65
+ /**
66
+ * Returns the number of listeners registered for `eventName`.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * emitter.on('build', handler)
71
+ * emitter.listenerCount('build') // 1
72
+ * ```
73
+ */
74
+ listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number;
66
75
  /**
67
76
  * Removes all listeners from every event channel.
68
77
  *
@@ -86,43 +95,58 @@ declare class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[
86
95
  */
87
96
  type PossiblePromise<T> = Promise<T> | T;
88
97
  //#endregion
89
- //#region src/FileManager.d.ts
98
+ //#region src/createRenderer.d.ts
90
99
  /**
91
- * In-memory file store for generated files.
100
+ * Minimal interface any Kubb renderer must satisfy.
92
101
  *
93
- * Files with the same `path` are merged sources, imports, and exports are concatenated.
94
- * The `files` getter returns all stored files sorted by path length (shortest first).
102
+ * The generic `TElement` is the type of the element the renderer accepts —
103
+ * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for
104
+ * your own renderer. Defaults to `unknown` so that generators which do not
105
+ * care about the element type continue to work without specifying it.
106
+ *
107
+ * This allows core to drive rendering without a hard dependency on
108
+ * `@kubb/renderer-jsx` or any specific renderer implementation.
109
+ */
110
+ type Renderer<TElement = unknown> = {
111
+ render(element: TElement): Promise<void>;
112
+ unmount(error?: Error | number | null): void;
113
+ readonly files: Array<FileNode>;
114
+ };
115
+ /**
116
+ * A factory function that produces a fresh {@link Renderer} per render.
117
+ *
118
+ * Generators use this to declare which renderer handles their output.
119
+ */
120
+ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
121
+ /**
122
+ * Creates a renderer factory for use in generator definitions.
123
+ *
124
+ * Wrap your renderer factory function with this helper to register it as the
125
+ * renderer for a generator. Core will call this factory once per render cycle
126
+ * to obtain a fresh renderer instance.
95
127
  *
96
128
  * @example
97
129
  * ```ts
98
- * import { FileManager } from '@kubb/core'
130
+ * // packages/renderer-jsx/src/index.ts
131
+ * export const jsxRenderer = createRenderer(() => {
132
+ * const runtime = new Runtime()
133
+ * return {
134
+ * async render(element) { await runtime.render(element) },
135
+ * get files() { return runtime.nodes },
136
+ * unmount(error) { runtime.unmount(error) },
137
+ * }
138
+ * })
99
139
  *
100
- * const manager = new FileManager()
101
- * manager.upsert(myFile)
102
- * console.log(manager.files) // all stored files
140
+ * // packages/plugin-zod/src/generators/zodGenerator.tsx
141
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
142
+ * export const zodGenerator = defineGenerator<PluginZod>({
143
+ * name: 'zod',
144
+ * renderer: jsxRenderer,
145
+ * schema(node, options) { return <File ...>...</File> },
146
+ * })
103
147
  * ```
104
148
  */
105
- declare class FileManager {
106
- #private;
107
- /**
108
- * Adds one or more files. Files with the same path are merged — sources, imports,
109
- * and exports from all calls with the same path are concatenated together.
110
- */
111
- add(...files: Array<FileNode>): Array<FileNode>;
112
- /**
113
- * Adds or merges one or more files.
114
- * If a file with the same path already exists, its sources/imports/exports are merged together.
115
- */
116
- upsert(...files: Array<FileNode>): Array<FileNode>;
117
- getByPath(path: string): FileNode | null;
118
- deleteByPath(path: string): void;
119
- clear(): void;
120
- /**
121
- * All stored files, sorted by path length (shorter paths first).
122
- * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
123
- */
124
- get files(): Array<FileNode>;
125
- }
149
+ declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
126
150
  //#endregion
127
151
  //#region src/constants.d.ts
128
152
  /**
@@ -248,80 +272,6 @@ type Storage = {
248
272
  */
249
273
  declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
250
274
  //#endregion
251
- //#region src/defineGenerator.d.ts
252
- /**
253
- * A generator is a named object with optional `schema`, `operation`, and `operations`
254
- * methods. Each method is called with `this = PluginContext` of the parent plugin,
255
- * giving full access to `this.config`, `this.resolver`, `this.adapter`,
256
- * `this.driver`, etc.
257
- *
258
- * Return a React element, an array of `FileNode`, or `void` to handle file
259
- * writing manually via `this.upsertFile`. Both React and core (non-React) generators
260
- * use the same method signatures — the return type determines how output is handled.
261
- *
262
- * @example
263
- * ```ts
264
- * export const typeGenerator = defineGenerator<PluginTs>({
265
- * name: 'typescript',
266
- * schema(node, options) {
267
- * const { adapter, resolver, root } = this
268
- * return <File ...><Type node={node} resolver={resolver} /></File>
269
- * },
270
- * operation(node, options) {
271
- * return <File ...><OperationType node={node} /></File>
272
- * },
273
- * })
274
- * ```
275
- */
276
- type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
277
- /** Used in diagnostic messages and debug output. */name: string;
278
- /**
279
- * Called for each schema node in the AST walk.
280
- * `this` is the parent plugin's context with `adapter` and `inputNode` guaranteed present.
281
- * `options` contains the per-node resolved options (after exclude/include/override).
282
- */
283
- schema?: (this: GeneratorContext<TOptions>, node: SchemaNode, options: TOptions['resolvedOptions']) => PossiblePromise<KubbReactNode | Array<FileNode> | void>;
284
- /**
285
- * Called for each operation node in the AST walk.
286
- * `this` is the parent plugin's context with `adapter` and `inputNode` guaranteed present.
287
- */
288
- operation?: (this: GeneratorContext<TOptions>, node: OperationNode, options: TOptions['resolvedOptions']) => PossiblePromise<KubbReactNode | Array<FileNode> | void>;
289
- /**
290
- * Called once after all operations have been walked.
291
- * `this` is the parent plugin's context with `adapter` and `inputNode` guaranteed present.
292
- */
293
- operations?: (this: GeneratorContext<TOptions>, nodes: Array<OperationNode>, options: TOptions['resolvedOptions']) => PossiblePromise<KubbReactNode | Array<FileNode> | void>;
294
- };
295
- /**
296
- * Defines a generator. Returns the object as-is with correct `this` typings.
297
- * No type discrimination (`type: 'react' | 'core'`) needed — `applyHookResult`
298
- * handles React elements and `File[]` uniformly.
299
- */
300
- declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generator: Generator<TOptions>): Generator<TOptions>;
301
- /**
302
- * Merges an array of generators into a single generator.
303
- *
304
- * The merged generator's `schema`, `operation`, and `operations` methods run
305
- * the corresponding method from each input generator in sequence, applying each
306
- * result via `applyHookResult`. This eliminates the need to write the loop
307
- * manually in each plugin.
308
- *
309
- * @param generators - Array of generators to merge into a single generator.
310
- *
311
- * @example
312
- * ```ts
313
- * const merged = mergeGenerators(generators)
314
- *
315
- * return {
316
- * name: pluginName,
317
- * schema: merged.schema,
318
- * operation: merged.operation,
319
- * operations: merged.operations,
320
- * }
321
- * ```
322
- */
323
- declare function mergeGenerators<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generators: Array<Generator<TOptions>>): Generator<TOptions>;
324
- //#endregion
325
275
  //#region src/defineParser.d.ts
326
276
  type PrintOptions = {
327
277
  extname?: FileNode['extname'];
@@ -332,7 +282,8 @@ type Parser<TMeta extends object = any> = {
332
282
  * File extensions this parser handles.
333
283
  * Use `undefined` to create a catch-all fallback parser.
334
284
  *
335
- * @example ['.ts', '.js']
285
+ * @example Handled extensions
286
+ * `['.ts', '.js']`
336
287
  */
337
288
  extNames: Array<FileNode['extname']> | undefined;
338
289
  /**
@@ -362,6 +313,54 @@ type Parser<TMeta extends object = any> = {
362
313
  */
363
314
  declare function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta>;
364
315
  //#endregion
316
+ //#region src/createKubb.d.ts
317
+ /**
318
+ * Full output produced by a successful or failed build.
319
+ */
320
+ type BuildOutput = {
321
+ /**
322
+ * Plugins that threw during installation, paired with the caught error.
323
+ */
324
+ failedPlugins: Set<{
325
+ plugin: Plugin;
326
+ error: Error;
327
+ }>;
328
+ files: Array<FileNode>;
329
+ driver: PluginDriver;
330
+ /**
331
+ * Elapsed time in milliseconds for each plugin, keyed by plugin name.
332
+ */
333
+ pluginTimings: Map<string, number>;
334
+ error?: Error;
335
+ /**
336
+ * Raw generated source, keyed by absolute file path.
337
+ */
338
+ sources: Map<string, string>;
339
+ };
340
+ type KubbOptions = {
341
+ config: Config;
342
+ hooks?: AsyncEventEmitter<KubbHooks>;
343
+ };
344
+ /**
345
+ * Creates a Kubb instance bound to a single config entry.
346
+ *
347
+ * The instance holds shared state (`hooks`, `sources`, `driver`, `config`) across the
348
+ * `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
349
+ * calling `setup()` or `build()`.
350
+ *
351
+ * @example
352
+ * ```ts
353
+ * const kubb = createKubb({ config })
354
+ *
355
+ * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {
356
+ * console.log(`${plugin.name} completed in ${duration}ms`)
357
+ * })
358
+ *
359
+ * const { files, failedPlugins } = await kubb.safeBuild()
360
+ * ```
361
+ */
362
+ declare function createKubb(options: KubbOptions): Kubb$1;
363
+ //#endregion
365
364
  //#region src/Kubb.d.ts
366
365
  type DebugInfo = {
367
366
  date: Date;
@@ -387,6 +386,46 @@ type HookResult<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
387
386
  parameters?: Array<unknown>;
388
387
  output?: unknown;
389
388
  };
389
+ /**
390
+ * The instance returned by {@link createKubb}.
391
+ */
392
+ type Kubb$1 = {
393
+ /**
394
+ * The shared event emitter. Attach listeners here before calling `setup()` or `build()`.
395
+ */
396
+ readonly hooks: AsyncEventEmitter<KubbHooks>;
397
+ /**
398
+ * Raw generated source, keyed by absolute file path.
399
+ * Populated after a successful `build()` or `safeBuild()` call.
400
+ */
401
+ readonly sources: Map<string, string>;
402
+ /**
403
+ * The plugin driver. Available after `setup()` has been called.
404
+ */
405
+ readonly driver: PluginDriver | undefined;
406
+ /**
407
+ * The resolved config with applied defaults. Available after `setup()` has been called.
408
+ */
409
+ readonly config: Config | undefined;
410
+ /**
411
+ * Initializes all Kubb infrastructure: validates input, applies config defaults,
412
+ * runs the adapter, and creates the PluginDriver.
413
+ *
414
+ * Calling `build()` or `safeBuild()` without calling `setup()` first will
415
+ * automatically invoke `setup()` before proceeding.
416
+ */
417
+ setup(): Promise<void>;
418
+ /**
419
+ * Runs a full Kubb build and throws on any error or plugin failure.
420
+ * Automatically calls `setup()` if it has not been called yet.
421
+ */
422
+ build(): Promise<BuildOutput>;
423
+ /**
424
+ * Runs a full Kubb build and captures errors instead of throwing.
425
+ * Automatically calls `setup()` if it has not been called yet.
426
+ */
427
+ safeBuild(): Promise<BuildOutput>;
428
+ };
390
429
  /**
391
430
  * Events emitted during the Kubb code generation lifecycle.
392
431
  * These events can be listened to for logging, progress tracking, and custom integrations.
@@ -394,49 +433,49 @@ type HookResult<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
394
433
  * @example
395
434
  * ```typescript
396
435
  * import type { AsyncEventEmitter } from '@internals/utils'
397
- * import type { KubbEvents } from '@kubb/core'
436
+ * import type { KubbHooks } from '@kubb/core'
398
437
  *
399
- * const events: AsyncEventEmitter<KubbEvents> = new AsyncEventEmitter()
438
+ * const hooks: AsyncEventEmitter<KubbHooks> = new AsyncEventEmitter()
400
439
  *
401
- * events.on('lifecycle:start', () => {
440
+ * hooks.on('kubb:lifecycle:start', () => {
402
441
  * console.log('Starting Kubb generation')
403
442
  * })
404
443
  *
405
- * events.on('plugin:end', (plugin, { duration }) => {
444
+ * hooks.on('kubb:plugin:end', (plugin, { duration }) => {
406
445
  * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)
407
446
  * })
408
447
  * ```
409
448
  */
410
- interface KubbEvents {
449
+ interface KubbHooks {
411
450
  /**
412
451
  * Emitted at the beginning of the Kubb lifecycle, before any code generation starts.
413
452
  */
414
- 'lifecycle:start': [version: string];
453
+ 'kubb:lifecycle:start': [version: string];
415
454
  /**
416
455
  * Emitted at the end of the Kubb lifecycle, after all code generation is complete.
417
456
  */
418
- 'lifecycle:end': [];
457
+ 'kubb:lifecycle:end': [];
419
458
  /**
420
459
  * Emitted when configuration loading starts.
421
460
  */
422
- 'config:start': [];
461
+ 'kubb:config:start': [];
423
462
  /**
424
463
  * Emitted when configuration loading is complete.
425
464
  */
426
- 'config:end': [configs: Array<Config>];
465
+ 'kubb:config:end': [configs: Array<Config>];
427
466
  /**
428
467
  * Emitted when code generation phase starts.
429
468
  */
430
- 'generation:start': [config: Config];
469
+ 'kubb:generation:start': [config: Config];
431
470
  /**
432
471
  * Emitted when code generation phase completes.
433
472
  */
434
- 'generation:end': [config: Config, files: Array<FileNode>, sources: Map<string, string>];
473
+ 'kubb:generation:end': [config: Config, files: Array<FileNode>, sources: Map<string, string>];
435
474
  /**
436
475
  * Emitted with a summary of the generation results.
437
476
  * Contains summary lines, title, and success status.
438
477
  */
439
- 'generation:summary': [config: Config, {
478
+ 'kubb:generation:summary': [config: Config, {
440
479
  failedPlugins: Set<{
441
480
  plugin: Plugin;
442
481
  error: Error;
@@ -449,32 +488,32 @@ interface KubbEvents {
449
488
  /**
450
489
  * Emitted when code formatting starts (e.g., running Biome or Prettier).
451
490
  */
452
- 'format:start': [];
491
+ 'kubb:format:start': [];
453
492
  /**
454
493
  * Emitted when code formatting completes.
455
494
  */
456
- 'format:end': [];
495
+ 'kubb:format:end': [];
457
496
  /**
458
497
  * Emitted when linting starts.
459
498
  */
460
- 'lint:start': [];
499
+ 'kubb:lint:start': [];
461
500
  /**
462
501
  * Emitted when linting completes.
463
502
  */
464
- 'lint:end': [];
503
+ 'kubb:lint:end': [];
465
504
  /**
466
505
  * Emitted when plugin hooks execution starts.
467
506
  */
468
- 'hooks:start': [];
507
+ 'kubb:hooks:start': [];
469
508
  /**
470
509
  * Emitted when plugin hooks execution completes.
471
510
  */
472
- 'hooks:end': [];
511
+ 'kubb:hooks:end': [];
473
512
  /**
474
513
  * Emitted when a single hook execution starts (e.g., format or lint).
475
514
  * The callback should be invoked when the command completes.
476
515
  */
477
- 'hook:start': [{
516
+ 'kubb:hook:start': [{
478
517
  id?: string;
479
518
  command: string;
480
519
  args?: readonly string[];
@@ -482,7 +521,7 @@ interface KubbEvents {
482
521
  /**
483
522
  * Emitted when a single hook execution completes.
484
523
  */
485
- 'hook:end': [{
524
+ 'kubb:hook:end': [{
486
525
  id?: string;
487
526
  command: string;
488
527
  args?: readonly string[];
@@ -492,38 +531,38 @@ interface KubbEvents {
492
531
  /**
493
532
  * Emitted when a new version of Kubb is available.
494
533
  */
495
- 'version:new': [currentVersion: string, latestVersion: string];
534
+ 'kubb:version:new': [currentVersion: string, latestVersion: string];
496
535
  /**
497
536
  * Informational message event.
498
537
  */
499
- info: [message: string, info?: string];
538
+ 'kubb:info': [message: string, info?: string];
500
539
  /**
501
540
  * Error event. Emitted when an error occurs during code generation.
502
541
  */
503
- error: [error: Error, meta?: Record<string, unknown>];
542
+ 'kubb:error': [error: Error, meta?: Record<string, unknown>];
504
543
  /**
505
544
  * Success message event.
506
545
  */
507
- success: [message: string, info?: string];
546
+ 'kubb:success': [message: string, info?: string];
508
547
  /**
509
548
  * Warning message event.
510
549
  */
511
- warn: [message: string, info?: string];
550
+ 'kubb:warn': [message: string, info?: string];
512
551
  /**
513
552
  * Debug event for detailed logging.
514
553
  * Contains timestamp, log messages, and optional filename.
515
554
  */
516
- debug: [info: DebugInfo];
555
+ 'kubb:debug': [info: DebugInfo];
517
556
  /**
518
557
  * Emitted when file processing starts.
519
558
  * Contains the list of files to be processed.
520
559
  */
521
- 'files:processing:start': [files: Array<FileNode>];
560
+ 'kubb:files:processing:start': [files: Array<FileNode>];
522
561
  /**
523
562
  * Emitted for each file being processed, providing progress updates.
524
563
  * Contains processed count, total count, percentage, and file details.
525
564
  */
526
- 'file:processing:update': [{
565
+ 'kubb:file:processing:update': [{
527
566
  /**
528
567
  * Number of files processed so far.
529
568
  */
@@ -554,16 +593,16 @@ interface KubbEvents {
554
593
  * Emitted when file processing completes.
555
594
  * Contains the list of processed files.
556
595
  */
557
- 'files:processing:end': [files: Array<FileNode>];
596
+ 'kubb:files:processing:end': [files: Array<FileNode>];
558
597
  /**
559
598
  * Emitted when a plugin starts executing.
560
599
  */
561
- 'plugin:start': [plugin: Plugin];
600
+ 'kubb:plugin:start': [plugin: Plugin];
562
601
  /**
563
602
  * Emitted when a plugin completes execution.
564
603
  * Duration in ms.
565
604
  */
566
- 'plugin:end': [plugin: Plugin, result: {
605
+ 'kubb:plugin:end': [plugin: Plugin, result: {
567
606
  duration: number;
568
607
  success: boolean;
569
608
  error?: Error;
@@ -572,70 +611,161 @@ interface KubbEvents {
572
611
  * Emitted when plugin hook progress tracking starts.
573
612
  * Contains the hook name and list of plugins to execute.
574
613
  */
575
- 'plugins:hook:progress:start': [progress: HookProgress];
614
+ 'kubb:plugins:hook:progress:start': [progress: HookProgress];
576
615
  /**
577
616
  * Emitted when plugin hook progress tracking ends.
578
617
  * Contains the hook name that completed.
579
618
  */
580
- 'plugins:hook:progress:end': [{
619
+ 'kubb:plugins:hook:progress:end': [{
581
620
  hookName: PluginLifecycleHooks;
582
621
  }];
583
622
  /**
584
623
  * Emitted when a plugin hook starts processing.
585
624
  * Contains strategy, hook name, plugin, parameters, and output.
586
625
  */
587
- 'plugins:hook:processing:start': [execution: HookExecution];
626
+ 'kubb:plugins:hook:processing:start': [execution: HookExecution];
588
627
  /**
589
628
  * Emitted when a plugin hook completes processing.
590
629
  * Contains duration, strategy, hook name, plugin, parameters, and output.
591
630
  */
592
- 'plugins:hook:processing:end': [result: HookResult];
631
+ 'kubb:plugins:hook:processing:end': [result: HookResult];
632
+ /**
633
+ * Fired once — before any plugin's `buildStart` runs — so that hook-style plugins
634
+ * can register generators, configure resolvers/transformers/renderers, or inject
635
+ * extra files. All `kubb:plugin:setup` handlers registered via `definePlugin` receive
636
+ * a plugin-specific context (with the correct `addGenerator` closure).
637
+ * External tooling can observe this event via `hooks.on('kubb:plugin:setup', …)`.
638
+ */
639
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
640
+ /**
641
+ * Fired immediately before the plugin execution loop begins.
642
+ * The adapter has already parsed the source and `inputNode` is available.
643
+ */
644
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
645
+ /**
646
+ * Fired after all files have been written to disk.
647
+ */
648
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
649
+ /**
650
+ * Emitted for each schema node during the AST walk.
651
+ * Generator listeners registered via `addGenerator()` in `kubb:plugin:setup` respond to this event.
652
+ * The `ctx.plugin.name` identifies which plugin is driving the current walk.
653
+ * `ctx.options` carries the per-node resolved options (after exclude/include/override).
654
+ */
655
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
656
+ /**
657
+ * Emitted for each operation node during the AST walk.
658
+ * Generator listeners registered via `addGenerator()` in `kubb:plugin:setup` respond to this event.
659
+ * The `ctx.plugin.name` identifies which plugin is driving the current walk.
660
+ * `ctx.options` carries the per-node resolved options (after exclude/include/override).
661
+ */
662
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
663
+ /**
664
+ * Emitted once after all operations have been walked, with the full collected array.
665
+ * Generator listeners with an `operations()` method respond to this event.
666
+ * The `ctx.plugin.name` identifies which plugin is driving the current walk.
667
+ * `ctx.options` carries the plugin-level resolved options for the batch call.
668
+ */
669
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
670
+ }
671
+ declare global {
672
+ namespace Kubb {
673
+ interface PluginContext {}
674
+ /**
675
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
676
+ * Augment this interface in each plugin's `types.ts` to enable automatic
677
+ * typing for `getPlugin` and `requirePlugin`.
678
+ *
679
+ * @example
680
+ * ```ts
681
+ * // packages/plugin-ts/src/types.ts
682
+ * declare global {
683
+ * namespace Kubb {
684
+ * interface PluginRegistry {
685
+ * 'plugin-ts': PluginTs
686
+ * }
687
+ * }
688
+ * }
689
+ * ```
690
+ */
691
+ interface PluginRegistry {}
692
+ }
593
693
  }
594
694
  //#endregion
595
- //#region src/defineConfig.d.ts
695
+ //#region src/definePlugin.d.ts
596
696
  /**
597
- * CLI options derived from command-line flags.
697
+ * Base hook handlers for all events except `kubb:plugin:setup`.
698
+ * These handlers have identical signatures regardless of the plugin's
699
+ * `PluginFactoryOptions` generic — they are split out so that the
700
+ * interface below only needs to override the one event that depends on
701
+ * the plugin type.
598
702
  */
599
- type CLIOptions = {
703
+ type PluginHooksBase = { [K in Exclude<keyof KubbHooks, 'kubb:plugin:setup'>]?: (...args: KubbHooks[K]) => void | Promise<void> };
704
+ /**
705
+ * Plugin hook handlers.
706
+ *
707
+ * `kubb:plugin:setup` is typed with the plugin's own `PluginFactoryOptions` so
708
+ * `ctx.setResolver`, `ctx.setOptions`, `ctx.options` etc. use the correct types.
709
+ *
710
+ * Uses interface + method shorthand for `kubb:plugin:setup`
711
+ * checking, allowing `PluginHooks<PluginTs>` to be assignable to `PluginHooks`.
712
+ *
713
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
714
+ */
715
+ interface PluginHooks<TFactory extends PluginFactoryOptions = PluginFactoryOptions> extends PluginHooksBase {
716
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
717
+ }
718
+ /**
719
+ * A hook-style plugin object produced by `definePlugin`.
720
+ * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property
721
+ * (matching Astro's integration naming convention).
722
+ *
723
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
724
+ */
725
+ type HookStylePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
600
726
  /**
601
- * Path to `kubb.config.js`.
727
+ * Unique name for the plugin, following the same naming convention as `createPlugin`.
602
728
  */
603
- config?: string;
729
+ name: string;
604
730
  /**
605
- * Enable watch mode for input files.
731
+ * Plugins that must be registered before this plugin executes.
732
+ * An error is thrown at startup when any listed dependency is missing.
606
733
  */
607
- watch?: boolean;
734
+ dependencies?: Array<string>;
608
735
  /**
609
- * Logging verbosity for CLI usage.
610
- *
611
- * - `silent`: hide non-essential logs
612
- * - `info`: show general logs (non-plugin-related)
613
- * - `debug`: include detailed plugin lifecycle logs
614
- * @default 'silent'
736
+ * The options passed by the user when calling the plugin factory.
615
737
  */
616
- logLevel?: 'silent' | 'info' | 'debug';
738
+ options?: TFactory['options'];
739
+ /**
740
+ * Lifecycle event handlers for this plugin.
741
+ * Any event from the global `KubbHooks` map can be subscribed to here.
742
+ */
743
+ hooks: PluginHooks<TFactory>;
617
744
  };
618
745
  /**
619
- * All accepted forms of a Kubb configuration.
620
- */
621
- type ConfigInput = PossiblePromise<UserConfig | UserConfig[]> | ((cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>);
622
- /**
623
- * Helper for defining a Kubb configuration.
746
+ * Creates a plugin factory using the new hook-style (`hooks:`) API.
624
747
  *
625
- * Accepts either:
626
- * - A config object or array of configs
627
- * - A function returning the config(s), optionally async,
628
- * receiving the CLI options as argument
748
+ * The returned factory is called with optional options and produces a `HookStylePlugin`
749
+ * that coexists with plugins created via the legacy `createPlugin` API in the same
750
+ * `kubb.config.ts`.
751
+ *
752
+ * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
753
+ * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
629
754
  *
630
755
  * @example
631
- * export default defineConfig(({ logLevel }) => ({
632
- * root: 'src',
633
- * plugins: [myPlugin()],
756
+ * ```ts
757
+ * // With PluginFactoryOptions (recommended for real plugins)
758
+ * export const pluginTs = definePlugin<PluginTs>((options) => ({
759
+ * name: 'plugin-ts',
760
+ * hooks: {
761
+ * 'kubb:plugin:setup'(ctx) {
762
+ * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
763
+ * },
764
+ * },
634
765
  * }))
635
- * @deprecated as of Kubb v5, @kubb/core will not expose `defineConfig` anymore. use the `kubb` package instead
766
+ * ```
636
767
  */
637
- declare function defineConfig(config: (cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>): typeof config;
638
- declare function defineConfig(config: PossiblePromise<UserConfig | UserConfig[]>): typeof config;
768
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => HookStylePlugin<TFactory>): (options?: TFactory['options']) => HookStylePlugin<TFactory>;
639
769
  //#endregion
640
770
  //#region src/utils/FunctionParams.d.ts
641
771
  type FunctionParamsASTWithoutType = {
@@ -676,11 +806,11 @@ type FileMetaBase = {
676
806
  type AddIndexesProps = {
677
807
  type: BarrelType | false | undefined;
678
808
  /**
679
- * Root based on root and output.path specified in the config
809
+ * Absolute output root derived from config `root` and `output.path`.
680
810
  */
681
811
  root: string;
682
812
  /**
683
- * Output for plugin
813
+ * Output settings for the plugin.
684
814
  */
685
815
  output: {
686
816
  path: string;
@@ -707,80 +837,6 @@ declare function getBarrelFiles(files: Array<FileNode>, {
707
837
  }: AddIndexesProps): Promise<Array<FileNode>>;
708
838
  //#endregion
709
839
  //#region src/types.d.ts
710
- declare global {
711
- namespace Kubb {
712
- interface PluginContext {}
713
- /**
714
- * Registry that maps plugin names to their `PluginFactoryOptions`.
715
- * Augment this interface in each plugin's `types.ts` to enable automatic
716
- * typing for `getPlugin` and `requirePlugin`.
717
- *
718
- * @example
719
- * ```ts
720
- * // packages/plugin-ts/src/types.ts
721
- * declare global {
722
- * namespace Kubb {
723
- * interface PluginRegistry {
724
- * 'plugin-ts': PluginTs
725
- * }
726
- * }
727
- * }
728
- * ```
729
- */
730
- interface PluginRegistry {}
731
- }
732
- }
733
- /**
734
- * Config used in `kubb.config.ts`
735
- *
736
- * @example
737
- * import { defineConfig } from '@kubb/core'
738
- * export default defineConfig({
739
- * ...
740
- * })
741
- */
742
- type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter'> & {
743
- /**
744
- * The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
745
- * @default process.cwd()
746
- */
747
- root?: string;
748
- /**
749
- * An array of parsers used to convert generated files to strings.
750
- * Each parser handles specific file extensions (e.g. `.ts`, `.tsx`).
751
- *
752
- * A catch-all fallback parser is always appended last for any unhandled extension.
753
- *
754
- * When omitted, `parserTsx` from `@kubb/parser-ts` is used automatically as the
755
- * default (requires `@kubb/parser-ts` to be installed as an optional dependency).
756
- * @default [parserTsx] — from `@kubb/parser-ts`
757
- * @example
758
- * ```ts
759
- * import { parserTs, tsxParser } from '@kubb/parser-ts'
760
- * export default defineConfig({
761
- * parsers: [parserTs, tsxParser],
762
- * })
763
- * ```
764
- */
765
- parsers?: Array<Parser>;
766
- /**
767
- * Adapter that converts the input file into a `@kubb/ast` `InputNode` — the universal
768
- * intermediate representation consumed by all Kubb plugins.
769
- *
770
- * When omitted, `adapterOas()` from `@kubb/adapter-oas` is used automatically as the
771
- * default (requires `@kubb/adapter-oas` to be installed as an optional dependency).
772
- *
773
- * - Use `@kubb/adapter-oas` for OpenAPI / Swagger (default).
774
- * - Use `@kubb/adapter-drizzle` or `@kubb/adapter-asyncapi` for other formats.
775
- *
776
- * @default adapterOas() — from `@kubb/adapter-oas`
777
- */
778
- adapter?: Adapter;
779
- /**
780
- * An array of Kubb plugins used for generation. Each plugin may have additional configurable options (defined within the plugin itself). If a plugin relies on another plugin, an error will occur if the required dependency is missing. Refer to “pre” for more details.
781
- */
782
- plugins?: Array<Omit<UnknownUserPlugin, 'inject'>>;
783
- };
784
840
  type InputPath = {
785
841
  /**
786
842
  * Specify your Swagger/OpenAPI file, either as an absolute path or a path relative to the root.
@@ -872,6 +928,12 @@ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
872
928
  path: string;
873
929
  }) => Array<ImportNode>;
874
930
  };
931
+ /**
932
+ * Controls how `index.ts` barrel files are generated.
933
+ * - `'all'` — exports every generated symbol from every file.
934
+ * - `'named'` — exports only explicitly named exports.
935
+ * - `'propagate'` — propagates re-exports from nested barrel files upward.
936
+ */
875
937
  type BarrelType = 'all' | 'named' | 'propagate';
876
938
  type DevtoolsOptions = {
877
939
  /**
@@ -930,13 +992,14 @@ type Config<TInput = Input> = {
930
992
  */
931
993
  adapter: Adapter;
932
994
  /**
933
- * You can use either `input.path` or `input.data`, depending on your specific needs.
995
+ * Source file or data to generate code from.
996
+ * Use `input.path` for a file on disk or `input.data` for an inline string or object.
934
997
  */
935
998
  input: TInput;
936
999
  output: {
937
1000
  /**
938
- * The path where all generated files receives exported.
939
- * This can be an absolute path or a path relative to the specified root option.
1001
+ * Output directory for generated files.
1002
+ * Accepts an absolute path or a path relative to `root`.
940
1003
  */
941
1004
  path: string;
942
1005
  /**
@@ -1009,11 +1072,28 @@ type Config<TInput = Input> = {
1009
1072
  override?: boolean;
1010
1073
  };
1011
1074
  /**
1012
- * An array of Kubb plugins that used in the generation.
1013
- * Each plugin may include additional configurable options(defined in the plugin itself).
1014
- * If a plugin depends on another plugin, an error is returned if the required dependency is missing. See pre for more details.
1075
+ * An array of Kubb plugins used for code generation.
1076
+ * Each plugin may declare additional configurable options.
1077
+ * If a plugin depends on another, an error is thrown when the dependency is missing.
1078
+ * Use `dependencies` on the plugin to declare execution order.
1015
1079
  */
1016
1080
  plugins: Array<Plugin>;
1081
+ /**
1082
+ * Project-wide renderer factory. All plugins and generators that do not declare their own
1083
+ * `renderer` ultimately fall back to this value.
1084
+ *
1085
+ * The resolution chain is: `generator.renderer` → `plugin.renderer` → `config.renderer` → `undefined` (raw `FileNode[]` mode).
1086
+ *
1087
+ * @example
1088
+ * ```ts
1089
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1090
+ * export default defineConfig({
1091
+ * renderer: jsxRenderer,
1092
+ * plugins: [pluginTs(), pluginZod()],
1093
+ * })
1094
+ * ```
1095
+ */
1096
+ renderer?: RendererFactory;
1017
1097
  /**
1018
1098
  * Devtools configuration for Kubb Studio integration.
1019
1099
  */
@@ -1083,21 +1163,6 @@ type Resolver = {
1083
1163
  resolveBanner(node: InputNode | null, context: ResolveBannerContext): string | undefined;
1084
1164
  resolveFooter(node: InputNode | null, context: ResolveBannerContext): string | undefined;
1085
1165
  };
1086
- /**
1087
- * The user-facing subset of a `Resolver` — everything except the four methods injected by
1088
- * `defineResolver` (`default`, `resolveOptions`, `resolvePath`, and `resolveFile`).
1089
- *
1090
- * All four injected methods can still be overridden by providing them explicitly in the builder.
1091
- *
1092
- * @example
1093
- * ```ts
1094
- * export const resolver = defineResolver<PluginTs>(() => ({
1095
- * name: 'default',
1096
- * resolveName(node) { return this.default(node.name, 'function') },
1097
- * }))
1098
- * ```
1099
- */
1100
- type UserResolver = Omit<Resolver, 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter'>;
1101
1166
  type PluginFactoryOptions<
1102
1167
  /**
1103
1168
  * Name to be used for the plugin.
@@ -1131,42 +1196,66 @@ TResolver extends Resolver = Resolver> = {
1131
1196
  resolvePathOptions: TResolvePathOptions;
1132
1197
  resolver: TResolver;
1133
1198
  };
1199
+ /**
1200
+ * @deprecated
1201
+ */
1134
1202
  type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1135
1203
  /**
1136
- * Unique name used for the plugin
1137
- * The name of the plugin follows the format scope:foo-bar or foo-bar, adding scope: can avoid naming conflicts with other plugins.
1138
- * @example @kubb/typescript
1204
+ * Unique name used for the plugin.
1205
+ * The name follows the format `scope:foo-bar` or `foo-bar` adding a scope avoids conflicts with other plugins.
1206
+ *
1207
+ * @example Plugin name
1208
+ * `'@kubb/typescript'`
1139
1209
  */
1140
1210
  name: TOptions['name'];
1141
1211
  /**
1142
- * Options set for a specific plugin(see kubb.config.js), passthrough of options.
1212
+ * Resolved options merged with output/include/exclude/override defaults for the current plugin.
1143
1213
  */
1144
1214
  options: TOptions['resolvedOptions'] & {
1145
1215
  output: Output;
1146
1216
  include?: Array<Include>;
1147
- exclude: Array<Exclude>;
1217
+ exclude: Array<Exclude$1>;
1148
1218
  override: Array<Override<TOptions['resolvedOptions']>>;
1149
1219
  };
1150
1220
  /**
1151
1221
  * The resolver for this plugin.
1152
- * Composed by `getPreset` from the preset resolver and the user's `resolver` partial override.
1222
+ * Set via `setResolver()` in `kubb:plugin:setup` or passed as a user option.
1153
1223
  */
1154
1224
  resolver?: TOptions['resolver'];
1155
1225
  /**
1156
1226
  * The composed transformer for this plugin.
1157
- * Composed by `getPreset` from the preset's transformers and the user's `transformer` visitor.
1158
- * When a visitor method returns `null`/`undefined`, the preset transformer's result is used instead.
1227
+ * Set via `setTransformer()` in `kubb:plugin:setup` or passed as a user option.
1159
1228
  */
1160
1229
  transformer?: Visitor;
1161
1230
  /**
1162
- * Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin is executed after these plugins.
1163
- * Can be used to validate dependent plugins.
1231
+ * Plugin-level renderer factory. All generators that do not declare their own `renderer`
1232
+ * inherit this value. A generator can explicitly opt out by setting `renderer: null`.
1233
+ *
1234
+ * @example
1235
+ * ```ts
1236
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1237
+ * createPlugin((options) => ({
1238
+ * name: 'my-plugin',
1239
+ * renderer: jsxRenderer,
1240
+ * generators: [
1241
+ * { name: 'types', schema(node) { return <File>...</File> } }, // inherits jsxRenderer
1242
+ * { name: 'raw', renderer: null, schema(node) { return [...] } }, // explicit opt-out
1243
+ * ],
1244
+ * }))
1245
+ * ```
1164
1246
  */
1165
- pre?: Array<string>;
1247
+ renderer?: RendererFactory;
1166
1248
  /**
1167
- * Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin is executed before these plugins.
1249
+ * Generators declared directly on the plugin. Each generator's `renderer` takes precedence
1250
+ * over `plugin.renderer`; set `renderer: null` on a generator to opt out of rendering even
1251
+ * when the plugin declares a renderer.
1168
1252
  */
1169
- post?: Array<string>;
1253
+ generators?: Array<Generator<any>>;
1254
+ /**
1255
+ * Specifies the plugins that the current plugin depends on. The current plugin is executed after all listed plugins.
1256
+ * An error is returned if any required dependency plugin is missing.
1257
+ */
1258
+ dependencies?: Array<string>;
1170
1259
  /**
1171
1260
  * When `apply` is defined, the plugin is only activated when `apply(config)` returns `true`.
1172
1261
  * Inspired by Vite's `apply` option.
@@ -1193,53 +1282,55 @@ type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> =
1193
1282
  */
1194
1283
  inject?: (this: PluginContext<TOptions>) => TOptions['context'];
1195
1284
  };
1285
+ /**
1286
+ * @deprecated
1287
+ */
1196
1288
  type UserPluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = UserPlugin<TOptions> & PluginLifecycle<TOptions>;
1197
- type UnknownUserPlugin = UserPlugin<PluginFactoryOptions<string, object, object, unknown, object>>;
1198
1289
  /**
1199
1290
  * Handler for a single schema node. Used by the `schema` hook on a plugin.
1200
1291
  */
1201
- type SchemaHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: SchemaNode, options: TOptions['resolvedOptions']) => PossiblePromise<KubbReactNode | Array<FileNode> | void>;
1292
+ type SchemaHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: SchemaNode, options: TOptions['resolvedOptions']) => PossiblePromise<unknown | Array<FileNode> | void>;
1202
1293
  /**
1203
1294
  * Handler for a single operation node. Used by the `operation` hook on a plugin.
1204
1295
  */
1205
- type OperationHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: OperationNode, options: TOptions['resolvedOptions']) => PossiblePromise<KubbReactNode | Array<FileNode> | void>;
1296
+ type OperationHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: OperationNode, options: TOptions['resolvedOptions']) => PossiblePromise<unknown | Array<FileNode> | void>;
1206
1297
  /**
1207
1298
  * Handler for all collected operation nodes. Used by the `operations` hook on a plugin.
1208
1299
  */
1209
- type OperationsHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, nodes: Array<OperationNode>, options: TOptions['resolvedOptions']) => PossiblePromise<KubbReactNode | Array<FileNode> | void>;
1300
+ type OperationsHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, nodes: Array<OperationNode>, options: TOptions['resolvedOptions']) => PossiblePromise<unknown | Array<FileNode> | void>;
1301
+ /**
1302
+ * @deprecated will be replaced with HookStylePlugin
1303
+ */
1210
1304
  type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1211
1305
  /**
1212
- * Unique name used for the plugin
1213
- * @example @kubb/typescript
1306
+ * Unique name used for the plugin.
1307
+ *
1308
+ * @example Plugin name
1309
+ * `'@kubb/typescript'`
1214
1310
  */
1215
1311
  name: TOptions['name'];
1216
1312
  /**
1217
- * Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin is executed after these plugins.
1218
- * Can be used to validate dependent plugins.
1219
- */
1220
- pre?: Array<string>;
1221
- /**
1222
- * Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin is executed before these plugins.
1313
+ * Specifies the plugins that the current plugin depends on. The current plugin is executed after all listed plugins.
1314
+ * An error is returned if any required dependency plugin is missing.
1223
1315
  */
1224
- post?: Array<string>;
1316
+ dependencies?: Array<string>;
1225
1317
  /**
1226
1318
  * Options set for a specific plugin(see kubb.config.js), passthrough of options.
1227
1319
  */
1228
1320
  options: TOptions['resolvedOptions'] & {
1229
1321
  output: Output;
1230
1322
  include?: Array<Include>;
1231
- exclude: Array<Exclude>;
1323
+ exclude: Array<Exclude$1>;
1232
1324
  override: Array<Override<TOptions['resolvedOptions']>>;
1233
1325
  };
1234
1326
  /**
1235
1327
  * The resolver for this plugin.
1236
- * Composed by `getPreset` from the preset resolver and the user's `resolver` partial override.
1328
+ * Set via `setResolver()` in `kubb:plugin:setup` or passed as a user option.
1237
1329
  */
1238
1330
  resolver: TOptions['resolver'];
1239
1331
  /**
1240
- * The composed transformer for this plugin. Accessible via `context.transformer`.
1241
- * Composed by `getPreset` from the preset's transformers and the user's `transformer` visitor.
1242
- * When a visitor method returns `null`/`undefined`, the preset transformer's result is used instead.
1332
+ * The composed transformer for this plugin.
1333
+ * Set via `setTransformer()` in `kubb:plugin:setup` or passed as a user option.
1243
1334
  */
1244
1335
  transformer?: Visitor;
1245
1336
  /**
@@ -1252,6 +1343,17 @@ type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1252
1343
  * Used in diagnostic messages and version-conflict detection.
1253
1344
  */
1254
1345
  version?: string;
1346
+ /**
1347
+ * Plugin-level renderer factory. All generators that do not declare their own `renderer`
1348
+ * inherit this value. A generator can explicitly opt out by setting `renderer: null`.
1349
+ */
1350
+ renderer?: RendererFactory;
1351
+ /**
1352
+ * Generators declared directly on the plugin. Each generator's `renderer` takes precedence
1353
+ * over `plugin.renderer`; set `renderer: null` on a generator to opt out of rendering even
1354
+ * when the plugin declares a renderer.
1355
+ */
1356
+ generators?: Array<Generator<any>>;
1255
1357
  buildStart: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1256
1358
  /**
1257
1359
  * Called once per plugin after all files have been written to disk.
@@ -1285,18 +1387,22 @@ type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1285
1387
  */
1286
1388
  inject: (this: PluginContext<TOptions>) => TOptions['context'];
1287
1389
  };
1390
+ /**
1391
+ * @deprecated
1392
+ */
1288
1393
  type PluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & PluginLifecycle<TOptions>;
1394
+ /**
1395
+ * @deprecated
1396
+ */
1289
1397
  type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1290
1398
  /**
1291
1399
  * Called once per plugin at the start of its processing phase, before schema/operation/operations hooks run.
1292
1400
  * Use this to set up shared state, fetch remote data, or perform any async initialization.
1293
- * @type hookParallel
1294
1401
  */
1295
1402
  buildStart?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1296
1403
  /**
1297
1404
  * Called once per plugin after all files have been written to disk.
1298
1405
  * Use this for post-processing, copying assets, or generating summary reports.
1299
- * @type hookParallel
1300
1406
  */
1301
1407
  buildEnd?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1302
1408
  /**
@@ -1324,22 +1430,29 @@ type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOption
1324
1430
  */
1325
1431
  operations?: OperationsHook<TOptions>;
1326
1432
  /**
1327
- * Resolve to a Path based on a baseName(example: `./Pet.ts`) and directory(example: `./models`).
1328
- * Options can als be included.
1329
- * @type hookFirst
1330
- * @example ('./Pet.ts', './src/gen/') => '/src/gen/Pet.ts'
1331
- * @deprecated this will be replaced by resolvers
1433
+ * Resolves a path from a baseName and directory.
1434
+ * Options can also be included.
1435
+ *
1436
+ * @example
1437
+ * `('./Pet.ts', './src/gen/') => '/src/gen/Pet.ts'`
1438
+ *
1439
+ * @deprecated Use resolvers instead.
1332
1440
  */
1333
1441
  resolvePath?: (this: PluginContext<TOptions>, baseName: FileNode['baseName'], mode?: 'single' | 'split', options?: TOptions['resolvePathOptions']) => string;
1334
1442
  /**
1335
- * Resolve to a name based on a string.
1443
+ * Resolves a display name from a raw string.
1336
1444
  * Useful when converting to PascalCase or camelCase.
1337
- * @type hookFirst
1338
- * @example ('pet') => 'Pet'
1339
- * @deprecated this will be replaced by resolvers
1445
+ *
1446
+ * @example
1447
+ * `('pet') => 'Pet'`
1448
+ *
1449
+ * @deprecated Use resolvers instead.
1340
1450
  */
1341
1451
  resolveName?: (this: PluginContext<TOptions>, name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
1342
1452
  };
1453
+ /**
1454
+ * @deprecated
1455
+ */
1343
1456
  type PluginLifecycleHooks = keyof PluginLifecycle;
1344
1457
  type PluginParameter<H extends PluginLifecycleHooks> = Parameters<Required<PluginLifecycle>[H]>;
1345
1458
  type ResolvePathParams<TOptions = object> = {
@@ -1347,7 +1460,7 @@ type ResolvePathParams<TOptions = object> = {
1347
1460
  baseName: FileNode['baseName'];
1348
1461
  mode?: 'single' | 'split';
1349
1462
  /**
1350
- * Options to be passed to 'resolvePath' 3th parameter
1463
+ * Options passed as the third argument to `resolvePath`.
1351
1464
  */
1352
1465
  options?: TOptions;
1353
1466
  };
@@ -1356,14 +1469,16 @@ type ResolveNameParams = {
1356
1469
  pluginName?: string;
1357
1470
  /**
1358
1471
  * Specifies the type of entity being named.
1359
- * - 'file' customizes the name of the created file (uses camelCase).
1360
- * - 'function' customizes the exported function names (uses camelCase).
1361
- * - 'type' customizes TypeScript types (uses PascalCase).
1362
- * - 'const' customizes variable names (uses camelCase).
1363
- * @default undefined
1472
+ * - `'file'` customizes the name of the created file (camelCase).
1473
+ * - `'function'` customizes the exported function names (camelCase).
1474
+ * - `'type'` customizes TypeScript type names (PascalCase).
1475
+ * - `'const'` customizes variable names (camelCase).
1364
1476
  */
1365
1477
  type?: 'file' | 'function' | 'type' | 'const';
1366
1478
  };
1479
+ /**
1480
+ * @deprecated
1481
+ */
1367
1482
  type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1368
1483
  config: Config;
1369
1484
  /**
@@ -1393,19 +1508,16 @@ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions>
1393
1508
  requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1394
1509
  requirePlugin(name: string): Plugin;
1395
1510
  /**
1396
- * Only add when the file does not exist yet
1511
+ * Add files only when they do not exist yet.
1397
1512
  */
1398
1513
  addFile: (...file: Array<FileNode>) => Promise<void>;
1399
1514
  /**
1400
- * merging multiple sources into the same output file
1515
+ * Merge multiple sources into the same output file.
1401
1516
  */
1402
1517
  upsertFile: (...file: Array<FileNode>) => Promise<void>;
1518
+ hooks: AsyncEventEmitter<KubbHooks>;
1403
1519
  /**
1404
- * @deprecated use this.warn, this.error, this.info instead
1405
- */
1406
- events: AsyncEventEmitter<KubbEvents>;
1407
- /**
1408
- * Current plugin
1520
+ * The current plugin.
1409
1521
  */
1410
1522
  plugin: Plugin<TOptions>;
1411
1523
  /**
@@ -1419,17 +1531,17 @@ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions>
1419
1531
  transformer: Visitor | undefined;
1420
1532
  /**
1421
1533
  * Emit a warning via the build event system.
1422
- * Shorthand for `this.events.emit('warn', message)`.
1534
+ * Shorthand for `this.hooks.emit('kubb:warn', message)`.
1423
1535
  */
1424
1536
  warn: (message: string) => void;
1425
1537
  /**
1426
1538
  * Emit an error via the build event system.
1427
- * Shorthand for `this.events.emit('error', error)`.
1539
+ * Shorthand for `this.hooks.emit('kubb:error', error)`.
1428
1540
  */
1429
1541
  error: (error: string | Error) => void;
1430
1542
  /**
1431
1543
  * Emit an info message via the build event system.
1432
- * Shorthand for `this.events.emit('info', message)`.
1544
+ * Shorthand for `this.hooks.emit('kubb:info', message)`.
1433
1545
  */
1434
1546
  info: (message: string) => void;
1435
1547
  /**
@@ -1445,7 +1557,7 @@ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions>
1445
1557
  */
1446
1558
  inputNode: InputNode;
1447
1559
  /**
1448
- * Return the adapter from `@kubb/ast`
1560
+ * The adapter from `@kubb/ast`.
1449
1561
  */
1450
1562
  adapter: Adapter;
1451
1563
  } | {
@@ -1453,23 +1565,27 @@ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions>
1453
1565
  adapter?: never;
1454
1566
  }) & Kubb.PluginContext;
1455
1567
  /**
1456
- * Narrowed `PluginContext` used as the `this` type inside generator and plugin AST hook methods.
1568
+ * Context object passed as the second argument to generator `schema`, `operation`, and
1569
+ * `operations` methods.
1570
+ *
1571
+ * Generators are only invoked from `runPluginAstHooks`, which already guards against a
1572
+ * missing adapter. This type reflects that guarantee — `ctx.adapter` and `ctx.inputNode`
1573
+ * are always defined, so no runtime checks or casts are needed inside generator bodies.
1457
1574
  *
1458
- * Generators and the `schema`/`operation`/`operations` plugin hooks are only invoked from
1459
- * `runPluginAstHooks`, which already guards against a missing adapter. This type reflects
1460
- * that guarantee — `this.adapter` and `this.inputNode` are always defined, so no runtime
1461
- * checks or casts are needed inside the method bodies.
1575
+ * `ctx.options` carries the per-node resolved options for `schema`/`operation` calls
1576
+ * (after exclude/include/override filtering) and the plugin-level options for `operations`.
1462
1577
  */
1463
1578
  type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Omit<PluginContext<TOptions>, 'adapter' | 'inputNode'> & {
1464
1579
  adapter: Adapter;
1465
1580
  inputNode: InputNode;
1581
+ options: TOptions['resolvedOptions'];
1466
1582
  };
1467
1583
  /**
1468
- * Specify the export location for the files and define the behavior of the output
1584
+ * Configure generated file output location and behavior.
1469
1585
  */
1470
1586
  type Output<_TOptions = unknown> = {
1471
1587
  /**
1472
- * Path to the output folder or file that will contain the generated code
1588
+ * Path to the output folder or file that will contain generated code.
1473
1589
  */
1474
1590
  path: string;
1475
1591
  /**
@@ -1478,11 +1594,13 @@ type Output<_TOptions = unknown> = {
1478
1594
  */
1479
1595
  barrelType?: BarrelType | false;
1480
1596
  /**
1481
- * Add a banner text in the beginning of every file
1597
+ * Text or function appended at the start of every generated file.
1598
+ * When a function, receives the current `InputNode` and must return a string.
1482
1599
  */
1483
1600
  banner?: string | ((node?: InputNode) => string);
1484
1601
  /**
1485
- * Add a footer text in the beginning of every file
1602
+ * Text or function appended at the end of every generated file.
1603
+ * When a function, receives the current `InputNode` and must return a string.
1486
1604
  */
1487
1605
  footer?: string | ((node?: InputNode) => string);
1488
1606
  /**
@@ -1493,14 +1611,14 @@ type Output<_TOptions = unknown> = {
1493
1611
  };
1494
1612
  type UserGroup = {
1495
1613
  /**
1496
- * Defines the type where to group the files.
1497
- * - 'tag' groups files by OpenAPI tags.
1498
- * - 'path' groups files by OpenAPI paths.
1499
- * @default undefined
1614
+ * Determines how files are grouped into subdirectories.
1615
+ * - `'tag'` groups files by OpenAPI tags.
1616
+ * - `'path'` groups files by OpenAPI paths.
1500
1617
  */
1501
1618
  type: 'tag' | 'path';
1502
1619
  /**
1503
- * Return the name of a group based on the group name, this is used for the file and name generation.
1620
+ * Returns the subdirectory name for a given group value.
1621
+ * Defaults to `${camelCase(group)}Controller` for tags and the first path segment for paths.
1504
1622
  */
1505
1623
  name?: (context: {
1506
1624
  group: string;
@@ -1508,14 +1626,13 @@ type UserGroup = {
1508
1626
  };
1509
1627
  type Group = {
1510
1628
  /**
1511
- * Defines the type where to group the files.
1512
- * - 'tag' groups files by OpenAPI tags.
1513
- * - 'path' groups files by OpenAPI paths.
1514
- * @default undefined
1629
+ * Determines how files are grouped into subdirectories.
1630
+ * - `'tag'` groups files by OpenAPI tags.
1631
+ * - `'path'` groups files by OpenAPI paths.
1515
1632
  */
1516
1633
  type: 'tag' | 'path';
1517
1634
  /**
1518
- * Return the name of a group based on the group name, this is used for the file and name generation.
1635
+ * Returns the subdirectory name for a given group value.
1519
1636
  */
1520
1637
  name: (context: {
1521
1638
  group: string;
@@ -1530,7 +1647,7 @@ type LoggerOptions = {
1530
1647
  /**
1531
1648
  * Shared context passed to all plugins, parsers, and other internals.
1532
1649
  */
1533
- type LoggerContext = AsyncEventEmitter<KubbEvents>;
1650
+ type LoggerContext = AsyncEventEmitter<KubbHooks>;
1534
1651
  type Logger<TOptions extends LoggerOptions = LoggerOptions> = {
1535
1652
  name: string;
1536
1653
  install: (context: LoggerContext, options?: TOptions) => void | Promise<void>;
@@ -1543,42 +1660,80 @@ type UserLogger<TOptions extends LoggerOptions = LoggerOptions> = Logger<TOption
1543
1660
  */
1544
1661
  type CompatibilityPreset = 'default' | 'kubbV4';
1545
1662
  /**
1546
- * A preset bundles a name, a resolver, optional AST transformers,
1547
- * and optional generators into a single reusable configuration object.
1548
- *
1549
- * @template TResolver - The concrete resolver type for this preset.
1663
+ * Context passed to a hook-style plugin's `kubb:plugin:setup` handler.
1664
+ * Provides methods to register generators, configure the resolver, transformer,
1665
+ * and renderer, as well as access to the current build configuration.
1550
1666
  */
1551
- type Preset<TResolver extends Resolver = Resolver> = {
1667
+ type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1552
1668
  /**
1553
- * Unique identifier for this preset.
1669
+ * Register a generator on this plugin. Generators are invoked during the AST walk
1670
+ * (schema/operation/operations) exactly like generators declared statically on `createPlugin`.
1554
1671
  */
1555
- name: string;
1672
+ addGenerator<TElement = unknown>(generator: Generator<TFactory, TElement>): void;
1556
1673
  /**
1557
- * The resolver used by this preset.
1674
+ * Set or partially override the resolver for this plugin.
1675
+ * The resolver controls file naming and path resolution for generated files.
1676
+ *
1677
+ * When `TFactory` is a concrete `PluginFactoryOptions` (e.g. `PluginClient`),
1678
+ * the resolver parameter is typed to the plugin's own resolver type (e.g. `ResolverClient`).
1558
1679
  */
1559
- resolver: TResolver;
1680
+ setResolver(resolver: Partial<TFactory['resolver']>): void;
1560
1681
  /**
1561
- * Optional AST visitors / transformers applied after resolving.
1682
+ * Set the AST transformer (visitor) for this plugin.
1683
+ * The transformer pre-processes nodes before they reach the generators.
1562
1684
  */
1563
- transformers?: Array<Visitor>;
1685
+ setTransformer(visitor: Visitor): void;
1564
1686
  /**
1565
- * Optional generators used by this preset. Plugin implementations cast this
1566
- * to their concrete generator type.
1687
+ * Set the renderer factory for this plugin.
1688
+ * Used to process JSX elements returned by generators.
1567
1689
  */
1568
- generators?: Array<Generator<any>>;
1690
+ setRenderer(renderer: RendererFactory): void;
1691
+ /**
1692
+ * Set the resolved options for the build loop. These options are merged into the
1693
+ * normalized plugin's `options` object (which includes `output`, `exclude`, `override`).
1694
+ *
1695
+ * Call this in `kubb:plugin:setup` to provide the resolved options that generators
1696
+ * and the build loop need (e.g., `enumType`, `optionalType`, `group`).
1697
+ */
1698
+ setOptions(options: TFactory['resolvedOptions']): void;
1699
+ /**
1700
+ * Inject a raw file into the build output, bypassing the normal generation pipeline.
1701
+ */
1702
+ injectFile(file: Pick<FileNode, 'baseName' | 'path'> & {
1703
+ sources?: FileNode['sources'];
1704
+ }): void;
1705
+ /**
1706
+ * Merge a partial config update into the current build configuration.
1707
+ */
1708
+ updateConfig(config: Partial<Config>): void;
1709
+ /**
1710
+ * The resolved build configuration at the time of setup.
1711
+ */
1712
+ config: Config;
1569
1713
  /**
1570
- * Optional printer factory used by this preset.
1571
- * The generator calls this function at render-time to produce a configured printer instance.
1714
+ * The plugin's own options as passed by the user.
1572
1715
  */
1573
- printer?: (options: any) => Printer;
1716
+ options: TFactory['options'];
1574
1717
  };
1575
1718
  /**
1576
- * A named registry of presets, keyed by preset name.
1577
- *
1578
- * @template TResolver - The concrete resolver type shared by all presets in this registry.
1579
- * @template TName - The union of valid preset name keys.
1719
+ * Context passed to a hook-style plugin's `kubb:build:start` handler.
1720
+ * Fires immediately before the plugin execution loop begins.
1580
1721
  */
1581
- type Presets<TResolver extends Resolver = Resolver> = Record<CompatibilityPreset, Preset<TResolver>>;
1722
+ type KubbBuildStartContext = {
1723
+ config: Config;
1724
+ adapter: Adapter;
1725
+ inputNode: InputNode;
1726
+ getPlugin(name: string): Plugin | undefined;
1727
+ };
1728
+ /**
1729
+ * Context passed to a hook-style plugin's `kubb:build:end` handler.
1730
+ * Fires after all files have been written to disk.
1731
+ */
1732
+ type KubbBuildEndContext = {
1733
+ files: Array<FileNode>;
1734
+ config: Config;
1735
+ outputDir: string;
1736
+ };
1582
1737
  type ByTag = {
1583
1738
  type: 'tag';
1584
1739
  pattern: string | RegExp;
@@ -1603,8 +1758,20 @@ type ByContentType = {
1603
1758
  type: 'contentType';
1604
1759
  pattern: string | RegExp;
1605
1760
  };
1606
- type Exclude = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1761
+ /**
1762
+ * A pattern filter that prevents matching nodes from being generated.
1763
+ * Match by `tag`, `operationId`, `path`, `method`, `contentType`, or `schemaName`.
1764
+ */
1765
+ type Exclude$1 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1766
+ /**
1767
+ * A pattern filter that restricts generation to only matching nodes.
1768
+ * Match by `tag`, `operationId`, `path`, `method`, `contentType`, or `schemaName`.
1769
+ */
1607
1770
  type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1771
+ /**
1772
+ * A pattern filter paired with partial option overrides applied when the pattern matches.
1773
+ * Match by `tag`, `operationId`, `path`, `method`, `schemaName`, or `contentType`.
1774
+ */
1608
1775
  type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
1609
1776
  options: Partial<TOptions>;
1610
1777
  };
@@ -1710,6 +1877,160 @@ type ResolveBannerContext = {
1710
1877
  output?: Pick<Output, 'banner' | 'footer'>;
1711
1878
  config: Config;
1712
1879
  };
1880
+ /**
1881
+ * CLI options derived from command-line flags.
1882
+ */
1883
+ type CLIOptions = {
1884
+ /**
1885
+ * Path to `kubb.config.js`.
1886
+ */
1887
+ config?: string;
1888
+ /**
1889
+ * Enable watch mode for input files.
1890
+ */
1891
+ watch?: boolean;
1892
+ /**
1893
+ * Logging verbosity for CLI usage.
1894
+ * @default 'silent'
1895
+ */
1896
+ logLevel?: 'silent' | 'info' | 'debug';
1897
+ };
1898
+ /**
1899
+ * All accepted forms of a Kubb configuration.
1900
+ *
1901
+ * Config is always `@kubb/core` {@link Config}.
1902
+ * - `PossibleConfig` accepts `Config`/`Config[]`/promise or a no-arg config factory.
1903
+ * - `PossibleConfig<TCliOptions>` accepts the same config forms or a config factory receiving `TCliOptions`.
1904
+ */
1905
+ type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Config[]> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>);
1906
+ /**
1907
+ * All accepted forms of a Kubb configuration.
1908
+ * @deprecated
1909
+ * Kept for backward compatibility. Prefer `PossibleConfig<CLIOptions>` in new code.
1910
+ */
1911
+ type ConfigInput = PossibleConfig<CLIOptions>;
1912
+ //#endregion
1913
+ //#region src/defineGenerator.d.ts
1914
+ /**
1915
+ * A generator is a named object with optional `schema`, `operation`, and `operations`
1916
+ * methods. Each method receives the AST node as the first argument and a typed
1917
+ * `ctx` object as the second, giving access to `ctx.config`, `ctx.resolver`,
1918
+ * `ctx.adapter`, `ctx.options`, `ctx.upsertFile`, etc.
1919
+ *
1920
+ * Generators that return renderer elements (e.g. JSX) must declare a `renderer`
1921
+ * factory so that core knows how to process the output without coupling core
1922
+ * to any specific renderer package.
1923
+ *
1924
+ * Return a renderer element, an array of `FileNode`, or `void` to handle file
1925
+ * writing manually via `ctx.upsertFile`.
1926
+ *
1927
+ * @example
1928
+ * ```ts
1929
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1930
+ *
1931
+ * export const typeGenerator = defineGenerator<PluginTs>({
1932
+ * name: 'typescript',
1933
+ * renderer: jsxRenderer,
1934
+ * schema(node, ctx) {
1935
+ * const { adapter, resolver, root, options } = ctx
1936
+ * return <File ...><Type node={node} resolver={resolver} /></File>
1937
+ * },
1938
+ * operation(node, ctx) {
1939
+ * const { options } = ctx
1940
+ * return <File ...><OperationType node={node} /></File>
1941
+ * },
1942
+ * })
1943
+ * ```
1944
+ */
1945
+ type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
1946
+ /**
1947
+ * Used in diagnostic messages and debug output.
1948
+ */
1949
+ name: string;
1950
+ /**
1951
+ * Optional renderer factory that produces a {@link Renderer} for each render cycle.
1952
+ *
1953
+ * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
1954
+ * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
1955
+ *
1956
+ * Generators that only return `Array<FileNode>` or `void` do not need to set this.
1957
+ *
1958
+ * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin
1959
+ * declares a `renderer` (overrides the plugin-level fallback).
1960
+ *
1961
+ * @example
1962
+ * ```ts
1963
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1964
+ * export const myGenerator = defineGenerator<PluginTs>({
1965
+ * renderer: jsxRenderer,
1966
+ * schema(node, ctx) { return <File ...>...</File> },
1967
+ * })
1968
+ * ```
1969
+ */
1970
+ renderer?: RendererFactory<TElement> | null;
1971
+ /**
1972
+ * Called for each schema node in the AST walk.
1973
+ * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
1974
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1975
+ */
1976
+ schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1977
+ /**
1978
+ * Called for each operation node in the AST walk.
1979
+ * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
1980
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1981
+ */
1982
+ operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1983
+ /**
1984
+ * Called once after all operations have been walked.
1985
+ * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
1986
+ * plus `ctx.options` with the plugin-level options for the batch call.
1987
+ */
1988
+ operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1989
+ };
1990
+ /**
1991
+ * Defines a generator. Returns the object as-is with correct `this` typings.
1992
+ * `applyHookResult` handles renderer elements and `File[]` uniformly using
1993
+ * the generator's declared `renderer` factory.
1994
+ */
1995
+ declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
1996
+ //#endregion
1997
+ //#region src/FileManager.d.ts
1998
+ /**
1999
+ * In-memory file store for generated files.
2000
+ *
2001
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
2002
+ * The `files` getter returns all stored files sorted by path length (shortest first).
2003
+ *
2004
+ * @example
2005
+ * ```ts
2006
+ * import { FileManager } from '@kubb/core'
2007
+ *
2008
+ * const manager = new FileManager()
2009
+ * manager.upsert(myFile)
2010
+ * console.log(manager.files) // all stored files
2011
+ * ```
2012
+ */
2013
+ declare class FileManager {
2014
+ #private;
2015
+ /**
2016
+ * Adds one or more files. Files with the same path are merged — sources, imports,
2017
+ * and exports from all calls with the same path are concatenated together.
2018
+ */
2019
+ add(...files: Array<FileNode>): Array<FileNode>;
2020
+ /**
2021
+ * Adds or merges one or more files.
2022
+ * If a file with the same path already exists, its sources/imports/exports are merged together.
2023
+ */
2024
+ upsert(...files: Array<FileNode>): Array<FileNode>;
2025
+ getByPath(path: string): FileNode | null;
2026
+ deleteByPath(path: string): void;
2027
+ clear(): void;
2028
+ /**
2029
+ * All stored files, sorted by path length (shorter paths first).
2030
+ * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
2031
+ */
2032
+ get files(): Array<FileNode>;
2033
+ }
1713
2034
  //#endregion
1714
2035
  //#region src/PluginDriver.d.ts
1715
2036
  type RequiredPluginLifecycle = Required<PluginLifecycle>;
@@ -1728,7 +2049,7 @@ type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseRe
1728
2049
  plugin: Plugin;
1729
2050
  };
1730
2051
  type Options = {
1731
- events: AsyncEventEmitter<KubbEvents>;
2052
+ hooks?: AsyncEventEmitter<KubbHooks>;
1732
2053
  /**
1733
2054
  * @default Number.POSITIVE_INFINITY
1734
2055
  */
@@ -1772,7 +2093,54 @@ declare class PluginDriver {
1772
2093
  readonly fileManager: FileManager;
1773
2094
  readonly plugins: Map<string, Plugin>;
1774
2095
  constructor(config: Config, options: Options);
1775
- get events(): AsyncEventEmitter<KubbEvents>;
2096
+ get hooks(): AsyncEventEmitter<KubbHooks>;
2097
+ /**
2098
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
2099
+ *
2100
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
2101
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
2102
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
2103
+ *
2104
+ * All other hooks are iterated and registered directly as pass-through listeners.
2105
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
2106
+ *
2107
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
2108
+ * the plugin lifecycle without modifying plugin behavior.
2109
+ */
2110
+ registerPluginHooks(hookPlugin: HookStylePlugin, normalizedPlugin: Plugin): void;
2111
+ /**
2112
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
2113
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
2114
+ *
2115
+ * Call this once from `safeBuild` before the plugin execution loop begins.
2116
+ */
2117
+ emitSetupHooks(): Promise<void>;
2118
+ /**
2119
+ * Registers a generator for the given plugin on the shared event emitter.
2120
+ *
2121
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
2122
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
2123
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
2124
+ * so that generators from different plugins do not cross-fire.
2125
+ *
2126
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
2127
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
2128
+ * declares a renderer.
2129
+ *
2130
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
2131
+ */
2132
+ registerGenerator(pluginName: string, gen: Generator<any>): void;
2133
+ /**
2134
+ * Returns `true` when at least one generator was registered for the given plugin
2135
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
2136
+ *
2137
+ * Used by the build loop to decide whether to walk the AST and emit generator events
2138
+ * for a plugin that has no static `plugin.generators`.
2139
+ */
2140
+ hasRegisteredGenerators(pluginName: string): boolean;
2141
+ dispose(): void;
2142
+ setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
2143
+ getResolver(pluginName: string): Resolver;
1776
2144
  getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown>;
1777
2145
  /**
1778
2146
  * @deprecated use resolvers context instead
@@ -1843,7 +2211,7 @@ declare class PluginDriver {
1843
2211
  skipped?: ReadonlySet<Plugin> | null;
1844
2212
  }): SafeParseResult<H> | null;
1845
2213
  /**
1846
- * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.
2214
+ * Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
1847
2215
  */
1848
2216
  hookParallel<H extends PluginLifecycleHooks, TOutput = void>({
1849
2217
  hookName,
@@ -1853,7 +2221,7 @@ declare class PluginDriver {
1853
2221
  parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
1854
2222
  }): Promise<Awaited<TOutput>[]>;
1855
2223
  /**
1856
- * Chains plugins
2224
+ * Execute a lifecycle hook sequentially for all plugins that implement it.
1857
2225
  */
1858
2226
  hookSeq<H extends PluginLifecycleHooks>({
1859
2227
  hookName,
@@ -1871,5 +2239,5 @@ declare class PluginDriver {
1871
2239
  requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
1872
2240
  }
1873
2241
  //#endregion
1874
- export { FunctionParamsAST as $, Preset as A, Resolver as B, Plugin as C, PluginLifecycleHooks as D, PluginLifecycle as E, ResolveBannerContext as F, UserConfig as G, ResolverFileParams as H, ResolveNameParams as I, UserPlugin as J, UserGroup as K, ResolveOptionsContext as L, Printer$1 as M, PrinterFactoryOptions as N, PluginParameter as O, PrinterPartial as P, getBarrelFiles as Q, ResolvePathOptions as R, Override as S, PluginFactoryOptions as T, ResolverPathParams as U, ResolverContext as V, SchemaHook as W, UserResolver as X, UserPluginWithLifeCycle as Y, FileMetaBase as Z, LoggerContext as _, AdapterSource as a, defineParser as at, OperationsHook as b, Config as c, mergeGenerators as ct, GeneratorContext as d, formatters as dt, CLIOptions as et, Group as f, linters as ft, Logger as g, InputPath as h, AdapterFactoryOptions as i, Parser as it, Presets as j, PluginWithLifeCycle as k, DevtoolsOptions as l, Storage as lt, InputData as m, AsyncEventEmitter as mt, getMode as n, defineConfig as nt, BarrelType as o, Generator as ot, Include as p, logLevel as pt, UserLogger as q, Adapter as r, KubbEvents as rt, CompatibilityPreset as s, defineGenerator as st, PluginDriver as t, ConfigInput as tt, Exclude as u, createStorage as ut, LoggerOptions as v, PluginContext as w, Output as x, OperationHook as y, ResolvePathParams as z };
1875
- //# sourceMappingURL=PluginDriver-BBi_41VF.d.ts.map
2242
+ export { getBarrelFiles as $, Plugin as A, ResolveOptionsContext as B, Logger as C, OperationsHook as D, OperationHook as E, PluginParameter as F, ResolverFileParams as G, ResolvePathParams as H, PluginWithLifeCycle as I, UserGroup as J, ResolverPathParams as K, PossibleConfig as L, PluginFactoryOptions as M, PluginLifecycle as N, Output as O, PluginLifecycleHooks as P, FileMetaBase as Q, ResolveBannerContext as R, KubbPluginSetupContext as S, LoggerOptions as T, Resolver as U, ResolvePathOptions as V, ResolverContext as W, UserPlugin as X, UserLogger as Y, UserPluginWithLifeCycle as Z, Include as _, createRenderer as _t, Adapter as a, KubbHooks as at, KubbBuildEndContext as b, BarrelType as c, Parser as ct, Config as d, createStorage as dt, FunctionParamsAST as et, ConfigInput as f, formatters as ft, Group as g, RendererFactory as gt, GeneratorContext as h, Renderer as ht, defineGenerator as i, Kubb$1 as it, PluginContext as j, Override as k, CLIOptions as l, defineParser as lt, Exclude$1 as m, logLevel as mt, getMode as n, PluginHooks as nt, AdapterFactoryOptions as o, BuildOutput as ot, DevtoolsOptions as p, linters as pt, SchemaHook as q, Generator as r, definePlugin as rt, AdapterSource as s, createKubb as st, PluginDriver as t, HookStylePlugin as tt, CompatibilityPreset as u, Storage as ut, InputData as v, AsyncEventEmitter as vt, LoggerContext as w, KubbBuildStartContext as x, InputPath as y, ResolveNameParams as z };
2243
+ //# sourceMappingURL=PluginDriver-D8lWvtUg.d.ts.map