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

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/diagnostics-CQYd4UQZ.d.ts +2888 -0
  4. package/dist/index.cjs +2350 -1102
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +80 -138
  7. package/dist/index.js +2344 -1101
  8. package/dist/index.js.map +1 -1
  9. package/dist/memoryStorage-9cOBg7bL.cjs +1022 -0
  10. package/dist/memoryStorage-9cOBg7bL.cjs.map +1 -0
  11. package/dist/memoryStorage-C-3NpTDQ.js +884 -0
  12. package/dist/memoryStorage-C-3NpTDQ.js.map +1 -0
  13. package/dist/mocks.cjs +84 -24
  14. package/dist/mocks.cjs.map +1 -1
  15. package/dist/mocks.d.ts +37 -11
  16. package/dist/mocks.js +86 -28
  17. package/dist/mocks.js.map +1 -1
  18. package/package.json +9 -23
  19. package/dist/PluginDriver-Cu1Kj9S-.cjs +0 -1075
  20. package/dist/PluginDriver-Cu1Kj9S-.cjs.map +0 -1
  21. package/dist/PluginDriver-D8Z0Htid.js +0 -978
  22. package/dist/PluginDriver-D8Z0Htid.js.map +0 -1
  23. package/dist/createKubb-Cagd4PIe.d.ts +0 -2082
  24. package/src/FileManager.ts +0 -115
  25. package/src/FileProcessor.ts +0 -86
  26. package/src/PluginDriver.ts +0 -457
  27. package/src/constants.ts +0 -35
  28. package/src/createAdapter.ts +0 -108
  29. package/src/createKubb.ts +0 -1268
  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 -90
  42. package/src/storages/memoryStorage.ts +0 -55
  43. package/src/types.ts +0 -41
  44. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -0,0 +1,2888 @@
1
+ import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
2
+ import { Enforce, FileNode, HttpMethod, ImportNode, InputMeta, InputNode, Macro, Node, OperationNode, SchemaNode, UserFileNode } 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 Array<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]: Array<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> | 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
+ * Removes a previously registered listener.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * emitter.off('build', handler)
52
+ * ```
53
+ */
54
+ off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
55
+ /**
56
+ * Returns the number of listeners registered for `eventName`.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * emitter.on('build', handler)
61
+ * emitter.listenerCount('build') // 1
62
+ * ```
63
+ */
64
+ listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number;
65
+ /**
66
+ * Raises or lowers the per-event listener ceiling before Node warns about a memory leak.
67
+ * Set this above the expected listener count when many listeners attach by design.
68
+ *
69
+ * @example
70
+ * ```ts
71
+ * emitter.setMaxListeners(40)
72
+ * ```
73
+ */
74
+ setMaxListeners(max: number): void;
75
+ /**
76
+ * Removes all listeners from every event channel.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * emitter.removeAll()
81
+ * ```
82
+ */
83
+ removeAll(): void;
84
+ }
85
+ //#endregion
86
+ //#region ../../internals/utils/src/promise.d.ts
87
+ /** A value that may already be resolved or still pending.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * function load(id: string): PossiblePromise<string> {
92
+ * return cache.get(id) ?? fetchRemote(id)
93
+ * }
94
+ * ```
95
+ */
96
+ type PossiblePromise<T> = Promise<T> | T;
97
+ //#endregion
98
+ //#region src/createAdapter.d.ts
99
+ /**
100
+ * Source data handed to an adapter's `parse` function. Mirrors the config
101
+ * input shape with paths resolved to absolute.
102
+ *
103
+ * - `{ type: 'path' }`: single file on disk.
104
+ * - `{ type: 'data' }`: raw string or parsed object provided inline.
105
+ */
106
+ type AdapterSource = {
107
+ type: 'path';
108
+ path: string;
109
+ } | {
110
+ type: 'data';
111
+ data: string | unknown;
112
+ };
113
+ /**
114
+ * Generic parameters used by `createAdapter` and the resulting `Adapter` type.
115
+ *
116
+ * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).
117
+ * - `TOptions`: user-facing options accepted by the adapter factory.
118
+ * - `TResolvedOptions`: options after defaults are applied.
119
+ * - `TDocument`: type of the parsed source document.
120
+ */
121
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
122
+ name: TName;
123
+ options: TOptions;
124
+ resolvedOptions: TResolvedOptions;
125
+ document: TDocument;
126
+ };
127
+ /**
128
+ * Converts input files or inline data into Kubb's universal AST `InputNode`.
129
+ *
130
+ * Adapters live between the spec format and the plugins. The built-in
131
+ * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can
132
+ * support GraphQL, gRPC, or another schema language.
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * import { defineConfig } from 'kubb'
137
+ * import { adapterOas } from '@kubb/adapter-oas'
138
+ * import { pluginTs } from '@kubb/plugin-ts'
139
+ *
140
+ * export default defineConfig({
141
+ * input: { path: './petStore.yaml' },
142
+ * output: { path: './src/gen' },
143
+ * adapter: adapterOas(),
144
+ * plugins: [pluginTs()],
145
+ * })
146
+ * ```
147
+ */
148
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
149
+ /**
150
+ * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
151
+ */
152
+ name: TOptions['name'];
153
+ /**
154
+ * Resolved adapter options after defaults have been applied.
155
+ */
156
+ options: TOptions['resolvedOptions'];
157
+ /**
158
+ * Parsed source document after the first `parse()` call. `null` before parsing.
159
+ */
160
+ document: TOptions['document'] | null;
161
+ /**
162
+ * Parse the source into a universal `InputNode`.
163
+ */
164
+ parse: (source: AdapterSource) => PossiblePromise<InputNode>;
165
+ /**
166
+ * Extract `ImportNode` entries for a schema tree.
167
+ * Returns an empty array before the first `parse()` call.
168
+ *
169
+ * The `resolve` callback receives the collision-corrected schema name and must
170
+ * return `{ name, path }` for the import, or `undefined` to skip it.
171
+ */
172
+ getImports: (node: SchemaNode, resolve: (schemaName: string) => {
173
+ name: string;
174
+ path: string;
175
+ }) => Array<ImportNode>;
176
+ /**
177
+ * Validate the document at the given path or URL.
178
+ */
179
+ validate: (input: string, options?: {
180
+ throwOnError?: boolean;
181
+ }) => Promise<void>;
182
+ /**
183
+ * Memory-efficient streaming variant of `parse()`.
184
+ *
185
+ * Returns an `InputNode<true>` whose `schemas` and `operations` are `AsyncIterable`.
186
+ * Each `for await` loop creates a fresh parse pass over the cached in-memory document.
187
+ * No pre-built arrays are held in memory.
188
+ */
189
+ stream?: (source: AdapterSource) => Promise<InputNode<true>>;
190
+ };
191
+ type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>;
192
+ /**
193
+ * Defines a custom adapter that translates a spec format into Kubb's universal
194
+ * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
195
+ * handles OpenAPI/Swagger documents.
196
+ *
197
+ * Adapters must return an `InputNode` from `parse`. That node is what every
198
+ * plugin in the build consumes.
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * import { createAdapter, ast, type AdapterFactoryOptions } from '@kubb/core'
203
+ *
204
+ * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
205
+ *
206
+ * export const myAdapter = createAdapter<MyAdapter>((options) => ({
207
+ * name: 'my-adapter',
208
+ * options,
209
+ * document: null,
210
+ * async parse(_source) {
211
+ * // Convert the source (path or inline data) into an InputNode.
212
+ * return ast.factory.createInput()
213
+ * },
214
+ * getImports: () => [],
215
+ * async validate() {
216
+ * // Throw here when the spec is invalid.
217
+ * },
218
+ * }))
219
+ * ```
220
+ */
221
+ declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T>;
222
+ //#endregion
223
+ //#region src/constants.d.ts
224
+ /**
225
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
226
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
227
+ * these instead of inlining the string at a throw site.
228
+ */
229
+ declare const diagnosticCode: {
230
+ /**
231
+ * Fallback for an unstructured error with no specific code.
232
+ */
233
+ readonly unknown: "KUBB_UNKNOWN";
234
+ /**
235
+ * The `input.path` file or URL could not be read.
236
+ */
237
+ readonly inputNotFound: "KUBB_INPUT_NOT_FOUND";
238
+ /**
239
+ * An adapter was configured without an `input`.
240
+ */
241
+ readonly inputRequired: "KUBB_INPUT_REQUIRED";
242
+ /**
243
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
244
+ */
245
+ readonly refNotFound: "KUBB_REF_NOT_FOUND";
246
+ /**
247
+ * A server variable value is not allowed by its `enum`.
248
+ */
249
+ readonly invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE";
250
+ /**
251
+ * A required plugin is missing from the config.
252
+ */
253
+ readonly pluginNotFound: "KUBB_PLUGIN_NOT_FOUND";
254
+ /**
255
+ * A plugin threw while generating.
256
+ */
257
+ readonly pluginFailed: "KUBB_PLUGIN_FAILED";
258
+ /**
259
+ * A plugin reported a non-fatal warning through `ctx.warn`.
260
+ */
261
+ readonly pluginWarning: "KUBB_PLUGIN_WARNING";
262
+ /**
263
+ * A plugin reported an informational message through `ctx.info`.
264
+ */
265
+ readonly pluginInfo: "KUBB_PLUGIN_INFO";
266
+ /**
267
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
268
+ * adapters to emit as a `warning`.
269
+ */
270
+ readonly unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT";
271
+ /**
272
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
273
+ * to emit as an `info`.
274
+ */
275
+ readonly deprecated: "KUBB_DEPRECATED";
276
+ /**
277
+ * An adapter is required but the config has none. The build cannot read the input
278
+ * without one.
279
+ */
280
+ readonly adapterRequired: "KUBB_ADAPTER_REQUIRED";
281
+ /**
282
+ * A resolved output path escapes the output directory, which can stem from a path
283
+ * traversal in the spec or a misconfigured `group.name`.
284
+ */
285
+ readonly pathTraversal: "KUBB_PATH_TRAVERSAL";
286
+ /**
287
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
288
+ */
289
+ readonly invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS";
290
+ /**
291
+ * A post-generate shell hook (`hooks.done`) exited with a failure.
292
+ */
293
+ readonly hookFailed: "KUBB_HOOK_FAILED";
294
+ /**
295
+ * The formatter pass over the generated files failed.
296
+ */
297
+ readonly formatFailed: "KUBB_FORMAT_FAILED";
298
+ /**
299
+ * The linter pass over the generated files failed.
300
+ */
301
+ readonly lintFailed: "KUBB_LINT_FAILED";
302
+ /**
303
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
304
+ */
305
+ readonly performance: "KUBB_PERFORMANCE";
306
+ /**
307
+ * Not a failure. A newer Kubb version is available on npm.
308
+ */
309
+ readonly updateAvailable: "KUBB_UPDATE_AVAILABLE";
310
+ };
311
+ /**
312
+ * Union of the stable {@link diagnosticCode} values.
313
+ */
314
+ type DiagnosticCode = (typeof diagnosticCode)[keyof typeof diagnosticCode];
315
+ //#endregion
316
+ //#region src/createReporter.d.ts
317
+ /**
318
+ * Numeric log-level thresholds used internally to compare verbosity.
319
+ *
320
+ * Higher numbers are more verbose.
321
+ */
322
+ declare const logLevel: {
323
+ readonly silent: number;
324
+ readonly error: 0;
325
+ readonly warn: 1;
326
+ readonly info: 3;
327
+ readonly verbose: 4;
328
+ };
329
+ /**
330
+ * A built-in reporter that renders a run's output, independent of the live logger view.
331
+ *
332
+ * - `cli` renders the per-config summary to the terminal (the default).
333
+ * - `json` writes a machine-readable report to stdout, for CI.
334
+ * - `file` writes a config's diagnostics to `.kubb/kubb-<name>-<timestamp>.log`.
335
+ */
336
+ type ReporterName = 'cli' | 'json' | 'file';
337
+ /**
338
+ * One config's outcome within a run, as handed to a {@link Reporter}.
339
+ */
340
+ type GenerationResult = {
341
+ config: Config;
342
+ /**
343
+ * Diagnostics collected while generating this config.
344
+ */
345
+ diagnostics: Array<Diagnostic>;
346
+ /**
347
+ * Number of files written for this config.
348
+ */
349
+ filesCreated: number;
350
+ status: 'success' | 'failed';
351
+ /**
352
+ * `process.hrtime()` snapshot taken when this config started generating.
353
+ */
354
+ hrStart: [number, number];
355
+ };
356
+ /**
357
+ * Render settings passed alongside the {@link GenerationResult}. These are not part of the run
358
+ * data, such as the output verbosity.
359
+ */
360
+ type ReporterContext = {
361
+ /**
362
+ * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`
363
+ * (`silent`, `error`, `warn`, `info`, `verbose`).
364
+ */
365
+ logLevel: (typeof logLevel)[keyof typeof logLevel];
366
+ };
367
+ /**
368
+ * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter
369
+ * never sees the event emitter. `report` runs once per config. `drain`, when present, runs once
370
+ * after the last config.
371
+ */
372
+ type Reporter = {
373
+ /**
374
+ * Display name, matching a {@link ReporterName} for the built-ins.
375
+ */
376
+ name: string;
377
+ /**
378
+ * Called once per config with that config's result and the render context.
379
+ */
380
+ report: (result: GenerationResult, context: ReporterContext) => void | Promise<void>;
381
+ /**
382
+ * Optional finalizer called once after the run's last config. The host wires it to
383
+ * `kubb:lifecycle:end`. {@link createReporter} closes it over the values that `report` returned.
384
+ */
385
+ drain?: (context: ReporterContext) => void | Promise<void>;
386
+ };
387
+ /**
388
+ * Reporter definition passed to {@link createReporter}. `report` returns the value to collect for
389
+ * this config (e.g. a built report), and the optional `drain` receives the collected reports to
390
+ * emit as one document. `T` is inferred from `report`'s return type.
391
+ */
392
+ type UserReporter<T = void> = {
393
+ name: string;
394
+ report: (result: GenerationResult, context: ReporterContext) => T | Promise<T>;
395
+ drain?: (context: ReporterContext, reports: Array<T>) => void | Promise<void>;
396
+ };
397
+ /**
398
+ * Defines a reporter. When the definition has a `drain`, the returned reporter buffers each value
399
+ * `report` returns and hands the array to `drain` once, then clears it. Without a `drain`, nothing
400
+ * is buffered. Wiring the reporter onto the run's events is the host's job, so the reporter only
401
+ * ever deals with a {@link GenerationResult}.
402
+ *
403
+ * @example
404
+ * ```ts
405
+ * import { createReporter, Diagnostics } from '@kubb/core'
406
+ *
407
+ * export const jsonReporter = createReporter({
408
+ * name: 'json',
409
+ * report(result) {
410
+ * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
411
+ * },
412
+ * drain(context, reports) {
413
+ * process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
414
+ * },
415
+ * })
416
+ * ```
417
+ */
418
+ declare function createReporter<T = void>(reporter: UserReporter<T>): Reporter;
419
+ //#endregion
420
+ //#region src/createStorage.d.ts
421
+ /**
422
+ * Backend that persists generated files. Kubb ships with `fsStorage` (writes
423
+ * to disk) and `memoryStorage` (keeps everything in RAM). Implement this
424
+ * interface to write somewhere else, such as S3 or a database.
425
+ */
426
+ type Storage = {
427
+ /**
428
+ * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).
429
+ */
430
+ readonly name: string;
431
+ /**
432
+ * Returns `true` when an entry for `key` exists.
433
+ */
434
+ hasItem(key: string): Promise<boolean>;
435
+ /**
436
+ * Reads the stored string. Returns `null` when the key is missing.
437
+ */
438
+ getItem(key: string): Promise<string | null>;
439
+ /**
440
+ * Stores `value` under `key`, creating any required structure (directories,
441
+ * buckets, ...).
442
+ */
443
+ setItem(key: string, value: string): Promise<void>;
444
+ /**
445
+ * Deletes the entry for `key`. No-op when the key does not exist.
446
+ */
447
+ removeItem(key: string): Promise<void>;
448
+ /**
449
+ * Returns every key. Pass `base` to filter to keys starting with that prefix.
450
+ */
451
+ getKeys(base?: string): Promise<Array<string>>;
452
+ /**
453
+ * Removes every entry. Pass `base` to scope the wipe to a key prefix.
454
+ */
455
+ clear(base?: string): Promise<void>;
456
+ /**
457
+ * Optional teardown hook for a backend to flush buffers, close connections,
458
+ * or release file locks.
459
+ */
460
+ dispose?(): Promise<void>;
461
+ };
462
+ /**
463
+ * Defines a custom storage backend. The builder receives user options and
464
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
465
+ * storages. A custom backend writes generated files elsewhere, such as cloud
466
+ * storage or a database.
467
+ *
468
+ * @example In-memory storage (the built-in implementation)
469
+ * ```ts
470
+ * import { createStorage } from '@kubb/core'
471
+ *
472
+ * export const memoryStorage = createStorage(() => {
473
+ * const store = new Map<string, string>()
474
+ *
475
+ * return {
476
+ * name: 'memory',
477
+ * async hasItem(key) {
478
+ * return store.has(key)
479
+ * },
480
+ * async getItem(key) {
481
+ * return store.get(key) ?? null
482
+ * },
483
+ * async setItem(key, value) {
484
+ * store.set(key, value)
485
+ * },
486
+ * async removeItem(key) {
487
+ * store.delete(key)
488
+ * },
489
+ * async getKeys(base) {
490
+ * const keys = [...store.keys()]
491
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
492
+ * },
493
+ * async clear(base) {
494
+ * if (!base) store.clear()
495
+ * },
496
+ * }
497
+ * })
498
+ * ```
499
+ */
500
+ declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
501
+ //#endregion
502
+ //#region src/createRenderer.d.ts
503
+ /**
504
+ * Minimal interface any Kubb renderer must satisfy.
505
+ *
506
+ * `TElement` is the type the renderer accepts, for example `KubbReactElement`
507
+ * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
508
+ * `unknown` so generators that don't care about the element type work without
509
+ * specifying it.
510
+ */
511
+ type Renderer<TElement = unknown> = {
512
+ /**
513
+ * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
514
+ * Called once per render cycle. Must resolve before {@link files} is read.
515
+ */
516
+ render(element: TElement): Promise<void>;
517
+ /**
518
+ * Accumulated {@link FileNode} results produced by the last {@link render} call.
519
+ * Not populated when {@link stream} is implemented.
520
+ */
521
+ readonly files: Array<FileNode>;
522
+ /**
523
+ * When present, core calls this instead of {@link render} and {@link files},
524
+ * forwarding each file to `FileManager` as soon as it is ready.
525
+ */
526
+ stream?(element: TElement): Iterable<FileNode>;
527
+ /**
528
+ * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`
529
+ * runs cleanup on every exit path, including thrown errors.
530
+ */
531
+ [Symbol.dispose](): void;
532
+ };
533
+ /**
534
+ * A factory function that produces a fresh {@link Renderer} per render cycle.
535
+ *
536
+ * Generators use this to declare which renderer handles their output.
537
+ */
538
+ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
539
+ /**
540
+ * Defines a renderer factory. Renderers turn the generator's return value
541
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
542
+ * written to disk.
543
+ *
544
+ * A renderer can target output formats beyond JSX, for instance a Handlebars
545
+ * renderer or one that writes binary files. Plugins and generators pick the
546
+ * renderer to use via the `renderer` field on `defineGenerator`.
547
+ *
548
+ * @example A minimal renderer that wraps a custom runtime
549
+ * ```ts
550
+ * import { createRenderer } from '@kubb/core'
551
+ *
552
+ * export const myRenderer = createRenderer(() => {
553
+ * const runtime = new MyRuntime()
554
+ * return {
555
+ * async render(element) {
556
+ * await runtime.render(element)
557
+ * },
558
+ * get files() {
559
+ * return runtime.files
560
+ * },
561
+ * [Symbol.dispose]() {
562
+ * runtime.dispose()
563
+ * },
564
+ * }
565
+ * })
566
+ * ```
567
+ */
568
+ declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
569
+ //#endregion
570
+ //#region src/defineResolver.d.ts
571
+ /**
572
+ * Type/string pattern filter for include/exclude/override matching.
573
+ */
574
+ type PatternFilter = {
575
+ type: string;
576
+ pattern: string | RegExp;
577
+ };
578
+ /**
579
+ * Pattern filter with partial option overrides applied when the pattern matches.
580
+ */
581
+ type PatternOverride<TOptions> = PatternFilter & {
582
+ options: Omit<Partial<TOptions>, 'override'>;
583
+ };
584
+ /**
585
+ * Context for resolving filtered options for a given operation or schema node.
586
+ *
587
+ * @internal
588
+ */
589
+ type ResolveOptionsContext<TOptions> = {
590
+ options: TOptions;
591
+ exclude?: Array<PatternFilter>;
592
+ include?: Array<PatternFilter>;
593
+ override?: Array<PatternOverride<TOptions>>;
594
+ };
595
+ /**
596
+ * Base constraint for all plugin resolver objects.
597
+ *
598
+ * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`
599
+ * are injected automatically by `defineResolver`. Extend this type to add custom resolution methods.
600
+ *
601
+ * @example
602
+ * ```ts
603
+ * type MyResolver = Resolver & {
604
+ * resolveName(node: SchemaNode): string
605
+ * resolveTypedName(node: SchemaNode): string
606
+ * }
607
+ * ```
608
+ */
609
+ type Resolver = {
610
+ name: string;
611
+ pluginName: string;
612
+ default(name: string, type?: 'file' | 'function' | 'type' | 'const'): string;
613
+ resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
614
+ resolvePath(params: ResolverPathParams, context: ResolverContext): string;
615
+ resolveFile(params: ResolverFileParams, context: ResolverContext): FileNode;
616
+ resolveBanner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
617
+ resolveFooter(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
618
+ };
619
+ /**
620
+ * File-specific parameters for `Resolver.resolvePath`.
621
+ *
622
+ * Pass alongside a `ResolverContext` to identify which file to resolve.
623
+ * Provide `tag` for tag-based grouping or `path` for path-based grouping.
624
+ *
625
+ * @example
626
+ * ```ts
627
+ * resolver.resolvePath(
628
+ * { baseName: 'petTypes.ts', tag: 'pets' },
629
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
630
+ * )
631
+ * // → '/src/types/pets/petTypes.ts'
632
+ * ```
633
+ */
634
+ type ResolverPathParams = {
635
+ baseName: FileNode['baseName'];
636
+ /**
637
+ * Tag value used when `group.type === 'tag'`.
638
+ */
639
+ tag?: string;
640
+ /**
641
+ * Path value used when `group.type === 'path'`.
642
+ */
643
+ path?: string;
644
+ };
645
+ /**
646
+ * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.
647
+ *
648
+ * Describes where on disk output is rooted, which output config is active, and the optional
649
+ * grouping strategy that controls subdirectory layout.
650
+ *
651
+ * @example
652
+ * ```ts
653
+ * const context: ResolverContext = {
654
+ * root: config.root,
655
+ * output,
656
+ * group,
657
+ * }
658
+ * ```
659
+ */
660
+ type ResolverContext = {
661
+ root: string;
662
+ output: Output;
663
+ group?: Group;
664
+ /**
665
+ * Plugin name used to populate `meta.pluginName` on the resolved file.
666
+ */
667
+ pluginName?: string;
668
+ };
669
+ /**
670
+ * File-specific parameters for `Resolver.resolveFile`.
671
+ *
672
+ * Pass alongside a `ResolverContext` to fully describe the file to resolve.
673
+ * `tag` and `path` are used only when a matching `group` is present in the context.
674
+ *
675
+ * @example
676
+ * ```ts
677
+ * resolver.resolveFile(
678
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
679
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
680
+ * )
681
+ * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }
682
+ * ```
683
+ */
684
+ type ResolverFileParams = {
685
+ name: string;
686
+ extname: FileNode['extname'];
687
+ /**
688
+ * Tag value used when `group.type === 'tag'`.
689
+ */
690
+ tag?: string;
691
+ /**
692
+ * Path value used when `group.type === 'path'`.
693
+ */
694
+ path?: string;
695
+ };
696
+ /**
697
+ * Per-file context describing the file a banner/footer is being resolved for.
698
+ *
699
+ * Supplied by the generator (or the barrel plugin) at resolve-time and merged
700
+ * into `BannerMeta` so a `banner`/`footer` function can branch on the file kind,
701
+ * e.g. omit a `'use server'` directive on re-export files.
702
+ */
703
+ type ResolveBannerFile = {
704
+ /**
705
+ * Full output path of the file being generated.
706
+ */
707
+ path: string;
708
+ /**
709
+ * File name only, e.g. `'stocks.ts'`.
710
+ */
711
+ baseName: string;
712
+ /**
713
+ * `true` for `index.ts` re-export barrels.
714
+ */
715
+ isBarrel?: boolean;
716
+ /**
717
+ * `true` for group `[dir]/[dir].ts` aggregation files.
718
+ */
719
+ isAggregation?: boolean;
720
+ };
721
+ /**
722
+ * Document metadata extended with per-file context, passed to a `banner`/`footer` function.
723
+ *
724
+ * Carries everything in {@link InputMeta} plus the file the banner is rendered into, so a
725
+ * single function can decide per file (e.g. skip a directive on barrel/aggregation files).
726
+ *
727
+ * @example Skip a directive on re-export files
728
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
729
+ */
730
+ type BannerMeta = InputMeta & {
731
+ /**
732
+ * Full output path of the file being generated.
733
+ */
734
+ filePath: string;
735
+ /**
736
+ * File name only, e.g. `'stocks.ts'`.
737
+ */
738
+ baseName: string;
739
+ /**
740
+ * `true` for `index.ts` re-export barrels.
741
+ */
742
+ isBarrel: boolean;
743
+ /**
744
+ * `true` for group `[dir]/[dir].ts` aggregation files.
745
+ */
746
+ isAggregation: boolean;
747
+ };
748
+ /**
749
+ * Context passed to `Resolver.resolveBanner` and `Resolver.resolveFooter`.
750
+ *
751
+ * `output` is optional, since not every plugin configures a banner/footer.
752
+ * `config` carries the global Kubb config, used to derive the default Kubb banner.
753
+ * `file` carries per-file context forwarded to a `banner`/`footer` function.
754
+ *
755
+ * @example
756
+ * ```ts
757
+ * resolver.resolveBanner(meta, { output: { banner: '// generated' }, config })
758
+ * // → '// generated'
759
+ * ```
760
+ */
761
+ type ResolveBannerContext = {
762
+ output?: Pick<Output, 'banner' | 'footer'>;
763
+ config: Config;
764
+ file?: ResolveBannerFile;
765
+ };
766
+ /**
767
+ * Builder type for the plugin-specific resolver fields.
768
+ *
769
+ * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`
770
+ * are optional, with built-in fallbacks injected when omitted.
771
+ *
772
+ * Methods in the returned object can call sibling resolver methods via `this`.
773
+ */
774
+ 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'>> & {
775
+ name: string;
776
+ pluginName: T['name'];
777
+ } & ThisType<T['resolver']>;
778
+ /**
779
+ * Default path resolver used by `defineResolver`.
780
+ *
781
+ * - `mode: 'file'` resolves directly to `output.path` (the full file path, extension included).
782
+ * - `mode: 'directory'` (default) resolves to `output.path/{baseName}`, or into a
783
+ * subdirectory when `group` and a `tag`/`path` value are provided.
784
+ *
785
+ * A custom `group.name` function overrides the default subdirectory naming.
786
+ * For `tag` groups the default is the camelCased tag.
787
+ * For `path` groups the default is the first path segment after `/`.
788
+ *
789
+ * @example Flat output
790
+ * ```ts
791
+ * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
792
+ * // → '/src/types/petTypes.ts'
793
+ * ```
794
+ *
795
+ * @example Tag-based grouping
796
+ * ```ts
797
+ * defaultResolvePath(
798
+ * { baseName: 'petTypes.ts', tag: 'pets' },
799
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
800
+ * )
801
+ * // → '/src/types/pets/petTypes.ts'
802
+ * ```
803
+ *
804
+ * @example Path-based grouping
805
+ * ```ts
806
+ * defaultResolvePath(
807
+ * { baseName: 'petTypes.ts', path: '/pets/list' },
808
+ * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
809
+ * )
810
+ * // → '/src/types/pets/petTypes.ts'
811
+ * ```
812
+ *
813
+ * @example Single file (`mode: 'file'`)
814
+ * ```ts
815
+ * defaultResolvePath(
816
+ * { baseName: 'petTypes.ts' },
817
+ * { root: '/src', output: { path: 'types.ts', mode: 'file' } },
818
+ * )
819
+ * // → '/src/types.ts'
820
+ * ```
821
+ */
822
+ /**
823
+ * Defines a plugin resolver. The resolver is the object that decides what
824
+ * every generated symbol and file path is called. Built-in defaults handle
825
+ * name casing, include/exclude/override filtering, output path computation,
826
+ * and file construction. Supply your own to override any of them:
827
+ *
828
+ * - `default` sets the name casing strategy (camelCase or PascalCase).
829
+ * - `resolveOptions` does include/exclude/override filtering.
830
+ * - `resolvePath` computes the output path.
831
+ * - `resolveFile` builds the full `FileNode`.
832
+ * - `resolveBanner` and `resolveFooter` produce the top and bottom of file text.
833
+ *
834
+ * Methods in the returned object can call sibling resolver methods via `this`.
835
+ * A custom rule can delegate to a default, for example `this.default(name, 'type')`.
836
+ *
837
+ * @example Basic resolver with naming helpers
838
+ * ```ts
839
+ * export const resolverTs = defineResolver<PluginTs>(() => ({
840
+ * name: 'default',
841
+ * resolveName(name) {
842
+ * return this.default(name, 'function')
843
+ * },
844
+ * resolveTypeName(name) {
845
+ * return this.default(name, 'type')
846
+ * },
847
+ * }))
848
+ * ```
849
+ *
850
+ * @example Custom output path
851
+ * ```ts
852
+ * import path from 'node:path'
853
+ *
854
+ * export const resolverTs = defineResolver<PluginTs>(() => ({
855
+ * name: 'custom',
856
+ * resolvePath({ baseName }, { root, output }) {
857
+ * return path.resolve(root, output.path, 'generated', baseName)
858
+ * },
859
+ * }))
860
+ * ```
861
+ */
862
+ declare function defineResolver<T extends PluginFactoryOptions>(build: ResolverBuilder<T>): T['resolver'];
863
+ //#endregion
864
+ //#region src/definePlugin.d.ts
865
+ /**
866
+ * Reads a type from a registry, falling back to `{}` when the key is absent. Lets
867
+ * `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry` be augmented without
868
+ * touching core.
869
+ *
870
+ * @internal
871
+ */
872
+ type ExtractRegistryKey$1<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
873
+ /**
874
+ * How a plugin consolidates its generated code into files.
875
+ * - `'directory'` writes one file per operation or schema under `path`.
876
+ * - `'file'` writes everything into a single file.
877
+ */
878
+ type OutputMode = 'directory' | 'file';
879
+ /**
880
+ * Output configuration shared by every plugin. Each plugin extends this with
881
+ * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.
882
+ */
883
+ type Output<_TOptions = unknown> = {
884
+ /**
885
+ * Directory where the plugin writes its generated code, resolved against the global
886
+ * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file
887
+ * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).
888
+ */
889
+ path: string;
890
+ /**
891
+ * How generated code is consolidated into files.
892
+ * - `'directory'` writes one file per operation or schema under `path`.
893
+ * - `'file'` writes everything into a single file. The `path` must include the file extension.
894
+ *
895
+ * @default 'directory'
896
+ */
897
+ mode?: OutputMode;
898
+ /**
899
+ * Text prepended to every generated file. Useful for license headers,
900
+ * lint disables, or `@ts-nocheck` directives.
901
+ *
902
+ * A string is applied to every file (including barrel and aggregation re-export files).
903
+ * Pass a function to compute the banner from the file's `BannerMeta` document metadata
904
+ * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can
905
+ * skip the banner on specific files.
906
+ *
907
+ * @example Add a directive to source files but not re-export files
908
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
909
+ */
910
+ banner?: string | ((meta: BannerMeta) => string);
911
+ /**
912
+ * Text appended at the end of every generated file. Mirror of `banner`.
913
+ * Pass a function to compute the footer from the file's `BannerMeta`.
914
+ */
915
+ footer?: string | ((meta: BannerMeta) => string);
916
+ } & ExtractRegistryKey$1<Kubb.PluginOptionsRegistry, 'output'>;
917
+ /**
918
+ * Groups generated files into subdirectories based on an OpenAPI tag or path
919
+ * segment.
920
+ */
921
+ type Group = {
922
+ /**
923
+ * Property used to assign each operation to a group.
924
+ * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).
925
+ * - `'path'` uses the first segment of the operation's URL.
926
+ */
927
+ type: 'tag' | 'path';
928
+ /**
929
+ * Returns the subdirectory name from the group key. Defaults to the camelCased tag for
930
+ * `tag` groups, or the camelCased first path segment for `path` groups.
931
+ */
932
+ name?: (context: {
933
+ group: string;
934
+ }) => string;
935
+ };
936
+ /**
937
+ * Couples `output.mode` with the plugin's `group` option at the type level.
938
+ * - `mode: 'file'` forbids `group` (a single file has nothing to group).
939
+ * - `mode: 'directory'` (or no mode) allows an optional `group` to organize
940
+ * files into per-group subdirectories.
941
+ *
942
+ * Intersect into a plugin's `Options` type instead of declaring `output` and
943
+ * `group` directly, since `mode` lives inside `output` while `group` is its sibling.
944
+ * The generic keeps a plugin's extended `Output` shape intact.
945
+ *
946
+ * @example
947
+ * ```ts
948
+ * export type Options = OutputOptions & {
949
+ * exclude?: Array<Exclude>
950
+ * }
951
+ * ```
952
+ */
953
+ type OutputOptions<TOutput extends Output = Output> = {
954
+ output?: TOutput & {
955
+ mode?: 'directory';
956
+ };
957
+ group?: Group;
958
+ } | {
959
+ output: TOutput & {
960
+ mode: 'file';
961
+ };
962
+ group?: never;
963
+ };
964
+ type ByTag = {
965
+ /**
966
+ * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
967
+ */
968
+ type: 'tag';
969
+ /**
970
+ * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
971
+ */
972
+ pattern: string | RegExp;
973
+ };
974
+ type ByOperationId = {
975
+ /**
976
+ * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
977
+ */
978
+ type: 'operationId';
979
+ /**
980
+ * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
981
+ */
982
+ pattern: string | RegExp;
983
+ };
984
+ type ByPath = {
985
+ /**
986
+ * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
987
+ */
988
+ type: 'path';
989
+ /**
990
+ * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
991
+ */
992
+ pattern: string | RegExp;
993
+ };
994
+ type ByMethod = {
995
+ /**
996
+ * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`.
997
+ */
998
+ type: 'method';
999
+ /**
1000
+ * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,
1001
+ * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`) or a regex.
1002
+ */
1003
+ pattern: HttpMethod | RegExp;
1004
+ };
1005
+ type BySchemaName = {
1006
+ /**
1007
+ * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
1008
+ */
1009
+ type: 'schemaName';
1010
+ /**
1011
+ * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
1012
+ */
1013
+ pattern: string | RegExp;
1014
+ };
1015
+ type ByContentType = {
1016
+ /**
1017
+ * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
1018
+ */
1019
+ type: 'contentType';
1020
+ /**
1021
+ * Content type to match (case-sensitive). Can be a literal string or regex pattern.
1022
+ */
1023
+ pattern: string | RegExp;
1024
+ };
1025
+ /**
1026
+ * Filter that skips matching operations or schemas during generation, for example
1027
+ * deprecated endpoints or internal-only schemas.
1028
+ *
1029
+ * @example
1030
+ * ```ts
1031
+ * exclude: [
1032
+ * { type: 'tag', pattern: 'internal' },
1033
+ * { type: 'path', pattern: /^\/admin/ },
1034
+ * { type: 'operationId', pattern: /^deprecated_/ },
1035
+ * ]
1036
+ * ```
1037
+ */
1038
+ type Exclude$1 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1039
+ /**
1040
+ * Filter that restricts generation to operations or schemas matching at least
1041
+ * one entry. Useful for partial builds (one tag, one API version).
1042
+ *
1043
+ * @example
1044
+ * ```ts
1045
+ * include: [
1046
+ * { type: 'tag', pattern: 'public' },
1047
+ * { type: 'path', pattern: /^\/api\/v1/ },
1048
+ * ]
1049
+ * ```
1050
+ */
1051
+ type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1052
+ /**
1053
+ * Filter paired with a partial options object. When the filter matches, the
1054
+ * options are merged on top of the plugin defaults for that operation only.
1055
+ * Useful for "this one tag goes to a different folder" rules.
1056
+ *
1057
+ * Entries are evaluated top to bottom. The first matching entry wins.
1058
+ *
1059
+ * @example
1060
+ * ```ts
1061
+ * override: [
1062
+ * {
1063
+ * type: 'tag',
1064
+ * pattern: 'admin',
1065
+ * options: { output: { path: './src/gen/admin' } },
1066
+ * },
1067
+ * {
1068
+ * type: 'operationId',
1069
+ * pattern: 'listPets',
1070
+ * options: { enumType: 'literal' },
1071
+ * },
1072
+ * ]
1073
+ * ```
1074
+ */
1075
+ type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
1076
+ options: Omit<Partial<TOptions>, 'override'>;
1077
+ };
1078
+ type PluginFactoryOptions<
1079
+ /**
1080
+ * Unique plugin name.
1081
+ */
1082
+ TName extends string = string,
1083
+ /**
1084
+ * User-facing plugin options.
1085
+ */
1086
+ TOptions extends object = object,
1087
+ /**
1088
+ * Plugin options after defaults are applied.
1089
+ */
1090
+ TResolvedOptions extends object = TOptions,
1091
+ /**
1092
+ * Resolver that encapsulates naming and path-resolution helpers.
1093
+ * Define with `defineResolver` and export alongside the plugin.
1094
+ */
1095
+ TResolver extends Resolver = Resolver> = {
1096
+ name: TName;
1097
+ options: TOptions;
1098
+ resolvedOptions: TResolvedOptions;
1099
+ resolver: TResolver;
1100
+ };
1101
+ /**
1102
+ * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and
1103
+ * sets its resolver, transformer, and options.
1104
+ */
1105
+ type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1106
+ /**
1107
+ * Register one or more generators dynamically. Generators fire during the AST walk
1108
+ * (schema/operation/operations) just like generators declared statically on `createPlugin`.
1109
+ *
1110
+ * Pass generators as separate arguments. Spread an existing list to register it in one call.
1111
+ *
1112
+ * @example
1113
+ * ```ts
1114
+ * ctx.addGenerator(myGenerator)
1115
+ * ctx.addGenerator(schemaGenerator, operationGenerator)
1116
+ * ctx.addGenerator(...selectedGenerators)
1117
+ * ```
1118
+ */
1119
+ addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void;
1120
+ /**
1121
+ * Set or override the resolver for this plugin.
1122
+ * The resolver controls file naming and path resolution.
1123
+ */
1124
+ setResolver(resolver: Partial<TFactory['resolver']>): void;
1125
+ /**
1126
+ * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they
1127
+ * are added, after any macros from earlier `addMacro` calls.
1128
+ */
1129
+ addMacro(macro: Macro): void;
1130
+ /**
1131
+ * Replace this plugin's macros with `macros`.
1132
+ */
1133
+ setMacros(macros: ReadonlyArray<Macro>): void;
1134
+ /**
1135
+ * Set resolved options merged into the normalized plugin's `options`.
1136
+ * Call this in `kubb:plugin:setup` to provide options generators need.
1137
+ */
1138
+ setOptions(options: TFactory['resolvedOptions']): void;
1139
+ /**
1140
+ * Inject a raw file into the build output, bypassing the generation pipeline.
1141
+ *
1142
+ * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the
1143
+ * generated folder verbatim, instead of building its content from `sources`.
1144
+ */
1145
+ injectFile(userFileNode: UserFileNode): void;
1146
+ /**
1147
+ * Merge a partial config update into the current build configuration.
1148
+ */
1149
+ updateConfig(config: Partial<Config>): void;
1150
+ /**
1151
+ * The resolved build configuration at setup time.
1152
+ */
1153
+ config: Config;
1154
+ /**
1155
+ * The plugin's user-provided options.
1156
+ */
1157
+ options: TFactory['options'];
1158
+ };
1159
+ /**
1160
+ * A plugin object produced by `definePlugin`. Its lifecycle handlers live under a single
1161
+ * `hooks` property rather than flat methods.
1162
+ */
1163
+ type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1164
+ /**
1165
+ * Unique name for the plugin, following the same naming convention as `createPlugin`.
1166
+ */
1167
+ name: string;
1168
+ /**
1169
+ * Plugins that must be registered before this plugin executes.
1170
+ * An error is thrown at startup when any listed dependency is missing.
1171
+ */
1172
+ dependencies?: Array<string>;
1173
+ /**
1174
+ * Controls the execution order of this plugin relative to others.
1175
+ *
1176
+ * - `'pre'` runs before all normal plugins.
1177
+ * - `'post'` runs after all normal plugins.
1178
+ * - `undefined` (default) runs in declaration order among normal plugins.
1179
+ *
1180
+ * Dependency constraints always take precedence over `enforce`.
1181
+ */
1182
+ enforce?: Enforce;
1183
+ /**
1184
+ * The options passed by the user when calling the plugin factory.
1185
+ */
1186
+ options?: TFactory['options'];
1187
+ /**
1188
+ * Lifecycle event handlers for this plugin.
1189
+ * Any event from the global `KubbHooks` map can be subscribed to here.
1190
+ */
1191
+ hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void> } & {
1192
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
1193
+ };
1194
+ };
1195
+ /**
1196
+ * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the
1197
+ * public `Plugin` type.
1198
+ *
1199
+ * @internal
1200
+ */
1201
+ type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
1202
+ options: TOptions['resolvedOptions'] & {
1203
+ output: Output;
1204
+ include?: Array<Include>;
1205
+ exclude: Array<Exclude$1>;
1206
+ override: Array<Override<TOptions['resolvedOptions']>>;
1207
+ };
1208
+ resolver: TOptions['resolver'];
1209
+ macros?: Array<Macro>;
1210
+ generators?: Array<Generator>;
1211
+ apply?: (config: Config) => boolean;
1212
+ version?: string;
1213
+ };
1214
+ type KubbPluginStartContext = {
1215
+ plugin: NormalizedPlugin;
1216
+ };
1217
+ type KubbPluginEndContext = {
1218
+ plugin: NormalizedPlugin;
1219
+ duration: number;
1220
+ success: boolean;
1221
+ error?: Error;
1222
+ config: Config;
1223
+ /**
1224
+ * Returns all files currently in the file manager (lazy snapshot).
1225
+ * Includes files added by plugins that have already run.
1226
+ */
1227
+ readonly files: ReadonlyArray<FileNode>;
1228
+ /**
1229
+ * Upsert one or more files into the file manager.
1230
+ */
1231
+ upsertFile: (...files: Array<FileNode>) => void;
1232
+ };
1233
+ /**
1234
+ * Wraps a plugin factory and returns a function that accepts user options and
1235
+ * yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
1236
+ *
1237
+ * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
1238
+ * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
1239
+ * convention (`plugin-react-query`, `plugin-zod`, ...).
1240
+ *
1241
+ * @example
1242
+ * ```ts
1243
+ * import { definePlugin } from '@kubb/core'
1244
+ *
1245
+ * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
1246
+ * name: 'plugin-ts',
1247
+ * hooks: {
1248
+ * 'kubb:plugin:setup'(ctx) {
1249
+ * ctx.setResolver(resolverTs)
1250
+ * },
1251
+ * },
1252
+ * }))
1253
+ * ```
1254
+ */
1255
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): (options?: TFactory['options']) => Plugin<TFactory>;
1256
+ //#endregion
1257
+ //#region src/FileManager.d.ts
1258
+ /**
1259
+ * Hooks fired by a `FileManager`.
1260
+ *
1261
+ * - `upsert` fires once per resolved file added through `add` or `upsert`.
1262
+ */
1263
+ type FileManagerHooks = {
1264
+ upsert: [file: FileNode];
1265
+ };
1266
+ /**
1267
+ * In-memory file store for generated files. Files sharing a `path` are merged
1268
+ * (sources/imports/exports concatenated). The `files` getter is sorted by
1269
+ * path length (barrel `index.ts` last within a bucket).
1270
+ *
1271
+ * @example
1272
+ * ```ts
1273
+ * const manager = new FileManager()
1274
+ * manager.upsert(myFile)
1275
+ * manager.files // sorted view
1276
+ * ```
1277
+ */
1278
+ declare class FileManager {
1279
+ #private;
1280
+ /**
1281
+ * Subscribe to file-store changes. Listeners on `upsert` see each resolved file as it lands
1282
+ * through `add` or `upsert`.
1283
+ */
1284
+ readonly hooks: AsyncEventEmitter<FileManagerHooks>;
1285
+ add(...files: Array<FileNode>): Array<FileNode>;
1286
+ upsert(...files: Array<FileNode>): Array<FileNode>;
1287
+ getByPath(path: string): FileNode | null;
1288
+ deleteByPath(path: string): void;
1289
+ clear(): void;
1290
+ /**
1291
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
1292
+ * `kubb:build:end`.
1293
+ */
1294
+ dispose(): void;
1295
+ [Symbol.dispose](): void;
1296
+ /**
1297
+ * All stored files in stable sort order (shortest path first, barrel files
1298
+ * last within a length bucket). Returns a cached view, do not mutate.
1299
+ */
1300
+ get files(): Array<FileNode>;
1301
+ }
1302
+ //#endregion
1303
+ //#region src/KubbDriver.d.ts
1304
+ type Options = {
1305
+ hooks: AsyncEventEmitter<KubbHooks>;
1306
+ };
1307
+ type RequirePluginContext = {
1308
+ /**
1309
+ * Name of the plugin that declared the dependency, included in the error so users can
1310
+ * trace which plugin needs the missing one.
1311
+ */
1312
+ requiredBy?: string;
1313
+ };
1314
+ declare class KubbDriver {
1315
+ #private;
1316
+ readonly config: Config;
1317
+ readonly options: Options;
1318
+ /**
1319
+ * The streaming `InputNode<true>` produced by the adapter. Set after adapter setup.
1320
+ * Parse-only adapters are wrapped automatically.
1321
+ */
1322
+ inputNode: InputNode<true> | null;
1323
+ adapter: Adapter | null;
1324
+ /**
1325
+ * Central file store for all generated files.
1326
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1327
+ * add files. This property gives direct read/write access when needed.
1328
+ */
1329
+ readonly fileManager: FileManager;
1330
+ readonly plugins: Map<string, NormalizedPlugin>;
1331
+ constructor(config: Config, options: Options);
1332
+ /**
1333
+ * Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
1334
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1335
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1336
+ * so `run` can parse it later.
1337
+ */
1338
+ setup(): Promise<void>;
1339
+ get hooks(): AsyncEventEmitter<KubbHooks>;
1340
+ /**
1341
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
1342
+ * can configure generators, resolvers, macros and renderers before `buildStart` runs.
1343
+ *
1344
+ * Called once from `run` before the plugin execution loop begins.
1345
+ */
1346
+ emitSetupHooks(): Promise<void>;
1347
+ /**
1348
+ * Registers a generator for the given plugin on the shared event emitter.
1349
+ *
1350
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1351
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1352
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1353
+ * so that generators from different plugins do not cross-fire.
1354
+ *
1355
+ * The renderer comes from `generator.renderer`. Set `generator.renderer = null` (or leave it
1356
+ * unset) to opt out of rendering.
1357
+ *
1358
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1359
+ */
1360
+ registerGenerator(pluginName: string, generator: Generator): void;
1361
+ /**
1362
+ * Returns `true` when at least one generator was registered for the given plugin
1363
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
1364
+ *
1365
+ * Used by the build loop to decide whether to walk the AST and emit generator events
1366
+ * for a plugin that has no static `plugin.generators`.
1367
+ */
1368
+ hasEventGenerators(pluginName: string): boolean;
1369
+ /**
1370
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
1371
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
1372
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
1373
+ * contributes a `timing` diagnostic for the run summary.
1374
+ */
1375
+ run({
1376
+ storage
1377
+ }: {
1378
+ storage: Storage;
1379
+ }): Promise<{
1380
+ diagnostics: Array<Diagnostic>;
1381
+ }>;
1382
+ /**
1383
+ * Stores whatever a generator method or `kubb:generate:*` hook returned.
1384
+ *
1385
+ * - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.
1386
+ * - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the
1387
+ * produced files go to `fileManager.upsert`.
1388
+ * - A falsy result is treated as a no-op. The generator wrote files itself via
1389
+ * `ctx.upsertFile`.
1390
+ *
1391
+ * Pass `renderer` when the result may be a renderer element. Generators that only return
1392
+ * `Array<FileNode>` do not need one.
1393
+ */
1394
+ dispatch<TElement = unknown>({
1395
+ result,
1396
+ renderer
1397
+ }: {
1398
+ result: TElement | Array<FileNode> | undefined | null;
1399
+ renderer?: RendererFactory<TElement> | null;
1400
+ }): Promise<void>;
1401
+ /**
1402
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1403
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
1404
+ *
1405
+ * @internal
1406
+ */
1407
+ dispose(): void;
1408
+ [Symbol.dispose](): void;
1409
+ /**
1410
+ * Merges `partial` with the plugin's default resolver and stores the result.
1411
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
1412
+ * get the up-to-date resolver without going through `getResolver()`.
1413
+ */
1414
+ setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
1415
+ /**
1416
+ * Returns the resolver for the given plugin.
1417
+ *
1418
+ * Resolution order: dynamic resolver set via `setPluginResolver` → static resolver on the
1419
+ * plugin → lazily created default resolver (identity name, no path transforms).
1420
+ */
1421
+ getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver'];
1422
+ getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver;
1423
+ getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options'>;
1424
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1425
+ getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
1426
+ /**
1427
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1428
+ */
1429
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName, context?: RequirePluginContext): Plugin<Kubb.PluginRegistry[TName]>;
1430
+ requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string, context?: RequirePluginContext): Plugin<TOptions>;
1431
+ }
1432
+ //#endregion
1433
+ //#region src/defineGenerator.d.ts
1434
+ /**
1435
+ * Context passed to a generator's `schema`, `operation`, and `operations` methods.
1436
+ *
1437
+ * The driver sets `adapter` on the context before it runs a generator, so methods can read it
1438
+ * without a null check. `ctx.options` carries the per-node options after exclude/include/override
1439
+ * filtering for `schema` and `operation`, or the plugin-level options for `operations`.
1440
+ */
1441
+ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1442
+ /**
1443
+ * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
1444
+ * full plugin list.
1445
+ */
1446
+ config: Config;
1447
+ /**
1448
+ * Absolute path to the current plugin's output directory.
1449
+ */
1450
+ root: string;
1451
+ /**
1452
+ * The driver running this build. Most generators never need it. Prefer the scoped helpers
1453
+ * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.
1454
+ */
1455
+ driver: KubbDriver;
1456
+ /**
1457
+ * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
1458
+ */
1459
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1460
+ getPlugin(name: string): Plugin | undefined;
1461
+ /**
1462
+ * Get a plugin by name, throws an error if not found.
1463
+ */
1464
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1465
+ requirePlugin(name: string): Plugin;
1466
+ /**
1467
+ * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
1468
+ */
1469
+ getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver'];
1470
+ getResolver(name: string): Resolver;
1471
+ /**
1472
+ * Add files only if they don't exist.
1473
+ */
1474
+ addFile: (...file: Array<FileNode>) => Promise<void>;
1475
+ /**
1476
+ * Merge sources into the same output file.
1477
+ */
1478
+ upsertFile: (...file: Array<FileNode>) => Promise<void>;
1479
+ /**
1480
+ * The build's event bus. Emit or listen to any `KubbHooks` event, for example to react to
1481
+ * `kubb:build:end` from inside a generator.
1482
+ */
1483
+ hooks: AsyncEventEmitter<KubbHooks>;
1484
+ /**
1485
+ * The current plugin instance.
1486
+ */
1487
+ plugin: Plugin<TOptions>;
1488
+ /**
1489
+ * The current plugin's resolver. It decides what every generated symbol and file path is
1490
+ * called. Kubb picks a `setResolver` registration first, then the plugin's static
1491
+ * `resolver`, then the built-in default.
1492
+ *
1493
+ * @example Resolve a type name
1494
+ * `ctx.resolver.default('pet', 'type') // 'Pet'`
1495
+ *
1496
+ * @example Resolve an output file
1497
+ * `ctx.resolver.resolveFile({ name: 'pet', extname: '.ts' }, { root, output })`
1498
+ */
1499
+ resolver: TOptions['resolver'];
1500
+ /**
1501
+ * Report a warning. Collected as a `warning` diagnostic attributed to the current
1502
+ * plugin. It surfaces in the run summary but does not fail the build. For a structured
1503
+ * diagnostic with a code and source location, use `Diagnostics.report` or throw a
1504
+ * `Diagnostics.Error` directly.
1505
+ */
1506
+ warn: (message: string) => void;
1507
+ /**
1508
+ * Report an error. Collected as an `error` diagnostic attributed to the current
1509
+ * plugin, which fails the build.
1510
+ */
1511
+ error: (error: string | Error) => void;
1512
+ /**
1513
+ * Report an informational message. Collected as an `info` diagnostic attributed to
1514
+ * the current plugin.
1515
+ */
1516
+ info: (message: string) => void;
1517
+ /**
1518
+ * The configured adapter instance.
1519
+ */
1520
+ adapter: Adapter;
1521
+ /**
1522
+ * Document metadata from the adapter: title, version, base URL, and pre-computed
1523
+ * schema index fields (`circularNames`, `enumNames`).
1524
+ */
1525
+ meta: InputMeta;
1526
+ /**
1527
+ * Resolved options after exclude/include/override filtering.
1528
+ */
1529
+ options: TOptions['resolvedOptions'];
1530
+ };
1531
+ /**
1532
+ * Declares a named generator unit that walks the AST and emits files.
1533
+ *
1534
+ * `schema` runs for each schema node and `operation` for each operation node. `operations` runs
1535
+ * once after every operation node is walked. JSX-based generators require a `renderer` factory.
1536
+ * Return `Array<FileNode>` directly, or call `ctx.upsertFile()` manually and return `null` to
1537
+ * bypass rendering.
1538
+ *
1539
+ * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
1540
+ *
1541
+ * @example
1542
+ * ```ts
1543
+ * import { defineGenerator } from '@kubb/core'
1544
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1545
+ *
1546
+ * export const typeGenerator = defineGenerator({
1547
+ * name: 'typescript',
1548
+ * renderer: jsxRenderer,
1549
+ * schema(node, ctx) {
1550
+ * const { adapter, resolver, root, options } = ctx
1551
+ * return <File ...><Type node={node} resolver={resolver} /></File>
1552
+ * },
1553
+ * })
1554
+ * ```
1555
+ */
1556
+ type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
1557
+ /**
1558
+ * Used in diagnostic messages and debug output.
1559
+ */
1560
+ name: string;
1561
+ /**
1562
+ * Optional renderer factory that produces a {@link Renderer} for each render cycle.
1563
+ *
1564
+ * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
1565
+ * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
1566
+ *
1567
+ * Generators that only return `Array<FileNode>` or `void` do not need to set this.
1568
+ *
1569
+ * Leave it unset or set `renderer: null` to opt out of rendering.
1570
+ *
1571
+ * @example
1572
+ * ```ts
1573
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1574
+ * export const myGenerator = defineGenerator<PluginTs>({
1575
+ * renderer: jsxRenderer,
1576
+ * schema(node, ctx) { return <File ...>...</File> },
1577
+ * })
1578
+ * ```
1579
+ */
1580
+ renderer?: RendererFactory<TElement> | null;
1581
+ /**
1582
+ * Called for each schema node in the AST walk.
1583
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
1584
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1585
+ */
1586
+ schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>;
1587
+ /**
1588
+ * Called for each operation node in the AST walk.
1589
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
1590
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1591
+ */
1592
+ operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>;
1593
+ /**
1594
+ * Called once after all operations have been walked.
1595
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
1596
+ * plus `ctx.options` with the plugin-level options for the batch call.
1597
+ */
1598
+ operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>;
1599
+ };
1600
+ /**
1601
+ * Defines a generator: a unit of work that runs during the plugin's AST walk
1602
+ * and produces files. Plugins register generators via `ctx.addGenerator()`
1603
+ * inside `kubb:plugin:setup`.
1604
+ *
1605
+ * The returned object is the input as-is, but with `this` types preserved so
1606
+ * `schema`/`operation`/`operations` methods are correctly typed against the
1607
+ * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
1608
+ * are both handled by the runtime, so pick whichever style fits.
1609
+ *
1610
+ * @example JSX-based schema generator
1611
+ * ```tsx
1612
+ * import { defineGenerator } from '@kubb/core'
1613
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1614
+ *
1615
+ * export const typeGenerator = defineGenerator({
1616
+ * name: 'typescript',
1617
+ * renderer: jsxRenderer,
1618
+ * schema(node, ctx) {
1619
+ * return (
1620
+ * <File path={`${ctx.root}/${node.name}.ts`}>
1621
+ * <Type node={node} resolver={ctx.resolver} />
1622
+ * </File>
1623
+ * )
1624
+ * },
1625
+ * })
1626
+ * ```
1627
+ */
1628
+ declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
1629
+ //#endregion
1630
+ //#region src/defineParser.d.ts
1631
+ type PrintOptions = {
1632
+ extname?: FileNode['extname'];
1633
+ };
1634
+ /**
1635
+ * Converts a resolved {@link FileNode} into the final source string that gets
1636
+ * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
1637
+ * for new file types (JSON, Markdown, ...).
1638
+ */
1639
+ type Parser<TMeta extends object = object, TNode = unknown> = {
1640
+ /**
1641
+ * Display name used in diagnostics and the parser registry.
1642
+ */
1643
+ name: string;
1644
+ /**
1645
+ * File extensions this parser handles. The driver registers the parser for each
1646
+ * extension in this list. A parser with `undefined` here is not registered, so
1647
+ * files of an unclaimed extension fall back to joining their sources verbatim.
1648
+ *
1649
+ * @example
1650
+ * `['.ts', '.js']`
1651
+ */
1652
+ extNames: Array<FileNode['extname']> | undefined;
1653
+ /**
1654
+ * Serialize the file's AST into source code.
1655
+ */
1656
+ parse(file: FileNode<TMeta>, options?: PrintOptions): string;
1657
+ /**
1658
+ * Render compiler AST nodes for this parser's language into source text.
1659
+ * Plugins call this to format the nodes they assemble before handing them
1660
+ * back to the parser as `FileNode.sources`.
1661
+ */
1662
+ print(...nodes: Array<TNode>): string;
1663
+ };
1664
+ /**
1665
+ * Defines a parser with type-safe `this`. Used to register handlers for new
1666
+ * file extensions or to plug a non-TypeScript output into the build.
1667
+ *
1668
+ * @example
1669
+ * ```ts
1670
+ * import { defineParser } from '@kubb/core'
1671
+ * import { extractStringsFromNodes } from '@kubb/ast/utils'
1672
+ *
1673
+ * export const jsonParser = defineParser({
1674
+ * name: 'json',
1675
+ * extNames: ['.json'],
1676
+ * parse(file) {
1677
+ * return file.sources
1678
+ * .map((source) => extractStringsFromNodes(source.nodes ?? []))
1679
+ * .join('\n')
1680
+ * },
1681
+ * print(...nodes) {
1682
+ * return nodes.map(String).join('\n')
1683
+ * },
1684
+ * })
1685
+ * ```
1686
+ */
1687
+ declare function defineParser<T extends Parser>(parser: T): T;
1688
+ //#endregion
1689
+ //#region src/createKubb.d.ts
1690
+ type CreateKubbOptions = {
1691
+ hooks?: AsyncEventEmitter<KubbHooks>;
1692
+ };
1693
+ /**
1694
+ * Kubb code-generation instance bound to a single config entry. Resolves the user
1695
+ * config in the constructor, so `config` is available right away, and shares `hooks`,
1696
+ * `storage`, and `driver` across the `setup → build` lifecycle.
1697
+ *
1698
+ * `createKubb` takes a plain config object (the shape `defineConfig` produces),
1699
+ * not a fluent builder.
1700
+ *
1701
+ * Attach event listeners to `.hooks` before calling `setup()` or `build()`.
1702
+ *
1703
+ * @example
1704
+ * ```ts
1705
+ * const kubb = createKubb(userConfig)
1706
+ * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))
1707
+ * const { files, diagnostics } = await kubb.safeBuild()
1708
+ * ```
1709
+ */
1710
+ declare class Kubb$1 {
1711
+ #private;
1712
+ readonly hooks: AsyncEventEmitter<KubbHooks>;
1713
+ readonly config: Config;
1714
+ constructor(userConfig: UserConfig, options?: CreateKubbOptions);
1715
+ get storage(): Storage;
1716
+ get driver(): KubbDriver;
1717
+ /**
1718
+ * Initializes the driver and storage. `build()` calls this automatically.
1719
+ */
1720
+ setup(): Promise<void>;
1721
+ /**
1722
+ * Runs the full pipeline and throws on any plugin error.
1723
+ * Automatically calls `setup()` if needed.
1724
+ */
1725
+ build(): Promise<BuildOutput>;
1726
+ /**
1727
+ * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.
1728
+ * Automatically calls `setup()` if needed. This is the canonical call: it never throws on
1729
+ * plugin errors, so callers stay in control of how failures surface.
1730
+ */
1731
+ safeBuild(): Promise<BuildOutput>;
1732
+ dispose(): void;
1733
+ [Symbol.dispose](): void;
1734
+ }
1735
+ /**
1736
+ * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent
1737
+ * to `new Kubb(userConfig, options)` and the canonical public entry point.
1738
+ *
1739
+ * @example
1740
+ * ```ts
1741
+ * import { createKubb } from '@kubb/core'
1742
+ * import { adapterOas } from '@kubb/adapter-oas'
1743
+ * import { pluginTs } from '@kubb/plugin-ts'
1744
+ *
1745
+ * const kubb = createKubb({
1746
+ * input: { path: './petStore.yaml' },
1747
+ * output: { path: './src/gen' },
1748
+ * adapter: adapterOas(),
1749
+ * plugins: [pluginTs()],
1750
+ * })
1751
+ *
1752
+ * await kubb.build()
1753
+ * ```
1754
+ */
1755
+ declare function createKubb(userConfig: UserConfig, options?: CreateKubbOptions): Kubb$1;
1756
+ //#endregion
1757
+ //#region src/FileProcessor.d.ts
1758
+ /**
1759
+ * Hooks fired by a `FileProcessor`.
1760
+ *
1761
+ * - `start` opens a batch, from `run` or a queue flush.
1762
+ * - `update` fires once per file as it is converted.
1763
+ * - `end` closes a batch.
1764
+ * - `enqueue` fires for every `enqueue` call.
1765
+ * - `drain` fires when `drain()` empties the queue with no in-flight batch left.
1766
+ */
1767
+ type FileProcessorHooks = {
1768
+ start: [files: Array<FileNode>];
1769
+ update: [params: {
1770
+ file: FileNode;
1771
+ source?: string;
1772
+ processed: number;
1773
+ total: number;
1774
+ percentage: number;
1775
+ }];
1776
+ end: [files: Array<FileNode>];
1777
+ enqueue: [file: FileNode];
1778
+ drain: [];
1779
+ };
1780
+ /**
1781
+ * Per-file progress record yielded by `stream` and surfaced through the `update` event.
1782
+ */
1783
+ type ParsedFile = {
1784
+ file: FileNode;
1785
+ source: string;
1786
+ processed: number;
1787
+ total: number;
1788
+ percentage: number;
1789
+ };
1790
+ //#endregion
1791
+ //#region src/types.d.ts
1792
+ /**
1793
+ * Extracts a type from a registry, falling back to `{}` when the key doesn't exist.
1794
+ * Lets plugins augment `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`
1795
+ * without changing core.
1796
+ *
1797
+ * @internal
1798
+ */
1799
+ type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
1800
+ /**
1801
+ * Path to an input file to generate from, absolute or relative to the config file. The adapter
1802
+ * parses it (e.g. an OpenAPI YAML or JSON spec) into the universal AST.
1803
+ */
1804
+ type InputPath = {
1805
+ /**
1806
+ * Path to your Swagger/OpenAPI file, absolute or relative to the config file location.
1807
+ *
1808
+ * @example
1809
+ * ```ts
1810
+ * { path: './petstore.yaml' }
1811
+ * { path: '/absolute/path/to/openapi.json' }
1812
+ * ```
1813
+ */
1814
+ path: string;
1815
+ };
1816
+ /**
1817
+ * Inline spec to generate from, passed directly instead of read from a file. A string
1818
+ * (YAML/JSON) or a parsed object.
1819
+ */
1820
+ type InputData = {
1821
+ /**
1822
+ * Swagger/OpenAPI data as a string (YAML/JSON) or a parsed object.
1823
+ *
1824
+ * @example
1825
+ * ```ts
1826
+ * { data: fs.readFileSync('./openapi.yaml', 'utf8') }
1827
+ * { data: { openapi: '3.1.0', info: { ... } } }
1828
+ * ```
1829
+ */
1830
+ data: string | unknown;
1831
+ };
1832
+ type Input = InputPath | InputData;
1833
+ /**
1834
+ * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to
1835
+ * write it (output), how (plugins), and the runtime pieces (parsers, storage). See
1836
+ * `UserConfig` for the relaxed form with defaults applied.
1837
+ *
1838
+ * @private
1839
+ */
1840
+ type Config<TInput = Input> = {
1841
+ /**
1842
+ * Display name for this configuration in CLI output and logs.
1843
+ * Useful when running multiple builds with `defineConfig` arrays.
1844
+ *
1845
+ * @example
1846
+ * ```ts
1847
+ * name: 'api-client'
1848
+ * ```
1849
+ */
1850
+ name?: string;
1851
+ /**
1852
+ * Project root directory, absolute or relative to the config file. Already
1853
+ * resolved on the `Config` instance (see `UserConfig` for the optional
1854
+ * form that defaults to `process.cwd()`).
1855
+ */
1856
+ root: string;
1857
+ /**
1858
+ * Parsers that convert generated files into strings. Each parser handles a
1859
+ * set of file extensions, and a fallback parser handles anything else.
1860
+ *
1861
+ * Already resolved on the `Config` instance (see `UserConfig` for the
1862
+ * optional form that defaults to `[parserTs, parserTsx, parserMd]`).
1863
+ *
1864
+ * @example
1865
+ * ```ts
1866
+ * import { defineConfig } from 'kubb'
1867
+ * import { parserTs, parserTsx } from '@kubb/parser-ts'
1868
+ *
1869
+ * export default defineConfig({
1870
+ * parsers: [parserTs, parserTsx],
1871
+ * })
1872
+ * ```
1873
+ */
1874
+ parsers: Array<Parser>;
1875
+ /**
1876
+ * Adapter that parses input files into the universal AST representation.
1877
+ * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
1878
+ *
1879
+ * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
1880
+ * injected via `injectFile` are written, but no AST walk occurs and generator hooks
1881
+ * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
1882
+ *
1883
+ * @example
1884
+ * ```ts
1885
+ * import { adapterOas } from '@kubb/adapter-oas'
1886
+ * export default defineConfig({
1887
+ * adapter: adapterOas(),
1888
+ * input: { path: './petstore.yaml' },
1889
+ * })
1890
+ * ```
1891
+ */
1892
+ adapter?: Adapter;
1893
+ /**
1894
+ * Source file or data to generate code from.
1895
+ * Use `input.path` for a file path or `input.data` for inline data.
1896
+ * Required when an adapter is configured. Omit it when running in plugin-only mode.
1897
+ */
1898
+ input?: TInput;
1899
+ output: {
1900
+ /**
1901
+ * Output directory for generated files, absolute or relative to `root`. Plugins can nest
1902
+ * subdirectories under it by grouping strategy (tag, path).
1903
+ *
1904
+ * @example
1905
+ * ```ts
1906
+ * output: {
1907
+ * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
1908
+ * }
1909
+ * ```
1910
+ */
1911
+ path: string;
1912
+ /**
1913
+ * Remove every file in the output directory before the build, so stale output isn't mixed
1914
+ * with new files. Leave `false` to preserve manual edits in the output directory.
1915
+ *
1916
+ * @example
1917
+ * ```ts
1918
+ * clean: true // wipes ./src/gen/* before generating
1919
+ * ```
1920
+ */
1921
+ clean?: boolean;
1922
+ /**
1923
+ * Format the generated files after generation. `'auto'` runs the first formatter it finds
1924
+ * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.
1925
+ *
1926
+ * @example
1927
+ * ```ts
1928
+ * format: 'auto' // auto-detect oxfmt, biome, or prettier
1929
+ * format: 'prettier' // force prettier
1930
+ * format: false // skip formatting
1931
+ * ```
1932
+ */
1933
+ format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
1934
+ /**
1935
+ * Lint the generated files after generation. `'auto'` runs the first linter it finds
1936
+ * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.
1937
+ *
1938
+ * @example
1939
+ * ```ts
1940
+ * lint: 'auto' // auto-detect oxlint, biome, or eslint
1941
+ * lint: 'eslint' // force eslint
1942
+ * lint: false // skip linting
1943
+ * ```
1944
+ */
1945
+ lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
1946
+ /**
1947
+ * Rewrite import extensions in generated files, e.g. emit `.js` imports from `.ts` sources for
1948
+ * ESM dual packages. Keys are the source extension, values the output, and `''` drops it.
1949
+ *
1950
+ * @default { '.ts': '.ts' }
1951
+ * @example
1952
+ * ```ts
1953
+ * extension: { '.ts': '.js' } // generates import './api.js' instead of './api.ts'
1954
+ * extension: { '.ts': '', '.tsx': '.jsx' }
1955
+ * ```
1956
+ */
1957
+ extension?: Record<FileNode['extname'], FileNode['extname'] | ''>;
1958
+ /**
1959
+ * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds
1960
+ * source, title, description, and API version, and `false` omits it.
1961
+ *
1962
+ * @default 'simple'
1963
+ * @example
1964
+ * ```ts
1965
+ * defaultBanner: 'simple' // "This file was autogenerated by Kubb"
1966
+ * defaultBanner: 'full' // adds source, title, description, API version
1967
+ * defaultBanner: false // no banner
1968
+ * ```
1969
+ */
1970
+ defaultBanner?: 'simple' | 'full' | false;
1971
+ } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
1972
+ /**
1973
+ * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`
1974
+ * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.
1975
+ *
1976
+ * @default fsStorage()
1977
+ * @example
1978
+ * ```ts
1979
+ * import { memoryStorage } from '@kubb/core'
1980
+ *
1981
+ * // Keep generated files in memory (useful for testing, CI pipelines)
1982
+ * storage: memoryStorage()
1983
+ *
1984
+ * // Use custom S3 storage
1985
+ * storage: myS3Storage()
1986
+ * ```
1987
+ *
1988
+ * @see {@link Storage} interface for implementing custom backends.
1989
+ */
1990
+ storage: Storage;
1991
+ /**
1992
+ * Plugins that run during the build to generate code and transform the AST. Each one processes
1993
+ * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin
1994
+ * that depends on another throws when that plugin isn't registered.
1995
+ *
1996
+ * @example
1997
+ * ```ts
1998
+ * import { pluginTs } from '@kubb/plugin-ts'
1999
+ * import { pluginZod } from '@kubb/plugin-zod'
2000
+ *
2001
+ * plugins: [
2002
+ * pluginTs({ output: { path: './src/gen' } }),
2003
+ * pluginZod({ output: { path: './src/gen' } }),
2004
+ * ]
2005
+ * ```
2006
+ */
2007
+ plugins: Array<Plugin>;
2008
+ /**
2009
+ * Lifecycle hooks that run external tools (prettier, eslint, a custom script) on build events.
2010
+ *
2011
+ * Currently supports the `done` hook, which fires after all plugins complete.
2012
+ *
2013
+ * @example
2014
+ * ```ts
2015
+ * hooks: {
2016
+ * done: 'prettier --write "./src/gen"', // auto-format generated files
2017
+ * // or multiple commands:
2018
+ * done: ['prettier --write "./src/gen"', 'eslint --fix "./src/gen"']
2019
+ * }
2020
+ * ```
2021
+ */
2022
+ hooks?: {
2023
+ /**
2024
+ * Command(s) to run after all plugins finish generating, for post-processing the output.
2025
+ *
2026
+ * Pass a single command string, or an array to run them in sequence.
2027
+ * Commands run relative to the `root` directory.
2028
+ *
2029
+ * @example
2030
+ * ```ts
2031
+ * done: 'prettier --write "./src/gen"'
2032
+ * done: ['prettier --write "./src/gen"', 'eslint --fix "./src/gen"']
2033
+ * ```
2034
+ */
2035
+ done?: string | Array<string>;
2036
+ };
2037
+ /**
2038
+ * The reporters available to the run, registered as instances. The host
2039
+ * (the CLI via `--reporter`) selects which ones to trigger by `name` with {@link selectReporters}.
2040
+ * `defineConfig` from the `kubb` package registers the built-in `cli`, `json`, and `file`
2041
+ * reporters by default.
2042
+ *
2043
+ * - `cli` writes the end-of-run summary to the terminal.
2044
+ * - `json` writes a machine-readable report to stdout, for CI.
2045
+ * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.
2046
+ *
2047
+ * @example
2048
+ * ```ts
2049
+ * import { cliReporter, jsonReporter } from '@kubb/core'
2050
+ *
2051
+ * reporters: [cliReporter, jsonReporter, myReporter]
2052
+ * ```
2053
+ */
2054
+ reporters: Array<Reporter>;
2055
+ };
2056
+ /**
2057
+ * Partial `Config` for user-facing entry points with sensible defaults.
2058
+ *
2059
+ * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
2060
+ * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
2061
+ * `storage`, and `hooks`.
2062
+ *
2063
+ * @example
2064
+ * ```ts
2065
+ * export default defineConfig({
2066
+ * input: { path: './petstore.yaml' },
2067
+ * output: { path: './src/gen' },
2068
+ * plugins: [pluginTs(), pluginZod()],
2069
+ * })
2070
+ * ```
2071
+ */
2072
+ type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage' | 'reporters'> & {
2073
+ /**
2074
+ * Project root directory, absolute or relative to the config file location.
2075
+ * @default process.cwd()
2076
+ */
2077
+ root?: string;
2078
+ /**
2079
+ * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
2080
+ * @default [parserTs, parserTsx, parserMd] // applied by `defineConfig` from the `kubb` package
2081
+ */
2082
+ parsers?: Array<Parser>;
2083
+ /**
2084
+ * Adapter that parses your API specification into Kubb's universal AST.
2085
+ * When omitted, Kubb runs in plugin-only mode.
2086
+ */
2087
+ adapter?: Adapter;
2088
+ /**
2089
+ * Plugins that execute during the build to generate code and transform the AST.
2090
+ * @default []
2091
+ */
2092
+ plugins?: Array<Plugin>;
2093
+ /**
2094
+ * Storage backend that controls where and how generated files are persisted.
2095
+ * @default fsStorage()
2096
+ */
2097
+ storage?: Storage;
2098
+ /**
2099
+ * Reporters available to the run. `defineConfig` registers the built-in `cli`, `json`, and
2100
+ * `file` reporters when omitted.
2101
+ * @default [cliReporter, jsonReporter, fileReporter] // applied by `defineConfig` from the `kubb` package
2102
+ */
2103
+ reporters?: Array<Reporter>;
2104
+ };
2105
+ declare global {
2106
+ namespace Kubb {
2107
+ /**
2108
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
2109
+ * Augment this interface in each plugin's `types.ts` to enable automatic
2110
+ * typing for `getPlugin` and `requirePlugin`.
2111
+ *
2112
+ * @example
2113
+ * ```ts
2114
+ * // packages/plugin-ts/src/types.ts
2115
+ * declare global {
2116
+ * namespace Kubb {
2117
+ * interface PluginRegistry {
2118
+ * 'plugin-ts': PluginTs
2119
+ * }
2120
+ * }
2121
+ * }
2122
+ * ```
2123
+ */
2124
+ interface PluginRegistry {}
2125
+ /**
2126
+ * Extension point for root `Config['output']` options.
2127
+ * Augment the `output` key in plugin packages to add extra fields
2128
+ * to the global output configuration without touching core types.
2129
+ *
2130
+ * @example
2131
+ * ```ts
2132
+ * // packages/plugin-barrel/src/plugin.ts
2133
+ * declare global {
2134
+ * namespace Kubb {
2135
+ * interface ConfigOptionsRegistry {
2136
+ * output: {
2137
+ * barrel?: import('./types.ts').BarrelConfig | false
2138
+ * }
2139
+ * }
2140
+ * }
2141
+ * }
2142
+ * ```
2143
+ */
2144
+ interface ConfigOptionsRegistry {}
2145
+ /**
2146
+ * Extension point for per-plugin `Output` options.
2147
+ * Augment the `output` key in plugin packages to add extra fields
2148
+ * to the per-plugin output configuration without touching core types.
2149
+ *
2150
+ * @example
2151
+ * ```ts
2152
+ * // packages/plugin-barrel/src/plugin.ts
2153
+ * declare global {
2154
+ * namespace Kubb {
2155
+ * interface PluginOptionsRegistry {
2156
+ * output: {
2157
+ * barrel?: import('./types.ts').PluginBarrelConfig | false
2158
+ * }
2159
+ * }
2160
+ * }
2161
+ * }
2162
+ * ```
2163
+ */
2164
+ interface PluginOptionsRegistry {}
2165
+ }
2166
+ }
2167
+ /**
2168
+ * Lifecycle events emitted during Kubb code generation.
2169
+ * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
2170
+ *
2171
+ * @example
2172
+ * ```ts
2173
+ * kubb.hooks.on('kubb:lifecycle:start', () => {
2174
+ * console.log('Starting Kubb generation')
2175
+ * })
2176
+ *
2177
+ * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
2178
+ * console.log(`${plugin.name} completed in ${duration}ms`)
2179
+ * })
2180
+ * ```
2181
+ */
2182
+ interface KubbHooks {
2183
+ 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
2184
+ 'kubb:lifecycle:end': [];
2185
+ 'kubb:generation:start': [ctx: KubbGenerationStartContext];
2186
+ 'kubb:generation:end': [ctx: KubbGenerationEndContext];
2187
+ 'kubb:format:start': [];
2188
+ 'kubb:format:end': [];
2189
+ 'kubb:lint:start': [];
2190
+ 'kubb:lint:end': [];
2191
+ 'kubb:hooks:start': [];
2192
+ 'kubb:hooks:end': [];
2193
+ 'kubb:hook:start': [ctx: KubbHookStartContext];
2194
+ 'kubb:hook:line': [ctx: KubbHookLineContext];
2195
+ 'kubb:hook:end': [ctx: KubbHookEndContext];
2196
+ 'kubb:info': [ctx: KubbInfoContext];
2197
+ 'kubb:error': [ctx: KubbErrorContext];
2198
+ 'kubb:success': [ctx: KubbSuccessContext];
2199
+ 'kubb:warn': [ctx: KubbWarnContext];
2200
+ 'kubb:diagnostic': [ctx: KubbDiagnosticContext];
2201
+ 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
2202
+ 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext];
2203
+ 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
2204
+ 'kubb:plugin:start': [ctx: KubbPluginStartContext];
2205
+ 'kubb:plugin:end': [ctx: KubbPluginEndContext];
2206
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
2207
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
2208
+ 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
2209
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
2210
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
2211
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
2212
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
2213
+ }
2214
+ type KubbBuildStartContext = {
2215
+ /**
2216
+ * Resolved configuration for this build.
2217
+ */
2218
+ config: Config;
2219
+ /**
2220
+ * Adapter that parsed the input into the universal AST.
2221
+ */
2222
+ adapter: Adapter;
2223
+ /**
2224
+ * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
2225
+ * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
2226
+ */
2227
+ meta: InputMeta | undefined;
2228
+ /**
2229
+ * Looks up a registered plugin by name, typed by the plugin registry.
2230
+ */
2231
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
2232
+ getPlugin(name: string): Plugin | undefined;
2233
+ /**
2234
+ * Snapshot of all files accumulated so far.
2235
+ */
2236
+ readonly files: ReadonlyArray<FileNode>;
2237
+ /**
2238
+ * Adds or merges one or more files into the file manager.
2239
+ */
2240
+ upsertFile: (...files: Array<FileNode>) => void;
2241
+ };
2242
+ type KubbPluginsEndContext = {
2243
+ /**
2244
+ * Resolved configuration for this build.
2245
+ */
2246
+ config: Config;
2247
+ /**
2248
+ * Snapshot of all files accumulated across all plugins.
2249
+ */
2250
+ readonly files: ReadonlyArray<FileNode>;
2251
+ /**
2252
+ * Adds or merges one or more files into the file manager.
2253
+ */
2254
+ upsertFile: (...files: Array<FileNode>) => void;
2255
+ };
2256
+ type KubbBuildEndContext = {
2257
+ /**
2258
+ * All files generated during this build.
2259
+ */
2260
+ files: Array<FileNode>;
2261
+ /**
2262
+ * Resolved configuration for this build.
2263
+ */
2264
+ config: Config;
2265
+ /**
2266
+ * Absolute path to the output directory.
2267
+ */
2268
+ outputDir: string;
2269
+ };
2270
+ type KubbLifecycleStartContext = {
2271
+ /**
2272
+ * Current Kubb version string.
2273
+ */
2274
+ version: string;
2275
+ };
2276
+ type KubbGenerationStartContext = {
2277
+ /**
2278
+ * Resolved configuration for this generation run.
2279
+ */
2280
+ config: Config;
2281
+ };
2282
+ type KubbGenerationEndContext = {
2283
+ /**
2284
+ * Resolved configuration for this generation run.
2285
+ */
2286
+ config: Config;
2287
+ /**
2288
+ * Read-only view of the files written during this build.
2289
+ * Reads go directly to `config.storage`, nothing extra is held in memory.
2290
+ *
2291
+ * @example Read a generated file
2292
+ * `const code = await storage.getItem('/src/gen/pet.ts')`
2293
+ *
2294
+ * @example Walk every generated file
2295
+ * ```ts
2296
+ * for (const path of await storage.getKeys()) {
2297
+ * const code = await storage.getItem(path)
2298
+ * }
2299
+ * ```
2300
+ */
2301
+ storage: Storage;
2302
+ /**
2303
+ * Diagnostics collected during the build: error/warning/info problems plus a
2304
+ * `performance` diagnostic per plugin. The end-of-run summary derives its failure counts
2305
+ * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.
2306
+ */
2307
+ diagnostics?: Array<Diagnostic>;
2308
+ /**
2309
+ * `'success'` when all plugins completed without errors, `'failed'` otherwise.
2310
+ */
2311
+ status?: 'success' | 'failed';
2312
+ /**
2313
+ * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.
2314
+ */
2315
+ hrStart?: [number, number];
2316
+ /**
2317
+ * Total number of files created during this run.
2318
+ */
2319
+ filesCreated?: number;
2320
+ };
2321
+ type KubbInfoContext = {
2322
+ /**
2323
+ * Human-readable info message.
2324
+ */
2325
+ message: string;
2326
+ /**
2327
+ * Optional supplementary detail.
2328
+ */
2329
+ info?: string;
2330
+ };
2331
+ type KubbErrorContext = {
2332
+ /**
2333
+ * The caught error.
2334
+ */
2335
+ error: Error;
2336
+ /**
2337
+ * Optional structured metadata for additional context.
2338
+ */
2339
+ meta?: Record<string, unknown>;
2340
+ };
2341
+ type KubbSuccessContext = {
2342
+ /**
2343
+ * Human-readable success message.
2344
+ */
2345
+ message: string;
2346
+ /**
2347
+ * Optional supplementary detail.
2348
+ */
2349
+ info?: string;
2350
+ };
2351
+ type KubbWarnContext = {
2352
+ /**
2353
+ * Human-readable warning message.
2354
+ */
2355
+ message: string;
2356
+ /**
2357
+ * Optional supplementary detail.
2358
+ */
2359
+ info?: string;
2360
+ };
2361
+ type KubbDiagnosticContext = {
2362
+ /**
2363
+ * The structured diagnostic to render: a build problem or a version-update notice.
2364
+ */
2365
+ diagnostic: ProblemDiagnostic | UpdateDiagnostic;
2366
+ };
2367
+ type KubbFilesProcessingStartContext = {
2368
+ /**
2369
+ * Files about to be serialized and written.
2370
+ */
2371
+ files: Array<FileNode>;
2372
+ };
2373
+ type KubbFileProcessingUpdate = {
2374
+ /**
2375
+ * Number of files processed so far in this batch.
2376
+ */
2377
+ processed: number;
2378
+ /**
2379
+ * Total number of files in this batch.
2380
+ */
2381
+ total: number;
2382
+ /**
2383
+ * Completion percentage, `0` to `100`.
2384
+ */
2385
+ percentage: number;
2386
+ /**
2387
+ * Serialized file content, or `undefined` when the file produced no output.
2388
+ */
2389
+ source?: string;
2390
+ /**
2391
+ * The file that was just processed.
2392
+ */
2393
+ file: FileNode;
2394
+ /**
2395
+ * Resolved configuration for this build.
2396
+ */
2397
+ config: Config;
2398
+ };
2399
+ type KubbFilesProcessingUpdateContext = {
2400
+ /**
2401
+ * All files processed in this flush chunk.
2402
+ */
2403
+ files: Array<KubbFileProcessingUpdate>;
2404
+ };
2405
+ type KubbFilesProcessingEndContext = {
2406
+ /**
2407
+ * All files that were serialized in this batch.
2408
+ */
2409
+ files: Array<FileNode>;
2410
+ };
2411
+ type KubbHookStartContext = {
2412
+ /**
2413
+ * Optional identifier for correlating start/end events.
2414
+ */
2415
+ id?: string;
2416
+ /**
2417
+ * The shell command that is about to run.
2418
+ */
2419
+ command: string;
2420
+ /**
2421
+ * Parsed argument list, when available.
2422
+ */
2423
+ args?: ReadonlyArray<string>;
2424
+ };
2425
+ /**
2426
+ * Emitted for each line streamed from a hook's stdout while it runs.
2427
+ * A logger correlates the line to its active UI element via `id`.
2428
+ */
2429
+ type KubbHookLineContext = {
2430
+ /**
2431
+ * Identifier matching the corresponding `kubb:hook:start` event.
2432
+ */
2433
+ id: string;
2434
+ /**
2435
+ * A single streamed stdout line, without its trailing newline.
2436
+ */
2437
+ line: string;
2438
+ };
2439
+ type KubbHookEndContext = {
2440
+ /**
2441
+ * Optional identifier matching the corresponding `kubb:hook:start` event.
2442
+ */
2443
+ id?: string;
2444
+ /**
2445
+ * The shell command that ran.
2446
+ */
2447
+ command: string;
2448
+ /**
2449
+ * Parsed argument list, when available.
2450
+ */
2451
+ args?: ReadonlyArray<string>;
2452
+ /**
2453
+ * `true` when the command exited with code `0`.
2454
+ */
2455
+ success: boolean;
2456
+ /**
2457
+ * Error thrown by the command, or `null` on success.
2458
+ */
2459
+ error: Error | null;
2460
+ /**
2461
+ * Captured stdout from the process, populated when it exits non-zero.
2462
+ */
2463
+ stdout?: string;
2464
+ /**
2465
+ * Captured stderr from the process, populated when it exits non-zero.
2466
+ */
2467
+ stderr?: string;
2468
+ };
2469
+ /**
2470
+ * CLI options derived from command-line flags.
2471
+ */
2472
+ type CLIOptions = {
2473
+ /**
2474
+ * Path to the Kubb config file.
2475
+ */
2476
+ config?: string;
2477
+ /**
2478
+ * OpenAPI input path passed as the positional argument to `kubb generate`.
2479
+ * Overrides `config.input.path` when set.
2480
+ */
2481
+ input?: string;
2482
+ /**
2483
+ * Re-run generation whenever input files change.
2484
+ */
2485
+ watch?: boolean;
2486
+ /**
2487
+ * Controls how much output the CLI prints.
2488
+ *
2489
+ * @default 'info'
2490
+ */
2491
+ logLevel?: 'silent' | 'info' | 'verbose';
2492
+ /**
2493
+ * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.
2494
+ */
2495
+ reporters?: Array<ReporterName>;
2496
+ };
2497
+ /**
2498
+ * All accepted forms of a Kubb configuration.
2499
+ * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).
2500
+ */
2501
+ type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Array<Config>> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>);
2502
+ /**
2503
+ * Full output produced by a successful or failed build.
2504
+ */
2505
+ type BuildOutput = {
2506
+ /**
2507
+ * Structured diagnostics collected during the build: error/warning/info problems
2508
+ * (each with a code, severity, and where known a JSON-pointer location) plus a
2509
+ * `performance` diagnostic per plugin. Includes a top-level diagnostic when the build
2510
+ * threw before completing. Use {@link Diagnostics.hasError} to test for failure.
2511
+ */
2512
+ diagnostics: Array<Diagnostic>;
2513
+ /**
2514
+ * All files generated during this build.
2515
+ */
2516
+ files: Array<FileNode>;
2517
+ /**
2518
+ * The plugin driver that orchestrated this build.
2519
+ */
2520
+ driver: KubbDriver;
2521
+ /**
2522
+ * Read-only view of every file written during this build.
2523
+ * Reads go straight to `config.storage`, nothing extra is held in memory.
2524
+ *
2525
+ * @example Read a generated file
2526
+ * `const code = await buildOutput.storage.getItem('/src/gen/pet.ts')`
2527
+ *
2528
+ * @example List all generated file paths
2529
+ * `const paths = await buildOutput.storage.getKeys()`
2530
+ */
2531
+ storage: Storage;
2532
+ };
2533
+ //#endregion
2534
+ //#region src/diagnostics.d.ts
2535
+ /**
2536
+ * How serious a diagnostic is. `error` fails the build, `warning` and `info`
2537
+ * are reported but do not.
2538
+ */
2539
+ type DiagnosticSeverity = 'error' | 'warning' | 'info';
2540
+ /**
2541
+ * A human-readable explanation of a diagnostic code: a short title, what triggers it, and how
2542
+ * to resolve it. This is the source of truth the kubb.dev `/diagnostics/<slug>` pages mirror, so
2543
+ * every code stays documented in one place. Adding a code without documenting it fails the build.
2544
+ */
2545
+ type DiagnosticDoc = {
2546
+ /**
2547
+ * Short title shown as the docs heading.
2548
+ */
2549
+ title: string;
2550
+ /**
2551
+ * What triggers the diagnostic.
2552
+ */
2553
+ cause: string;
2554
+ /**
2555
+ * The action that resolves it.
2556
+ */
2557
+ fix: string;
2558
+ };
2559
+ /**
2560
+ * Points a diagnostic back into the source document. Inputs are parsed into an
2561
+ * object model with no line/column, so locations carry a JSON pointer the adapter
2562
+ * builds (the OAS adapter emits `#/components/schemas/Pet`). A `config` diagnostic
2563
+ * points at the Kubb config itself and so has no pointer.
2564
+ */
2565
+ type DiagnosticLocation = {
2566
+ kind: 'schema';
2567
+ /**
2568
+ * RFC 6901 JSON pointer into the source document.
2569
+ */
2570
+ pointer: string;
2571
+ /**
2572
+ * The original reference when the diagnostic stems from an unresolved one.
2573
+ */
2574
+ ref?: string;
2575
+ } | {
2576
+ kind: 'operation' | 'document';
2577
+ /**
2578
+ * RFC 6901 JSON pointer into the source document.
2579
+ */
2580
+ pointer: string;
2581
+ } | {
2582
+ kind: 'config';
2583
+ };
2584
+ /**
2585
+ * What a diagnostic carries.
2586
+ * - `problem` is a build issue shown to the user, and the only kind rendered as a problem.
2587
+ * - `performance` records a plugin's elapsed time.
2588
+ * - `update` is a version notice.
2589
+ */
2590
+ type DiagnosticKind = 'problem' | 'performance' | 'update';
2591
+ /**
2592
+ * Codes that describe a build problem: every {@link DiagnosticCode} except the
2593
+ * `performance` and `updateAvailable` codes, which ride on their own variants.
2594
+ */
2595
+ type ProblemCode = Exclude<DiagnosticCode, typeof diagnosticCode.performance | typeof diagnosticCode.updateAvailable>;
2596
+ /**
2597
+ * A build problem collected during a run, gathered into the result instead of
2598
+ * aborting on the first failure.
2599
+ */
2600
+ type ProblemDiagnostic = {
2601
+ /**
2602
+ * @default 'problem'
2603
+ */
2604
+ kind?: 'problem';
2605
+ /**
2606
+ * Stable identifier for the problem, from the {@link diagnosticCode} catalog.
2607
+ */
2608
+ code: ProblemCode;
2609
+ severity: DiagnosticSeverity;
2610
+ message: string;
2611
+ location?: DiagnosticLocation;
2612
+ /**
2613
+ * A suggested fix, phrased as an action the user can take.
2614
+ */
2615
+ help?: string;
2616
+ /**
2617
+ * Name of the plugin or subsystem that produced the diagnostic.
2618
+ */
2619
+ plugin?: string;
2620
+ /**
2621
+ * The underlying error, when the diagnostic wraps a thrown one.
2622
+ */
2623
+ cause?: Error;
2624
+ };
2625
+ /**
2626
+ * A per-plugin performance record, built with {@link Diagnostics.performance}. The `performance`
2627
+ * kind keeps it out of the problem list. It feeds the per-plugin timing bars, and reporters sum
2628
+ * these into the run total.
2629
+ */
2630
+ type PerformanceDiagnostic = {
2631
+ kind: 'performance';
2632
+ code: typeof diagnosticCode.performance;
2633
+ severity: 'info';
2634
+ message: string;
2635
+ /**
2636
+ * The plugin this measurement belongs to.
2637
+ */
2638
+ plugin: string;
2639
+ /**
2640
+ * Elapsed milliseconds.
2641
+ */
2642
+ duration: number;
2643
+ };
2644
+ /**
2645
+ * A notice that a newer Kubb version is available on npm, built with {@link Diagnostics.update}.
2646
+ * It renders like any info diagnostic.
2647
+ */
2648
+ type UpdateDiagnostic = {
2649
+ kind: 'update';
2650
+ code: typeof diagnosticCode.updateAvailable;
2651
+ severity: 'info';
2652
+ message: string;
2653
+ /**
2654
+ * The running Kubb version.
2655
+ */
2656
+ currentVersion: string;
2657
+ /**
2658
+ * The newest version published on npm.
2659
+ */
2660
+ latestVersion: string;
2661
+ };
2662
+ /**
2663
+ * A structured record collected during a build, discriminated on `kind`: a
2664
+ * {@link ProblemDiagnostic} for an issue, a {@link PerformanceDiagnostic} for a per-plugin
2665
+ * timing, or an {@link UpdateDiagnostic} for a version notice.
2666
+ */
2667
+ type Diagnostic = ProblemDiagnostic | PerformanceDiagnostic | UpdateDiagnostic;
2668
+ /**
2669
+ * Maps each {@link DiagnosticCode} to the variant it selects, for {@link narrow}.
2670
+ * Every {@link ProblemCode} selects a {@link ProblemDiagnostic}, and the two bookkeeping codes
2671
+ * select their own variant.
2672
+ */
2673
+ type DiagnosticByCode = Record<ProblemCode, ProblemDiagnostic> & Record<typeof diagnosticCode.performance, PerformanceDiagnostic> & Record<typeof diagnosticCode.updateAvailable, UpdateDiagnostic>;
2674
+ /**
2675
+ * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.
2676
+ *
2677
+ * @example
2678
+ * ```ts
2679
+ * const update = narrow(diagnostic, diagnosticCode.updateAvailable)
2680
+ * if (update) {
2681
+ * console.log(update.latestVersion)
2682
+ * }
2683
+ * ```
2684
+ */
2685
+ declare function narrow<C extends DiagnosticCode>(diagnostic: Diagnostic, code: C): DiagnosticByCode[C] | null;
2686
+ /**
2687
+ * A {@link Diagnostic} reduced to its JSON-safe fields plus a `docsUrl`, for
2688
+ * machine-readable output (the `--reporter json` report, the MCP tools). Drops the
2689
+ * non-serializable `cause` and the `kind`/`duration` bookkeeping.
2690
+ */
2691
+ type SerializedDiagnostic = {
2692
+ code: DiagnosticCode;
2693
+ severity: DiagnosticSeverity;
2694
+ message: string;
2695
+ location?: DiagnosticLocation;
2696
+ help?: string;
2697
+ plugin?: string;
2698
+ /**
2699
+ * The kubb.dev docs link for the code, omitted for the unknown fallback.
2700
+ */
2701
+ docsUrl?: string;
2702
+ };
2703
+ /**
2704
+ * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
2705
+ * that lets deep code report a diagnostic without threading a callback.
2706
+ *
2707
+ * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
2708
+ * `Diagnostics.scope` activates it for a run, so anything inside that run (the
2709
+ * adapter parse, a lazily consumed stream, a generator) reports through
2710
+ * `Diagnostics.report` and lands in the same run.
2711
+ */
2712
+ declare class Diagnostics {
2713
+ #private;
2714
+ /**
2715
+ * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
2716
+ */
2717
+ static code: {
2718
+ readonly unknown: "KUBB_UNKNOWN";
2719
+ readonly inputNotFound: "KUBB_INPUT_NOT_FOUND";
2720
+ readonly inputRequired: "KUBB_INPUT_REQUIRED";
2721
+ readonly refNotFound: "KUBB_REF_NOT_FOUND";
2722
+ readonly invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE";
2723
+ readonly pluginNotFound: "KUBB_PLUGIN_NOT_FOUND";
2724
+ readonly pluginFailed: "KUBB_PLUGIN_FAILED";
2725
+ readonly pluginWarning: "KUBB_PLUGIN_WARNING";
2726
+ readonly pluginInfo: "KUBB_PLUGIN_INFO";
2727
+ readonly unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT";
2728
+ readonly deprecated: "KUBB_DEPRECATED";
2729
+ readonly adapterRequired: "KUBB_ADAPTER_REQUIRED";
2730
+ readonly pathTraversal: "KUBB_PATH_TRAVERSAL";
2731
+ readonly invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS";
2732
+ readonly hookFailed: "KUBB_HOOK_FAILED";
2733
+ readonly formatFailed: "KUBB_FORMAT_FAILED";
2734
+ readonly lintFailed: "KUBB_LINT_FAILED";
2735
+ readonly performance: "KUBB_PERFORMANCE";
2736
+ readonly updateAvailable: "KUBB_UPDATE_AVAILABLE";
2737
+ };
2738
+ /**
2739
+ * Type guard for a build {@link ProblemDiagnostic}.
2740
+ */
2741
+ static isProblem: (diagnostic: Diagnostic) => diagnostic is ProblemDiagnostic;
2742
+ /**
2743
+ * Type guard for a version-update {@link UpdateDiagnostic}.
2744
+ */
2745
+ static isUpdate: (diagnostic: Diagnostic) => diagnostic is UpdateDiagnostic;
2746
+ /**
2747
+ * Type guard for a per-plugin {@link PerformanceDiagnostic}.
2748
+ */
2749
+ static isPerformance: (diagnostic: Diagnostic) => diagnostic is PerformanceDiagnostic;
2750
+ /**
2751
+ * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.
2752
+ */
2753
+ static narrow: typeof narrow;
2754
+ /**
2755
+ * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
2756
+ * through the existing throw/catch paths while keeping their code and location.
2757
+ *
2758
+ * @example
2759
+ * ```ts
2760
+ * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
2761
+ * ```
2762
+ */
2763
+ static Error: {
2764
+ new (diagnostic: ProblemDiagnostic): {
2765
+ diagnostic: ProblemDiagnostic;
2766
+ name: string;
2767
+ message: string;
2768
+ stack?: string;
2769
+ cause?: unknown;
2770
+ };
2771
+ isError(error: unknown): error is Error;
2772
+ isError(value: unknown): value is Error;
2773
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
2774
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
2775
+ prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
2776
+ stackTraceLimit: number;
2777
+ };
2778
+ /**
2779
+ * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
2780
+ * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
2781
+ * that carries a `code`.
2782
+ */
2783
+ static isError(error: unknown): error is InstanceType<typeof Diagnostics.Error>;
2784
+ /**
2785
+ * Runs `fn` with `sink` as the active diagnostic sink for the whole async
2786
+ * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
2787
+ */
2788
+ static scope<T>(sink: (diagnostic: Diagnostic) => void, fn: () => T): T;
2789
+ /**
2790
+ * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
2791
+ * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
2792
+ * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
2793
+ * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
2794
+ */
2795
+ static report(diagnostic: Diagnostic): boolean;
2796
+ /**
2797
+ * Emits a diagnostic on the run's `kubb:diagnostic` event so the loggers render it live.
2798
+ * Use it instead of calling `hooks.emit('kubb:diagnostic', ...)` directly. To collect a
2799
+ * diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
2800
+ */
2801
+ static emit(hooks: AsyncEventEmitter<KubbHooks>, diagnostic: ProblemDiagnostic | UpdateDiagnostic): Promise<void>;
2802
+ /**
2803
+ * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
2804
+ * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
2805
+ */
2806
+ static from(error: unknown): ProblemDiagnostic;
2807
+ /**
2808
+ * Builds a per-plugin performance record. Reporters sum these into the run total.
2809
+ */
2810
+ static performance({
2811
+ plugin,
2812
+ duration
2813
+ }: {
2814
+ plugin: string;
2815
+ duration: number;
2816
+ }): PerformanceDiagnostic;
2817
+ /**
2818
+ * Builds the version-update notice shown when a newer Kubb is published on npm.
2819
+ */
2820
+ static update({
2821
+ currentVersion,
2822
+ latestVersion
2823
+ }: {
2824
+ currentVersion: string;
2825
+ latestVersion: string;
2826
+ }): UpdateDiagnostic;
2827
+ /**
2828
+ * True when any diagnostic is an error, the severity that fails a build. Non-error
2829
+ * diagnostics are ignored.
2830
+ */
2831
+ static hasError(diagnostics: ReadonlyArray<Diagnostic>): boolean;
2832
+ /**
2833
+ * Names of the plugins that failed, deduped, derived from the error diagnostics
2834
+ * that carry a `plugin`.
2835
+ */
2836
+ static failedPlugins(diagnostics: ReadonlyArray<Diagnostic>): Array<string>;
2837
+ /**
2838
+ * Counts `problem` diagnostics by severity for the run summary. `performance` and
2839
+ * `update` diagnostics are ignored.
2840
+ */
2841
+ static count(diagnostics: ReadonlyArray<Diagnostic>): {
2842
+ errors: number;
2843
+ warnings: number;
2844
+ infos: number;
2845
+ };
2846
+ /**
2847
+ * Drops duplicate `problem` diagnostics that share a code, location pointer, and
2848
+ * plugin, so the same issue reported across several passes is shown once. Non-problem
2849
+ * diagnostics are always kept.
2850
+ */
2851
+ static dedupe(diagnostics: ReadonlyArray<Diagnostic>): Array<Diagnostic>;
2852
+ /**
2853
+ * Builds the kubb.dev docs URL for a diagnostic code, e.g.
2854
+ * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics/kubb-ref-not-found`.
2855
+ */
2856
+ static docsUrl(code: string): string;
2857
+ /**
2858
+ * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
2859
+ * `/diagnostics/<slug>` page.
2860
+ */
2861
+ static explain(code: DiagnosticCode): DiagnosticDoc;
2862
+ /**
2863
+ * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
2864
+ * consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
2865
+ * fields are omitted rather than set to `undefined`.
2866
+ */
2867
+ static serialize(diagnostic: Diagnostic): SerializedDiagnostic;
2868
+ /**
2869
+ * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
2870
+ * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
2871
+ * rows (`at:` pointer, `fix:` help, `see:` docs link).
2872
+ *
2873
+ * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
2874
+ * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
2875
+ */
2876
+ static format(diagnostic: Diagnostic): {
2877
+ headline: string;
2878
+ details: Array<string>;
2879
+ };
2880
+ /**
2881
+ * The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
2882
+ * indented detail rows. Used where there is no gutter (plain and file output).
2883
+ */
2884
+ static formatLines(diagnostic: Diagnostic): Array<string>;
2885
+ }
2886
+ //#endregion
2887
+ export { KubbPluginSetupContext as $, KubbHookStartContext as A, Adapter as At, ParsedFile as B, KubbFilesProcessingEndContext as C, GenerationResult as Ct, KubbGenerationStartContext as D, UserReporter as Dt, KubbGenerationEndContext as E, ReporterName as Et, KubbSuccessContext as F, Generator as G, createKubb as H, KubbWarnContext as I, KubbDriver as J, GeneratorContext as K, PossibleConfig as L, KubbInfoContext as M, AdapterSource as Mt, KubbLifecycleStartContext as N, createAdapter as Nt, KubbHookEndContext as O, createReporter as Ot, KubbPluginsEndContext as P, AsyncEventEmitter as Pt, KubbPluginEndContext as Q, UserConfig as R, KubbFileProcessingUpdate as S, createStorage as St, KubbFilesProcessingUpdateContext as T, ReporterContext as Tt, Parser as U, Kubb$1 as V, defineParser as W, Group as X, Exclude$1 as Y, Include as Z, InputPath as _, defineResolver as _t, DiagnosticLocation as a, Override as at, KubbDiagnosticContext as b, createRenderer as bt, PerformanceDiagnostic as c, definePlugin as ct, SerializedDiagnostic as d, ResolveBannerFile as dt, KubbPluginStartContext as et, UpdateDiagnostic as f, ResolveOptionsContext as ft, InputData as g, ResolverPathParams as gt, Config as h, ResolverFileParams as ht, DiagnosticKind as i, OutputOptions as it, KubbHooks as j, AdapterFactoryOptions as jt, KubbHookLineContext as k, logLevel as kt, ProblemCode as l, BannerMeta as lt, CLIOptions as m, ResolverContext as mt, DiagnosticByCode as n, Output as nt, DiagnosticSeverity as o, Plugin as ot, BuildOutput as p, Resolver as pt, defineGenerator as q, DiagnosticDoc as r, OutputMode as rt, Diagnostics as s, PluginFactoryOptions as st, Diagnostic as t, NormalizedPlugin as tt, ProblemDiagnostic as u, ResolveBannerContext as ut, KubbBuildEndContext as v, Renderer as vt, KubbFilesProcessingStartContext as w, Reporter as wt, KubbErrorContext as x, Storage as xt, KubbBuildStartContext as y, RendererFactory as yt, FileProcessorHooks as z };
2888
+ //# sourceMappingURL=diagnostics-CQYd4UQZ.d.ts.map