@kubb/core 5.8.0 → 5.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
1
+ import { t as __name } from "./rolldown-runtime-CRm0XQPb.js";
2
2
  import { Enforce, FileNode, HttpMethod, ImportNode, InputMeta, InputNode, Macro, Node, OperationNode, SchemaNode, UserFileNode } from "@kubb/ast";
3
3
  //#region ../../internals/utils/src/promise.d.ts
4
4
  /** A value that may already be resolved or still pending.
@@ -26,118 +26,139 @@ type PossiblePromise<T> = Promise<T> | T;
26
26
  */
27
27
  type LiteralUnion<T extends Base, Base = string> = T | (Base & {});
28
28
  //#endregion
29
- //#region src/createAdapter.d.ts
29
+ //#region src/defineParser.d.ts
30
30
  /**
31
- * Source data handed to an adapter's `parse` function. Mirrors the config
32
- * input shape with paths resolved to absolute.
33
- *
34
- * - `{ type: 'path' }`: single file on disk.
35
- * - `{ type: 'data' }`: raw string or parsed object provided inline.
31
+ * Converts a resolved {@link FileNode} into the final source string that gets
32
+ * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
33
+ * for new file types (JSON, Markdown, ...).
36
34
  */
37
- type AdapterSource = {
38
- type: 'path';
39
- path: string;
40
- } | {
41
- type: 'data';
42
- data: string | unknown;
35
+ type Parser<TMeta extends object = object, TNode = unknown, TOptions extends object = object> = ExtensionNamed & {
36
+ /**
37
+ * The options passed to the parser factory.
38
+ */
39
+ options?: TOptions;
40
+ /**
41
+ * File extensions this parser handles. The driver registers the parser for each
42
+ * extension in this list. A parser with `undefined` here is not registered, so
43
+ * files of an unclaimed extension fall back to joining their sources verbatim.
44
+ *
45
+ * @example
46
+ * `['.ts', '.js']`
47
+ */
48
+ extNames: Array<FileNode['extname']> | undefined;
49
+ /**
50
+ * Serialize the file's AST into source code.
51
+ */
52
+ parse(file: FileNode<TMeta>): string;
53
+ /**
54
+ * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.
55
+ */
56
+ copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>;
57
+ /**
58
+ * Render compiler AST nodes for this parser's language into source text.
59
+ * Plugins call this to format the nodes they assemble before handing them
60
+ * back to the parser as `FileNode.sources`.
61
+ */
62
+ print(...nodes: Array<TNode>): string;
43
63
  };
44
64
  /**
45
- * Generic parameters used by `createAdapter` and the resulting `Adapter` type.
46
- *
47
- * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).
48
- * - `TOptions`: user-facing options accepted by the adapter factory.
49
- * - `TResolvedOptions`: options after defaults are applied.
50
- * - `TDocument`: type of the parsed source document.
65
+ * Takes the user's options and returns the parser methods.
51
66
  */
52
- type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
53
- name: TName;
54
- options: TOptions;
55
- resolvedOptions: TResolvedOptions;
56
- document: TDocument;
57
- };
67
+ type ParserBuild<TOptions extends object, TMeta extends object, TNode> = (options: TOptions) => Omit<Parser<TMeta, TNode>, 'name' | 'meta' | 'options'>;
58
68
  /**
59
- * Converts input files or inline data into Kubb's universal AST `InputNode`.
69
+ * The object passed to `defineExtension` with `kind: 'parser'`. `build` receives the user's options and returns the parser methods.
70
+ */
71
+ type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {
72
+ meta: ExtensionMeta;
73
+ } & ({
74
+ build: ParserBuild<TOptions, TMeta, TNode>;
75
+ } | {
76
+ /**
77
+ * @deprecated Renamed to `build`.
78
+ */
79
+ setup: ParserBuild<TOptions, TMeta, TNode>;
80
+ });
81
+ /**
82
+ * The function `defineExtension` returns for a parser. Call it with user options to get a `Parser`.
83
+ */
84
+ type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<'parser', TOptions, Parser<TMeta, TNode, TOptions>>;
85
+ /**
86
+ * Defines a parser from one object and returns a factory that takes the user's options.
87
+ * Register the result in the `parsers` array on `defineConfig`.
60
88
  *
61
- * Adapters live between the spec format and the plugins. The built-in
62
- * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can
63
- * support GraphQL, gRPC, or another schema language.
89
+ * @deprecated Use `defineExtension` with `kind: 'parser'` instead.
90
+ */
91
+ declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: ParserDefinition<TOptions, TMeta, TNode>): ParserFactory<TOptions, TMeta, TNode>;
92
+ /**
93
+ * Wraps a factory function that returns a `Parser`. Without `meta`, the parser gets `{ name }`.
64
94
  *
65
- * @example
66
- * ```ts
67
- * import { defineConfig } from 'kubb'
68
- * import { adapterOas } from '@kubb/adapter-oas'
69
- * import { pluginTs } from '@kubb/plugin-ts'
95
+ * @deprecated Pass a definition object with `kind: 'parser'`, `meta`, and `build` to `defineExtension` instead. The factory form is removed in the next major.
96
+ */
97
+ declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(factory: (options: TOptions) => Parser<TMeta, TNode>): ((options?: TOptions) => Parser<TMeta, TNode>) & {
98
+ kind: 'parser';
99
+ };
100
+ //#endregion
101
+ //#region src/createRenderer.d.ts
102
+ /**
103
+ * Minimal interface any Kubb renderer must satisfy.
70
104
  *
71
- * export default defineConfig({
72
- * input: './petStore.yaml',
73
- * output: { path: './src/gen' },
74
- * adapter: adapterOas(),
75
- * plugins: [pluginTs()],
76
- * })
77
- * ```
105
+ * `TElement` is the type the renderer accepts, for example `KubbReactElement`
106
+ * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
107
+ * `unknown` so generators that don't care about the element type work without
108
+ * specifying it.
78
109
  */
79
- type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
80
- /**
81
- * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
82
- */
83
- name: TOptions['name'];
84
- /**
85
- * Resolved adapter options after defaults have been applied.
86
- */
87
- options: TOptions['resolvedOptions'];
110
+ type Renderer<TElement = unknown> = {
88
111
  /**
89
- * Parsed source document after the first `parse()` call. `null` before parsing.
112
+ * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
113
+ * Called once per render cycle. Must resolve before {@link files} is read.
90
114
  */
91
- document: TOptions['document'] | null;
115
+ render(element: TElement): Promise<void>;
92
116
  /**
93
- * Parse the source into a universal `InputNode`.
94
- *
95
- * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on
96
- * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`
97
- * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's
98
- * last segment need no stamp.
117
+ * Accumulated {@link FileNode} results produced by the last {@link render} call.
99
118
  */
100
- parse: (source: AdapterSource, options?: {
101
- signal?: AbortSignal;
102
- }) => PossiblePromise<InputNode>;
119
+ readonly files: Array<FileNode>;
103
120
  /**
104
- * Validate the document at the given path or URL.
121
+ * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`
122
+ * runs cleanup on every exit path, including thrown errors.
105
123
  */
106
- validate: (input: string, options?: {
107
- throwOnError?: boolean;
108
- }) => Promise<void>;
124
+ [Symbol.dispose](): void;
109
125
  };
110
- type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>;
111
126
  /**
112
- * Defines a custom adapter that translates a spec format into Kubb's universal
113
- * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
114
- * handles OpenAPI/Swagger documents.
127
+ * A factory function that produces a fresh {@link Renderer} per render cycle.
115
128
  *
116
- * Adapters must return an `InputNode` from `parse`. That node is what every
117
- * plugin in the build consumes.
129
+ * Generators use this to declare which renderer handles their output.
130
+ */
131
+ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
132
+ /**
133
+ * Defines a renderer factory. Renderers turn the generator's return value
134
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
135
+ * written to disk.
118
136
  *
119
- * @example
137
+ * A renderer can target output formats beyond JSX, for instance a Handlebars
138
+ * renderer or one that writes binary files. Plugins and generators pick the
139
+ * renderer to use via the `renderer` field on `defineGenerator`.
140
+ *
141
+ * @example A minimal renderer that wraps a custom runtime
120
142
  * ```ts
121
- * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
122
- * import { ast } from '@kubb/ast'
123
- *
124
- * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
125
- *
126
- * export const myAdapter = createAdapter<MyAdapter>((options) => ({
127
- * name: 'my-adapter',
128
- * options,
129
- * document: null,
130
- * async parse(_source) {
131
- * // Convert the source (path or inline data) into an InputNode.
132
- * return ast.factory.createInput()
133
- * },
134
- * async validate() {
135
- * // Throw here when the spec is invalid.
136
- * },
137
- * }))
143
+ * import { createRenderer } from '@kubb/core'
144
+ *
145
+ * export const myRenderer = createRenderer(() => {
146
+ * const runtime = new MyRuntime()
147
+ * return {
148
+ * async render(element) {
149
+ * await runtime.render(element)
150
+ * },
151
+ * get files() {
152
+ * return runtime.files
153
+ * },
154
+ * [Symbol.dispose]() {
155
+ * runtime.dispose()
156
+ * },
157
+ * }
158
+ * })
138
159
  * ```
139
160
  */
140
- declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T>;
161
+ declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
141
162
  //#endregion
142
163
  //#region src/constants.d.ts
143
164
  /**
@@ -249,10 +270,6 @@ declare const diagnosticCode: {
249
270
  * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
250
271
  */
251
272
  readonly invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS";
252
- /**
253
- * An extension's options fail its options `schema`.
254
- */
255
- readonly invalidOptions: "KUBB_INVALID_OPTIONS";
256
273
  /**
257
274
  * A post-generate command (`output.postGenerate`) exited with a failure.
258
275
  */
@@ -568,7 +585,6 @@ declare class Diagnostics {
568
585
  readonly pathTraversal: "KUBB_PATH_TRAVERSAL";
569
586
  readonly cleanRoot: "KUBB_CLEAN_ROOT";
570
587
  readonly invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS";
571
- readonly invalidOptions: "KUBB_INVALID_OPTIONS";
572
588
  readonly postGenerateFailed: "KUBB_POST_GENERATE_FAILED";
573
589
  readonly formatFailed: "KUBB_FORMAT_FAILED";
574
590
  readonly lintFailed: "KUBB_LINT_FAILED";
@@ -931,1264 +947,966 @@ type Storage = {
931
947
  */
932
948
  declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
933
949
  //#endregion
934
- //#region src/createRenderer.d.ts
950
+ //#region src/outputManifest.d.ts
935
951
  /**
936
- * Minimal interface any Kubb renderer must satisfy.
937
- *
938
- * `TElement` is the type the renderer accepts, for example `KubbReactElement`
939
- * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
940
- * `unknown` so generators that don't care about the element type work without
941
- * specifying it.
952
+ * Remembers what the output passes did to each generated file, so the next run can tell "the
953
+ * formatter already turned this exact source into what is stored" apart from a real change.
954
+ * Without it the storage compares Kubb's bytes against the formatter's, never matches, and
955
+ * rewrites the whole output tree on every build.
942
956
  */
943
- type Renderer<TElement = unknown> = {
957
+ type OutputManifest = {
944
958
  /**
945
- * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
946
- * Called once per render cycle. Must resolve before {@link files} is read.
959
+ * `true` when `source` is known to come out of the output passes as exactly the content stored,
960
+ * meaning the write can be skipped.
947
961
  */
948
- render(element: TElement): Promise<void>;
962
+ isUpToDate(options: {
963
+ key: string;
964
+ source: string;
965
+ disk: string;
966
+ }): boolean;
949
967
  /**
950
- * Accumulated {@link FileNode} results produced by the last {@link render} call.
968
+ * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes
969
+ * can have changed and so the only kind `commit` has to re-read.
951
970
  */
952
- readonly files: Array<FileNode>;
971
+ track(options: {
972
+ key: string;
973
+ source: string;
974
+ }): void;
953
975
  /**
954
- * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`
955
- * runs cleanup on every exit path, including thrown errors.
976
+ * Re-reads the files written this run and persists their source/output pairs on top of what is
977
+ * stored. Nothing is pruned: a run generating a different set of files, or writing to a different
978
+ * storage in the same root, must not evict what another run recorded.
956
979
  */
957
- [Symbol.dispose](): void;
980
+ commit(): Promise<void>;
958
981
  };
982
+ //#endregion
983
+ //#region src/FileManager.d.ts
959
984
  /**
960
- * A factory function that produces a fresh {@link Renderer} per render cycle.
961
- *
962
- * Generators use this to declare which renderer handles their output.
985
+ * Hooks fired around a `FileManager#write` batch: `start` before it, `update` per file, `end` after.
963
986
  */
964
- type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
987
+ type FileManagerHooks = {
988
+ start: [files: Array<FileNode>];
989
+ update: [params: {
990
+ file: FileNode;
991
+ source?: string;
992
+ processed: number;
993
+ total: number;
994
+ percentage: number;
995
+ }];
996
+ end: [files: Array<FileNode>];
997
+ };
998
+ type ParseOptions = {
999
+ parsers?: Map<FileNode['extname'], Parser>;
1000
+ };
1001
+ type WriteOptions = ParseOptions & {
1002
+ storage: Storage;
1003
+ signal?: AbortSignal;
1004
+ /**
1005
+ * Consulted before each write so a file the output passes already normalized is recognized as
1006
+ * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.
1007
+ */
1008
+ manifest?: OutputManifest;
1009
+ };
965
1010
  /**
966
- * Defines a renderer factory. Renderers turn the generator's return value
967
- * (JSX, a template string, a tree of any shape) into `FileNode`s that get
968
- * written to disk.
969
- *
970
- * A renderer can target output formats beyond JSX, for instance a Handlebars
971
- * renderer or one that writes binary files. Plugins and generators pick the
972
- * renderer to use via the `renderer` field on `defineGenerator`.
1011
+ * In-memory file store for generated files, and the writer that turns them into source
1012
+ * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
1013
+ * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
1014
+ * within a bucket).
973
1015
  *
974
- * @example A minimal renderer that wraps a custom runtime
1016
+ * @example
975
1017
  * ```ts
976
- * import { createRenderer } from '@kubb/core'
977
- *
978
- * export const myRenderer = createRenderer(() => {
979
- * const runtime = new MyRuntime()
980
- * return {
981
- * async render(element) {
982
- * await runtime.render(element)
983
- * },
984
- * get files() {
985
- * return runtime.files
986
- * },
987
- * [Symbol.dispose]() {
988
- * runtime.dispose()
989
- * },
990
- * }
991
- * })
1018
+ * const manager = new FileManager()
1019
+ * manager.upsert(myFile)
1020
+ * manager.files // sorted view
1021
+ * await manager.write(manager.files, { storage: fsStorage() })
992
1022
  * ```
993
1023
  */
994
- declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
995
- //#endregion
996
- //#region src/standardSchema.d.ts
997
- /**
998
- * The parts of the Standard Schema v1 interfaces (https://standardschema.dev) that Kubb reads,
999
- * copied as the spec recommends so core needs no schema library. Zod, Valibot and ArkType
1000
- * schemas all match them.
1001
- */
1002
- interface StandardSchemaV1<Input = unknown, Output = Input> {
1003
- readonly '~standard': StandardSchemaV1.Props<Input, Output>;
1004
- }
1005
- declare namespace StandardSchemaV1 {
1006
- interface Props<Input = unknown, Output = Input> {
1007
- readonly version: 1;
1008
- readonly vendor: string;
1009
- readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
1010
- readonly types?: Types<Input, Output> | undefined;
1011
- }
1012
- type Result<Output> = SuccessResult<Output> | FailureResult;
1013
- interface SuccessResult<Output> {
1014
- readonly value: Output;
1015
- readonly issues?: undefined;
1016
- }
1017
- interface FailureResult {
1018
- readonly issues: ReadonlyArray<Issue>;
1019
- }
1020
- interface Issue {
1021
- readonly message: string;
1022
- readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
1023
- }
1024
- interface PathSegment {
1025
- readonly key: PropertyKey;
1026
- }
1027
- interface Types<Input = unknown, Output = Input> {
1028
- readonly input: Input;
1029
- readonly output: Output;
1030
- }
1031
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
1032
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
1033
- }
1034
- //#endregion
1035
- //#region src/defineExtension.d.ts
1036
- /**
1037
- * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.
1038
- */
1039
- type ExtensionKind = 'plugin' | 'adapter' | 'parser';
1040
- /**
1041
- * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.
1042
- * Studio, the kubb.dev registry, and the docs read the rest.
1043
- */
1044
- type ExtensionMeta<TName extends string = string> = {
1024
+ declare class FileManager {
1025
+ #private;
1026
+ readonly hooks: Hookable<FileManagerHooks>;
1027
+ add(...files: Array<FileNode>): Array<FileNode>;
1028
+ upsert(...files: Array<FileNode>): Array<FileNode>;
1029
+ /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
1030
+ dispatch<TElement = unknown>({ result, renderer }: {
1031
+ result: TElement | Array<FileNode> | undefined | null;
1032
+ renderer?: RendererFactory<TElement> | null;
1033
+ }): Promise<void>;
1045
1034
  /**
1046
- * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.
1035
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
1036
+ * `kubb:build:end`.
1047
1037
  */
1048
- name: TName;
1038
+ dispose(): void;
1049
1039
  /**
1050
- * Package version. Dependents check their `version` range against it.
1040
+ * All stored files in stable sort order (shortest path first, barrel files
1041
+ * last within a length bucket). Returns a cached view, do not mutate.
1051
1042
  */
1052
- version?: string;
1053
- displayName?: string;
1043
+ get files(): Array<FileNode>;
1054
1044
  /**
1055
- * One-sentence summary of what the extension generates or does.
1045
+ * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1056
1046
  */
1057
- description?: string;
1058
- category?: string;
1059
- icon?: {
1060
- light: string;
1061
- dark?: string;
1062
- };
1063
- tags?: Array<string>;
1047
+ parse(file: FileNode, { parsers }?: ParseOptions): Promise<string>;
1064
1048
  /**
1065
- * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.
1049
+ * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
1050
+ * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
1051
+ * memory rather than holding every source, while still overlapping each file's write with the
1052
+ * next file's parse. Each `update` carries the file's input position, so a consumer can present
1053
+ * the files in generation order even though they finish in whatever order they parse.
1054
+ *
1055
+ * A file the storage already holds is skipped, so a rebuild that generates identical output
1056
+ * writes nothing and leaves every mtime where it was.
1066
1057
  */
1067
- compatibility?: {
1068
- kubb?: string;
1069
- node?: string;
1070
- };
1071
- docs?: string;
1072
- };
1073
- /**
1074
- * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.
1075
- */
1076
- type ExtensionNamed = {
1077
- name?: string;
1078
- meta?: ExtensionMeta;
1079
- };
1080
- /**
1081
- * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
1082
- */
1083
- declare function resolveMeta({ name, meta }: ExtensionNamed): ExtensionMeta;
1084
- /**
1085
- * Sets how Kubb checks one entry in a `dependencies` record.
1086
- */
1087
- type ExtensionDependency = {
1058
+ write(files: Array<FileNode>, { storage, parsers, manifest, signal }: WriteOptions): Promise<void>;
1059
+ }
1060
+ //#endregion
1061
+ //#region src/KubbDriver.d.ts
1062
+ type Options = {
1063
+ hooks: Hookable<KubbHooks>;
1064
+ signal?: AbortSignal;
1088
1065
  /**
1089
- * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.
1066
+ * Passed to `fileManager.write` so files the output passes already normalized are left alone.
1090
1067
  */
1091
- version?: string;
1068
+ manifest?: OutputManifest;
1092
1069
  /**
1093
- * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.
1094
- * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.
1070
+ * The output directory `output.clean` empties. Emptied right before the files are written, so a
1071
+ * run that fails earlier leaves the previous output in place.
1095
1072
  */
1096
- optional?: boolean;
1073
+ cleanPath?: string;
1097
1074
  };
1098
- /**
1099
- * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.
1100
- */
1101
- type ExtensionDependencies<TOptions = object> = ExtensionDependencyRecord | {
1102
- resolve(options: TOptions, kubb: {
1103
- config: Config;
1104
- }): ExtensionDependencyRecord;
1105
- }['resolve'];
1106
- /**
1107
- * Maps each dependency's plugin name to how Kubb checks it.
1108
- */
1109
- type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>;
1110
- /**
1111
- * The function an extension definition returns. Call it with user options to get the extension.
1112
- */
1113
- type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string, TParsedOptions = TOptions> = {
1114
- (options?: TOptions): TExtension;
1115
- kind: TKind;
1116
- meta: ExtensionMeta<TName>;
1075
+ type RequirePluginContext = {
1117
1076
  /**
1118
- * The definition's options schema, so tools can read it without calling the factory.
1077
+ * Name of the plugin that declared the dependency, included in the error so users can
1078
+ * trace which plugin needs the missing one.
1119
1079
  */
1120
- schema?: StandardSchemaV1<TOptions, TParsedOptions>;
1121
- };
1122
- //#endregion
1123
- //#region src/Resolver.d.ts
1124
- /**
1125
- * Context for resolving filtered options for a given operation or schema node.
1126
- *
1127
- * @internal
1128
- */
1129
- type ResolveOptionsContext<TOptions> = {
1130
- options: TOptions;
1131
- exclude?: Array<Filter>;
1132
- include?: Array<Filter>;
1133
- override?: Array<Override<TOptions>>;
1080
+ requiredBy?: string;
1134
1081
  };
1135
- /**
1136
- * The built-in resolution machinery exposed on every resolver as `resolver.default`.
1137
- * Plugins delegate to it via `this.default.*` and set their own conventions through
1138
- * the top-level `name` and `file` entries.
1139
- */
1140
- type ResolverDefault = {
1082
+ declare class KubbDriver {
1083
+ #private;
1084
+ readonly config: Config;
1085
+ readonly options: Options;
1141
1086
  /**
1142
- * Built-in camelCase casing for a generated identifier.
1087
+ * The `InputNode` produced by the adapter. Set after adapter setup.
1143
1088
  */
1144
- name(name: string): string;
1145
- options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
1146
- path(options: ResolvePathOptions): string;
1147
- file(options: ResolveFileOptions): FileNode;
1148
- banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
1149
- footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
1150
- };
1151
- /**
1152
- * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that
1153
- * grouping keys off.
1154
- */
1155
- type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {
1156
- baseName: FileNode['baseName'];
1157
- };
1158
- /**
1159
- * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the
1160
- * output goes (`root`, `output`, `group`).
1161
- *
1162
- * @example
1163
- * ```ts
1164
- * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
1165
- * // → '/src/types/pets/petTypes.ts'
1166
- * ```
1167
- */
1168
- type ResolvePathOptions = ResolverPathParams & {
1089
+ inputNode: InputNode | null;
1090
+ adapter: Adapter | null;
1169
1091
  /**
1170
- * Absolute project root that the output path is resolved against.
1092
+ * Central file store for all generated files.
1093
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1094
+ * add files. This property gives direct read/write access when needed.
1171
1095
  */
1172
- root: string;
1096
+ readonly fileManager: FileManager;
1097
+ readonly plugins: Map<string, NormalizedPlugin>;
1098
+ constructor(config: Config, options: Options);
1173
1099
  /**
1174
- * Active output config; `output.path` is the base directory.
1100
+ * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
1101
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1102
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1103
+ * so `run` can parse it later.
1175
1104
  */
1176
- output: Output;
1105
+ setup(): Promise<void>;
1106
+ get hooks(): Hookable<Kubb.KubbHooksRegistry>;
1177
1107
  /**
1178
- * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).
1108
+ * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
1109
+ * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
1110
+ * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
1111
+ * plugins can configure generators, resolvers, macros, and options before `buildStart`.
1179
1112
  */
1180
- group?: Group;
1181
- };
1182
- /**
1183
- * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus
1184
- * the optional `tag`/`path` that grouping keys off.
1185
- */
1186
- type ResolverFileParams = {
1187
- name: string;
1188
- extname: FileNode['extname'];
1113
+ setupHooks(): Promise<void>;
1114
+ /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
1115
+ hasHookGenerators(pluginName: string): boolean;
1189
1116
  /**
1190
- * Tag value used when `group.type === 'tag'`.
1117
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
1118
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
1119
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
1120
+ * contributes a `timing` diagnostic for the run summary.
1191
1121
  */
1192
- tag?: string;
1122
+ run(): Promise<{
1123
+ diagnostics: Array<Diagnostic>;
1124
+ }>;
1125
+ /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
1126
+ dispatch<TElement = unknown>(params: {
1127
+ result: TElement | Array<FileNode> | undefined | null;
1128
+ renderer?: RendererFactory<TElement> | null;
1129
+ }): Promise<void>;
1193
1130
  /**
1194
- * Path value used when `group.type === 'path'`.
1131
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1132
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
1133
+ *
1134
+ * @internal
1195
1135
  */
1196
- path?: string;
1197
- };
1136
+ dispose(): void;
1137
+ [Symbol.dispose](): void;
1138
+ /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */
1139
+ getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver'];
1140
+ getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'>;
1141
+ getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1142
+ /**
1143
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1144
+ */
1145
+ requirePlugin<TName extends PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>;
1146
+ }
1147
+ //#endregion
1148
+ //#region src/output/runHook.d.ts
1198
1149
  /**
1199
- * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,
1200
- * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).
1201
- *
1202
- * @example
1203
- * ```ts
1204
- * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
1205
- * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }
1206
- * ```
1150
+ * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.
1207
1151
  */
1208
- type ResolveFileOptions = ResolverFileParams & {
1209
- root: string;
1210
- output: Output;
1211
- group?: Group;
1152
+ type HookResult = {
1153
+ success: true;
1154
+ error: null;
1155
+ } | {
1156
+ success: false;
1157
+ error: Error;
1158
+ stdout?: string;
1159
+ stderr?: string;
1160
+ };
1161
+ type RunHookOptions = {
1162
+ hooks: Hookable<KubbHooks>;
1163
+ /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */
1164
+ command: string;
1165
+ args?: ReadonlyArray<string>;
1166
+ /** Label shown instead of the command line, for example a `postGenerate` step name. */
1167
+ name?: string;
1168
+ /** Working directory for the command. Defaults to the current process directory. */
1169
+ cwd?: string;
1170
+ signal?: AbortSignal;
1212
1171
  };
1213
1172
  /**
1214
- * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated
1215
- * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema
1216
- * name becomes the imported identifier; it defaults to the resolver's top-level `name`.
1217
- *
1218
- * @example
1219
- * ```ts
1220
- * resolver.imports({ node, root, output, group })
1221
- * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
1222
- * ```
1173
+ * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
1174
+ * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
1175
+ * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
1176
+ * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
1177
+ * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
1223
1178
  */
1224
- type ResolveImportsOptions = {
1225
- /**
1226
- * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.
1227
- */
1228
- node: SchemaNode;
1229
- root: string;
1230
- output: Output;
1231
- group?: Group;
1232
- /**
1233
- * Extension of the generated files the imports point at.
1234
- *
1235
- * @default '.ts'
1236
- */
1237
- extname?: FileNode['extname'];
1238
- /**
1239
- * Overrides how a referenced schema name becomes the imported identifier, for example to
1240
- * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.
1241
- */
1242
- name?: (schemaName: string) => string;
1243
- };
1179
+ declare function runHook({ hooks, command, args, name, cwd, signal }: RunHookOptions): Promise<HookResult>;
1180
+ //#endregion
1181
+ //#region src/types.d.ts
1244
1182
  /**
1245
- * The `file` field of a resolver: decides what a generated file is called and, optionally, where
1246
- * it lives. This is how a resolver renames or relocates its files, replacing the older per-call
1247
- * `resolveName` hook.
1183
+ * Source to generate from. Kubb detects what it was given:
1248
1184
  *
1249
- * @example Suffix every generated file
1250
- * ```ts
1251
- * file: {
1252
- * baseName({ name, extname }) {
1253
- * return `${name}Faker${extname}`
1254
- * },
1255
- * }
1256
- * ```
1185
+ * - A string that is a local file path (absolute or relative to the config file) or a URL is
1186
+ * read and parsed by the adapter (e.g. an OpenAPI YAML or JSON spec).
1187
+ * - A string that is inline OpenAPI content (JSON or YAML) is parsed directly.
1188
+ * - A parsed object is used as-is, without touching the filesystem.
1257
1189
  *
1258
- * @example Own the full path
1190
+ * @example
1259
1191
  * ```ts
1260
- * file: {
1261
- * path({ baseName, output }) {
1262
- * return `${output.path}/mocks/${baseName}`
1263
- * },
1264
- * }
1192
+ * './petstore.yaml' // local path
1193
+ * 'https://example.com/openapi.json' // URL
1194
+ * '{ "openapi": "3.1.0", "info": {...} }' // inline JSON
1195
+ * { openapi: '3.1.0', info: { ... } } // parsed object
1265
1196
  * ```
1266
1197
  */
1267
- type ResolverFile = {
1268
- /**
1269
- * Builds the file's complete base name, extension included, from the identifier and the target
1270
- * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver
1271
- * helpers through `this`.
1272
- */
1273
- baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'];
1274
- /**
1275
- * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`
1276
- * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches
1277
- * sibling resolver helpers through `this`.
1278
- */
1279
- path?(params: ResolverFilePathParams): string;
1280
- };
1198
+ type Input = string | Record<string, unknown>;
1281
1199
  /**
1282
- * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,
1283
- * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are
1284
- * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the
1285
- * returned path is resolved against it.
1200
+ * A post-generate step: a shell command string, or an object that pairs the command with a `name`
1201
+ * shown in the CLI output. Steps run in sequence after the generated files are formatted and linted.
1286
1202
  */
1287
- type ResolverFilePathParams = {
1288
- baseName: FileNode['baseName'];
1289
- output: Output;
1203
+ type PostGenerateCommand = string | {
1204
+ name?: string;
1205
+ command: string;
1290
1206
  };
1291
1207
  /**
1292
- * Per-file context describing the file a banner/footer is being resolved for, so a
1293
- * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`
1294
- * directive on re-export files).
1208
+ * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to
1209
+ * write it (output), how (plugins), and the runtime pieces (parsers, storage). See
1210
+ * `UserConfig` for the relaxed form with defaults applied.
1211
+ *
1212
+ * @private
1295
1213
  */
1296
- type ResolveBannerFile = {
1297
- /**
1298
- * Full output path of the file being generated.
1299
- */
1300
- path: string;
1301
- /**
1302
- * File name only, e.g. `'stocks.ts'`.
1303
- */
1304
- baseName: string;
1305
- /**
1306
- * `true` for `index.ts` re-export barrels.
1307
- */
1308
- isBarrel?: boolean;
1214
+ type Config<TInput = Input> = {
1309
1215
  /**
1310
- * `true` for group `[dir]/[dir].ts` aggregation files.
1216
+ * Display name for this configuration in CLI output and logs.
1217
+ * Useful when running multiple builds with `defineConfig` arrays.
1218
+ *
1219
+ * @example
1220
+ * ```ts
1221
+ * name: 'api-client'
1222
+ * ```
1311
1223
  */
1312
- isAggregation?: boolean;
1313
- };
1314
- /**
1315
- * Document metadata extended with per-file context, passed to a `banner`/`footer` function.
1316
- *
1317
- * @example Skip a directive on re-export files
1318
- * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
1319
- */
1320
- type BannerMeta = InputMeta & {
1224
+ name?: string;
1321
1225
  /**
1322
- * Full output path of the file being generated.
1226
+ * Project root directory, absolute or relative to the config file. Already
1227
+ * resolved on the `Config` instance (see `UserConfig` for the optional
1228
+ * form that defaults to `process.cwd()`).
1323
1229
  */
1324
- filePath: string;
1230
+ root: string;
1325
1231
  /**
1326
- * File name only, e.g. `'stocks.ts'`.
1232
+ * Parsers that convert generated files into strings. Each parser handles a
1233
+ * set of file extensions, and a fallback parser handles anything else.
1234
+ *
1235
+ * Already resolved on the `Config` instance (see `UserConfig` for the
1236
+ * optional form that defaults to `[parserTs(), parserTsx(), parserMd()]`).
1237
+ *
1238
+ * @example
1239
+ * ```ts
1240
+ * import { defineConfig } from 'kubb'
1241
+ * import { parserTs, parserTsx } from '@kubb/parser-ts'
1242
+ *
1243
+ * export default defineConfig({
1244
+ * parsers: [parserTs(), parserTsx()],
1245
+ * })
1246
+ * ```
1327
1247
  */
1328
- baseName: string;
1248
+ parsers: Array<Parser>;
1329
1249
  /**
1330
- * `true` for `index.ts` re-export barrels.
1250
+ * Adapter that parses input files into the universal AST representation.
1251
+ * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
1252
+ *
1253
+ * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
1254
+ * injected via `injectFile` are written, but no AST walk occurs and generator hooks
1255
+ * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
1256
+ *
1257
+ * @example
1258
+ * ```ts
1259
+ * import { adapterOas } from '@kubb/adapter-oas'
1260
+ * export default defineConfig({
1261
+ * adapter: adapterOas(),
1262
+ * input: './petstore.yaml',
1263
+ * })
1264
+ * ```
1331
1265
  */
1332
- isBarrel: boolean;
1266
+ adapter?: Adapter;
1333
1267
  /**
1334
- * `true` for group `[dir]/[dir].ts` aggregation files.
1268
+ * Source to generate code from: a local file path, a URL, inline OpenAPI content
1269
+ * (JSON or YAML string), or a parsed spec object. Kubb detects which one it was given.
1270
+ * Required when an adapter is configured. Omit it when running in plugin-only mode.
1335
1271
  */
1336
- isAggregation: boolean;
1337
- };
1338
- /**
1339
- * Context passed to `resolver.default.banner` and `resolver.default.footer`.
1340
- * `output` is optional since not every plugin configures a banner/footer, and `config`
1341
- * carries the global Kubb config used to derive the default Kubb banner.
1342
- */
1343
- type ResolveBannerContext = {
1344
- output?: Pick<Output, 'banner' | 'footer'>;
1345
- config: Config;
1346
- file?: ResolveBannerFile;
1347
- };
1348
- /**
1349
- * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.
1350
- * `default` is the built-in machinery and is not user-settable.
1351
- */
1352
- type ResolverBuildOptions = {
1353
- pluginName: string;
1354
- name?: (name: string) => string;
1355
- file?: ResolverFile;
1356
- };
1357
- /**
1358
- * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
1359
- * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind
1360
- * `this` to the full resolver. Namespaces are partial, so a patch may override a single method
1361
- * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the
1362
- * job of this patch, that is what a custom plugin is for.
1363
- */
1364
- type ResolverPatch<T extends Resolver = Resolver> = { [K in keyof Omit<T, keyof Resolver>]?: T[K] extends ((...args: Array<never>) => unknown) ? T[K] : Partial<T[K]>; } & {
1365
- imports?: T['imports'];
1366
- name?: T['name'];
1367
- file?: ResolverFile;
1368
- } & ThisType<T>;
1369
- /**
1370
- * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
1371
- * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
1372
- * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
1373
- * reachable and a `file` override is never dropped.
1374
- */
1375
- declare const resolverOptions: unique symbol;
1376
- /**
1377
- * Base constraint for all plugin resolver objects.
1378
- *
1379
- * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
1380
- * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
1381
- * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
1382
- *
1383
- * @example Top-level helper
1384
- * ```ts
1385
- * type MyResolver = Resolver & {
1386
- * typeName(name: string): string
1387
- * }
1388
- * ```
1389
- *
1390
- * @example Grouped namespace
1391
- * ```ts
1392
- * type MyResolver = Resolver & {
1393
- * query: {
1394
- * name(node: OperationNode): string
1395
- * keyName(node: OperationNode): string
1396
- * }
1397
- * }
1398
- * ```
1399
- */
1400
- declare class Resolver {
1401
- #private;
1402
- readonly pluginName: string;
1403
- /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
1404
- readonly default: ResolverDefault;
1405
- constructor(options: ResolverBuildOptions);
1406
- /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
1407
- get [resolverOptions](): ResolverBuildOptions;
1408
- name(name: string): string;
1409
- file(options: ResolveFileOptions): FileNode;
1272
+ input?: TInput;
1273
+ output: {
1274
+ /**
1275
+ * Output directory for generated files, absolute or relative to `root`. Plugins can nest
1276
+ * subdirectories under it by grouping strategy (tag, path).
1277
+ *
1278
+ * @example
1279
+ * ```ts
1280
+ * output: {
1281
+ * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
1282
+ * }
1283
+ * ```
1284
+ */
1285
+ path: string;
1286
+ /**
1287
+ * Remove every file in the output directory before the build, so stale output isn't mixed
1288
+ * with new files. Leave `false` to preserve manual edits in the output directory.
1289
+ *
1290
+ * clean only removes generated code. When `path` resolves to the project root or an ancestor
1291
+ * of it, the build throws instead of wiping `kubb.config` and your source files.
1292
+ *
1293
+ * @example
1294
+ * ```ts
1295
+ * clean: true // wipes ./src/gen/* before generating
1296
+ * ```
1297
+ */
1298
+ clean?: boolean;
1299
+ /**
1300
+ * Format the generated files after generation. `'auto'` runs the first formatter it finds
1301
+ * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.
1302
+ *
1303
+ * @example
1304
+ * ```ts
1305
+ * format: 'auto' // auto-detect oxfmt, biome, or prettier
1306
+ * format: 'prettier' // force prettier
1307
+ * format: false // skip formatting
1308
+ * ```
1309
+ */
1310
+ format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
1311
+ /**
1312
+ * Lint the generated files after generation. `'auto'` runs the first linter it finds
1313
+ * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.
1314
+ *
1315
+ * @example
1316
+ * ```ts
1317
+ * lint: 'auto' // auto-detect oxlint, biome, or eslint
1318
+ * lint: 'eslint' // force eslint
1319
+ * lint: false // skip linting
1320
+ * ```
1321
+ */
1322
+ lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
1323
+ /**
1324
+ * Shell commands to run after the generated files are formatted and linted, for post-processing
1325
+ * such as a type check or a custom script. Steps run in sequence from the `root` directory. Pass
1326
+ * a plain command string, or `{ name, command }` to label the step in the CLI output.
1327
+ *
1328
+ * @example
1329
+ * ```ts
1330
+ * postGenerate: ['npm run typecheck']
1331
+ * postGenerate: [{ name: 'types', command: 'npm run typecheck' }, 'biome check --write ./src/gen']
1332
+ * ```
1333
+ */
1334
+ postGenerate?: Array<PostGenerateCommand>;
1335
+ /**
1336
+ * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds
1337
+ * source, title, and OpenAPI spec version, and `false` omits it.
1338
+ *
1339
+ * @default 'simple'
1340
+ * @example
1341
+ * ```ts
1342
+ * defaultBanner: 'simple' // "Generated by Kubb (https://kubb.dev/). Do not edit manually."
1343
+ * defaultBanner: 'full' // adds source, title, and OpenAPI spec version
1344
+ * defaultBanner: false // no banner
1345
+ * ```
1346
+ */
1347
+ defaultBanner?: 'simple' | 'full' | false;
1348
+ } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
1410
1349
  /**
1411
- * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
1412
- * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
1413
- * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
1414
- * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
1415
- * `name` override wins over both.
1350
+ * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`
1351
+ * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.
1416
1352
  *
1417
- * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
1418
- * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
1419
- * reads the same ref set instead of re-scanning it per plugin.
1353
+ * @default fsStorage()
1354
+ * @example
1355
+ * ```ts
1356
+ * import { memoryStorage } from '@kubb/core'
1357
+ *
1358
+ * // Keep generated files in memory (useful for testing, CI pipelines)
1359
+ * storage: memoryStorage()
1360
+ *
1361
+ * // Use custom S3 storage
1362
+ * storage: myS3Storage()
1363
+ * ```
1364
+ *
1365
+ * @see {@link Storage} interface for implementing custom backends.
1420
1366
  */
1421
- imports(options: ResolveImportsOptions): Array<ImportNode>;
1367
+ storage: Storage;
1422
1368
  /**
1423
- * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
1424
- * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
1425
- * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
1426
- * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
1427
- * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
1428
- * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
1429
- * copies.
1369
+ * Plugins that run during the build to generate code and transform the AST. Each one processes
1370
+ * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin
1371
+ * that depends on another throws when that plugin isn't registered.
1430
1372
  *
1431
- * @example Fold several partial overrides onto a resolver
1373
+ * @example
1432
1374
  * ```ts
1433
- * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
1375
+ * import { pluginTs } from '@kubb/plugin-ts'
1376
+ * import { pluginZod } from '@kubb/plugin-zod'
1377
+ *
1378
+ * plugins: [
1379
+ * pluginTs({ output: { path: './src/gen' } }),
1380
+ * pluginZod({ output: { path: './src/gen' } }),
1381
+ * ]
1434
1382
  * ```
1435
1383
  */
1436
- static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T;
1437
- }
1438
- //#endregion
1439
- //#region src/definePlugin.d.ts
1440
- /** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */
1441
- type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
1442
- /**
1443
- * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from
1444
- * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.
1445
- */
1446
- type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>;
1447
- /**
1448
- * Resolves a plugin name to its `PluginFactoryOptions`. A name registered in `Kubb.PluginRegistry`
1449
- * maps to its exact factory options, any other string falls back to the generic options.
1450
- */
1451
- type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginFactoryOptions;
1452
- /**
1453
- * How a plugin consolidates its generated code into files.
1454
- * - `'file'` writes everything into a single file.
1455
- * - `'directory'` writes one file per operation or schema under `path`.
1456
- */
1457
- type OutputMode = 'directory' | 'file';
1458
- /**
1459
- * Output configuration shared by every plugin. Each plugin extends this with
1460
- * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.
1461
- */
1462
- type Output = {
1463
- /**
1464
- * Directory where the plugin writes its generated code, resolved against the global
1465
- * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file
1466
- * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).
1467
- */
1468
- path: string;
1384
+ plugins: Array<Plugin>;
1469
1385
  /**
1470
- * How generated code is consolidated into files.
1471
- * - `'file'` writes everything into a single file. The `path` must include the file extension.
1472
- * - `'directory'` writes one file per operation or schema under `path`.
1386
+ * The reporters available to the run, registered as instances. The host
1387
+ * (the CLI via `--reporter`) selects which ones to trigger by `name` with {@link selectReporters}.
1388
+ * `defineConfig` from the `kubb` package registers the built-in `cli`, `json`, `file`, and
1389
+ * `html` reporters by default.
1473
1390
  *
1474
- * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.
1475
- */
1476
- mode?: OutputMode;
1477
- /**
1478
- * Text prepended to every generated file. Useful for license headers,
1479
- * lint disables, or `@ts-nocheck` directives.
1391
+ * - `cli` writes the end-of-run summary to the terminal.
1392
+ * - `json` writes a machine-readable report to stdout, for CI.
1393
+ * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.
1394
+ * - `html` writes a static HTML report; opt-in via `--reporter html`.
1480
1395
  *
1481
- * A string is applied to every file (including barrel and aggregation re-export files).
1482
- * Pass a function to compute the banner from the file's `BannerMeta` document metadata
1483
- * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can
1484
- * skip the banner on specific files.
1396
+ * @example
1397
+ * ```ts
1398
+ * import { cliReporter, jsonReporter } from '@kubb/core'
1485
1399
  *
1486
- * @example Add a directive to source files but not re-export files
1487
- * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
1488
- */
1489
- banner?: string | ((meta: BannerMeta) => string);
1490
- /**
1491
- * Text appended at the end of every generated file. Mirror of `banner`.
1492
- * Pass a function to compute the footer from the file's `BannerMeta`.
1493
- */
1494
- footer?: string | ((meta: BannerMeta) => string);
1495
- } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>;
1496
- /**
1497
- * Groups generated files into subdirectories based on an OpenAPI tag or path
1498
- * segment.
1499
- */
1500
- type Group = {
1501
- /**
1502
- * Property used to assign each operation to a group.
1503
- * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).
1504
- * - `'path'` uses the first segment of the operation's URL.
1505
- */
1506
- type: 'tag' | 'path';
1507
- /**
1508
- * Returns the subdirectory name from the group key. Defaults to the camelCased tag for
1509
- * `tag` groups, or the first path segment as written in the spec for `path` groups.
1400
+ * reporters: [cliReporter, jsonReporter, myReporter]
1401
+ * ```
1510
1402
  */
1511
- name?: (context: {
1512
- group: string;
1513
- }) => string;
1403
+ reporters: Array<Reporter>;
1514
1404
  };
1515
1405
  /**
1516
- * Couples `output.mode` with the plugin's `group` option at the type level.
1517
- * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).
1518
- * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.
1519
- *
1520
- * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything
1521
- * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set
1522
- * `mode: 'directory'` explicitly only to override that inference, such as a directory
1523
- * name that carries a dot (`path: 'clients.v2'`).
1406
+ * Partial `Config` for user-facing entry points with sensible defaults.
1524
1407
  *
1525
- * Intersect into a plugin's `Options` type instead of declaring `output` and
1526
- * `group` directly, since `mode` lives inside `output` while `group` is its sibling.
1527
- * The generic keeps a plugin's extended `Output` shape intact.
1408
+ * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
1409
+ * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
1410
+ * `storage`, and `hooks`.
1528
1411
  *
1529
1412
  * @example
1530
1413
  * ```ts
1531
- * export type Options = OutputOptions & {
1532
- * exclude?: Array<Exclude>
1533
- * }
1534
- * ```
1414
+ * export default defineConfig({
1415
+ * input: './petstore.yaml',
1416
+ * output: { path: './src/gen' },
1417
+ * plugins: [pluginTs(), pluginZod()],
1418
+ * })
1419
+ * ```
1535
1420
  */
1536
- type OutputOptions<TOutput extends Output = Output> = {
1537
- output?: TOutput & {
1538
- mode?: 'directory';
1539
- };
1540
- group?: Group;
1541
- } | {
1542
- output?: TOutput & {
1543
- mode: 'file';
1544
- };
1545
- group?: never;
1546
- };
1547
- /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
1548
- declare function assertPluginOption({ plugin, option, value, allowed }: {
1549
- plugin: string;
1550
- option: string;
1551
- value: unknown;
1552
- allowed: ReadonlyArray<unknown>;
1553
- }): void;
1554
- type ByTag = {
1421
+ type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage' | 'reporters'> & {
1555
1422
  /**
1556
- * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
1423
+ * Project root directory, absolute or relative to the config file location.
1424
+ * @default process.cwd()
1557
1425
  */
1558
- type: 'tag';
1426
+ root?: string;
1559
1427
  /**
1560
- * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
1428
+ * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
1429
+ * @default [parserTs(), parserTsx(), parserMd()] // applied by `defineConfig` from the `kubb` package
1561
1430
  */
1562
- pattern: string | RegExp;
1563
- };
1564
- type ByOperationId = {
1431
+ parsers?: Array<Parser>;
1565
1432
  /**
1566
- * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
1433
+ * Adapter that parses your API specification into Kubb's universal AST.
1434
+ * When omitted, Kubb runs in plugin-only mode.
1567
1435
  */
1568
- type: 'operationId';
1436
+ adapter?: Adapter;
1569
1437
  /**
1570
- * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
1438
+ * Plugins that execute during the build to generate code and transform the AST.
1439
+ * @default []
1571
1440
  */
1572
- pattern: string | RegExp;
1573
- };
1574
- type ByPath = {
1441
+ plugins?: Array<Plugin>;
1575
1442
  /**
1576
- * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
1443
+ * Storage backend that controls where and how generated files are persisted.
1444
+ * @default fsStorage()
1577
1445
  */
1578
- type: 'path';
1446
+ storage?: Storage;
1579
1447
  /**
1580
- * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
1448
+ * Reporters available to the run. `defineConfig` registers the built-in `cli`, `json`, `file`,
1449
+ * and `html` reporters when omitted.
1450
+ * @default [cliReporter, jsonReporter, fileReporter, htmlReporter] // applied by `defineConfig` from the `kubb` package
1581
1451
  */
1582
- pattern: string | RegExp;
1452
+ reporters?: Array<Reporter>;
1583
1453
  };
1584
- type ByMethod = {
1454
+ declare global {
1455
+ namespace Kubb {
1456
+ /**
1457
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
1458
+ * Augment this interface in each plugin's `types.ts` to enable automatic
1459
+ * typing for `getPlugin` and `requirePlugin`.
1460
+ *
1461
+ * @example
1462
+ * ```ts
1463
+ * // packages/plugin-ts/src/types.ts
1464
+ * declare global {
1465
+ * namespace Kubb {
1466
+ * interface PluginRegistry {
1467
+ * 'plugin-ts': PluginTs
1468
+ * }
1469
+ * }
1470
+ * }
1471
+ * ```
1472
+ */
1473
+ interface PluginRegistry {}
1474
+ /**
1475
+ * Extension point for root `Config['output']` options.
1476
+ * Augment the `output` key in plugin packages to add extra fields
1477
+ * to the global output configuration without touching core types.
1478
+ *
1479
+ * @example
1480
+ * ```ts
1481
+ * // packages/plugin-barrel/src/plugin.ts
1482
+ * declare global {
1483
+ * namespace Kubb {
1484
+ * interface ConfigOptionsRegistry {
1485
+ * output: {
1486
+ * barrel?: import('./types.ts').BarrelConfig | false
1487
+ * }
1488
+ * }
1489
+ * }
1490
+ * }
1491
+ * ```
1492
+ */
1493
+ interface ConfigOptionsRegistry {}
1494
+ /**
1495
+ * Extension point for per-plugin `Output` options.
1496
+ * Augment the `output` key in plugin packages to add extra fields
1497
+ * to the per-plugin output configuration without touching core types.
1498
+ *
1499
+ * @example
1500
+ * ```ts
1501
+ * // packages/plugin-barrel/src/plugin.ts
1502
+ * declare global {
1503
+ * namespace Kubb {
1504
+ * interface PluginOptionsRegistry {
1505
+ * output: {
1506
+ * barrel?: import('./types.ts').PluginBarrelConfig | false
1507
+ * }
1508
+ * }
1509
+ * }
1510
+ * }
1511
+ * ```
1512
+ */
1513
+ interface PluginOptionsRegistry {}
1514
+ /**
1515
+ * Registry of hook names to their listener argument tuples.
1516
+ * Augment this interface to add hook events without touching core types.
1517
+ *
1518
+ * @example
1519
+ * ```ts
1520
+ * // packages/my-plugin/src/hooks.ts
1521
+ * declare global {
1522
+ * namespace Kubb {
1523
+ * interface KubbHooksRegistry {
1524
+ * 'my-plugin:ready': [ctx: { count: number }]
1525
+ * }
1526
+ * }
1527
+ * }
1528
+ * ```
1529
+ */
1530
+ interface KubbHooksRegistry {
1531
+ 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
1532
+ 'kubb:lifecycle:end': [];
1533
+ 'kubb:generation:start': [ctx: KubbGenerationStartContext];
1534
+ 'kubb:generation:end': [ctx: KubbGenerationEndContext];
1535
+ 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
1536
+ 'kubb:setup:start': [];
1537
+ 'kubb:setup:end': [];
1538
+ 'kubb:format:start': [];
1539
+ 'kubb:format:end': [];
1540
+ 'kubb:lint:start': [];
1541
+ 'kubb:lint:end': [];
1542
+ 'kubb:hooks:start': [];
1543
+ 'kubb:hooks:end': [];
1544
+ 'kubb:hook:start': [ctx: KubbHookStartContext];
1545
+ 'kubb:hook:line': [ctx: KubbHookLineContext];
1546
+ 'kubb:hook:end': [ctx: KubbHookEndContext];
1547
+ 'kubb:info': [ctx: KubbInfoContext];
1548
+ 'kubb:error': [ctx: KubbErrorContext];
1549
+ 'kubb:success': [ctx: KubbSuccessContext];
1550
+ 'kubb:warn': [ctx: KubbWarnContext];
1551
+ 'kubb:diagnostic': [ctx: KubbDiagnosticContext];
1552
+ 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
1553
+ 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext];
1554
+ 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
1555
+ 'kubb:plugin:start': [ctx: KubbPluginStartContext];
1556
+ 'kubb:plugin:end': [ctx: KubbPluginEndContext];
1557
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
1558
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
1559
+ 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
1560
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
1561
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
1562
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
1563
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
1564
+ }
1565
+ }
1566
+ }
1567
+ /**
1568
+ * Lifecycle hooks emitted during Kubb code generation.
1569
+ * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
1570
+ *
1571
+ * A package can add its own hook names to this type by augmenting
1572
+ * {@link Kubb.KubbHooksRegistry} instead of exporting a second, separate hook type. Studio's
1573
+ * connection and RPC hooks intentionally use its separate `StudioHooks` registry.
1574
+ *
1575
+ * @example
1576
+ * ```ts
1577
+ * kubb.hooks.hook('kubb:lifecycle:start', () => {
1578
+ * console.log('Starting Kubb generation')
1579
+ * })
1580
+ *
1581
+ * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => {
1582
+ * console.log(`${plugin.name} completed in ${duration}ms`)
1583
+ * })
1584
+ * ```
1585
+ */
1586
+ type KubbHooks = Kubb.KubbHooksRegistry;
1587
+ /** The file access every file-carrying hook context shares: a lazy snapshot of the files so far, and a way to add more. */
1588
+ type FilesContext = {
1589
+ /** Snapshot of all files accumulated so far, including those added by plugins that already ran. */
1590
+ readonly files: ReadonlyArray<FileNode>;
1591
+ /** Adds or merges one or more files into the file manager. */
1592
+ upsertFile: (...files: Array<FileNode>) => void;
1593
+ };
1594
+ type KubbBuildStartContext = FilesContext & {
1585
1595
  /**
1586
- * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`.
1596
+ * Resolved configuration for this build.
1587
1597
  */
1588
- type: 'method';
1598
+ config: Config;
1589
1599
  /**
1590
- * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,
1591
- * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`) or a regex.
1600
+ * Adapter that parsed the input into the universal AST.
1592
1601
  */
1593
- pattern: HttpMethod | RegExp;
1602
+ adapter: Adapter;
1603
+ /**
1604
+ * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
1605
+ * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
1606
+ */
1607
+ meta: InputMeta | undefined;
1608
+ /**
1609
+ * Looks up a registered plugin by name, typed by the plugin registry.
1610
+ */
1611
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1594
1612
  };
1595
- type BySchemaName = {
1613
+ type KubbPluginsEndContext = FilesContext & {
1596
1614
  /**
1597
- * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
1615
+ * Resolved configuration for this build.
1598
1616
  */
1599
- type: 'schemaName';
1617
+ config: Config;
1618
+ };
1619
+ type KubbBuildEndContext = {
1600
1620
  /**
1601
- * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
1621
+ * All files generated during this build.
1602
1622
  */
1603
- pattern: string | RegExp;
1623
+ files: Array<FileNode>;
1624
+ /**
1625
+ * Resolved configuration for this build.
1626
+ */
1627
+ config: Config;
1628
+ /**
1629
+ * Absolute path to the output directory.
1630
+ */
1631
+ outputDir: string;
1604
1632
  };
1605
- type ByContentType = {
1633
+ type KubbLifecycleStartContext = {
1606
1634
  /**
1607
- * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
1635
+ * Current Kubb version string.
1608
1636
  */
1609
- type: 'contentType';
1637
+ version: string;
1638
+ };
1639
+ type KubbGenerationStartContext = {
1610
1640
  /**
1611
- * Content type to match (case-sensitive). Can be a literal string or regex pattern.
1641
+ * Resolved configuration for this generation run.
1612
1642
  */
1613
- pattern: string | RegExp;
1643
+ config: Config;
1614
1644
  };
1615
- /**
1616
- * Pattern filter for include, exclude, and override rules. Matches operations or schemas
1617
- * by tag, operationId, path, method, content type, or schema name.
1618
- */
1619
- type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1620
- /**
1621
- * Filter that skips matching operations or schemas during generation, for example
1622
- * deprecated endpoints or internal-only schemas.
1623
- *
1624
- * @example
1625
- * ```ts
1626
- * exclude: [
1627
- * { type: 'tag', pattern: 'internal' },
1628
- * { type: 'path', pattern: /^\/admin/ },
1629
- * { type: 'operationId', pattern: /^deprecated_/ },
1630
- * ]
1631
- * ```
1632
- */
1633
- type Exclude$1 = Filter;
1634
- /**
1635
- * Filter that restricts generation to operations or schemas matching at least
1636
- * one entry. Useful for partial builds (one tag, one API version).
1637
- *
1638
- * @example
1639
- * ```ts
1640
- * include: [
1641
- * { type: 'tag', pattern: 'public' },
1642
- * { type: 'path', pattern: /^\/api\/v1/ },
1643
- * ]
1644
- * ```
1645
- */
1646
- type Include = Filter;
1647
- /**
1648
- * Filter paired with a partial options object. When the filter matches, the
1649
- * options are merged on top of the plugin defaults for that operation only.
1650
- * Useful for "this one tag goes to a different folder" rules.
1651
- *
1652
- * Entries are evaluated top to bottom. The first matching entry wins.
1653
- *
1654
- * @example
1655
- * ```ts
1656
- * override: [
1657
- * {
1658
- * type: 'tag',
1659
- * pattern: 'admin',
1660
- * options: { output: { path: './src/gen/admin' } },
1661
- * },
1662
- * {
1663
- * type: 'operationId',
1664
- * pattern: 'listPets',
1665
- * options: { enumType: 'literal' },
1666
- * },
1667
- * ]
1668
- * ```
1669
- */
1670
- type Override<TOptions> = Filter & {
1671
- options: Omit<Partial<TOptions>, 'override'>;
1672
- };
1673
- type PluginFactoryOptions<
1674
- /**
1675
- * Unique plugin name.
1676
- */
1677
- TName extends string = string,
1678
- /**
1679
- * User-facing plugin options.
1680
- */
1681
- TOptions extends object = object,
1682
- /**
1683
- * Plugin options after defaults are applied.
1684
- */
1685
- TResolvedOptions extends object = TOptions,
1686
- /**
1687
- * Resolver that encapsulates naming and path-resolution helpers.
1688
- * Define with `createResolver` and export alongside the plugin.
1689
- */
1690
- TResolver extends Resolver = Resolver,
1691
- /**
1692
- * Plugin options after the options `schema` parsed them, with its defaults applied.
1693
- */
1694
- TParsedOptions extends object = TOptions> = {
1695
- name: TName;
1696
- options: TOptions;
1697
- parsedOptions: TParsedOptions;
1698
- resolvedOptions: TResolvedOptions;
1699
- resolver: TResolver;
1700
- };
1701
- type AsObject<T> = T extends object ? T : object;
1702
- type InferOptionsInput<TOptions> = TOptions extends StandardSchemaV1 ? AsObject<StandardSchemaV1.InferInput<TOptions>> : TOptions;
1703
- type InferOptionsOutput<TOptions> = TOptions extends StandardSchemaV1 ? AsObject<StandardSchemaV1.InferOutput<TOptions>> : TOptions;
1704
- /**
1705
- * Type parameter for the object form of `definePlugin`. Same shape as `PluginFactoryOptions`, except that
1706
- * `TOptions` can also be the plugin's options schema. Then `options` is the schema's input type, and
1707
- * `parsedOptions` and the default `resolvedOptions` are its output type.
1708
- */
1709
- type PluginType<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = InferOptionsOutput<TOptions>, TResolver extends Resolver = Resolver> = PluginFactoryOptions<TName, InferOptionsInput<TOptions>, TResolvedOptions, TResolver, InferOptionsOutput<TOptions>>;
1710
- /**
1711
- * The options a user passes to a plugin with options schema `TSchema`: the schema's input type, before defaults apply.
1712
- */
1713
- type PluginOptions<TSchema extends StandardSchemaV1> = StandardSchemaV1.InferInput<TSchema>;
1714
- /**
1715
- * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and
1716
- * sets its resolver, transformer, and options.
1717
- */
1718
- type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1645
+ type KubbGenerationEndContext = {
1719
1646
  /**
1720
- * Register one or more generators dynamically. Generators fire during the AST walk
1721
- * (schema/operation/operations) just like generators declared statically on `createPlugin`.
1647
+ * Resolved configuration for this generation run.
1648
+ */
1649
+ config: Config;
1650
+ /**
1651
+ * Read-only view of the files written during this build.
1652
+ * Reads go directly to `config.storage`, nothing extra is held in memory.
1722
1653
  *
1723
- * Pass generators as separate arguments. Spread an existing list to register it in one call.
1654
+ * @example Read a generated file
1655
+ * `const code = await storage.readItem('/src/gen/pet.ts')`
1724
1656
  *
1725
- * @example
1657
+ * @example Walk every generated file
1726
1658
  * ```ts
1727
- * ctx.addGenerator(myGenerator)
1728
- * ctx.addGenerator(schemaGenerator, operationGenerator)
1729
- * ctx.addGenerator(...selectedGenerators)
1659
+ * for (const path of await storage.readKeys()) {
1660
+ * const code = await storage.readItem(path)
1661
+ * }
1730
1662
  * ```
1731
1663
  */
1732
- addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void;
1664
+ storage: Storage;
1733
1665
  /**
1734
- * Set or override the resolver for this plugin.
1735
- * The resolver controls file naming and path resolution. Overrides merge over the built-in
1736
- * defaults, so a partial `core` or a single namespace method replaces only what it names.
1666
+ * Diagnostics collected during the build: error/warning/info problems plus a
1667
+ * `performance` diagnostic per plugin. The end-of-run summary derives its failure counts
1668
+ * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.
1737
1669
  */
1738
- setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void;
1670
+ diagnostics?: Array<Diagnostic>;
1739
1671
  /**
1740
- * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they
1741
- * are added, after any macros from earlier `addMacro` calls.
1672
+ * `'success'` when all plugins completed without errors, `'failed'` otherwise.
1742
1673
  */
1743
- addMacro(macro: Macro): void;
1674
+ status?: 'success' | 'failed';
1744
1675
  /**
1745
- * Replace this plugin's macros with `macros`.
1676
+ * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.
1746
1677
  */
1747
- setMacros(macros: ReadonlyArray<Macro>): void;
1678
+ hrStart?: [number, number];
1748
1679
  /**
1749
- * Set resolved options merged into the normalized plugin's `options`.
1750
- * Call this in `kubb:plugin:setup` to provide options generators need.
1680
+ * Total number of files created during this run.
1751
1681
  */
1752
- setOptions(options: TFactory['resolvedOptions']): void;
1682
+ filesCreated?: number;
1683
+ };
1684
+ /** A human-readable message with optional detail, as carried by `kubb:info`, `kubb:success`, and `kubb:warn`. */
1685
+ type KubbMessageContext = {
1753
1686
  /**
1754
- * Inject a raw file into the build output, bypassing the generation pipeline.
1755
- *
1756
- * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the
1757
- * generated folder, instead of building its content from `sources`.
1687
+ * Human-readable message.
1758
1688
  */
1759
- injectFile(userFileNode: UserFileNode): void;
1760
- /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */
1761
- requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
1689
+ message: string;
1762
1690
  /**
1763
- * The resolved build configuration at setup time.
1691
+ * Optional supplementary detail.
1764
1692
  */
1765
- config: Config;
1693
+ info?: string;
1694
+ };
1695
+ type KubbInfoContext = KubbMessageContext;
1696
+ type KubbSuccessContext = KubbMessageContext;
1697
+ type KubbWarnContext = KubbMessageContext;
1698
+ type KubbErrorContext = {
1699
+ /**
1700
+ * The caught error.
1701
+ */
1702
+ error: Error;
1766
1703
  /**
1767
- * The plugin's options, parsed by its options `schema` when it has one.
1704
+ * Optional structured metadata for additional context.
1768
1705
  */
1769
- options: TFactory['parsedOptions'];
1706
+ meta?: Record<string, unknown>;
1770
1707
  };
1771
- /**
1772
- * A plugin object produced by `definePlugin`. Its lifecycle handlers live under a single
1773
- * `hooks` property rather than flat methods.
1774
- */
1775
- type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionNamed & {
1708
+ type KubbDiagnosticContext = {
1776
1709
  /**
1777
- * Plugins this one builds on. They run first when the config has them. An array only orders
1778
- * plugins. A record also fails the run when a required entry is missing or out of range.
1710
+ * The structured diagnostic to render: a build problem or a version-update notice.
1779
1711
  */
1780
- dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['parsedOptions']>;
1712
+ diagnostic: ProblemDiagnostic | UpdateDiagnostic;
1713
+ };
1714
+ type KubbGenerationSummaryContext = {
1715
+ duration: number;
1716
+ fileCount: number;
1717
+ failedPlugins: number;
1718
+ status: 'success' | 'failed';
1719
+ };
1720
+ type KubbFilesProcessingStartContext = {
1781
1721
  /**
1782
- * Controls the execution order of this plugin relative to others.
1783
- *
1784
- * - `'pre'` runs before all normal plugins.
1785
- * - `'post'` runs after all normal plugins.
1786
- * - `undefined` (default) runs in declaration order among normal plugins.
1787
- *
1788
- * Dependency constraints always take precedence over `enforce`.
1722
+ * Files about to be serialized and written.
1789
1723
  */
1790
- enforce?: Enforce;
1724
+ files: Array<FileNode>;
1725
+ };
1726
+ type KubbFileProcessingUpdate = {
1791
1727
  /**
1792
- * The options passed by the user when calling the plugin factory.
1728
+ * Number of files processed so far in this batch.
1793
1729
  */
1794
- options?: TFactory['options'];
1730
+ processed: number;
1795
1731
  /**
1796
- * The options after the plugin's options `schema` parsed them, with its defaults applied. Set only when the plugin has a `schema`.
1732
+ * Total number of files in this batch.
1797
1733
  */
1798
- parsedOptions?: TFactory['parsedOptions'];
1734
+ total: number;
1799
1735
  /**
1800
- * Lifecycle hook handlers for this plugin.
1801
- * Any hook from the global `KubbHooks` map can be subscribed to here.
1736
+ * Completion percentage, `0` to `100`.
1802
1737
  */
1803
- hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>; } & {
1804
- 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
1805
- };
1738
+ percentage: number;
1739
+ /**
1740
+ * The file that was just processed.
1741
+ */
1742
+ file: FileNode;
1743
+ /**
1744
+ * Resolved configuration for this build.
1745
+ */
1746
+ config: Config;
1747
+ };
1748
+ type KubbFilesProcessingUpdateContext = {
1749
+ /**
1750
+ * All files processed in this flush chunk.
1751
+ */
1752
+ files: Array<KubbFileProcessingUpdate>;
1753
+ };
1754
+ type KubbFilesProcessingEndContext = {
1755
+ /**
1756
+ * All files that were serialized in this batch.
1757
+ */
1758
+ files: Array<FileNode>;
1759
+ };
1760
+ type KubbHookStartContext = {
1761
+ /**
1762
+ * Optional identifier for correlating start/end hooks.
1763
+ */
1764
+ id?: string;
1765
+ /**
1766
+ * The shell command that is about to run.
1767
+ */
1768
+ command: string;
1769
+ /**
1770
+ * Optional label for the command, shown in the CLI output when set.
1771
+ */
1772
+ name?: string;
1806
1773
  /**
1807
- * Runs before `kubb:plugin:setup`. Takes the parsed options and returns the resolved options.
1774
+ * Parsed argument list, when available.
1808
1775
  */
1809
- setup?(options: TFactory['parsedOptions'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>;
1776
+ args?: ReadonlyArray<string>;
1810
1777
  };
1811
1778
  /**
1812
- * The object passed to `definePlugin`.
1779
+ * Emitted for each line streamed from a hook's stdout while it runs.
1780
+ * A logger correlates the line to its active UI element via `id`.
1813
1781
  */
1814
- type PluginDefinition<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {
1815
- meta: ExtensionMeta<TFactory['name']>;
1782
+ type KubbHookLineContext = {
1816
1783
  /**
1817
- * Any Standard Schema, such as a Zod schema, that validates the options and applies their defaults
1818
- * when the factory is called. Invalid options throw `KUBB_INVALID_OPTIONS`. The schema must validate synchronously.
1784
+ * Identifier matching the corresponding `kubb:hook:start` hook.
1819
1785
  */
1820
- schema?: StandardSchemaV1<TFactory['options'], TFactory['parsedOptions']>;
1821
- hooks?: Plugin<TFactory>['hooks'];
1786
+ id: string;
1787
+ /**
1788
+ * A single streamed stdout line, without its trailing newline.
1789
+ */
1790
+ line: string;
1822
1791
  };
1792
+ /** Emitted when a hook subprocess ends: its `kubb:hook:start` context plus the outcome. */
1793
+ type KubbHookEndContext = KubbHookStartContext & HookResult;
1823
1794
  /**
1824
- * The function `definePlugin` returns. Call it with user options to get a `Plugin`.
1795
+ * CLI options derived from command-line flags.
1825
1796
  */
1826
- type PluginFactory<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name'], TFactory['parsedOptions']>;
1827
- /**
1828
- * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the
1829
- * public `Plugin` type.
1830
- *
1831
- * @internal
1832
- */
1833
- type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
1834
- name: string;
1835
- meta: ExtensionMeta;
1836
- dependencies?: Array<PluginName> | ExtensionDependencyRecord;
1837
- options: TOptions['resolvedOptions'] & {
1838
- output: Output;
1839
- include?: Array<Include>;
1840
- exclude: Array<Exclude$1>;
1841
- override: Array<Override<TOptions['resolvedOptions']>>;
1842
- };
1843
- resolver: TOptions['resolver'];
1844
- macros?: Array<Macro>;
1845
- generators?: Array<Generator>;
1846
- };
1847
- type KubbPluginStartContext = {
1848
- plugin: NormalizedPlugin;
1849
- };
1850
- type KubbPluginEndContext = FilesContext & {
1851
- plugin: NormalizedPlugin;
1852
- duration: number;
1853
- success: boolean;
1854
- error?: Error;
1855
- config: Config;
1856
- };
1857
- /**
1858
- * Defines a plugin from one object and returns a factory that takes the user's options.
1859
- * Name plugins `plugin-<feature>`. Set `schema` to validate the options and apply their defaults
1860
- * before `setup` receives them.
1861
- *
1862
- * @example
1863
- * ```ts
1864
- * export const pluginZod = definePlugin<PluginZod>({
1865
- * meta: { name: 'plugin-zod', compatibility: { kubb: '>=5.7.0' } },
1866
- * dependencies: { 'plugin-ts': { optional: true } },
1867
- * setup(options, kubb) {
1868
- * kubb.addGenerator(zodGenerator)
1869
- * return { ...options, inferred: options.inferred ?? false }
1870
- * },
1871
- * })
1872
- * ```
1873
- */
1874
- declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory>;
1875
- /**
1876
- * Wraps a factory function that returns a `Plugin`. Without `meta`, the plugin gets `{ name }`.
1877
- *
1878
- * @deprecated Pass a definition object with `meta` and `setup` instead. The factory form is removed in the next major.
1879
- */
1880
- declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): ((options?: TFactory['options']) => Plugin<TFactory>) & {
1881
- kind: 'plugin';
1882
- };
1883
- //#endregion
1884
- //#region src/defineParser.d.ts
1885
- /**
1886
- * Converts a resolved {@link FileNode} into the final source string that gets
1887
- * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
1888
- * for new file types (JSON, Markdown, ...).
1889
- */
1890
- type Parser<TMeta extends object = object, TNode = unknown> = ExtensionNamed & {
1797
+ type CLIOptions = {
1891
1798
  /**
1892
- * File extensions this parser handles. The driver registers the parser for each
1893
- * extension in this list. A parser with `undefined` here is not registered, so
1894
- * files of an unclaimed extension fall back to joining their sources verbatim.
1895
- *
1896
- * @example
1897
- * `['.ts', '.js']`
1799
+ * Path to the Kubb config file.
1898
1800
  */
1899
- extNames: Array<FileNode['extname']> | undefined;
1801
+ config?: string;
1900
1802
  /**
1901
- * Serialize the file's AST into source code.
1803
+ * OpenAPI input path or URL passed as the positional argument to `kubb generate`.
1804
+ * Overrides `config.input` when set.
1902
1805
  */
1903
- parse(file: FileNode<TMeta>): string;
1806
+ input?: string;
1904
1807
  /**
1905
- * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.
1808
+ * Re-run generation whenever input files change.
1906
1809
  */
1907
- copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>;
1810
+ watch?: boolean;
1908
1811
  /**
1909
- * Render compiler AST nodes for this parser's language into source text.
1910
- * Plugins call this to format the nodes they assemble before handing them
1911
- * back to the parser as `FileNode.sources`.
1812
+ * Controls how much output the CLI prints.
1813
+ *
1814
+ * @default 'info'
1912
1815
  */
1913
- print(...nodes: Array<TNode>): string;
1914
- };
1915
- /**
1916
- * The object passed to `defineParser`. `setup` receives the user's options and returns the parser methods.
1917
- */
1918
- type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {
1919
- meta: ExtensionMeta;
1920
- setup(options: TOptions): Omit<Parser<TMeta, TNode>, 'name' | 'meta'>;
1816
+ logLevel?: 'silent' | 'info' | 'verbose';
1817
+ /**
1818
+ * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.
1819
+ */
1820
+ reporters?: Array<ReporterName>;
1921
1821
  };
1922
1822
  /**
1923
- * The function `defineParser` returns. Call it with user options to get a `Parser`.
1924
- */
1925
- type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<'parser', TOptions, Parser<TMeta, TNode>>;
1926
- /**
1927
- * Defines a parser from one object and returns a factory that takes the user's options.
1928
- * Register the result in the `parsers` array on `defineConfig`.
1929
- */
1930
- declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: ParserDefinition<TOptions, TMeta, TNode>): ParserFactory<TOptions, TMeta, TNode>;
1931
- /**
1932
- * Wraps a factory function that returns a `Parser`. Without `meta`, the parser gets `{ name }`.
1933
- *
1934
- * @deprecated Pass a definition object with `meta` and `setup` instead. The factory form is removed in the next major.
1823
+ * All accepted forms of a Kubb configuration.
1824
+ * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).
1935
1825
  */
1936
- declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(factory: (options: TOptions) => Parser<TMeta, TNode>): ((options?: TOptions) => Parser<TMeta, TNode>) & {
1937
- kind: 'parser';
1938
- };
1939
- //#endregion
1940
- //#region src/outputManifest.d.ts
1826
+ type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Array<Config>> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>);
1941
1827
  /**
1942
- * Remembers what the output passes did to each generated file, so the next run can tell "the
1943
- * formatter already turned this exact source into what is stored" apart from a real change.
1944
- * Without it the storage compares Kubb's bytes against the formatter's, never matches, and
1945
- * rewrites the whole output tree on every build.
1828
+ * Full output produced by a successful or failed build.
1946
1829
  */
1947
- type OutputManifest = {
1830
+ type BuildOutput = {
1948
1831
  /**
1949
- * `true` when `source` is known to come out of the output passes as exactly the content stored,
1950
- * meaning the write can be skipped.
1832
+ * Structured diagnostics collected during the build: error/warning/info problems
1833
+ * (each with a code, severity, and where known a JSON-pointer location) plus a
1834
+ * `performance` diagnostic per plugin. Includes a top-level diagnostic when the build
1835
+ * threw before completing. Use {@link Diagnostics.hasError} to test for failure.
1951
1836
  */
1952
- isUpToDate(options: {
1953
- key: string;
1954
- source: string;
1955
- disk: string;
1956
- }): boolean;
1837
+ diagnostics: Array<Diagnostic>;
1957
1838
  /**
1958
- * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes
1959
- * can have changed and so the only kind `commit` has to re-read.
1839
+ * All files generated during this build.
1960
1840
  */
1961
- track(options: {
1962
- key: string;
1963
- source: string;
1964
- }): void;
1841
+ files: Array<FileNode>;
1965
1842
  /**
1966
- * Re-reads the files written this run and persists their source/output pairs on top of what is
1967
- * stored. Nothing is pruned: a run generating a different set of files, or writing to a different
1968
- * storage in the same root, must not evict what another run recorded.
1843
+ * The plugin driver that orchestrated this build.
1969
1844
  */
1970
- commit(): Promise<void>;
1971
- };
1972
- //#endregion
1973
- //#region src/FileManager.d.ts
1974
- /**
1975
- * Hooks fired around a `FileManager#write` batch: `start` before it, `update` per file, `end` after.
1976
- */
1977
- type FileManagerHooks = {
1978
- start: [files: Array<FileNode>];
1979
- update: [params: {
1980
- file: FileNode;
1981
- source?: string;
1982
- processed: number;
1983
- total: number;
1984
- percentage: number;
1985
- }];
1986
- end: [files: Array<FileNode>];
1987
- };
1988
- type ParseOptions = {
1989
- parsers?: Map<FileNode['extname'], Parser>;
1990
- };
1991
- type WriteOptions = ParseOptions & {
1992
- storage: Storage;
1993
- signal?: AbortSignal;
1845
+ driver: KubbDriver;
1994
1846
  /**
1995
- * Consulted before each write so a file the output passes already normalized is recognized as
1996
- * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.
1847
+ * The configured `Storage` backend, for reading back a generated file's final content.
1848
+ * Use `files` to list what this build produced.
1849
+ *
1850
+ * @example Read a generated file
1851
+ * `const code = await buildOutput.storage.readItem('/src/gen/pet.ts')`
1997
1852
  */
1998
- manifest?: OutputManifest;
1853
+ storage: Storage;
1999
1854
  };
1855
+ //#endregion
1856
+ //#region src/nodeCache.d.ts
2000
1857
  /**
2001
- * In-memory file store for generated files, and the writer that turns them into source
2002
- * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
2003
- * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
2004
- * within a bucket).
1858
+ * Per-node memo shared by every plugin that generates from the same schema or operation node in
1859
+ * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the
1860
+ * same instance to each plugin's generator context, so work derived purely from the node (its
1861
+ * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by
1862
+ * the rest instead of being recomputed per plugin.
2005
1863
  *
2006
- * @example
1864
+ * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different
1865
+ * derivations of the same node never collide.
1866
+ *
1867
+ * @example Fill on first read, reuse afterwards
2007
1868
  * ```ts
2008
- * const manager = new FileManager()
2009
- * manager.upsert(myFile)
2010
- * manager.files // sorted view
2011
- * await manager.write(manager.files, { storage: fsStorage() })
1869
+ * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))
2012
1870
  * ```
2013
1871
  */
2014
- declare class FileManager {
2015
- #private;
2016
- readonly hooks: Hookable<FileManagerHooks>;
2017
- add(...files: Array<FileNode>): Array<FileNode>;
2018
- upsert(...files: Array<FileNode>): Array<FileNode>;
2019
- /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
2020
- dispatch<TElement = unknown>({ result, renderer }: {
2021
- result: TElement | Array<FileNode> | undefined | null;
2022
- renderer?: RendererFactory<TElement> | null;
2023
- }): Promise<void>;
1872
+ type NodeCache = {
2024
1873
  /**
2025
- * Releases all stored files and clears every `hooks` listener. Called by the core after
2026
- * `kubb:build:end`.
1874
+ * Returns the value stored under `key`, or `undefined` when nothing is stored yet.
2027
1875
  */
2028
- dispose(): void;
1876
+ readItem<TValue>(key: string): TValue | undefined;
2029
1877
  /**
2030
- * All stored files in stable sort order (shortest path first, barrel files
2031
- * last within a length bucket). Returns a cached view, do not mutate.
1878
+ * Stores `value` under `key`, overwriting any previous value, and returns it.
2032
1879
  */
2033
- get files(): Array<FileNode>;
1880
+ writeItem<TValue>(key: string, value: TValue): TValue;
2034
1881
  /**
2035
- * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1882
+ * Returns the value stored under `key`, computing and storing it with `factory` on the first
1883
+ * call. Later calls with the same key return the stored value without running `factory` again.
2036
1884
  */
2037
- parse(file: FileNode, { parsers }?: ParseOptions): Promise<string>;
1885
+ ensureItem<TValue>(key: string, factory: () => TValue): TValue;
1886
+ };
1887
+ //#endregion
1888
+ //#region src/defineGenerator.d.ts
1889
+ /**
1890
+ * Context passed to a generator's `schema`, `operation`, and `operations` methods.
1891
+ *
1892
+ * The driver sets `adapter` on the context before it runs a generator, so methods can read it
1893
+ * without a null check. `ctx.options` carries the per-node options after exclude/include/override
1894
+ * filtering for `schema` and `operation`, or the plugin-level options for `operations`.
1895
+ */
1896
+ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
2038
1897
  /**
2039
- * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
2040
- * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
2041
- * memory rather than holding every source, while still overlapping each file's write with the
2042
- * next file's parse. Each `update` carries the file's input position, so a consumer can present
2043
- * the files in generation order even though they finish in whatever order they parse.
2044
- *
2045
- * A file the storage already holds is skipped, so a rebuild that generates identical output
2046
- * writes nothing and leaves every mtime where it was.
1898
+ * Stops cooperative generation work at the next safe checkpoint.
2047
1899
  */
2048
- write(files: Array<FileNode>, { storage, parsers, manifest, signal }: WriteOptions): Promise<void>;
2049
- }
2050
- //#endregion
2051
- //#region src/KubbDriver.d.ts
2052
- type Options = {
2053
- hooks: Hookable<KubbHooks>;
2054
1900
  signal?: AbortSignal;
2055
1901
  /**
2056
- * Passed to `fileManager.write` so files the output passes already normalized are left alone.
1902
+ * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
1903
+ * full plugin list.
2057
1904
  */
2058
- manifest?: OutputManifest;
1905
+ config: Config;
2059
1906
  /**
2060
- * The output directory `output.clean` empties. Emptied right before the files are written, so a
2061
- * run that fails earlier leaves the previous output in place.
1907
+ * Absolute path to the current plugin's output directory.
2062
1908
  */
2063
- cleanPath?: string;
2064
- };
2065
- type RequirePluginContext = {
2066
- /**
2067
- * Name of the plugin that declared the dependency, included in the error so users can
2068
- * trace which plugin needs the missing one.
2069
- */
2070
- requiredBy?: string;
2071
- };
2072
- declare class KubbDriver {
2073
- #private;
2074
- readonly config: Config;
2075
- readonly options: Options;
2076
- /**
2077
- * The `InputNode` produced by the adapter. Set after adapter setup.
2078
- */
2079
- inputNode: InputNode | null;
2080
- adapter: Adapter | null;
2081
- /**
2082
- * Central file store for all generated files.
2083
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
2084
- * add files. This property gives direct read/write access when needed.
2085
- */
2086
- readonly fileManager: FileManager;
2087
- readonly plugins: Map<string, NormalizedPlugin>;
2088
- constructor(config: Config, options: Options);
2089
- /**
2090
- * Normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
2091
- * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
2092
- * `'post'`. When the config has an adapter, the adapter source is resolved from the input
2093
- * so `run` can parse it later.
2094
- */
2095
- setup(): Promise<void>;
2096
- get hooks(): Hookable<Kubb.KubbHooksRegistry>;
2097
- /**
2098
- * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
2099
- * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
2100
- * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
2101
- * plugins can configure generators, resolvers, macros, and options before `buildStart`.
2102
- */
2103
- setupHooks(): Promise<void>;
2104
- /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
2105
- hasHookGenerators(pluginName: string): boolean;
2106
- /**
2107
- * Runs the full plugin pipeline. Returns the diagnostics collected so far even
2108
- * when an outer hook throws, since the orchestrator preserves partial state by capturing
2109
- * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
2110
- * contributes a `timing` diagnostic for the run summary.
2111
- */
2112
- run(): Promise<{
2113
- diagnostics: Array<Diagnostic>;
2114
- }>;
2115
- /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
2116
- dispatch<TElement = unknown>(params: {
2117
- result: TElement | Array<FileNode> | undefined | null;
2118
- renderer?: RendererFactory<TElement> | null;
2119
- }): Promise<void>;
2120
- /**
2121
- * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
2122
- * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
2123
- *
2124
- * @internal
2125
- */
2126
- dispose(): void;
2127
- [Symbol.dispose](): void;
2128
- /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */
2129
- getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver'];
2130
- getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'>;
2131
- getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2132
- /**
2133
- * Like `getPlugin` but throws a descriptive error when the plugin is not found.
2134
- */
2135
- requirePlugin<TName extends PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>;
2136
- }
2137
- //#endregion
2138
- //#region src/nodeCache.d.ts
2139
- /**
2140
- * Per-node memo shared by every plugin that generates from the same schema or operation node in
2141
- * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the
2142
- * same instance to each plugin's generator context, so work derived purely from the node (its
2143
- * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by
2144
- * the rest instead of being recomputed per plugin.
2145
- *
2146
- * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different
2147
- * derivations of the same node never collide.
2148
- *
2149
- * @example Fill on first read, reuse afterwards
2150
- * ```ts
2151
- * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))
2152
- * ```
2153
- */
2154
- type NodeCache = {
2155
- /**
2156
- * Returns the value stored under `key`, or `undefined` when nothing is stored yet.
2157
- */
2158
- readItem<TValue>(key: string): TValue | undefined;
2159
- /**
2160
- * Stores `value` under `key`, overwriting any previous value, and returns it.
2161
- */
2162
- writeItem<TValue>(key: string, value: TValue): TValue;
2163
- /**
2164
- * Returns the value stored under `key`, computing and storing it with `factory` on the first
2165
- * call. Later calls with the same key return the stored value without running `factory` again.
2166
- */
2167
- ensureItem<TValue>(key: string, factory: () => TValue): TValue;
2168
- };
2169
- //#endregion
2170
- //#region src/defineGenerator.d.ts
2171
- /**
2172
- * Context passed to a generator's `schema`, `operation`, and `operations` methods.
2173
- *
2174
- * The driver sets `adapter` on the context before it runs a generator, so methods can read it
2175
- * without a null check. `ctx.options` carries the per-node options after exclude/include/override
2176
- * filtering for `schema` and `operation`, or the plugin-level options for `operations`.
2177
- */
2178
- type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
2179
- /**
2180
- * Stops cooperative generation work at the next safe checkpoint.
2181
- */
2182
- signal?: AbortSignal;
2183
- /**
2184
- * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
2185
- * full plugin list.
2186
- */
2187
- config: Config;
2188
- /**
2189
- * Absolute path to the current plugin's output directory.
2190
- */
2191
- root: string;
1909
+ root: string;
2192
1910
  /**
2193
1911
  * The driver running this build. Most generators never need it. Prefer the scoped helpers
2194
1912
  * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.
@@ -2393,713 +2111,968 @@ type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TEl
2393
2111
  */
2394
2112
  declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
2395
2113
  //#endregion
2396
- //#region src/output/runHook.d.ts
2114
+ //#region src/Resolver.d.ts
2397
2115
  /**
2398
- * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.
2116
+ * Context for resolving filtered options for a given operation or schema node.
2117
+ *
2118
+ * @internal
2399
2119
  */
2400
- type HookResult = {
2401
- success: true;
2402
- error: null;
2403
- } | {
2404
- success: false;
2405
- error: Error;
2406
- stdout?: string;
2407
- stderr?: string;
2120
+ type ResolveOptionsContext<TOptions> = {
2121
+ options: TOptions;
2122
+ exclude?: Array<Filter>;
2123
+ include?: Array<Filter>;
2124
+ override?: Array<Override<TOptions>>;
2408
2125
  };
2409
- type RunHookOptions = {
2410
- hooks: Hookable<KubbHooks>;
2411
- /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */
2412
- command: string;
2413
- args?: ReadonlyArray<string>;
2414
- /** Label shown instead of the command line, for example a `postGenerate` step name. */
2415
- name?: string;
2416
- /** Working directory for the command. Defaults to the current process directory. */
2417
- cwd?: string;
2418
- signal?: AbortSignal;
2126
+ /**
2127
+ * The built-in resolution machinery exposed on every resolver as `resolver.default`.
2128
+ * Plugins delegate to it via `this.default.*` and set their own conventions through
2129
+ * the top-level `name` and `file` entries.
2130
+ */
2131
+ type ResolverDefault = {
2132
+ /**
2133
+ * Built-in camelCase casing for a generated identifier.
2134
+ */
2135
+ name(name: string): string;
2136
+ options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
2137
+ path(options: ResolvePathOptions): string;
2138
+ file(options: ResolveFileOptions): FileNode;
2139
+ banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
2140
+ footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
2419
2141
  };
2420
2142
  /**
2421
- * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
2422
- * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
2423
- * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
2424
- * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
2425
- * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
2143
+ * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that
2144
+ * grouping keys off.
2426
2145
  */
2427
- declare function runHook({ hooks, command, args, name, cwd, signal }: RunHookOptions): Promise<HookResult>;
2428
- //#endregion
2429
- //#region src/types.d.ts
2146
+ type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {
2147
+ baseName: FileNode['baseName'];
2148
+ };
2430
2149
  /**
2431
- * Source to generate from. Kubb detects what it was given:
2432
- *
2433
- * - A string that is a local file path (absolute or relative to the config file) or a URL is
2434
- * read and parsed by the adapter (e.g. an OpenAPI YAML or JSON spec).
2435
- * - A string that is inline OpenAPI content (JSON or YAML) is parsed directly.
2436
- * - A parsed object is used as-is, without touching the filesystem.
2150
+ * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the
2151
+ * output goes (`root`, `output`, `group`).
2437
2152
  *
2438
2153
  * @example
2439
2154
  * ```ts
2440
- * './petstore.yaml' // local path
2441
- * 'https://example.com/openapi.json' // URL
2442
- * '{ "openapi": "3.1.0", "info": {...} }' // inline JSON
2443
- * { openapi: '3.1.0', info: { ... } } // parsed object
2155
+ * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
2156
+ * // → '/src/types/pets/petTypes.ts'
2444
2157
  * ```
2445
2158
  */
2446
- type Input = string | Record<string, unknown>;
2447
- /**
2448
- * A post-generate step: a shell command string, or an object that pairs the command with a `name`
2449
- * shown in the CLI output. Steps run in sequence after the generated files are formatted and linted.
2450
- */
2451
- type PostGenerateCommand = string | {
2452
- name?: string;
2453
- command: string;
2159
+ type ResolvePathOptions = ResolverPathParams & {
2160
+ /**
2161
+ * Absolute project root that the output path is resolved against.
2162
+ */
2163
+ root: string;
2164
+ /**
2165
+ * Active output config; `output.path` is the base directory.
2166
+ */
2167
+ output: Output;
2168
+ /**
2169
+ * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).
2170
+ */
2171
+ group?: Group;
2454
2172
  };
2455
2173
  /**
2456
- * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to
2457
- * write it (output), how (plugins), and the runtime pieces (parsers, storage). See
2458
- * `UserConfig` for the relaxed form with defaults applied.
2459
- *
2460
- * @private
2174
+ * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus
2175
+ * the optional `tag`/`path` that grouping keys off.
2461
2176
  */
2462
- type Config<TInput = Input> = {
2177
+ type ResolverFileParams = {
2178
+ name: string;
2179
+ extname: FileNode['extname'];
2463
2180
  /**
2464
- * Display name for this configuration in CLI output and logs.
2465
- * Useful when running multiple builds with `defineConfig` arrays.
2466
- *
2467
- * @example
2468
- * ```ts
2469
- * name: 'api-client'
2470
- * ```
2181
+ * Tag value used when `group.type === 'tag'`.
2471
2182
  */
2472
- name?: string;
2183
+ tag?: string;
2473
2184
  /**
2474
- * Project root directory, absolute or relative to the config file. Already
2475
- * resolved on the `Config` instance (see `UserConfig` for the optional
2476
- * form that defaults to `process.cwd()`).
2185
+ * Path value used when `group.type === 'path'`.
2477
2186
  */
2187
+ path?: string;
2188
+ };
2189
+ /**
2190
+ * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,
2191
+ * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).
2192
+ *
2193
+ * @example
2194
+ * ```ts
2195
+ * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
2196
+ * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }
2197
+ * ```
2198
+ */
2199
+ type ResolveFileOptions = ResolverFileParams & {
2478
2200
  root: string;
2479
- /**
2480
- * Parsers that convert generated files into strings. Each parser handles a
2481
- * set of file extensions, and a fallback parser handles anything else.
2482
- *
2483
- * Already resolved on the `Config` instance (see `UserConfig` for the
2484
- * optional form that defaults to `[parserTs(), parserTsx(), parserMd()]`).
2485
- *
2486
- * @example
2487
- * ```ts
2488
- * import { defineConfig } from 'kubb'
2489
- * import { parserTs, parserTsx } from '@kubb/parser-ts'
2490
- *
2491
- * export default defineConfig({
2492
- * parsers: [parserTs(), parserTsx()],
2493
- * })
2494
- * ```
2201
+ output: Output;
2202
+ group?: Group;
2203
+ };
2204
+ /**
2205
+ * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated
2206
+ * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema
2207
+ * name becomes the imported identifier; it defaults to the resolver's top-level `name`.
2208
+ *
2209
+ * @example
2210
+ * ```ts
2211
+ * resolver.imports({ node, root, output, group })
2212
+ * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
2213
+ * ```
2214
+ */
2215
+ type ResolveImportsOptions = {
2216
+ /**
2217
+ * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.
2495
2218
  */
2496
- parsers: Array<Parser>;
2219
+ node: SchemaNode;
2220
+ root: string;
2221
+ output: Output;
2222
+ group?: Group;
2497
2223
  /**
2498
- * Adapter that parses input files into the universal AST representation.
2499
- * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
2500
- *
2501
- * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
2502
- * injected via `injectFile` are written, but no AST walk occurs and generator hooks
2503
- * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
2224
+ * Extension of the generated files the imports point at.
2504
2225
  *
2505
- * @example
2506
- * ```ts
2507
- * import { adapterOas } from '@kubb/adapter-oas'
2508
- * export default defineConfig({
2509
- * adapter: adapterOas(),
2510
- * input: './petstore.yaml',
2511
- * })
2512
- * ```
2226
+ * @default '.ts'
2513
2227
  */
2514
- adapter?: Adapter;
2228
+ extname?: FileNode['extname'];
2515
2229
  /**
2516
- * Source to generate code from: a local file path, a URL, inline OpenAPI content
2517
- * (JSON or YAML string), or a parsed spec object. Kubb detects which one it was given.
2518
- * Required when an adapter is configured. Omit it when running in plugin-only mode.
2230
+ * Overrides how a referenced schema name becomes the imported identifier, for example to
2231
+ * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.
2519
2232
  */
2520
- input?: TInput;
2521
- output: {
2522
- /**
2523
- * Output directory for generated files, absolute or relative to `root`. Plugins can nest
2524
- * subdirectories under it by grouping strategy (tag, path).
2525
- *
2526
- * @example
2527
- * ```ts
2528
- * output: {
2529
- * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
2530
- * }
2531
- * ```
2532
- */
2533
- path: string;
2534
- /**
2535
- * Remove every file in the output directory before the build, so stale output isn't mixed
2536
- * with new files. Leave `false` to preserve manual edits in the output directory.
2537
- *
2538
- * clean only removes generated code. When `path` resolves to the project root or an ancestor
2539
- * of it, the build throws instead of wiping `kubb.config` and your source files.
2540
- *
2541
- * @example
2542
- * ```ts
2543
- * clean: true // wipes ./src/gen/* before generating
2544
- * ```
2545
- */
2546
- clean?: boolean;
2547
- /**
2548
- * Format the generated files after generation. `'auto'` runs the first formatter it finds
2549
- * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.
2550
- *
2551
- * @example
2552
- * ```ts
2553
- * format: 'auto' // auto-detect oxfmt, biome, or prettier
2554
- * format: 'prettier' // force prettier
2555
- * format: false // skip formatting
2556
- * ```
2557
- */
2558
- format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
2559
- /**
2560
- * Lint the generated files after generation. `'auto'` runs the first linter it finds
2561
- * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.
2562
- *
2563
- * @example
2564
- * ```ts
2565
- * lint: 'auto' // auto-detect oxlint, biome, or eslint
2566
- * lint: 'eslint' // force eslint
2567
- * lint: false // skip linting
2568
- * ```
2569
- */
2570
- lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
2571
- /**
2572
- * Shell commands to run after the generated files are formatted and linted, for post-processing
2573
- * such as a type check or a custom script. Steps run in sequence from the `root` directory. Pass
2574
- * a plain command string, or `{ name, command }` to label the step in the CLI output.
2575
- *
2576
- * @example
2577
- * ```ts
2578
- * postGenerate: ['npm run typecheck']
2579
- * postGenerate: [{ name: 'types', command: 'npm run typecheck' }, 'biome check --write ./src/gen']
2580
- * ```
2581
- */
2582
- postGenerate?: Array<PostGenerateCommand>;
2583
- /**
2584
- * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds
2585
- * source, title, and OpenAPI spec version, and `false` omits it.
2586
- *
2587
- * @default 'simple'
2588
- * @example
2589
- * ```ts
2590
- * defaultBanner: 'simple' // "Generated by Kubb (https://kubb.dev/). Do not edit manually."
2591
- * defaultBanner: 'full' // adds source, title, and OpenAPI spec version
2592
- * defaultBanner: false // no banner
2593
- * ```
2594
- */
2595
- defaultBanner?: 'simple' | 'full' | false;
2596
- } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
2233
+ name?: (schemaName: string) => string;
2234
+ };
2235
+ /**
2236
+ * The `file` field of a resolver: decides what a generated file is called and, optionally, where
2237
+ * it lives. This is how a resolver renames or relocates its files, replacing the older per-call
2238
+ * `resolveName` hook.
2239
+ *
2240
+ * @example Suffix every generated file
2241
+ * ```ts
2242
+ * file: {
2243
+ * baseName({ name, extname }) {
2244
+ * return `${name}Faker${extname}`
2245
+ * },
2246
+ * }
2247
+ * ```
2248
+ *
2249
+ * @example Own the full path
2250
+ * ```ts
2251
+ * file: {
2252
+ * path({ baseName, output }) {
2253
+ * return `${output.path}/mocks/${baseName}`
2254
+ * },
2255
+ * }
2256
+ * ```
2257
+ */
2258
+ type ResolverFile = {
2597
2259
  /**
2598
- * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`
2599
- * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.
2600
- *
2601
- * @default fsStorage()
2602
- * @example
2603
- * ```ts
2604
- * import { memoryStorage } from '@kubb/core'
2605
- *
2606
- * // Keep generated files in memory (useful for testing, CI pipelines)
2607
- * storage: memoryStorage()
2608
- *
2609
- * // Use custom S3 storage
2610
- * storage: myS3Storage()
2611
- * ```
2612
- *
2613
- * @see {@link Storage} interface for implementing custom backends.
2260
+ * Builds the file's complete base name, extension included, from the identifier and the target
2261
+ * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver
2262
+ * helpers through `this`.
2614
2263
  */
2615
- storage: Storage;
2264
+ baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'];
2616
2265
  /**
2617
- * Plugins that run during the build to generate code and transform the AST. Each one processes
2618
- * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin
2619
- * that depends on another throws when that plugin isn't registered.
2620
- *
2621
- * @example
2622
- * ```ts
2623
- * import { pluginTs } from '@kubb/plugin-ts'
2624
- * import { pluginZod } from '@kubb/plugin-zod'
2625
- *
2626
- * plugins: [
2627
- * pluginTs({ output: { path: './src/gen' } }),
2628
- * pluginZod({ output: { path: './src/gen' } }),
2629
- * ]
2630
- * ```
2266
+ * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`
2267
+ * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches
2268
+ * sibling resolver helpers through `this`.
2631
2269
  */
2632
- plugins: Array<Plugin>;
2270
+ path?(params: ResolverFilePathParams): string;
2271
+ };
2272
+ /**
2273
+ * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,
2274
+ * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are
2275
+ * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the
2276
+ * returned path is resolved against it.
2277
+ */
2278
+ type ResolverFilePathParams = {
2279
+ baseName: FileNode['baseName'];
2280
+ output: Output;
2281
+ };
2282
+ /**
2283
+ * Per-file context describing the file a banner/footer is being resolved for, so a
2284
+ * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`
2285
+ * directive on re-export files).
2286
+ */
2287
+ type ResolveBannerFile = {
2633
2288
  /**
2634
- * The reporters available to the run, registered as instances. The host
2635
- * (the CLI via `--reporter`) selects which ones to trigger by `name` with {@link selectReporters}.
2636
- * `defineConfig` from the `kubb` package registers the built-in `cli`, `json`, `file`, and
2637
- * `html` reporters by default.
2638
- *
2639
- * - `cli` writes the end-of-run summary to the terminal.
2640
- * - `json` writes a machine-readable report to stdout, for CI.
2641
- * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.
2642
- * - `html` writes a static HTML report; opt-in via `--reporter html`.
2643
- *
2644
- * @example
2645
- * ```ts
2646
- * import { cliReporter, jsonReporter } from '@kubb/core'
2647
- *
2648
- * reporters: [cliReporter, jsonReporter, myReporter]
2649
- * ```
2289
+ * Full output path of the file being generated.
2650
2290
  */
2651
- reporters: Array<Reporter>;
2291
+ path: string;
2292
+ /**
2293
+ * File name only, e.g. `'stocks.ts'`.
2294
+ */
2295
+ baseName: string;
2296
+ /**
2297
+ * `true` for `index.ts` re-export barrels.
2298
+ */
2299
+ isBarrel?: boolean;
2300
+ /**
2301
+ * `true` for group `[dir]/[dir].ts` aggregation files.
2302
+ */
2303
+ isAggregation?: boolean;
2652
2304
  };
2653
2305
  /**
2654
- * Partial `Config` for user-facing entry points with sensible defaults.
2306
+ * Document metadata extended with per-file context, passed to a `banner`/`footer` function.
2655
2307
  *
2656
- * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
2657
- * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
2658
- * `storage`, and `hooks`.
2308
+ * @example Skip a directive on re-export files
2309
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
2310
+ */
2311
+ type BannerMeta = InputMeta & {
2312
+ /**
2313
+ * Full output path of the file being generated.
2314
+ */
2315
+ filePath: string;
2316
+ /**
2317
+ * File name only, e.g. `'stocks.ts'`.
2318
+ */
2319
+ baseName: string;
2320
+ /**
2321
+ * `true` for `index.ts` re-export barrels.
2322
+ */
2323
+ isBarrel: boolean;
2324
+ /**
2325
+ * `true` for group `[dir]/[dir].ts` aggregation files.
2326
+ */
2327
+ isAggregation: boolean;
2328
+ };
2329
+ /**
2330
+ * Context passed to `resolver.default.banner` and `resolver.default.footer`.
2331
+ * `output` is optional since not every plugin configures a banner/footer, and `config`
2332
+ * carries the global Kubb config used to derive the default Kubb banner.
2333
+ */
2334
+ type ResolveBannerContext = {
2335
+ output?: Pick<Output, 'banner' | 'footer'>;
2336
+ config: Config;
2337
+ file?: ResolveBannerFile;
2338
+ };
2339
+ /**
2340
+ * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.
2341
+ * `default` is the built-in machinery and is not user-settable.
2342
+ */
2343
+ type ResolverBuildOptions = {
2344
+ pluginName: string;
2345
+ name?: (name: string) => string;
2346
+ file?: ResolverFile;
2347
+ };
2348
+ /**
2349
+ * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
2350
+ * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind
2351
+ * `this` to the full resolver. Namespaces are partial, so a patch may override a single method
2352
+ * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the
2353
+ * job of this patch, that is what a custom plugin is for.
2354
+ */
2355
+ type ResolverPatch<T extends Resolver = Resolver> = { [K in keyof Omit<T, keyof Resolver>]?: T[K] extends ((...args: Array<never>) => unknown) ? T[K] : Partial<T[K]>; } & {
2356
+ imports?: T['imports'];
2357
+ name?: T['name'];
2358
+ file?: ResolverFile;
2359
+ } & ThisType<T>;
2360
+ /**
2361
+ * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
2362
+ * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
2363
+ * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
2364
+ * reachable and a `file` override is never dropped.
2365
+ */
2366
+ declare const resolverOptions: unique symbol;
2367
+ /**
2368
+ * Base constraint for all plugin resolver objects.
2659
2369
  *
2660
- * @example
2370
+ * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
2371
+ * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
2372
+ * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
2373
+ *
2374
+ * @example Top-level helper
2661
2375
  * ```ts
2662
- * export default defineConfig({
2663
- * input: './petstore.yaml',
2664
- * output: { path: './src/gen' },
2665
- * plugins: [pluginTs(), pluginZod()],
2666
- * })
2376
+ * type MyResolver = Resolver & {
2377
+ * typeName(name: string): string
2378
+ * }
2379
+ * ```
2380
+ *
2381
+ * @example Grouped namespace
2382
+ * ```ts
2383
+ * type MyResolver = Resolver & {
2384
+ * query: {
2385
+ * name(node: OperationNode): string
2386
+ * keyName(node: OperationNode): string
2387
+ * }
2388
+ * }
2667
2389
  * ```
2668
2390
  */
2669
- type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage' | 'reporters'> & {
2391
+ declare class Resolver {
2392
+ #private;
2393
+ readonly pluginName: string;
2394
+ /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
2395
+ readonly default: ResolverDefault;
2396
+ constructor(options: ResolverBuildOptions);
2397
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
2398
+ get [resolverOptions](): ResolverBuildOptions;
2399
+ name(name: string): string;
2400
+ file(options: ResolveFileOptions): FileNode;
2670
2401
  /**
2671
- * Project root directory, absolute or relative to the config file location.
2672
- * @default process.cwd()
2402
+ * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
2403
+ * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
2404
+ * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
2405
+ * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
2406
+ * `name` override wins over both.
2407
+ *
2408
+ * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
2409
+ * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
2410
+ * reads the same ref set instead of re-scanning it per plugin.
2411
+ */
2412
+ imports(options: ResolveImportsOptions): Array<ImportNode>;
2413
+ /**
2414
+ * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
2415
+ * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
2416
+ * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
2417
+ * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
2418
+ * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
2419
+ * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
2420
+ * copies.
2421
+ *
2422
+ * @example Fold several partial overrides onto a resolver
2423
+ * ```ts
2424
+ * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
2425
+ * ```
2426
+ */
2427
+ static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T;
2428
+ }
2429
+ //#endregion
2430
+ //#region src/definePlugin.d.ts
2431
+ /** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */
2432
+ type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
2433
+ /**
2434
+ * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from
2435
+ * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.
2436
+ */
2437
+ type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>;
2438
+ /**
2439
+ * Resolves a plugin name to its `PluginFactoryOptions`. A name registered in `Kubb.PluginRegistry`
2440
+ * maps to its exact factory options, any other string falls back to the generic options.
2441
+ */
2442
+ type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginFactoryOptions;
2443
+ /**
2444
+ * How a plugin consolidates its generated code into files.
2445
+ * - `'file'` writes everything into a single file.
2446
+ * - `'directory'` writes one file per operation or schema under `path`.
2447
+ */
2448
+ type OutputMode = 'directory' | 'file';
2449
+ /**
2450
+ * Output configuration shared by every plugin. Each plugin extends this with
2451
+ * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.
2452
+ */
2453
+ type Output = {
2454
+ /**
2455
+ * Directory where the plugin writes its generated code, resolved against the global
2456
+ * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file
2457
+ * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).
2673
2458
  */
2674
- root?: string;
2459
+ path: string;
2675
2460
  /**
2676
- * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
2677
- * @default [parserTs(), parserTsx(), parserMd()] // applied by `defineConfig` from the `kubb` package
2461
+ * How generated code is consolidated into files.
2462
+ * - `'file'` writes everything into a single file. The `path` must include the file extension.
2463
+ * - `'directory'` writes one file per operation or schema under `path`.
2464
+ *
2465
+ * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.
2678
2466
  */
2679
- parsers?: Array<Parser>;
2467
+ mode?: OutputMode;
2680
2468
  /**
2681
- * Adapter that parses your API specification into Kubb's universal AST.
2682
- * When omitted, Kubb runs in plugin-only mode.
2469
+ * Text prepended to every generated file. Useful for license headers,
2470
+ * lint disables, or `@ts-nocheck` directives.
2471
+ *
2472
+ * A string is applied to every file (including barrel and aggregation re-export files).
2473
+ * Pass a function to compute the banner from the file's `BannerMeta` document metadata
2474
+ * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can
2475
+ * skip the banner on specific files.
2476
+ *
2477
+ * @example Add a directive to source files but not re-export files
2478
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
2683
2479
  */
2684
- adapter?: Adapter;
2480
+ banner?: string | ((meta: BannerMeta) => string);
2685
2481
  /**
2686
- * Plugins that execute during the build to generate code and transform the AST.
2687
- * @default []
2482
+ * Text appended at the end of every generated file. Mirror of `banner`.
2483
+ * Pass a function to compute the footer from the file's `BannerMeta`.
2688
2484
  */
2689
- plugins?: Array<Plugin>;
2485
+ footer?: string | ((meta: BannerMeta) => string);
2486
+ } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>;
2487
+ /**
2488
+ * Groups generated files into subdirectories based on an OpenAPI tag or path
2489
+ * segment.
2490
+ */
2491
+ type Group = {
2690
2492
  /**
2691
- * Storage backend that controls where and how generated files are persisted.
2692
- * @default fsStorage()
2493
+ * Property used to assign each operation to a group.
2494
+ * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).
2495
+ * - `'path'` uses the first segment of the operation's URL.
2693
2496
  */
2694
- storage?: Storage;
2497
+ type: 'tag' | 'path';
2695
2498
  /**
2696
- * Reporters available to the run. `defineConfig` registers the built-in `cli`, `json`, `file`,
2697
- * and `html` reporters when omitted.
2698
- * @default [cliReporter, jsonReporter, fileReporter, htmlReporter] // applied by `defineConfig` from the `kubb` package
2499
+ * Returns the subdirectory name from the group key. Defaults to the camelCased tag for
2500
+ * `tag` groups, or the first path segment as written in the spec for `path` groups.
2699
2501
  */
2700
- reporters?: Array<Reporter>;
2502
+ name?: (context: {
2503
+ group: string;
2504
+ }) => string;
2701
2505
  };
2702
- declare global {
2703
- namespace Kubb {
2704
- /**
2705
- * Registry that maps plugin names to their `PluginFactoryOptions`.
2706
- * Augment this interface in each plugin's `types.ts` to enable automatic
2707
- * typing for `getPlugin` and `requirePlugin`.
2708
- *
2709
- * @example
2710
- * ```ts
2711
- * // packages/plugin-ts/src/types.ts
2712
- * declare global {
2713
- * namespace Kubb {
2714
- * interface PluginRegistry {
2715
- * 'plugin-ts': PluginTs
2716
- * }
2717
- * }
2718
- * }
2719
- * ```
2720
- */
2721
- interface PluginRegistry {}
2722
- /**
2723
- * Extension point for root `Config['output']` options.
2724
- * Augment the `output` key in plugin packages to add extra fields
2725
- * to the global output configuration without touching core types.
2726
- *
2727
- * @example
2728
- * ```ts
2729
- * // packages/plugin-barrel/src/plugin.ts
2730
- * declare global {
2731
- * namespace Kubb {
2732
- * interface ConfigOptionsRegistry {
2733
- * output: {
2734
- * barrel?: import('./types.ts').BarrelConfig | false
2735
- * }
2736
- * }
2737
- * }
2738
- * }
2739
- * ```
2740
- */
2741
- interface ConfigOptionsRegistry {}
2742
- /**
2743
- * Extension point for per-plugin `Output` options.
2744
- * Augment the `output` key in plugin packages to add extra fields
2745
- * to the per-plugin output configuration without touching core types.
2746
- *
2747
- * @example
2748
- * ```ts
2749
- * // packages/plugin-barrel/src/plugin.ts
2750
- * declare global {
2751
- * namespace Kubb {
2752
- * interface PluginOptionsRegistry {
2753
- * output: {
2754
- * barrel?: import('./types.ts').PluginBarrelConfig | false
2755
- * }
2756
- * }
2757
- * }
2758
- * }
2759
- * ```
2760
- */
2761
- interface PluginOptionsRegistry {}
2762
- /**
2763
- * Registry of hook names to their listener argument tuples.
2764
- * Augment this interface to add hook events without touching core types.
2765
- *
2766
- * @example
2767
- * ```ts
2768
- * // packages/my-plugin/src/hooks.ts
2769
- * declare global {
2770
- * namespace Kubb {
2771
- * interface KubbHooksRegistry {
2772
- * 'my-plugin:ready': [ctx: { count: number }]
2773
- * }
2774
- * }
2775
- * }
2776
- * ```
2777
- */
2778
- interface KubbHooksRegistry {
2779
- 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
2780
- 'kubb:lifecycle:end': [];
2781
- 'kubb:generation:start': [ctx: KubbGenerationStartContext];
2782
- 'kubb:generation:end': [ctx: KubbGenerationEndContext];
2783
- 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
2784
- 'kubb:setup:start': [];
2785
- 'kubb:setup:end': [];
2786
- 'kubb:format:start': [];
2787
- 'kubb:format:end': [];
2788
- 'kubb:lint:start': [];
2789
- 'kubb:lint:end': [];
2790
- 'kubb:hooks:start': [];
2791
- 'kubb:hooks:end': [];
2792
- 'kubb:hook:start': [ctx: KubbHookStartContext];
2793
- 'kubb:hook:line': [ctx: KubbHookLineContext];
2794
- 'kubb:hook:end': [ctx: KubbHookEndContext];
2795
- 'kubb:info': [ctx: KubbInfoContext];
2796
- 'kubb:error': [ctx: KubbErrorContext];
2797
- 'kubb:success': [ctx: KubbSuccessContext];
2798
- 'kubb:warn': [ctx: KubbWarnContext];
2799
- 'kubb:diagnostic': [ctx: KubbDiagnosticContext];
2800
- 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
2801
- 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext];
2802
- 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
2803
- 'kubb:plugin:start': [ctx: KubbPluginStartContext];
2804
- 'kubb:plugin:end': [ctx: KubbPluginEndContext];
2805
- 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
2806
- 'kubb:build:start': [ctx: KubbBuildStartContext];
2807
- 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
2808
- 'kubb:build:end': [ctx: KubbBuildEndContext];
2809
- 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
2810
- 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
2811
- 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
2812
- }
2813
- }
2814
- }
2815
2506
  /**
2816
- * Lifecycle hooks emitted during Kubb code generation.
2817
- * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
2507
+ * Couples `output.mode` with the plugin's `group` option at the type level.
2508
+ * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).
2509
+ * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.
2818
2510
  *
2819
- * A package can add its own hook names to this type by augmenting
2820
- * {@link Kubb.KubbHooksRegistry} instead of exporting a second, separate hook type. Studio's
2821
- * connection and RPC hooks intentionally use its separate `StudioHooks` registry.
2511
+ * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything
2512
+ * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set
2513
+ * `mode: 'directory'` explicitly only to override that inference, such as a directory
2514
+ * name that carries a dot (`path: 'clients.v2'`).
2515
+ *
2516
+ * Intersect into a plugin's `Options` type instead of declaring `output` and
2517
+ * `group` directly, since `mode` lives inside `output` while `group` is its sibling.
2518
+ * The generic keeps a plugin's extended `Output` shape intact.
2822
2519
  *
2823
2520
  * @example
2824
2521
  * ```ts
2825
- * kubb.hooks.hook('kubb:lifecycle:start', () => {
2826
- * console.log('Starting Kubb generation')
2827
- * })
2828
- *
2829
- * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => {
2830
- * console.log(`${plugin.name} completed in ${duration}ms`)
2831
- * })
2522
+ * export type Options = OutputOptions & {
2523
+ * exclude?: Array<Exclude>
2524
+ * }
2832
2525
  * ```
2833
2526
  */
2834
- type KubbHooks = Kubb.KubbHooksRegistry;
2835
- /** The file access every file-carrying hook context shares: a lazy snapshot of the files so far, and a way to add more. */
2836
- type FilesContext = {
2837
- /** Snapshot of all files accumulated so far, including those added by plugins that already ran. */
2838
- readonly files: ReadonlyArray<FileNode>;
2839
- /** Adds or merges one or more files into the file manager. */
2840
- upsertFile: (...files: Array<FileNode>) => void;
2527
+ type OutputOptions<TOutput extends Output = Output> = {
2528
+ output?: TOutput & {
2529
+ mode?: 'directory';
2530
+ };
2531
+ group?: Group;
2532
+ } | {
2533
+ output?: TOutput & {
2534
+ mode: 'file';
2535
+ };
2536
+ group?: never;
2841
2537
  };
2842
- type KubbBuildStartContext = FilesContext & {
2538
+ /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
2539
+ declare function assertPluginOption({ plugin, option, value, allowed }: {
2540
+ plugin: string;
2541
+ option: string;
2542
+ value: unknown;
2543
+ allowed: ReadonlyArray<unknown>;
2544
+ }): void;
2545
+ type ByTag = {
2843
2546
  /**
2844
- * Resolved configuration for this build.
2547
+ * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
2845
2548
  */
2846
- config: Config;
2549
+ type: 'tag';
2847
2550
  /**
2848
- * Adapter that parsed the input into the universal AST.
2551
+ * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
2849
2552
  */
2850
- adapter: Adapter;
2553
+ pattern: string | RegExp;
2554
+ };
2555
+ type ByOperationId = {
2851
2556
  /**
2852
- * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
2853
- * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
2557
+ * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
2854
2558
  */
2855
- meta: InputMeta | undefined;
2559
+ type: 'operationId';
2856
2560
  /**
2857
- * Looks up a registered plugin by name, typed by the plugin registry.
2561
+ * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
2858
2562
  */
2859
- getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2563
+ pattern: string | RegExp;
2860
2564
  };
2861
- type KubbPluginsEndContext = FilesContext & {
2565
+ type ByPath = {
2862
2566
  /**
2863
- * Resolved configuration for this build.
2567
+ * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
2864
2568
  */
2865
- config: Config;
2866
- };
2867
- type KubbBuildEndContext = {
2569
+ type: 'path';
2868
2570
  /**
2869
- * All files generated during this build.
2571
+ * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
2870
2572
  */
2871
- files: Array<FileNode>;
2573
+ pattern: string | RegExp;
2574
+ };
2575
+ type ByMethod = {
2872
2576
  /**
2873
- * Resolved configuration for this build.
2577
+ * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`.
2874
2578
  */
2875
- config: Config;
2579
+ type: 'method';
2876
2580
  /**
2877
- * Absolute path to the output directory.
2581
+ * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,
2582
+ * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`) or a regex.
2878
2583
  */
2879
- outputDir: string;
2584
+ pattern: HttpMethod | RegExp;
2880
2585
  };
2881
- type KubbLifecycleStartContext = {
2586
+ type BySchemaName = {
2882
2587
  /**
2883
- * Current Kubb version string.
2588
+ * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
2884
2589
  */
2885
- version: string;
2886
- };
2887
- type KubbGenerationStartContext = {
2590
+ type: 'schemaName';
2888
2591
  /**
2889
- * Resolved configuration for this generation run.
2592
+ * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
2890
2593
  */
2891
- config: Config;
2594
+ pattern: string | RegExp;
2892
2595
  };
2893
- type KubbGenerationEndContext = {
2596
+ type ByContentType = {
2894
2597
  /**
2895
- * Resolved configuration for this generation run.
2598
+ * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
2896
2599
  */
2897
- config: Config;
2600
+ type: 'contentType';
2898
2601
  /**
2899
- * Read-only view of the files written during this build.
2900
- * Reads go directly to `config.storage`, nothing extra is held in memory.
2602
+ * Content type to match (case-sensitive). Can be a literal string or regex pattern.
2603
+ */
2604
+ pattern: string | RegExp;
2605
+ };
2606
+ /**
2607
+ * Pattern filter for include, exclude, and override rules. Matches operations or schemas
2608
+ * by tag, operationId, path, method, content type, or schema name.
2609
+ */
2610
+ type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
2611
+ /**
2612
+ * Filter that skips matching operations or schemas during generation, for example
2613
+ * deprecated endpoints or internal-only schemas.
2614
+ *
2615
+ * @example
2616
+ * ```ts
2617
+ * exclude: [
2618
+ * { type: 'tag', pattern: 'internal' },
2619
+ * { type: 'path', pattern: /^\/admin/ },
2620
+ * { type: 'operationId', pattern: /^deprecated_/ },
2621
+ * ]
2622
+ * ```
2623
+ */
2624
+ type Exclude$1 = Filter;
2625
+ /**
2626
+ * Filter that restricts generation to operations or schemas matching at least
2627
+ * one entry. Useful for partial builds (one tag, one API version).
2628
+ *
2629
+ * @example
2630
+ * ```ts
2631
+ * include: [
2632
+ * { type: 'tag', pattern: 'public' },
2633
+ * { type: 'path', pattern: /^\/api\/v1/ },
2634
+ * ]
2635
+ * ```
2636
+ */
2637
+ type Include = Filter;
2638
+ /**
2639
+ * Filter paired with a partial options object. When the filter matches, the
2640
+ * options are merged on top of the plugin defaults for that operation only.
2641
+ * Useful for "this one tag goes to a different folder" rules.
2642
+ *
2643
+ * Entries are evaluated top to bottom. The first matching entry wins.
2644
+ *
2645
+ * @example
2646
+ * ```ts
2647
+ * override: [
2648
+ * {
2649
+ * type: 'tag',
2650
+ * pattern: 'admin',
2651
+ * options: { output: { path: './src/gen/admin' } },
2652
+ * },
2653
+ * {
2654
+ * type: 'operationId',
2655
+ * pattern: 'listPets',
2656
+ * options: { enumType: 'literal' },
2657
+ * },
2658
+ * ]
2659
+ * ```
2660
+ */
2661
+ type Override<TOptions> = Filter & {
2662
+ options: Omit<Partial<TOptions>, 'override'>;
2663
+ };
2664
+ type PluginFactoryOptions<
2665
+ /**
2666
+ * Unique plugin name.
2667
+ */
2668
+ TName extends string = string,
2669
+ /**
2670
+ * User-facing plugin options.
2671
+ */
2672
+ TOptions extends object = object,
2673
+ /**
2674
+ * Plugin options after defaults are applied.
2675
+ */
2676
+ TResolvedOptions extends object = TOptions,
2677
+ /**
2678
+ * Resolver that encapsulates naming and path-resolution helpers.
2679
+ * Define with `createResolver` and export alongside the plugin.
2680
+ */
2681
+ TResolver extends Resolver = Resolver> = {
2682
+ name: TName;
2683
+ options: TOptions;
2684
+ resolvedOptions: TResolvedOptions;
2685
+ resolver: TResolver;
2686
+ };
2687
+ /**
2688
+ * Type parameter for the object form of `defineExtension` with `kind: 'plugin'`. Same shape as `PluginFactoryOptions`.
2689
+ */
2690
+ type PluginType<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TResolver extends Resolver = Resolver> = PluginFactoryOptions<TName, TOptions, TResolvedOptions, TResolver>;
2691
+ /**
2692
+ * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and
2693
+ * sets its resolver, transformer, and options.
2694
+ */
2695
+ type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
2696
+ /**
2697
+ * Register one or more generators dynamically. Generators fire during the AST walk
2698
+ * (schema/operation/operations) just like generators declared statically on `createPlugin`.
2901
2699
  *
2902
- * @example Read a generated file
2903
- * `const code = await storage.readItem('/src/gen/pet.ts')`
2700
+ * Pass generators as separate arguments. Spread an existing list to register it in one call.
2904
2701
  *
2905
- * @example Walk every generated file
2702
+ * @example
2906
2703
  * ```ts
2907
- * for (const path of await storage.readKeys()) {
2908
- * const code = await storage.readItem(path)
2909
- * }
2704
+ * ctx.addGenerator(myGenerator)
2705
+ * ctx.addGenerator(schemaGenerator, operationGenerator)
2706
+ * ctx.addGenerator(...selectedGenerators)
2910
2707
  * ```
2911
2708
  */
2912
- storage: Storage;
2913
- /**
2914
- * Diagnostics collected during the build: error/warning/info problems plus a
2915
- * `performance` diagnostic per plugin. The end-of-run summary derives its failure counts
2916
- * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.
2917
- */
2918
- diagnostics?: Array<Diagnostic>;
2919
- /**
2920
- * `'success'` when all plugins completed without errors, `'failed'` otherwise.
2921
- */
2922
- status?: 'success' | 'failed';
2923
- /**
2924
- * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.
2925
- */
2926
- hrStart?: [number, number];
2709
+ addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void;
2927
2710
  /**
2928
- * Total number of files created during this run.
2711
+ * Set or override the resolver for this plugin.
2712
+ * The resolver controls file naming and path resolution. Overrides merge over the built-in
2713
+ * defaults, so a partial `core` or a single namespace method replaces only what it names.
2929
2714
  */
2930
- filesCreated?: number;
2931
- };
2932
- /** A human-readable message with optional detail, as carried by `kubb:info`, `kubb:success`, and `kubb:warn`. */
2933
- type KubbMessageContext = {
2715
+ setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void;
2934
2716
  /**
2935
- * Human-readable message.
2717
+ * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they
2718
+ * are added, after any macros from earlier `addMacro` calls.
2936
2719
  */
2937
- message: string;
2720
+ addMacro(macro: Macro): void;
2938
2721
  /**
2939
- * Optional supplementary detail.
2722
+ * Replace this plugin's macros with `macros`.
2940
2723
  */
2941
- info?: string;
2942
- };
2943
- type KubbInfoContext = KubbMessageContext;
2944
- type KubbSuccessContext = KubbMessageContext;
2945
- type KubbWarnContext = KubbMessageContext;
2946
- type KubbErrorContext = {
2724
+ setMacros(macros: ReadonlyArray<Macro>): void;
2947
2725
  /**
2948
- * The caught error.
2726
+ * Set resolved options merged into the normalized plugin's `options`.
2727
+ * Call this in `kubb:plugin:setup` to provide options generators need.
2949
2728
  */
2950
- error: Error;
2729
+ setOptions(options: TFactory['resolvedOptions']): void;
2951
2730
  /**
2952
- * Optional structured metadata for additional context.
2731
+ * Inject a raw file into the build output, bypassing the generation pipeline.
2732
+ *
2733
+ * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the
2734
+ * generated folder, instead of building its content from `sources`.
2953
2735
  */
2954
- meta?: Record<string, unknown>;
2955
- };
2956
- type KubbDiagnosticContext = {
2736
+ injectFile(userFileNode: UserFileNode): void;
2737
+ /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */
2738
+ requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
2957
2739
  /**
2958
- * The structured diagnostic to render: a build problem or a version-update notice.
2740
+ * The resolved build configuration at setup time.
2959
2741
  */
2960
- diagnostic: ProblemDiagnostic | UpdateDiagnostic;
2961
- };
2962
- type KubbGenerationSummaryContext = {
2963
- duration: number;
2964
- fileCount: number;
2965
- failedPlugins: number;
2966
- status: 'success' | 'failed';
2967
- };
2968
- type KubbFilesProcessingStartContext = {
2742
+ config: Config;
2969
2743
  /**
2970
- * Files about to be serialized and written.
2744
+ * The plugin's user-provided options.
2971
2745
  */
2972
- files: Array<FileNode>;
2746
+ options: TFactory['options'];
2973
2747
  };
2974
- type KubbFileProcessingUpdate = {
2748
+ /**
2749
+ * A plugin object produced by `defineExtension`. Its lifecycle handlers live under a single
2750
+ * `hooks` property rather than flat methods.
2751
+ */
2752
+ type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionNamed & {
2975
2753
  /**
2976
- * Number of files processed so far in this batch.
2754
+ * Plugins this one builds on. They run first when the config has them. An array only orders
2755
+ * plugins. A record also fails the run when a required entry is missing or out of range.
2977
2756
  */
2978
- processed: number;
2757
+ dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['options']>;
2979
2758
  /**
2980
- * Total number of files in this batch.
2759
+ * Controls the execution order of this plugin relative to others.
2760
+ *
2761
+ * - `'pre'` runs before all normal plugins.
2762
+ * - `'post'` runs after all normal plugins.
2763
+ * - `undefined` (default) runs in declaration order among normal plugins.
2764
+ *
2765
+ * Dependency constraints always take precedence over `enforce`.
2981
2766
  */
2982
- total: number;
2767
+ enforce?: Enforce;
2983
2768
  /**
2984
- * Completion percentage, `0` to `100`.
2769
+ * The options passed by the user when calling the plugin factory.
2985
2770
  */
2986
- percentage: number;
2771
+ options?: TFactory['options'];
2987
2772
  /**
2988
- * The file that was just processed.
2773
+ * Lifecycle hook handlers for this plugin.
2774
+ * Any hook from the global `KubbHooks` map can be subscribed to here.
2989
2775
  */
2990
- file: FileNode;
2776
+ hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>; } & {
2777
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
2778
+ };
2991
2779
  /**
2992
- * Resolved configuration for this build.
2780
+ * Runs before `kubb:plugin:setup`. Takes the user's options and returns the resolved options.
2993
2781
  */
2782
+ setup?(options: TFactory['options'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>;
2783
+ };
2784
+ /**
2785
+ * The object passed to `defineExtension` with `kind: 'plugin'`.
2786
+ */
2787
+ type PluginDefinition<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {
2788
+ meta: ExtensionMeta<TFactory['name']>;
2789
+ hooks?: Plugin<TFactory>['hooks'];
2790
+ };
2791
+ /**
2792
+ * The function `defineExtension` returns for a plugin. Call it with user options to get a `Plugin`.
2793
+ */
2794
+ type PluginFactory<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name']>;
2795
+ /**
2796
+ * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the
2797
+ * public `Plugin` type.
2798
+ *
2799
+ * @internal
2800
+ */
2801
+ type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
2802
+ name: string;
2803
+ meta: ExtensionMeta;
2804
+ dependencies?: Array<PluginName> | ExtensionDependencyRecord;
2805
+ options: TOptions['resolvedOptions'] & {
2806
+ output: Output;
2807
+ include?: Array<Include>;
2808
+ exclude: Array<Exclude$1>;
2809
+ override: Array<Override<TOptions['resolvedOptions']>>;
2810
+ };
2811
+ resolver: TOptions['resolver'];
2812
+ macros?: Array<Macro>;
2813
+ generators?: Array<Generator>;
2814
+ };
2815
+ type KubbPluginStartContext = {
2816
+ plugin: NormalizedPlugin;
2817
+ };
2818
+ type KubbPluginEndContext = FilesContext & {
2819
+ plugin: NormalizedPlugin;
2820
+ duration: number;
2821
+ success: boolean;
2822
+ error?: Error;
2994
2823
  config: Config;
2995
2824
  };
2996
- type KubbFilesProcessingUpdateContext = {
2997
- /**
2998
- * All files processed in this flush chunk.
2999
- */
3000
- files: Array<KubbFileProcessingUpdate>;
2825
+ /**
2826
+ * Defines a plugin from one object and returns a factory that takes the user's options.
2827
+ *
2828
+ * @deprecated Use `defineExtension` with `kind: 'plugin'` instead.
2829
+ */
2830
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory>;
2831
+ /**
2832
+ * Wraps a factory function that returns a `Plugin`. Without `meta`, the plugin gets `{ name }`.
2833
+ *
2834
+ * @deprecated Pass a definition object with `kind: 'plugin'`, `meta`, and `setup` to `defineExtension` instead. The factory form is removed in the next major.
2835
+ */
2836
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): ((options?: TFactory['options']) => Plugin<TFactory>) & {
2837
+ kind: 'plugin';
3001
2838
  };
3002
- type KubbFilesProcessingEndContext = {
2839
+ //#endregion
2840
+ //#region src/defineExtension.d.ts
2841
+ /**
2842
+ * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.
2843
+ */
2844
+ type ExtensionKind = 'plugin' | 'adapter' | 'parser';
2845
+ /**
2846
+ * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.
2847
+ * Studio, the kubb.dev registry, and the docs read the rest.
2848
+ */
2849
+ type ExtensionMeta<TName extends string = string> = {
3003
2850
  /**
3004
- * All files that were serialized in this batch.
2851
+ * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.
3005
2852
  */
3006
- files: Array<FileNode>;
3007
- };
3008
- type KubbHookStartContext = {
2853
+ name: TName;
3009
2854
  /**
3010
- * Optional identifier for correlating start/end hooks.
2855
+ * Package version. Dependents check their `version` range against it.
3011
2856
  */
3012
- id?: string;
2857
+ version?: string;
2858
+ displayName?: string;
3013
2859
  /**
3014
- * The shell command that is about to run.
2860
+ * One-sentence summary of what the extension generates or does.
3015
2861
  */
3016
- command: string;
2862
+ description?: string;
2863
+ category?: string;
2864
+ icon?: {
2865
+ light: string;
2866
+ dark?: string;
2867
+ };
2868
+ /** HTTPS image or video URLs. */
2869
+ media?: Array<string>;
2870
+ tags?: Array<string>;
3017
2871
  /**
3018
- * Optional label for the command, shown in the CLI output when set.
2872
+ * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.
3019
2873
  */
2874
+ compatibility?: {
2875
+ kubb?: string;
2876
+ node?: string;
2877
+ };
2878
+ docs?: string;
2879
+ };
2880
+ /**
2881
+ * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.
2882
+ */
2883
+ type ExtensionNamed = {
3020
2884
  name?: string;
3021
- /**
3022
- * Parsed argument list, when available.
3023
- */
3024
- args?: ReadonlyArray<string>;
2885
+ meta?: ExtensionMeta;
3025
2886
  };
3026
2887
  /**
3027
- * Emitted for each line streamed from a hook's stdout while it runs.
3028
- * A logger correlates the line to its active UI element via `id`.
2888
+ * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
3029
2889
  */
3030
- type KubbHookLineContext = {
2890
+ declare function resolveMeta({ name, meta }: ExtensionNamed): ExtensionMeta;
2891
+ /**
2892
+ * Sets how Kubb checks one entry in a `dependencies` record.
2893
+ */
2894
+ type ExtensionDependency = {
3031
2895
  /**
3032
- * Identifier matching the corresponding `kubb:hook:start` hook.
2896
+ * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.
3033
2897
  */
3034
- id: string;
2898
+ version?: string;
3035
2899
  /**
3036
- * A single streamed stdout line, without its trailing newline.
2900
+ * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.
2901
+ * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.
3037
2902
  */
3038
- line: string;
2903
+ optional?: boolean;
3039
2904
  };
3040
- /** Emitted when a hook subprocess ends: its `kubb:hook:start` context plus the outcome. */
3041
- type KubbHookEndContext = KubbHookStartContext & HookResult;
3042
2905
  /**
3043
- * CLI options derived from command-line flags.
2906
+ * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.
3044
2907
  */
3045
- type CLIOptions = {
2908
+ type ExtensionDependencies<TOptions = object> = ExtensionDependencyRecord | {
2909
+ resolve(options: TOptions, kubb: {
2910
+ config: Config;
2911
+ }): ExtensionDependencyRecord;
2912
+ }['resolve'];
2913
+ /**
2914
+ * Maps each dependency's plugin name to how Kubb checks it.
2915
+ */
2916
+ type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>;
2917
+ /**
2918
+ * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
2919
+ */
2920
+ declare function checkCompatibility(meta: ExtensionMeta): void;
2921
+ /**
2922
+ * The function an extension definition returns. Call it with user options to get the extension.
2923
+ */
2924
+ type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string> = {
2925
+ (options?: TOptions): TExtension;
2926
+ kind: TKind;
2927
+ meta: ExtensionMeta<TName>;
2928
+ };
2929
+ /**
2930
+ * Defines a parser and returns a factory that takes the user's options. `build` returns the parser methods.
2931
+ */
2932
+ declare function defineExtension<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: {
2933
+ kind: 'parser';
2934
+ meta: ExtensionMeta;
2935
+ build: ParserBuild<TOptions, TMeta, TNode>;
2936
+ }): ParserFactory<TOptions, TMeta, TNode>;
2937
+ /**
2938
+ * Defines an adapter and returns a factory that takes the user's options. `parse` must return an `InputNode`.
2939
+ */
2940
+ declare function defineExtension<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: {
2941
+ kind: 'adapter';
2942
+ } & AdapterDefinition<T>): AdapterFactory<T>;
2943
+ /**
2944
+ * Defines a plugin and returns a factory that takes the user's options. Name plugins `plugin-<feature>`.
2945
+ *
2946
+ * @example
2947
+ * ```ts
2948
+ * defineExtension<PluginZod>({ kind: 'plugin', meta: { name: 'plugin-zod' }, setup: (options) => options })
2949
+ * ```
2950
+ */
2951
+ declare function defineExtension<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(definition: {
2952
+ kind: 'plugin';
2953
+ } & PluginDefinition<TFactory>): PluginFactory<TFactory>;
2954
+ //#endregion
2955
+ //#region src/createAdapter.d.ts
2956
+ /**
2957
+ * Source data handed to an adapter's `parse` function. Mirrors the config
2958
+ * input shape with paths resolved to absolute.
2959
+ *
2960
+ * - `{ type: 'path' }`: single file on disk.
2961
+ * - `{ type: 'data' }`: raw string or parsed object provided inline.
2962
+ */
2963
+ type AdapterSource = {
2964
+ type: 'path';
2965
+ path: string;
2966
+ } | {
2967
+ type: 'data';
2968
+ data: string | unknown;
2969
+ };
2970
+ /**
2971
+ * Generic parameters used by `defineExtension` with `kind: 'adapter'` and the resulting `Adapter` type.
2972
+ *
2973
+ * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).
2974
+ * - `TOptions`: user-facing options accepted by the adapter factory.
2975
+ * - `TResolvedOptions`: options after defaults are applied.
2976
+ * - `TDocument`: type of the parsed source document.
2977
+ */
2978
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
2979
+ name: TName;
2980
+ options: TOptions;
2981
+ resolvedOptions: TResolvedOptions;
2982
+ document: TDocument;
2983
+ };
2984
+ /**
2985
+ * Converts input files or inline data into Kubb's universal AST `InputNode`.
2986
+ *
2987
+ * Adapters live between the spec format and the plugins. The built-in
2988
+ * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can
2989
+ * support GraphQL, gRPC, or another schema language.
2990
+ *
2991
+ * @example
2992
+ * ```ts
2993
+ * import { defineConfig } from 'kubb'
2994
+ * import { adapterOas } from '@kubb/adapter-oas'
2995
+ * import { pluginTs } from '@kubb/plugin-ts'
2996
+ *
2997
+ * export default defineConfig({
2998
+ * input: './petStore.yaml',
2999
+ * output: { path: './src/gen' },
3000
+ * adapter: adapterOas(),
3001
+ * plugins: [pluginTs()],
3002
+ * })
3003
+ * ```
3004
+ */
3005
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
3046
3006
  /**
3047
- * Path to the Kubb config file.
3007
+ * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
3048
3008
  */
3049
- config?: string;
3009
+ name: TOptions['name'];
3010
+ meta?: ExtensionMeta<TOptions['name']>;
3050
3011
  /**
3051
- * OpenAPI input path or URL passed as the positional argument to `kubb generate`.
3052
- * Overrides `config.input` when set.
3012
+ * Resolved adapter options after defaults have been applied.
3053
3013
  */
3054
- input?: string;
3014
+ options: TOptions['resolvedOptions'];
3055
3015
  /**
3056
- * Re-run generation whenever input files change.
3016
+ * Parsed source document after the first `parse()` call. `null` before parsing.
3057
3017
  */
3058
- watch?: boolean;
3018
+ document: TOptions['document'] | null;
3059
3019
  /**
3060
- * Controls how much output the CLI prints.
3020
+ * Parse the source into a universal `InputNode`.
3061
3021
  *
3062
- * @default 'info'
3022
+ * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on
3023
+ * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`
3024
+ * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's
3025
+ * last segment need no stamp.
3063
3026
  */
3064
- logLevel?: 'silent' | 'info' | 'verbose';
3027
+ parse: (source: AdapterSource, options?: {
3028
+ signal?: AbortSignal;
3029
+ }) => PossiblePromise<InputNode>;
3065
3030
  /**
3066
- * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.
3031
+ * Validate the document at the given path or URL.
3067
3032
  */
3068
- reporters?: Array<ReporterName>;
3033
+ validate: (input: string, options?: {
3034
+ throwOnError?: boolean;
3035
+ }) => Promise<void>;
3069
3036
  };
3037
+ type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>;
3070
3038
  /**
3071
- * All accepted forms of a Kubb configuration.
3072
- * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).
3073
- */
3074
- type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Array<Config>> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>);
3075
- /**
3076
- * Full output produced by a successful or failed build.
3039
+ * The object passed to `defineExtension` with `kind: 'adapter'`.
3077
3040
  */
3078
- type BuildOutput = {
3079
- /**
3080
- * Structured diagnostics collected during the build: error/warning/info problems
3081
- * (each with a code, severity, and where known a JSON-pointer location) plus a
3082
- * `performance` diagnostic per plugin. Includes a top-level diagnostic when the build
3083
- * threw before completing. Use {@link Diagnostics.hasError} to test for failure.
3084
- */
3085
- diagnostics: Array<Diagnostic>;
3086
- /**
3087
- * All files generated during this build.
3088
- */
3089
- files: Array<FileNode>;
3041
+ type AdapterDefinition<T extends AdapterFactoryOptions = AdapterFactoryOptions> = {
3042
+ meta: ExtensionMeta<T['name']>;
3090
3043
  /**
3091
- * The plugin driver that orchestrated this build.
3044
+ * Takes the user's options and returns the resolved options, which `build` receives and the adapter exposes as `options`.
3045
+ * Without `setup`, the user's options are the resolved options.
3092
3046
  */
3093
- driver: KubbDriver;
3047
+ setup?(options: T['options']): T['resolvedOptions'];
3094
3048
  /**
3095
- * The configured `Storage` backend, for reading back a generated file's final content.
3096
- * Use `files` to list what this build produced.
3097
- *
3098
- * @example Read a generated file
3099
- * `const code = await buildOutput.storage.readItem('/src/gen/pet.ts')`
3049
+ * Returns the adapter's document and methods for the resolved options.
3100
3050
  */
3101
- storage: Storage;
3051
+ build(options: T['resolvedOptions']): Omit<Adapter<T>, 'name' | 'meta' | 'options'>;
3052
+ };
3053
+ /**
3054
+ * The function `defineExtension` returns for an adapter. Call it with user options to get an `Adapter`.
3055
+ */
3056
+ type AdapterFactory<T extends AdapterFactoryOptions = AdapterFactoryOptions> = ExtensionFactory<'adapter', T['options'], Adapter<T>, T['name']>;
3057
+ /**
3058
+ * Defines a custom adapter that translates a spec format into Kubb's universal
3059
+ * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
3060
+ * handles OpenAPI/Swagger documents.
3061
+ *
3062
+ * Adapters must return an `InputNode` from `parse`. That node is what every
3063
+ * plugin in the build consumes.
3064
+ *
3065
+ * @deprecated Use `defineExtension` with `kind: 'adapter'` instead.
3066
+ */
3067
+ declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: AdapterDefinition<T>): AdapterFactory<T>;
3068
+ /**
3069
+ * Wraps a factory function that returns an `Adapter`.
3070
+ *
3071
+ * @deprecated Pass a definition object with `kind: 'adapter'`, `meta`, and `build` to `defineExtension` instead. The factory form is removed in the next major.
3072
+ */
3073
+ declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): ((options?: T['options']) => Adapter<T>) & {
3074
+ kind: 'adapter';
3102
3075
  };
3103
3076
  //#endregion
3104
- export { OutputOptions as $, ProblemCode as $t, HookResult as A, ExtensionMeta as At, ParserDefinition as B, ReporterContext as Bt, KubbMessageContext as C, ResolverPatch as Ct, PossibleConfig as D, ExtensionDependencyRecord as Dt, KubbWarnContext as E, ExtensionDependency as Et, defineGenerator as F, createRenderer as Ft, Group as G, logLevel as Gt, defineParser as H, ReporterPluginFiles as Ht, NodeCache as I, Storage as It, KubbPluginSetupContext as J, DiagnosticKind as Jt, Include as K, Diagnostic as Kt, KubbDriver as L, createStorage as Lt, runHook as M, StandardSchemaV1 as Mt, Generator as N, Renderer as Nt, PostGenerateCommand as O, ExtensionFactory as Ot, GeneratorContext as P, RendererFactory as Pt, OutputMode as Q, PerformanceDiagnostic as Qt, FileManagerHooks as R, GenerationResult as Rt, KubbLifecycleStartContext as S, ResolverFilePathParams as St, KubbSuccessContext as T, ExtensionDependencies as Tt, Exclude$1 as U, UserReporter as Ut, ParserFactory as V, ReporterName as Vt, Filter as W, createReporter as Wt, NormalizedPlugin as X, DiagnosticSeverity as Xt, KubbPluginStartContext as Y, DiagnosticLocation as Yt, Output as Z, Diagnostics as Zt, KubbHookEndContext as _, ResolvePathOptions as _t, Input as a, AdapterFactoryOptions as an, PluginName as at, KubbHooks as b, ResolverFile as bt, KubbDiagnosticContext as c, ResolvePluginOptions as ct, KubbFilesProcessingEndContext as d, BannerMeta as dt, ProblemDiagnostic as en, Override as et, KubbFilesProcessingStartContext as f, ResolveBannerContext as ft, KubbGenerationSummaryContext as g, ResolveOptionsContext as gt, KubbGenerationStartContext as h, ResolveImportsOptions as ht, FilesContext as i, Adapter as in, PluginFactoryOptions as it, RunHookOptions as j, resolveMeta as jt, UserConfig as k, ExtensionKind as kt, KubbErrorContext as l, assertPluginOption as lt, KubbGenerationEndContext as m, ResolveFileOptions as mt, CLIOptions as n, UpdateDiagnostic as nn, PluginDefinition as nt, KubbBuildEndContext as o, AdapterSource as on, PluginOptions as ot, KubbFilesProcessingUpdateContext as p, ResolveBannerFile as pt, KubbPluginEndContext as q, DiagnosticDoc as qt, Config as r, Hookable as rn, PluginFactory as rt, KubbBuildStartContext as s, createAdapter as sn, PluginType as st, BuildOutput as t, SerializedDiagnostic as tn, Plugin as tt, KubbFileProcessingUpdate as u, definePlugin as ut, KubbHookLineContext as v, Resolver as vt, KubbPluginsEndContext as w, ResolverPathParams as wt, KubbInfoContext as x, ResolverFileParams as xt, KubbHookStartContext as y, ResolverDefault as yt, Parser as z, Reporter as zt };
3105
- //# sourceMappingURL=types-anBcq2U0.d.ts.map
3077
+ export { defineGenerator as $, ProblemDiagnostic as $t, PluginFactory as A, HookResult as At, ResolveFileOptions as B, ReporterName as Bt, NormalizedPlugin as C, KubbMessageContext as Ct, Override as D, PossibleConfig as Dt, OutputOptions as E, KubbWarnContext as Et, assertPluginOption as F, Storage as Ft, ResolverDefault as G, Diagnostic as Gt, ResolveOptionsContext as H, UserReporter as Ht, definePlugin as I, createStorage as It, ResolverFilePathParams as J, DiagnosticLocation as Jt, ResolverFile as K, DiagnosticDoc as Kt, BannerMeta as L, GenerationResult as Lt, PluginName as M, runHook as Mt, PluginType as N, KubbDriver as Nt, Plugin as O, PostGenerateCommand as Ot, ResolvePluginOptions as P, FileManagerHooks as Pt, GeneratorContext as Q, ProblemCode as Qt, ResolveBannerContext as R, Reporter as Rt, KubbPluginStartContext as S, KubbLifecycleStartContext as St, OutputMode as T, KubbSuccessContext as Tt, ResolvePathOptions as U, createReporter as Ut, ResolveImportsOptions as V, ReporterPluginFiles as Vt, Resolver as W, logLevel as Wt, ResolverPathParams as X, Diagnostics as Xt, ResolverPatch as Y, DiagnosticSeverity as Yt, Generator as Z, PerformanceDiagnostic as Zt, Filter as _, KubbHookEndContext as _t, AdapterSource as a, createRenderer as an, Input as at, KubbPluginEndContext as b, KubbHooks as bt, ExtensionDependency as c, ParserFactory as cn, KubbDiagnosticContext as ct, ExtensionKind as d, KubbFilesProcessingEndContext as dt, SerializedDiagnostic as en, NodeCache as et, ExtensionMeta as f, KubbFilesProcessingStartContext as ft, Exclude$1 as g, KubbGenerationSummaryContext as gt, resolveMeta as h, KubbGenerationStartContext as ht, AdapterFactoryOptions as i, RendererFactory as in, FilesContext as it, PluginFactoryOptions as j, RunHookOptions as jt, PluginDefinition as k, UserConfig as kt, ExtensionDependencyRecord as l, defineParser as ln, KubbErrorContext as lt, defineExtension as m, KubbGenerationEndContext as mt, AdapterDefinition as n, Hookable as nn, CLIOptions as nt, createAdapter as o, Parser as on, KubbBuildEndContext as ot, checkCompatibility as p, KubbFilesProcessingUpdateContext as pt, ResolverFileParams as q, DiagnosticKind as qt, AdapterFactory as r, Renderer as rn, Config as rt, ExtensionDependencies as s, ParserDefinition as sn, KubbBuildStartContext as st, Adapter as t, UpdateDiagnostic as tn, BuildOutput as tt, ExtensionFactory as u, KubbFileProcessingUpdate as ut, Group as v, KubbHookLineContext as vt, Output as w, KubbPluginsEndContext as wt, KubbPluginSetupContext as x, KubbInfoContext as xt, Include as y, KubbHookStartContext as yt, ResolveBannerFile as z, ReporterContext as zt };
3078
+ //# sourceMappingURL=createAdapter-BpJYvJTw.d.ts.map