@kubb/core 5.0.0-alpha.36 → 5.0.0-alpha.39

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 (42) hide show
  1. package/dist/{PluginDriver-CCdkwR14.cjs → PluginDriver-BQwm8hDd.cjs} +70 -147
  2. package/dist/PluginDriver-BQwm8hDd.cjs.map +1 -0
  3. package/dist/{PluginDriver-B_65W4fv.js → PluginDriver-CgXFtmNP.js} +36 -96
  4. package/dist/PluginDriver-CgXFtmNP.js.map +1 -0
  5. package/dist/index.cjs +23 -341
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +5 -317
  8. package/dist/index.js +23 -311
  9. package/dist/index.js.map +1 -1
  10. package/dist/mocks.cjs +2 -3
  11. package/dist/mocks.cjs.map +1 -1
  12. package/dist/mocks.d.ts +2 -2
  13. package/dist/mocks.js +2 -2
  14. package/dist/mocks.js.map +1 -1
  15. package/dist/{PluginDriver-C9iBgYbk.d.ts → types-DUc5lEUp.d.ts} +596 -714
  16. package/package.json +4 -11
  17. package/src/PluginDriver.ts +18 -17
  18. package/src/constants.ts +0 -48
  19. package/src/createKubb.ts +1 -1
  20. package/src/defineResolver.ts +3 -3
  21. package/src/index.ts +3 -20
  22. package/src/mocks.ts +3 -3
  23. package/src/storages/fsStorage.ts +27 -7
  24. package/src/types.ts +3 -11
  25. package/src/utils/TreeNode.ts +3 -3
  26. package/src/utils/executeStrategies.ts +0 -16
  27. package/dist/PluginDriver-B_65W4fv.js.map +0 -1
  28. package/dist/PluginDriver-CCdkwR14.cjs.map +0 -1
  29. package/dist/chunk-ByKO4r7w.cjs +0 -38
  30. package/dist/hooks.cjs +0 -32
  31. package/dist/hooks.cjs.map +0 -1
  32. package/dist/hooks.d.ts +0 -23
  33. package/dist/hooks.js +0 -29
  34. package/dist/hooks.js.map +0 -1
  35. package/src/hooks/index.ts +0 -3
  36. package/src/hooks/useDriver.ts +0 -9
  37. package/src/hooks/useMode.ts +0 -8
  38. package/src/hooks/usePlugin.ts +0 -9
  39. package/src/utils/FunctionParams.ts +0 -155
  40. package/src/utils/formatters.ts +0 -45
  41. package/src/utils/getFunctionParams.ts +0 -254
  42. package/src/utils/linters.ts +0 -45
@@ -94,6 +94,25 @@ declare class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[
94
94
  */
95
95
  type PossiblePromise<T> = Promise<T> | T;
96
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
97
116
  //#region src/createRenderer.d.ts
98
117
  /**
99
118
  * Minimal interface any Kubb renderer must satisfy.
@@ -147,73 +166,6 @@ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
147
166
  */
148
167
  declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
149
168
  //#endregion
150
- //#region src/constants.d.ts
151
- /**
152
- * Base URL for the Kubb Studio web app.
153
- */
154
- declare const DEFAULT_STUDIO_URL: "https://studio.kubb.dev";
155
- /**
156
- * Numeric log-level thresholds used internally to compare verbosity.
157
- *
158
- * Higher numbers are more verbose.
159
- */
160
- declare const logLevel: {
161
- readonly silent: number;
162
- readonly error: 0;
163
- readonly warn: 1;
164
- readonly info: 3;
165
- readonly verbose: 4;
166
- readonly debug: 5;
167
- };
168
- /**
169
- * CLI command descriptors for each supported linter.
170
- *
171
- * Each entry contains the executable `command`, an `args` factory that maps an
172
- * output path to the correct argument list, and an `errorMessage` shown when
173
- * the linter is not found.
174
- */
175
- declare const linters: {
176
- readonly eslint: {
177
- readonly command: "eslint";
178
- readonly args: (outputPath: string) => string[];
179
- readonly errorMessage: "Eslint not found";
180
- };
181
- readonly biome: {
182
- readonly command: "biome";
183
- readonly args: (outputPath: string) => string[];
184
- readonly errorMessage: "Biome not found";
185
- };
186
- readonly oxlint: {
187
- readonly command: "oxlint";
188
- readonly args: (outputPath: string) => string[];
189
- readonly errorMessage: "Oxlint not found";
190
- };
191
- };
192
- /**
193
- * CLI command descriptors for each supported code formatter.
194
- *
195
- * Each entry contains the executable `command`, an `args` factory that maps an
196
- * output path to the correct argument list, and an `errorMessage` shown when
197
- * the formatter is not found.
198
- */
199
- declare const formatters: {
200
- readonly prettier: {
201
- readonly command: "prettier";
202
- readonly args: (outputPath: string) => string[];
203
- readonly errorMessage: "Prettier not found";
204
- };
205
- readonly biome: {
206
- readonly command: "biome";
207
- readonly args: (outputPath: string) => string[];
208
- readonly errorMessage: "Biome not found";
209
- };
210
- readonly oxfmt: {
211
- readonly command: "oxfmt";
212
- readonly args: (outputPath: string) => string[];
213
- readonly errorMessage: "Oxfmt not found";
214
- };
215
- };
216
- //#endregion
217
169
  //#region src/createStorage.d.ts
218
170
  type Storage = {
219
171
  /**
@@ -271,6 +223,90 @@ type Storage = {
271
223
  */
272
224
  declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
273
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
274
310
  //#region src/defineParser.d.ts
275
311
  type PrintOptions = {
276
312
  extname?: FileNode['extname'];
@@ -312,213 +348,533 @@ type Parser<TMeta extends object = any> = {
312
348
  */
313
349
  declare function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta>;
314
350
  //#endregion
315
- //#region src/createKubb.d.ts
351
+ //#region src/definePlugin.d.ts
316
352
  /**
317
- * Full output produced by a successful or failed build.
353
+ * Base hook handlers for all events except `kubb:plugin:setup`.
354
+ * These handlers have identical signatures regardless of the plugin's
355
+ * `PluginFactoryOptions` generic — they are split out so that the
356
+ * interface below only needs to override the one event that depends on
357
+ * the plugin type.
318
358
  */
319
- type BuildOutput = {
359
+ type PluginHooksBase = { [K in Exclude<keyof KubbHooks, 'kubb:plugin:setup'>]?: (...args: KubbHooks[K]) => void | Promise<void> };
360
+ /**
361
+ * Plugin hook handlers.
362
+ *
363
+ * `kubb:plugin:setup` is typed with the plugin's own `PluginFactoryOptions` so
364
+ * `ctx.setResolver`, `ctx.setOptions`, `ctx.options` etc. use the correct types.
365
+ *
366
+ * Uses interface + method shorthand for `kubb:plugin:setup`
367
+ * checking, allowing `PluginHooks<PluginTs>` to be assignable to `PluginHooks`.
368
+ *
369
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
370
+ */
371
+ interface PluginHooks<TFactory extends PluginFactoryOptions = PluginFactoryOptions> extends PluginHooksBase {
372
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
373
+ }
374
+ /**
375
+ * A hook-style plugin object produced by `definePlugin`.
376
+ * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property
377
+ * (matching Astro's integration naming convention).
378
+ *
379
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
380
+ */
381
+ type HookStylePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
320
382
  /**
321
- * Plugins that threw during installation, paired with the caught error.
383
+ * Unique name for the plugin, following the same naming convention as `createPlugin`.
322
384
  */
323
- failedPlugins: Set<{
324
- plugin: Plugin;
325
- error: Error;
326
- }>;
327
- files: Array<FileNode>;
328
- driver: PluginDriver;
385
+ name: string;
329
386
  /**
330
- * Elapsed time in milliseconds for each plugin, keyed by plugin name.
387
+ * Plugins that must be registered before this plugin executes.
388
+ * An error is thrown at startup when any listed dependency is missing.
331
389
  */
332
- pluginTimings: Map<string, number>;
333
- error?: Error;
390
+ dependencies?: Array<string>;
334
391
  /**
335
- * Raw generated source, keyed by absolute file path.
392
+ * The options passed by the user when calling the plugin factory.
336
393
  */
337
- sources: Map<string, string>;
338
- };
339
- type KubbOptions = {
340
- config: Config;
341
- hooks?: AsyncEventEmitter<KubbHooks>;
394
+ options?: TFactory['options'];
395
+ /**
396
+ * Lifecycle event handlers for this plugin.
397
+ * Any event from the global `KubbHooks` map can be subscribed to here.
398
+ */
399
+ hooks: PluginHooks<TFactory>;
342
400
  };
343
401
  /**
344
- * Creates a Kubb instance bound to a single config entry.
402
+ * Creates a plugin factory using the new hook-style (`hooks:`) API.
345
403
  *
346
- * The instance holds shared state (`hooks`, `sources`, `driver`, `config`) across the
347
- * `setup build` lifecycle. Attach event listeners to `kubb.hooks` before
348
- * calling `setup()` or `build()`.
404
+ * The returned factory is called with optional options and produces a `HookStylePlugin`
405
+ * that coexists with plugins created via the legacy `createPlugin` API in the same
406
+ * `kubb.config.ts`.
407
+ *
408
+ * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
409
+ * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
349
410
  *
350
411
  * @example
351
412
  * ```ts
352
- * const kubb = createKubb({ config })
353
- *
354
- * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {
355
- * console.log(`${plugin.name} completed in ${duration}ms`)
356
- * })
357
- *
358
- * const { files, failedPlugins } = await kubb.safeBuild()
413
+ * // With PluginFactoryOptions (recommended for real plugins)
414
+ * export const pluginTs = definePlugin<PluginTs>((options) => ({
415
+ * name: 'plugin-ts',
416
+ * hooks: {
417
+ * 'kubb:plugin:setup'(ctx) {
418
+ * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
419
+ * },
420
+ * },
421
+ * }))
359
422
  * ```
360
423
  */
361
- declare function createKubb(options: KubbOptions): Kubb$1;
424
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => HookStylePlugin<TFactory>): (options?: TFactory['options']) => HookStylePlugin<TFactory>;
362
425
  //#endregion
363
- //#region src/Kubb.d.ts
364
- type DebugInfo = {
365
- date: Date;
366
- logs: Array<string>;
367
- fileName?: string;
368
- };
369
- type HookProgress<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
370
- hookName: H;
371
- plugins: Array<Plugin>;
372
- };
373
- type HookExecution<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
374
- strategy: Strategy;
375
- hookName: H;
376
- plugin: Plugin;
377
- parameters?: Array<unknown>;
378
- output?: unknown;
379
- };
380
- type HookResult<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
381
- duration: number;
382
- strategy: Strategy;
383
- hookName: H;
384
- plugin: Plugin;
385
- parameters?: Array<unknown>;
386
- output?: unknown;
387
- };
426
+ //#region src/FileManager.d.ts
388
427
  /**
389
- * The instance returned by {@link createKubb}.
390
- */
391
- type Kubb$1 = {
392
- /**
393
- * The shared event emitter. Attach listeners here before calling `setup()` or `build()`.
394
- */
395
- readonly hooks: AsyncEventEmitter<KubbHooks>;
396
- /**
397
- * Raw generated source, keyed by absolute file path.
398
- * Populated after a successful `build()` or `safeBuild()` call.
399
- */
400
- readonly sources: Map<string, string>;
401
- /**
402
- * The plugin driver. Available after `setup()` has been called.
403
- */
404
- readonly driver: PluginDriver | undefined;
428
+ * In-memory file store for generated files.
429
+ *
430
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
431
+ * The `files` getter returns all stored files sorted by path length (shortest first).
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * import { FileManager } from '@kubb/core'
436
+ *
437
+ * const manager = new FileManager()
438
+ * manager.upsert(myFile)
439
+ * console.log(manager.files) // all stored files
440
+ * ```
441
+ */
442
+ declare class FileManager {
443
+ #private;
405
444
  /**
406
- * The resolved config with applied defaults. Available after `setup()` has been called.
445
+ * Adds one or more files. Files with the same path are merged sources, imports,
446
+ * and exports from all calls with the same path are concatenated together.
407
447
  */
408
- readonly config: Config | undefined;
448
+ add(...files: Array<FileNode>): Array<FileNode>;
409
449
  /**
410
- * Initializes all Kubb infrastructure: validates input, applies config defaults,
411
- * runs the adapter, and creates the PluginDriver.
412
- *
413
- * Calling `build()` or `safeBuild()` without calling `setup()` first will
414
- * automatically invoke `setup()` before proceeding.
450
+ * Adds or merges one or more files.
451
+ * If a file with the same path already exists, its sources/imports/exports are merged together.
415
452
  */
416
- setup(): Promise<void>;
453
+ upsert(...files: Array<FileNode>): Array<FileNode>;
454
+ getByPath(path: string): FileNode | null;
455
+ deleteByPath(path: string): void;
456
+ clear(): void;
417
457
  /**
418
- * Runs a full Kubb build and throws on any error or plugin failure.
419
- * Automatically calls `setup()` if it has not been called yet.
458
+ * All stored files, sorted by path length (shorter paths first).
459
+ * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
420
460
  */
421
- build(): Promise<BuildOutput>;
461
+ get files(): Array<FileNode>;
462
+ }
463
+ //#endregion
464
+ //#region src/PluginDriver.d.ts
465
+ type RequiredPluginLifecycle = Required<PluginLifecycle>;
466
+ /**
467
+ * Hook dispatch strategy used by the `PluginDriver`.
468
+ *
469
+ * - `hookFirst` — stops at the first non-null result.
470
+ * - `hookForPlugin` — calls only the matching plugin.
471
+ * - `hookParallel` — calls all plugins concurrently.
472
+ * - `hookSeq` — calls all plugins in order, threading the result.
473
+ */
474
+ type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq';
475
+ type ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H];
476
+ type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
477
+ result: Result;
478
+ plugin: Plugin;
479
+ };
480
+ type Options = {
481
+ hooks?: AsyncEventEmitter<KubbHooks>;
422
482
  /**
423
- * Runs a full Kubb build and captures errors instead of throwing.
424
- * Automatically calls `setup()` if it has not been called yet.
483
+ * @default Number.POSITIVE_INFINITY
425
484
  */
426
- safeBuild(): Promise<BuildOutput>;
485
+ concurrency?: number;
427
486
  };
428
487
  /**
429
- * Events emitted during the Kubb code generation lifecycle.
430
- * These events can be listened to for logging, progress tracking, and custom integrations.
431
- *
432
- * @example
433
- * ```typescript
434
- * import type { AsyncEventEmitter } from '@internals/utils'
435
- * import type { KubbHooks } from '@kubb/core'
436
- *
437
- * const hooks: AsyncEventEmitter<KubbHooks> = new AsyncEventEmitter()
438
- *
439
- * hooks.on('kubb:lifecycle:start', () => {
440
- * console.log('Starting Kubb generation')
441
- * })
442
- *
443
- * hooks.on('kubb:plugin:end', (plugin, { duration }) => {
444
- * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)
445
- * })
446
- * ```
488
+ * Parameters accepted by `PluginDriver.getFile` to resolve a generated file descriptor.
447
489
  */
448
- interface KubbHooks {
490
+ type GetFileOptions<TOptions = object> = {
491
+ name: string;
492
+ mode?: 'single' | 'split';
493
+ extname: FileNode['extname'];
494
+ pluginName: string;
495
+ options?: TOptions;
496
+ };
497
+ declare class PluginDriver {
498
+ #private;
499
+ readonly config: Config;
500
+ readonly options: Options;
449
501
  /**
450
- * Emitted at the beginning of the Kubb lifecycle, before any code generation starts.
502
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
503
+ *
504
+ * @example
505
+ * ```ts
506
+ * PluginDriver.getMode('src/gen/types.ts') // 'single'
507
+ * PluginDriver.getMode('src/gen/types') // 'split'
508
+ * ```
451
509
  */
452
- 'kubb:lifecycle:start': [version: string];
510
+ static getMode(fileOrFolder: string | undefined | null): 'single' | 'split';
453
511
  /**
454
- * Emitted at the end of the Kubb lifecycle, after all code generation is complete.
512
+ * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
513
+ * the build pipeline after the adapter's `parse()` resolves.
455
514
  */
456
- 'kubb:lifecycle:end': [];
515
+ inputNode: InputNode | undefined;
516
+ adapter: Adapter | undefined;
457
517
  /**
458
- * Emitted when configuration loading starts.
518
+ * Central file store for all generated files.
519
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
520
+ * add files; this property gives direct read/write access when needed.
459
521
  */
460
- 'kubb:config:start': [];
522
+ readonly fileManager: FileManager;
523
+ readonly plugins: Map<string, Plugin>;
524
+ constructor(config: Config, options: Options);
525
+ get hooks(): AsyncEventEmitter<KubbHooks>;
461
526
  /**
462
- * Emitted when configuration loading is complete.
527
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
528
+ *
529
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
530
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
531
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
532
+ *
533
+ * All other hooks are iterated and registered directly as pass-through listeners.
534
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
535
+ *
536
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
537
+ * the plugin lifecycle without modifying plugin behavior.
463
538
  */
464
- 'kubb:config:end': [configs: Array<Config>];
539
+ registerPluginHooks(hookPlugin: HookStylePlugin, normalizedPlugin: Plugin): void;
465
540
  /**
466
- * Emitted when code generation phase starts.
541
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
542
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
543
+ *
544
+ * Call this once from `safeBuild` before the plugin execution loop begins.
467
545
  */
468
- 'kubb:generation:start': [config: Config];
546
+ emitSetupHooks(): Promise<void>;
469
547
  /**
470
- * Emitted when code generation phase completes.
548
+ * Registers a generator for the given plugin on the shared event emitter.
549
+ *
550
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
551
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
552
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
553
+ * so that generators from different plugins do not cross-fire.
554
+ *
555
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
556
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
557
+ * declares a renderer.
558
+ *
559
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
471
560
  */
472
- 'kubb:generation:end': [config: Config, files: Array<FileNode>, sources: Map<string, string>];
561
+ registerGenerator(pluginName: string, gen: Generator): void;
473
562
  /**
474
- * Emitted with a summary of the generation results.
475
- * Contains summary lines, title, and success status.
563
+ * Returns `true` when at least one generator was registered for the given plugin
564
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
565
+ *
566
+ * Used by the build loop to decide whether to walk the AST and emit generator events
567
+ * for a plugin that has no static `plugin.generators`.
476
568
  */
477
- 'kubb:generation:summary': [config: Config, {
478
- failedPlugins: Set<{
479
- plugin: Plugin;
480
- error: Error;
481
- }>;
482
- status: 'success' | 'failed';
483
- hrStart: [number, number];
484
- filesCreated: number;
485
- pluginTimings?: Map<Plugin['name'], number>;
486
- }];
569
+ hasRegisteredGenerators(pluginName: string): boolean;
570
+ dispose(): void;
571
+ setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
572
+ getResolver(pluginName: string): Resolver;
573
+ getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown>;
487
574
  /**
488
- * Emitted when code formatting starts (e.g., running Biome or Prettier).
575
+ * @deprecated use resolvers context instead
489
576
  */
490
- 'kubb:format:start': [];
577
+ getFile<TOptions = object>({
578
+ name,
579
+ mode,
580
+ extname,
581
+ pluginName,
582
+ options
583
+ }: GetFileOptions<TOptions>): FileNode<{
584
+ pluginName: string;
585
+ }>;
491
586
  /**
492
- * Emitted when code formatting completes.
587
+ * @deprecated use resolvers context instead
493
588
  */
494
- 'kubb:format:end': [];
589
+ resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => string;
495
590
  /**
496
- * Emitted when linting starts.
591
+ * @deprecated use resolvers context instead
497
592
  */
498
- 'kubb:lint:start': [];
593
+ resolveName: (params: ResolveNameParams) => string;
499
594
  /**
500
- * Emitted when linting completes.
595
+ * Run a specific hookName for plugin x.
501
596
  */
502
- 'kubb:lint:end': [];
597
+ hookForPlugin<H extends PluginLifecycleHooks>({
598
+ pluginName,
599
+ hookName,
600
+ parameters
601
+ }: {
602
+ pluginName: string;
603
+ hookName: H;
604
+ parameters: PluginParameter<H>;
605
+ }): Promise<Array<ReturnType<ParseResult<H>> | null>>;
503
606
  /**
504
- * Emitted when plugin hooks execution starts.
607
+ * Run a specific hookName for plugin x.
505
608
  */
506
- 'kubb:hooks:start': [];
609
+ hookForPluginSync<H extends PluginLifecycleHooks>({
610
+ pluginName,
611
+ hookName,
612
+ parameters
613
+ }: {
614
+ pluginName: string;
615
+ hookName: H;
616
+ parameters: PluginParameter<H>;
617
+ }): Array<ReturnType<ParseResult<H>>> | null;
507
618
  /**
508
- * Emitted when plugin hooks execution completes.
619
+ * Returns the first non-null result.
509
620
  */
510
- 'kubb:hooks:end': [];
621
+ hookFirst<H extends PluginLifecycleHooks>({
622
+ hookName,
623
+ parameters,
624
+ skipped
625
+ }: {
626
+ hookName: H;
627
+ parameters: PluginParameter<H>;
628
+ skipped?: ReadonlySet<Plugin> | null;
629
+ }): Promise<SafeParseResult<H>>;
511
630
  /**
512
- * Emitted when a single hook execution starts (e.g., format or lint).
513
- * The callback should be invoked when the command completes.
631
+ * Returns the first non-null result.
514
632
  */
515
- 'kubb:hook:start': [{
516
- id?: string;
517
- command: string;
518
- args?: readonly string[];
519
- }];
633
+ hookFirstSync<H extends PluginLifecycleHooks>({
634
+ hookName,
635
+ parameters,
636
+ skipped
637
+ }: {
638
+ hookName: H;
639
+ parameters: PluginParameter<H>;
640
+ skipped?: ReadonlySet<Plugin> | null;
641
+ }): SafeParseResult<H> | null;
520
642
  /**
521
- * Emitted when a single hook execution completes.
643
+ * Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
644
+ */
645
+ hookParallel<H extends PluginLifecycleHooks, TOutput = void>({
646
+ hookName,
647
+ parameters
648
+ }: {
649
+ hookName: H;
650
+ parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
651
+ }): Promise<Awaited<TOutput>[]>;
652
+ /**
653
+ * Execute a lifecycle hook sequentially for all plugins that implement it.
654
+ */
655
+ hookSeq<H extends PluginLifecycleHooks>({
656
+ hookName,
657
+ parameters
658
+ }: {
659
+ hookName: H;
660
+ parameters?: PluginParameter<H>;
661
+ }): Promise<void>;
662
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
663
+ getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
664
+ /**
665
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
666
+ */
667
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>;
668
+ requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
669
+ }
670
+ //#endregion
671
+ //#region src/createKubb.d.ts
672
+ /**
673
+ * Full output produced by a successful or failed build.
674
+ */
675
+ type BuildOutput = {
676
+ /**
677
+ * Plugins that threw during installation, paired with the caught error.
678
+ */
679
+ failedPlugins: Set<{
680
+ plugin: Plugin;
681
+ error: Error;
682
+ }>;
683
+ files: Array<FileNode>;
684
+ driver: PluginDriver;
685
+ /**
686
+ * Elapsed time in milliseconds for each plugin, keyed by plugin name.
687
+ */
688
+ pluginTimings: Map<string, number>;
689
+ error?: Error;
690
+ /**
691
+ * Raw generated source, keyed by absolute file path.
692
+ */
693
+ sources: Map<string, string>;
694
+ };
695
+ type KubbOptions = {
696
+ config: Config;
697
+ hooks?: AsyncEventEmitter<KubbHooks>;
698
+ };
699
+ /**
700
+ * Creates a Kubb instance bound to a single config entry.
701
+ *
702
+ * The instance holds shared state (`hooks`, `sources`, `driver`, `config`) across the
703
+ * `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
704
+ * calling `setup()` or `build()`.
705
+ *
706
+ * @example
707
+ * ```ts
708
+ * const kubb = createKubb({ config })
709
+ *
710
+ * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {
711
+ * console.log(`${plugin.name} completed in ${duration}ms`)
712
+ * })
713
+ *
714
+ * const { files, failedPlugins } = await kubb.safeBuild()
715
+ * ```
716
+ */
717
+ declare function createKubb(options: KubbOptions): Kubb$1;
718
+ //#endregion
719
+ //#region src/Kubb.d.ts
720
+ type DebugInfo = {
721
+ date: Date;
722
+ logs: Array<string>;
723
+ fileName?: string;
724
+ };
725
+ type HookProgress<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
726
+ hookName: H;
727
+ plugins: Array<Plugin>;
728
+ };
729
+ type HookExecution<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
730
+ strategy: Strategy;
731
+ hookName: H;
732
+ plugin: Plugin;
733
+ parameters?: Array<unknown>;
734
+ output?: unknown;
735
+ };
736
+ type HookResult<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
737
+ duration: number;
738
+ strategy: Strategy;
739
+ hookName: H;
740
+ plugin: Plugin;
741
+ parameters?: Array<unknown>;
742
+ output?: unknown;
743
+ };
744
+ /**
745
+ * The instance returned by {@link createKubb}.
746
+ */
747
+ type Kubb$1 = {
748
+ /**
749
+ * The shared event emitter. Attach listeners here before calling `setup()` or `build()`.
750
+ */
751
+ readonly hooks: AsyncEventEmitter<KubbHooks>;
752
+ /**
753
+ * Raw generated source, keyed by absolute file path.
754
+ * Populated after a successful `build()` or `safeBuild()` call.
755
+ */
756
+ readonly sources: Map<string, string>;
757
+ /**
758
+ * The plugin driver. Available after `setup()` has been called.
759
+ */
760
+ readonly driver: PluginDriver | undefined;
761
+ /**
762
+ * The resolved config with applied defaults. Available after `setup()` has been called.
763
+ */
764
+ readonly config: Config | undefined;
765
+ /**
766
+ * Initializes all Kubb infrastructure: validates input, applies config defaults,
767
+ * runs the adapter, and creates the PluginDriver.
768
+ *
769
+ * Calling `build()` or `safeBuild()` without calling `setup()` first will
770
+ * automatically invoke `setup()` before proceeding.
771
+ */
772
+ setup(): Promise<void>;
773
+ /**
774
+ * Runs a full Kubb build and throws on any error or plugin failure.
775
+ * Automatically calls `setup()` if it has not been called yet.
776
+ */
777
+ build(): Promise<BuildOutput>;
778
+ /**
779
+ * Runs a full Kubb build and captures errors instead of throwing.
780
+ * Automatically calls `setup()` if it has not been called yet.
781
+ */
782
+ safeBuild(): Promise<BuildOutput>;
783
+ };
784
+ /**
785
+ * Events emitted during the Kubb code generation lifecycle.
786
+ * These events can be listened to for logging, progress tracking, and custom integrations.
787
+ *
788
+ * @example
789
+ * ```typescript
790
+ * import type { AsyncEventEmitter } from '@internals/utils'
791
+ * import type { KubbHooks } from '@kubb/core'
792
+ *
793
+ * const hooks: AsyncEventEmitter<KubbHooks> = new AsyncEventEmitter()
794
+ *
795
+ * hooks.on('kubb:lifecycle:start', () => {
796
+ * console.log('Starting Kubb generation')
797
+ * })
798
+ *
799
+ * hooks.on('kubb:plugin:end', (plugin, { duration }) => {
800
+ * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)
801
+ * })
802
+ * ```
803
+ */
804
+ interface KubbHooks {
805
+ /**
806
+ * Emitted at the beginning of the Kubb lifecycle, before any code generation starts.
807
+ */
808
+ 'kubb:lifecycle:start': [version: string];
809
+ /**
810
+ * Emitted at the end of the Kubb lifecycle, after all code generation is complete.
811
+ */
812
+ 'kubb:lifecycle:end': [];
813
+ /**
814
+ * Emitted when configuration loading starts.
815
+ */
816
+ 'kubb:config:start': [];
817
+ /**
818
+ * Emitted when configuration loading is complete.
819
+ */
820
+ 'kubb:config:end': [configs: Array<Config>];
821
+ /**
822
+ * Emitted when code generation phase starts.
823
+ */
824
+ 'kubb:generation:start': [config: Config];
825
+ /**
826
+ * Emitted when code generation phase completes.
827
+ */
828
+ 'kubb:generation:end': [config: Config, files: Array<FileNode>, sources: Map<string, string>];
829
+ /**
830
+ * Emitted with a summary of the generation results.
831
+ * Contains summary lines, title, and success status.
832
+ */
833
+ 'kubb:generation:summary': [config: Config, {
834
+ failedPlugins: Set<{
835
+ plugin: Plugin;
836
+ error: Error;
837
+ }>;
838
+ status: 'success' | 'failed';
839
+ hrStart: [number, number];
840
+ filesCreated: number;
841
+ pluginTimings?: Map<Plugin['name'], number>;
842
+ }];
843
+ /**
844
+ * Emitted when code formatting starts (e.g., running Biome or Prettier).
845
+ */
846
+ 'kubb:format:start': [];
847
+ /**
848
+ * Emitted when code formatting completes.
849
+ */
850
+ 'kubb:format:end': [];
851
+ /**
852
+ * Emitted when linting starts.
853
+ */
854
+ 'kubb:lint:start': [];
855
+ /**
856
+ * Emitted when linting completes.
857
+ */
858
+ 'kubb:lint:end': [];
859
+ /**
860
+ * Emitted when plugin hooks execution starts.
861
+ */
862
+ 'kubb:hooks:start': [];
863
+ /**
864
+ * Emitted when plugin hooks execution completes.
865
+ */
866
+ 'kubb:hooks:end': [];
867
+ /**
868
+ * Emitted when a single hook execution starts (e.g., format or lint).
869
+ * The callback should be invoked when the command completes.
870
+ */
871
+ 'kubb:hook:start': [{
872
+ id?: string;
873
+ command: string;
874
+ args?: readonly string[];
875
+ }];
876
+ /**
877
+ * Emitted when a single hook execution completes.
522
878
  */
523
879
  'kubb:hook:end': [{
524
880
  id?: string;
@@ -691,164 +1047,25 @@ declare global {
691
1047
  }
692
1048
  }
693
1049
  //#endregion
694
- //#region src/definePlugin.d.ts
695
- /**
696
- * Base hook handlers for all events except `kubb:plugin:setup`.
697
- * These handlers have identical signatures regardless of the plugin's
698
- * `PluginFactoryOptions` generic — they are split out so that the
699
- * interface below only needs to override the one event that depends on
700
- * the plugin type.
701
- */
702
- type PluginHooksBase = { [K in Exclude<keyof KubbHooks, 'kubb:plugin:setup'>]?: (...args: KubbHooks[K]) => void | Promise<void> };
703
- /**
704
- * Plugin hook handlers.
705
- *
706
- * `kubb:plugin:setup` is typed with the plugin's own `PluginFactoryOptions` so
707
- * `ctx.setResolver`, `ctx.setOptions`, `ctx.options` etc. use the correct types.
708
- *
709
- * Uses interface + method shorthand for `kubb:plugin:setup`
710
- * checking, allowing `PluginHooks<PluginTs>` to be assignable to `PluginHooks`.
711
- *
712
- * @template TFactory - The plugin's `PluginFactoryOptions` type.
713
- */
714
- interface PluginHooks<TFactory extends PluginFactoryOptions = PluginFactoryOptions> extends PluginHooksBase {
715
- 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
716
- }
717
- /**
718
- * A hook-style plugin object produced by `definePlugin`.
719
- * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property
720
- * (matching Astro's integration naming convention).
721
- *
722
- * @template TFactory - The plugin's `PluginFactoryOptions` type.
723
- */
724
- type HookStylePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
725
- /**
726
- * Unique name for the plugin, following the same naming convention as `createPlugin`.
727
- */
728
- name: string;
729
- /**
730
- * Plugins that must be registered before this plugin executes.
731
- * An error is thrown at startup when any listed dependency is missing.
732
- */
733
- dependencies?: Array<string>;
734
- /**
735
- * The options passed by the user when calling the plugin factory.
736
- */
737
- options?: TFactory['options'];
738
- /**
739
- * Lifecycle event handlers for this plugin.
740
- * Any event from the global `KubbHooks` map can be subscribed to here.
741
- */
742
- hooks: PluginHooks<TFactory>;
743
- };
744
- /**
745
- * Creates a plugin factory using the new hook-style (`hooks:`) API.
746
- *
747
- * The returned factory is called with optional options and produces a `HookStylePlugin`
748
- * that coexists with plugins created via the legacy `createPlugin` API in the same
749
- * `kubb.config.ts`.
750
- *
751
- * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
752
- * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
753
- *
754
- * @example
755
- * ```ts
756
- * // With PluginFactoryOptions (recommended for real plugins)
757
- * export const pluginTs = definePlugin<PluginTs>((options) => ({
758
- * name: 'plugin-ts',
759
- * hooks: {
760
- * 'kubb:plugin:setup'(ctx) {
761
- * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
762
- * },
763
- * },
764
- * }))
765
- * ```
766
- */
767
- declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => HookStylePlugin<TFactory>): (options?: TFactory['options']) => HookStylePlugin<TFactory>;
768
- //#endregion
769
- //#region src/utils/FunctionParams.d.ts
770
- type FunctionParamsASTWithoutType = {
771
- name?: string;
772
- type?: string;
773
- /**
774
- * @default true
775
- */
776
- required?: boolean;
777
- /**
778
- * @default true
779
- */
780
- enabled?: boolean;
781
- default?: string;
782
- };
783
- type FunctionParamsASTWithType = {
784
- name?: never;
785
- type: string;
786
- /**
787
- * @default true
788
- */
789
- required?: boolean;
790
- /**
791
- * @default true
792
- */
793
- enabled?: boolean;
794
- default?: string;
795
- };
796
- /**
797
- * @deprecated use ast package instead
798
- */
799
- type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType;
800
- //#endregion
801
- //#region src/utils/getBarrelFiles.d.ts
802
- type FileMetaBase = {
803
- pluginName?: string;
804
- };
805
- type AddIndexesProps = {
806
- type: BarrelType | false | undefined;
807
- /**
808
- * Absolute output root derived from config `root` and `output.path`.
809
- */
810
- root: string;
811
- /**
812
- * Output settings for the plugin.
813
- */
814
- output: {
815
- path: string;
816
- };
817
- group?: {
818
- output: string;
819
- exportAs: string;
820
- };
821
- meta?: FileMetaBase;
822
- };
823
- /**
824
- * Generates `index.ts` barrel files for all directories under `root/output.path`.
825
- *
826
- * - Returns an empty array when `type` is falsy or `'propagate'`.
827
- * - Skips generation when the output path itself ends with `index` (already a barrel).
828
- * - When `type` is `'all'`, strips named exports so every re-export becomes a wildcard (`export * from`).
829
- * - Attaches `meta` to each barrel file for downstream plugin identification.
830
- */
831
- declare function getBarrelFiles(files: Array<FileNode>, {
832
- type,
833
- meta,
834
- root,
835
- output
836
- }: AddIndexesProps): Promise<Array<FileNode>>;
837
- //#endregion
838
- //#region src/types.d.ts
839
- type InputPath = {
840
- /**
841
- * Specify your Swagger/OpenAPI file, either as an absolute path or a path relative to the root.
842
- */
843
- path: string;
844
- };
845
- type InputData = {
846
- /**
847
- * A `string` or `object` that contains your Swagger/OpenAPI data.
848
- */
849
- data: string | unknown;
850
- };
851
- type Input = InputPath | InputData;
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;
852
1069
  /**
853
1070
  * The raw source passed to an adapter's `parse` function.
854
1071
  * Mirrors the shape of `Config['input']` with paths already resolved to absolute.
@@ -1249,7 +1466,7 @@ type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> =
1249
1466
  * over `plugin.renderer`; set `renderer: null` on a generator to opt out of rendering even
1250
1467
  * when the plugin declares a renderer.
1251
1468
  */
1252
- generators?: Array<Generator<any>>;
1469
+ generators?: Array<Generator>;
1253
1470
  /**
1254
1471
  * Specifies the plugins that the current plugin depends on. The current plugin is executed after all listed plugins.
1255
1472
  * An error is returned if any required dependency plugin is missing.
@@ -1352,7 +1569,7 @@ type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1352
1569
  * over `plugin.renderer`; set `renderer: null` on a generator to opt out of rendering even
1353
1570
  * when the plugin declares a renderer.
1354
1571
  */
1355
- generators?: Array<Generator<any>>;
1572
+ generators?: Array<Generator>;
1356
1573
  buildStart: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1357
1574
  /**
1358
1575
  * Called once per plugin after all files have been written to disk.
@@ -1488,7 +1705,7 @@ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions>
1488
1705
  /**
1489
1706
  * Returns the output mode for the given output config.
1490
1707
  * Returns `'single'` when `output.path` has a file extension, `'split'` otherwise.
1491
- * Shorthand for `getMode(path.resolve(this.root, output.path))`.
1708
+ * Shorthand for `PluginDriver.getMode(path.resolve(this.root, output.path))`.
1492
1709
  */
1493
1710
  getMode: (output: {
1494
1711
  path: string;
@@ -1902,341 +2119,6 @@ type CLIOptions = {
1902
2119
  * - `PossibleConfig<TCliOptions>` accepts the same config forms or a config factory receiving `TCliOptions`.
1903
2120
  */
1904
2121
  type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Config[]> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>);
1905
- /**
1906
- * All accepted forms of a Kubb configuration.
1907
- * @deprecated
1908
- * Kept for backward compatibility. Prefer `PossibleConfig<CLIOptions>` in new code.
1909
- */
1910
- type ConfigInput = PossibleConfig<CLIOptions>;
1911
- //#endregion
1912
- //#region src/defineGenerator.d.ts
1913
- /**
1914
- * A generator is a named object with optional `schema`, `operation`, and `operations`
1915
- * methods. Each method receives the AST node as the first argument and a typed
1916
- * `ctx` object as the second, giving access to `ctx.config`, `ctx.resolver`,
1917
- * `ctx.adapter`, `ctx.options`, `ctx.upsertFile`, etc.
1918
- *
1919
- * Generators that return renderer elements (e.g. JSX) must declare a `renderer`
1920
- * factory so that core knows how to process the output without coupling core
1921
- * to any specific renderer package.
1922
- *
1923
- * Return a renderer element, an array of `FileNode`, or `void` to handle file
1924
- * writing manually via `ctx.upsertFile`.
1925
- *
1926
- * @example
1927
- * ```ts
1928
- * import { jsxRenderer } from '@kubb/renderer-jsx'
1929
- *
1930
- * export const typeGenerator = defineGenerator<PluginTs>({
1931
- * name: 'typescript',
1932
- * renderer: jsxRenderer,
1933
- * schema(node, ctx) {
1934
- * const { adapter, resolver, root, options } = ctx
1935
- * return <File ...><Type node={node} resolver={resolver} /></File>
1936
- * },
1937
- * operation(node, ctx) {
1938
- * const { options } = ctx
1939
- * return <File ...><OperationType node={node} /></File>
1940
- * },
1941
- * })
1942
- * ```
1943
- */
1944
- type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
1945
- /**
1946
- * Used in diagnostic messages and debug output.
1947
- */
1948
- name: string;
1949
- /**
1950
- * Optional renderer factory that produces a {@link Renderer} for each render cycle.
1951
- *
1952
- * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
1953
- * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
1954
- *
1955
- * Generators that only return `Array<FileNode>` or `void` do not need to set this.
1956
- *
1957
- * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin
1958
- * declares a `renderer` (overrides the plugin-level fallback).
1959
- *
1960
- * @example
1961
- * ```ts
1962
- * import { jsxRenderer } from '@kubb/renderer-jsx'
1963
- * export const myGenerator = defineGenerator<PluginTs>({
1964
- * renderer: jsxRenderer,
1965
- * schema(node, ctx) { return <File ...>...</File> },
1966
- * })
1967
- * ```
1968
- */
1969
- renderer?: RendererFactory<TElement> | null;
1970
- /**
1971
- * Called for each schema node in the AST walk.
1972
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
1973
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1974
- */
1975
- schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1976
- /**
1977
- * Called for each operation node in the AST walk.
1978
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
1979
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1980
- */
1981
- operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1982
- /**
1983
- * Called once after all operations have been walked.
1984
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
1985
- * plus `ctx.options` with the plugin-level options for the batch call.
1986
- */
1987
- operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1988
- };
1989
- /**
1990
- * Defines a generator. Returns the object as-is with correct `this` typings.
1991
- * `applyHookResult` handles renderer elements and `File[]` uniformly using
1992
- * the generator's declared `renderer` factory.
1993
- */
1994
- declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
1995
- //#endregion
1996
- //#region src/FileManager.d.ts
1997
- /**
1998
- * In-memory file store for generated files.
1999
- *
2000
- * Files with the same `path` are merged — sources, imports, and exports are concatenated.
2001
- * The `files` getter returns all stored files sorted by path length (shortest first).
2002
- *
2003
- * @example
2004
- * ```ts
2005
- * import { FileManager } from '@kubb/core'
2006
- *
2007
- * const manager = new FileManager()
2008
- * manager.upsert(myFile)
2009
- * console.log(manager.files) // all stored files
2010
- * ```
2011
- */
2012
- declare class FileManager {
2013
- #private;
2014
- /**
2015
- * Adds one or more files. Files with the same path are merged — sources, imports,
2016
- * and exports from all calls with the same path are concatenated together.
2017
- */
2018
- add(...files: Array<FileNode>): Array<FileNode>;
2019
- /**
2020
- * Adds or merges one or more files.
2021
- * If a file with the same path already exists, its sources/imports/exports are merged together.
2022
- */
2023
- upsert(...files: Array<FileNode>): Array<FileNode>;
2024
- getByPath(path: string): FileNode | null;
2025
- deleteByPath(path: string): void;
2026
- clear(): void;
2027
- /**
2028
- * All stored files, sorted by path length (shorter paths first).
2029
- * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
2030
- */
2031
- get files(): Array<FileNode>;
2032
- }
2033
- //#endregion
2034
- //#region src/PluginDriver.d.ts
2035
- type RequiredPluginLifecycle = Required<PluginLifecycle>;
2036
- /**
2037
- * Hook dispatch strategy used by the `PluginDriver`.
2038
- *
2039
- * - `hookFirst` — stops at the first non-null result.
2040
- * - `hookForPlugin` — calls only the matching plugin.
2041
- * - `hookParallel` — calls all plugins concurrently.
2042
- * - `hookSeq` — calls all plugins in order, threading the result.
2043
- */
2044
- type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq';
2045
- type ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H];
2046
- type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
2047
- result: Result;
2048
- plugin: Plugin;
2049
- };
2050
- type Options = {
2051
- hooks?: AsyncEventEmitter<KubbHooks>;
2052
- /**
2053
- * @default Number.POSITIVE_INFINITY
2054
- */
2055
- concurrency?: number;
2056
- };
2057
- /**
2058
- * Parameters accepted by `PluginDriver.getFile` to resolve a generated file descriptor.
2059
- */
2060
- type GetFileOptions<TOptions = object> = {
2061
- name: string;
2062
- mode?: 'single' | 'split';
2063
- extname: FileNode['extname'];
2064
- pluginName: string;
2065
- options?: TOptions;
2066
- };
2067
- /**
2068
- * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
2069
- *
2070
- * @example
2071
- * ```ts
2072
- * getMode('src/gen/types.ts') // 'single'
2073
- * getMode('src/gen/types') // 'split'
2074
- * ```
2075
- */
2076
- declare function getMode(fileOrFolder: string | undefined | null): 'single' | 'split';
2077
- declare class PluginDriver {
2078
- #private;
2079
- readonly config: Config;
2080
- readonly options: Options;
2081
- /**
2082
- * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
2083
- * the build pipeline after the adapter's `parse()` resolves.
2084
- */
2085
- inputNode: InputNode | undefined;
2086
- adapter: Adapter | undefined;
2087
- /**
2088
- * Central file store for all generated files.
2089
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
2090
- * add files; this property gives direct read/write access when needed.
2091
- */
2092
- readonly fileManager: FileManager;
2093
- readonly plugins: Map<string, Plugin>;
2094
- constructor(config: Config, options: Options);
2095
- get hooks(): AsyncEventEmitter<KubbHooks>;
2096
- /**
2097
- * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
2098
- *
2099
- * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
2100
- * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
2101
- * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
2102
- *
2103
- * All other hooks are iterated and registered directly as pass-through listeners.
2104
- * Any event key present in the global `KubbHooks` interface can be subscribed to.
2105
- *
2106
- * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
2107
- * the plugin lifecycle without modifying plugin behavior.
2108
- */
2109
- registerPluginHooks(hookPlugin: HookStylePlugin, normalizedPlugin: Plugin): void;
2110
- /**
2111
- * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
2112
- * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
2113
- *
2114
- * Call this once from `safeBuild` before the plugin execution loop begins.
2115
- */
2116
- emitSetupHooks(): Promise<void>;
2117
- /**
2118
- * Registers a generator for the given plugin on the shared event emitter.
2119
- *
2120
- * The generator's `schema`, `operation`, and `operations` methods are registered as
2121
- * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
2122
- * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
2123
- * so that generators from different plugins do not cross-fire.
2124
- *
2125
- * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
2126
- * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
2127
- * declares a renderer.
2128
- *
2129
- * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
2130
- */
2131
- registerGenerator(pluginName: string, gen: Generator<any>): void;
2132
- /**
2133
- * Returns `true` when at least one generator was registered for the given plugin
2134
- * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
2135
- *
2136
- * Used by the build loop to decide whether to walk the AST and emit generator events
2137
- * for a plugin that has no static `plugin.generators`.
2138
- */
2139
- hasRegisteredGenerators(pluginName: string): boolean;
2140
- dispose(): void;
2141
- setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
2142
- getResolver(pluginName: string): Resolver;
2143
- getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown>;
2144
- /**
2145
- * @deprecated use resolvers context instead
2146
- */
2147
- getFile<TOptions = object>({
2148
- name,
2149
- mode,
2150
- extname,
2151
- pluginName,
2152
- options
2153
- }: GetFileOptions<TOptions>): FileNode<{
2154
- pluginName: string;
2155
- }>;
2156
- /**
2157
- * @deprecated use resolvers context instead
2158
- */
2159
- resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => string;
2160
- /**
2161
- * @deprecated use resolvers context instead
2162
- */
2163
- resolveName: (params: ResolveNameParams) => string;
2164
- /**
2165
- * Run a specific hookName for plugin x.
2166
- */
2167
- hookForPlugin<H extends PluginLifecycleHooks>({
2168
- pluginName,
2169
- hookName,
2170
- parameters
2171
- }: {
2172
- pluginName: string;
2173
- hookName: H;
2174
- parameters: PluginParameter<H>;
2175
- }): Promise<Array<ReturnType<ParseResult<H>> | null>>;
2176
- /**
2177
- * Run a specific hookName for plugin x.
2178
- */
2179
- hookForPluginSync<H extends PluginLifecycleHooks>({
2180
- pluginName,
2181
- hookName,
2182
- parameters
2183
- }: {
2184
- pluginName: string;
2185
- hookName: H;
2186
- parameters: PluginParameter<H>;
2187
- }): Array<ReturnType<ParseResult<H>>> | null;
2188
- /**
2189
- * Returns the first non-null result.
2190
- */
2191
- hookFirst<H extends PluginLifecycleHooks>({
2192
- hookName,
2193
- parameters,
2194
- skipped
2195
- }: {
2196
- hookName: H;
2197
- parameters: PluginParameter<H>;
2198
- skipped?: ReadonlySet<Plugin> | null;
2199
- }): Promise<SafeParseResult<H>>;
2200
- /**
2201
- * Returns the first non-null result.
2202
- */
2203
- hookFirstSync<H extends PluginLifecycleHooks>({
2204
- hookName,
2205
- parameters,
2206
- skipped
2207
- }: {
2208
- hookName: H;
2209
- parameters: PluginParameter<H>;
2210
- skipped?: ReadonlySet<Plugin> | null;
2211
- }): SafeParseResult<H> | null;
2212
- /**
2213
- * Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
2214
- */
2215
- hookParallel<H extends PluginLifecycleHooks, TOutput = void>({
2216
- hookName,
2217
- parameters
2218
- }: {
2219
- hookName: H;
2220
- parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
2221
- }): Promise<Awaited<TOutput>[]>;
2222
- /**
2223
- * Execute a lifecycle hook sequentially for all plugins that implement it.
2224
- */
2225
- hookSeq<H extends PluginLifecycleHooks>({
2226
- hookName,
2227
- parameters
2228
- }: {
2229
- hookName: H;
2230
- parameters?: PluginParameter<H>;
2231
- }): Promise<void>;
2232
- getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
2233
- getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
2234
- /**
2235
- * Like `getPlugin` but throws a descriptive error when the plugin is not found.
2236
- */
2237
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>;
2238
- requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
2239
- }
2240
2122
  //#endregion
2241
- export { FileMetaBase as $, Override as A, ResolveNameParams as B, KubbPluginSetupContext as C, OperationHook as D, LoggerOptions as E, PluginLifecycleHooks as F, ResolverContext as G, ResolvePathOptions as H, PluginParameter as I, SchemaHook as J, ResolverFileParams as K, PluginWithLifeCycle as L, PluginContext as M, PluginFactoryOptions as N, OperationsHook as O, PluginLifecycle as P, UserPluginWithLifeCycle as Q, PossibleConfig as R, KubbBuildStartContext as S, LoggerContext as T, ResolvePathParams as U, ResolveOptionsContext as V, Resolver as W, UserLogger as X, UserGroup as Y, UserPlugin as Z, Group as _, RendererFactory as _t, defineGenerator as a, Kubb$1 as at, InputPath as b, AdapterSource as c, createKubb as ct, CompatibilityPreset as d, Storage as dt, getBarrelFiles as et, Config as f, createStorage as ft, GeneratorContext as g, Renderer as gt, Exclude$1 as h, logLevel as ht, Generator as i, definePlugin as it, Plugin as j, Output as k, BarrelType as l, Parser as lt, DevtoolsOptions as m, linters as mt, getMode as n, HookStylePlugin as nt, Adapter as o, KubbHooks as ot, ConfigInput as p, formatters as pt, ResolverPathParams as q, FileManager as r, PluginHooks as rt, AdapterFactoryOptions as s, BuildOutput as st, PluginDriver as t, FunctionParamsAST as tt, CLIOptions as u, defineParser as ut, Include as v, createRenderer as vt, Logger as w, KubbBuildEndContext as x, InputData as y, AsyncEventEmitter as yt, ResolveBannerContext as z };
2242
- //# sourceMappingURL=PluginDriver-C9iBgYbk.d.ts.map
2123
+ export { FileManager as $, PluginParameter as A, ResolverFileParams as B, Output as C, PluginFactoryOptions as D, PluginContext as E, ResolveOptionsContext as F, UserPlugin as G, SchemaHook as H, ResolvePathOptions as I, Kubb$1 as J, UserPluginWithLifeCycle as K, ResolvePathParams as L, PossibleConfig as M, ResolveBannerContext as N, PluginLifecycle as O, ResolveNameParams as P, PluginDriver as Q, Resolver as R, OperationsHook as S, Plugin as T, UserGroup as U, ResolverPathParams as V, UserLogger as W, BuildOutput as X, KubbHooks as Y, createKubb as Z, KubbPluginSetupContext as _, CLIOptions as a, Generator as at, LoggerOptions as b, DevtoolsOptions as c, createStorage as ct, Group as d, createRenderer as dt, HookStylePlugin as et, Include as f, logLevel as ft, KubbBuildStartContext as g, KubbBuildEndContext as h, BarrelType as i, defineParser as it, PluginWithLifeCycle as j, PluginLifecycleHooks as k, Exclude$1 as l, Renderer as lt, InputPath as m, AdapterFactoryOptions as n, definePlugin as nt, CompatibilityPreset as o, defineGenerator as ot, InputData as p, AsyncEventEmitter as pt, FileMetaBase as q, AdapterSource as r, Parser as rt, Config as s, Storage as st, Adapter as t, PluginHooks as tt, GeneratorContext as u, RendererFactory as ut, Logger as v, Override as w, OperationHook as x, LoggerContext as y, ResolverContext as z };
2124
+ //# sourceMappingURL=types-DUc5lEUp.d.ts.map