@kubb/core 5.0.0-beta.11 → 5.0.0-beta.110

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