@kubb/core 5.0.0-beta.9 → 5.0.0-beta.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +20 -123
  3. package/dist/index.cjs +2217 -1132
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +135 -178
  6. package/dist/index.js +2209 -1125
  7. package/dist/index.js.map +1 -1
  8. package/dist/mocks.cjs +77 -24
  9. package/dist/mocks.cjs.map +1 -1
  10. package/dist/mocks.d.ts +37 -11
  11. package/dist/mocks.js +79 -28
  12. package/dist/mocks.js.map +1 -1
  13. package/dist/types-BLFyAJLZ.d.ts +2785 -0
  14. package/dist/usingCtx-BriKju-v.js +577 -0
  15. package/dist/usingCtx-BriKju-v.js.map +1 -0
  16. package/dist/usingCtx-eyNeehd2.cjs +679 -0
  17. package/dist/usingCtx-eyNeehd2.cjs.map +1 -0
  18. package/package.json +7 -28
  19. package/dist/PluginDriver-Cu1Kj9S-.cjs +0 -1075
  20. package/dist/PluginDriver-Cu1Kj9S-.cjs.map +0 -1
  21. package/dist/PluginDriver-D8Z0Htid.js +0 -978
  22. package/dist/PluginDriver-D8Z0Htid.js.map +0 -1
  23. package/dist/createKubb-ALdb8lmq.d.ts +0 -2082
  24. package/src/FileManager.ts +0 -115
  25. package/src/FileProcessor.ts +0 -86
  26. package/src/PluginDriver.ts +0 -457
  27. package/src/constants.ts +0 -35
  28. package/src/createAdapter.ts +0 -108
  29. package/src/createKubb.ts +0 -1268
  30. package/src/createRenderer.ts +0 -57
  31. package/src/createStorage.ts +0 -70
  32. package/src/defineGenerator.ts +0 -175
  33. package/src/defineLogger.ts +0 -58
  34. package/src/defineMiddleware.ts +0 -62
  35. package/src/defineParser.ts +0 -44
  36. package/src/definePlugin.ts +0 -379
  37. package/src/defineResolver.ts +0 -654
  38. package/src/devtools.ts +0 -66
  39. package/src/index.ts +0 -20
  40. package/src/mocks.ts +0 -177
  41. package/src/storages/fsStorage.ts +0 -90
  42. package/src/storages/memoryStorage.ts +0 -55
  43. package/src/types.ts +0 -41
  44. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
package/dist/index.js CHANGED
@@ -1,150 +1,66 @@
1
- import { t as __name } from "./chunk--u3MIqq1.js";
2
- import { a as definePlugin, c as DEFAULT_STUDIO_URL, i as defineResolver, l as logLevel, n as applyHookResult, o as DEFAULT_BANNER, r as FileManager, s as DEFAULT_EXTENSION, t as PluginDriver, u as camelCase } from "./PluginDriver-D8Z0Htid.js";
3
- import { EventEmitter } from "node:events";
4
- import { access, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
5
- import { dirname, join, resolve } from "node:path";
6
- import * as ast from "@kubb/ast";
7
- import { collectUsedSchemaNames, extractStringsFromNodes, transform, walk } from "@kubb/ast";
8
- import { version } from "node:process";
9
- //#region ../../internals/utils/src/errors.ts
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { a as toFilePath, c as BuildError, d as camelCase, i as clean, l as getErrorMessage, n as FileManager, o as toPosixPath, r as Hookable, s as write, t as _usingCtx, u as toError } from "./usingCtx-BriKju-v.js";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { stripVTControlCharacters, styleText } from "node:util";
5
+ import { hash } from "node:crypto";
6
+ import { access, glob, readFile, rm } from "node:fs/promises";
7
+ import path, { join, relative, resolve } from "node:path";
8
+ import { ast, collectUsedSchemaNames, composeMacros, operationDef, schemaDef, transform } from "@kubb/ast";
9
+ import process$1 from "node:process";
10
+ //#region src/createAdapter.ts
10
11
  /**
11
- * Thrown when one or more errors occur during a Kubb build.
12
- * Carries the full list of underlying errors on `errors`.
12
+ * Defines a custom adapter that translates a spec format into Kubb's universal
13
+ * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
14
+ * handles OpenAPI/Swagger documents.
13
15
  *
14
- * @example
15
- * ```ts
16
- * throw new BuildError('Build failed', { errors: [err1, err2] })
17
- * ```
18
- */
19
- var BuildError = class extends Error {
20
- errors;
21
- constructor(message, options) {
22
- super(message, { cause: options.cause });
23
- this.name = "BuildError";
24
- this.errors = options.errors;
25
- }
26
- };
27
- /**
28
- * Coerces an unknown thrown value to an `Error` instance.
29
- * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
16
+ * Adapters must return an `InputNode` from `parse`. That node is what every
17
+ * plugin in the build consumes.
30
18
  *
31
19
  * @example
32
20
  * ```ts
33
- * try { ... } catch(err) {
34
- * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
35
- * }
21
+ * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
22
+ * import { ast } from '@kubb/ast'
23
+ *
24
+ * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
25
+ *
26
+ * export const myAdapter = createAdapter<MyAdapter>((options) => ({
27
+ * name: 'my-adapter',
28
+ * options,
29
+ * document: null,
30
+ * async parse(_source) {
31
+ * // Convert the source (path or inline data) into an InputNode.
32
+ * return ast.factory.createInput()
33
+ * },
34
+ * getImports: () => [],
35
+ * async validate() {
36
+ * // Throw here when the spec is invalid.
37
+ * },
38
+ * }))
36
39
  * ```
37
40
  */
38
- function toError(value) {
39
- return value instanceof Error ? value : new Error(String(value));
41
+ function createAdapter(build) {
42
+ return (options) => build(options ?? {});
40
43
  }
41
44
  //#endregion
42
- //#region ../../internals/utils/src/asyncEventEmitter.ts
45
+ //#region src/applyConfigDefaults.ts
43
46
  /**
44
- * Typed `EventEmitter` that awaits all async listeners before resolving.
45
- * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
46
- *
47
- * @example
48
- * ```ts
49
- * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
50
- * emitter.on('build', async (name) => { console.log(name) })
51
- * await emitter.emit('build', 'petstore') // all listeners awaited
52
- * ```
47
+ * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
48
+ * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
49
+ * registered. Both entry points construct their own adapter, barrel plugin, and output defaults
50
+ * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
51
+ * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
53
52
  */
54
- var AsyncEventEmitter = class {
55
- /**
56
- * Maximum number of listeners per event before Node emits a memory-leak warning.
57
- * @default 10
58
- */
59
- constructor(maxListener = 10) {
60
- this.#emitter.setMaxListeners(maxListener);
61
- }
62
- #emitter = new EventEmitter();
63
- /**
64
- * Emits `eventName` and awaits all registered listeners sequentially.
65
- * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
66
- *
67
- * @example
68
- * ```ts
69
- * await emitter.emit('build', 'petstore')
70
- * ```
71
- */
72
- async emit(eventName, ...eventArgs) {
73
- const listeners = this.#emitter.listeners(eventName);
74
- if (listeners.length === 0) return;
75
- for (const listener of listeners) try {
76
- await listener(...eventArgs);
77
- } catch (err) {
78
- let serializedArgs;
79
- try {
80
- serializedArgs = JSON.stringify(eventArgs);
81
- } catch {
82
- serializedArgs = String(eventArgs);
83
- }
84
- throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
53
+ function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
54
+ const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
55
+ return {
56
+ adapter: config.adapter ?? defaultAdapter,
57
+ plugins,
58
+ output: {
59
+ ...defaultOutput,
60
+ ...config.output
85
61
  }
86
- }
87
- /**
88
- * Registers a persistent listener for `eventName`.
89
- *
90
- * @example
91
- * ```ts
92
- * emitter.on('build', async (name) => { console.log(name) })
93
- * ```
94
- */
95
- on(eventName, handler) {
96
- this.#emitter.on(eventName, handler);
97
- }
98
- /**
99
- * Registers a one-shot listener that removes itself after the first invocation.
100
- *
101
- * @example
102
- * ```ts
103
- * emitter.onOnce('build', async (name) => { console.log(name) })
104
- * ```
105
- */
106
- onOnce(eventName, handler) {
107
- const wrapper = (...args) => {
108
- this.off(eventName, wrapper);
109
- return handler(...args);
110
- };
111
- this.on(eventName, wrapper);
112
- }
113
- /**
114
- * Removes a previously registered listener.
115
- *
116
- * @example
117
- * ```ts
118
- * emitter.off('build', handler)
119
- * ```
120
- */
121
- off(eventName, handler) {
122
- this.#emitter.off(eventName, handler);
123
- }
124
- /**
125
- * Returns the number of listeners registered for `eventName`.
126
- *
127
- * @example
128
- * ```ts
129
- * emitter.on('build', handler)
130
- * emitter.listenerCount('build') // 1
131
- * ```
132
- */
133
- listenerCount(eventName) {
134
- return this.#emitter.listenerCount(eventName);
135
- }
136
- /**
137
- * Removes all listeners from every event channel.
138
- *
139
- * @example
140
- * ```ts
141
- * emitter.removeAll()
142
- * ```
143
- */
144
- removeAll() {
145
- this.#emitter.removeAllListeners();
146
- }
147
- };
62
+ };
63
+ }
148
64
  //#endregion
149
65
  //#region ../../internals/utils/src/time.ts
150
66
  /**
@@ -179,560 +95,1807 @@ function formatMs(ms) {
179
95
  return `${Math.round(ms)}ms`;
180
96
  }
181
97
  //#endregion
182
- //#region ../../internals/utils/src/fs.ts
98
+ //#region ../../internals/utils/src/colors.ts
183
99
  /**
184
- * Resolves to `true` when the file or directory at `path` exists.
185
- * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.
186
- *
187
- * @example
188
- * ```ts
189
- * if (await exists('./kubb.config.ts')) {
190
- * const content = await read('./kubb.config.ts')
191
- * }
192
- * ```
100
+ * Parses a CSS hex color string (`#RGB`) into its RGB channels.
101
+ * Falls back to `255` for any channel that cannot be parsed.
102
+ */
103
+ function parseHex(color) {
104
+ const int = Number.parseInt(color.replace("#", ""), 16);
105
+ return Number.isNaN(int) ? {
106
+ r: 255,
107
+ g: 255,
108
+ b: 255
109
+ } : {
110
+ r: int >> 16 & 255,
111
+ g: int >> 8 & 255,
112
+ b: int & 255
113
+ };
114
+ }
115
+ /**
116
+ * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
117
+ * for the given hex color.
193
118
  */
194
- async function exists(path) {
195
- if (typeof Bun !== "undefined") return Bun.file(path).exists();
196
- return access(path).then(() => true, () => false);
119
+ function hex(color) {
120
+ const { r, g, b } = parseHex(color);
121
+ return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
197
122
  }
123
+ hex("#F55A17"), hex("#F5A217"), hex("#F58517"), hex("#B45309"), hex("#FFFFFF"), hex("#adadc6"), hex("#FDA4AF");
124
+ /**
125
+ * ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.
126
+ */
127
+ const randomColors = [
128
+ "black",
129
+ "red",
130
+ "green",
131
+ "yellow",
132
+ "blue",
133
+ "white",
134
+ "magenta",
135
+ "cyan",
136
+ "gray"
137
+ ];
198
138
  /**
199
- * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
200
- * Skips the write when the trimmed content is empty or identical to what is already on disk.
201
- * Creates any missing parent directories automatically.
202
- * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
139
+ * Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.
203
140
  *
204
141
  * @example
205
142
  * ```ts
206
- * await write('./src/Pet.ts', source) // writes and returns trimmed content
207
- * await write('./src/Pet.ts', source) // null — file unchanged
208
- * await write('./src/Pet.ts', ' ') // null — empty content skipped
143
+ * randomCliColor('petstore') // '\x1b[33m' + 'petstore' + '\x1b[39m' (always the same color for 'petstore')
209
144
  * ```
210
145
  */
211
- async function write(path, data, options = {}) {
212
- const trimmed = data.trim();
213
- if (trimmed === "") return null;
214
- const resolved = resolve(path);
215
- if (typeof Bun !== "undefined") {
216
- const file = Bun.file(resolved);
217
- if ((await file.exists() ? await file.text() : null) === trimmed) return null;
218
- await Bun.write(resolved, trimmed);
219
- return trimmed;
220
- }
221
- try {
222
- if (await readFile(resolved, { encoding: "utf-8" }) === trimmed) return null;
223
- } catch {}
224
- await mkdir(dirname(resolved), { recursive: true });
225
- await writeFile(resolved, trimmed, { encoding: "utf-8" });
226
- if (options.sanity) {
227
- const savedData = await readFile(resolved, { encoding: "utf-8" });
228
- if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
229
- return savedData;
230
- }
231
- return trimmed;
146
+ function randomCliColor(text) {
147
+ if (!text) return "";
148
+ const index = hash("sha256", text, "buffer").readUInt32BE(0) % randomColors.length;
149
+ return styleText(randomColors[index] ?? "white", text);
232
150
  }
151
+ //#endregion
152
+ //#region ../../internals/utils/src/promise.ts
233
153
  /**
234
- * Recursively removes `path`. Silently succeeds when `path` does not exist.
154
+ * Wraps `factory` with a keyed cache backed by the provided store.
235
155
  *
236
- * @example
156
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
157
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
158
+ * nest two `memoize` calls — the outer keyed by the first argument, the
159
+ * inner (created once per outer miss) keyed by the second.
160
+ *
161
+ * Because the cache is owned by the caller, it can be shared, inspected, or
162
+ * cleared independently of the memoized function.
163
+ *
164
+ * @example Single WeakMap key
237
165
  * ```ts
238
- * await clean('./dist')
166
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
167
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
168
+ * ```
169
+ *
170
+ * @example Single Map key (primitive)
171
+ * ```ts
172
+ * const cache = new Map<string, Resolver>()
173
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
174
+ * ```
175
+ *
176
+ * @example Two-level (object + primitive)
177
+ * ```ts
178
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
179
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
180
+ * fn(params)('camelcase')
239
181
  * ```
240
182
  */
241
- async function clean(path) {
242
- return rm(path, {
243
- recursive: true,
244
- force: true
245
- });
183
+ function memoize(store, factory) {
184
+ return (key) => {
185
+ if (store.has(key)) return store.get(key);
186
+ const value = factory(key);
187
+ store.set(key, value);
188
+ return value;
189
+ };
246
190
  }
247
191
  //#endregion
248
- //#region ../../internals/utils/src/reserved.ts
192
+ //#region package.json
193
+ var version = "5.0.0-beta.93";
194
+ //#endregion
195
+ //#region src/constants.ts
249
196
  /**
250
- * JavaScript and Java reserved words.
251
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
197
+ * Plugin `include` filter types that select operations directly. When one of these is set
198
+ * without a `schemaName` include, the generate phase pre-scans operations to compute the set
199
+ * of schemas they reach, so unreachable schemas can be pruned for that plugin.
252
200
  */
253
- const reservedWords = new Set([
254
- "abstract",
255
- "arguments",
256
- "boolean",
257
- "break",
258
- "byte",
259
- "case",
260
- "catch",
261
- "char",
262
- "class",
263
- "const",
264
- "continue",
265
- "debugger",
266
- "default",
267
- "delete",
268
- "do",
269
- "double",
270
- "else",
271
- "enum",
272
- "eval",
273
- "export",
274
- "extends",
275
- "false",
276
- "final",
277
- "finally",
278
- "float",
279
- "for",
280
- "function",
281
- "goto",
282
- "if",
283
- "implements",
284
- "import",
285
- "in",
286
- "instanceof",
287
- "int",
288
- "interface",
289
- "let",
290
- "long",
291
- "native",
292
- "new",
293
- "null",
294
- "package",
295
- "private",
296
- "protected",
297
- "public",
298
- "return",
299
- "short",
300
- "static",
301
- "super",
302
- "switch",
303
- "synchronized",
304
- "this",
305
- "throw",
306
- "throws",
307
- "transient",
308
- "true",
309
- "try",
310
- "typeof",
311
- "var",
312
- "void",
313
- "volatile",
314
- "while",
315
- "with",
316
- "yield",
317
- "Array",
318
- "Date",
319
- "hasOwnProperty",
320
- "Infinity",
321
- "isFinite",
322
- "isNaN",
323
- "isPrototypeOf",
324
- "length",
325
- "Math",
326
- "name",
327
- "NaN",
328
- "Number",
329
- "Object",
330
- "prototype",
331
- "String",
332
- "toString",
333
- "undefined",
334
- "valueOf"
201
+ const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
202
+ "tag",
203
+ "operationId",
204
+ "path",
205
+ "method",
206
+ "contentType"
335
207
  ]);
336
208
  /**
337
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
209
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
210
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
211
+ * these instead of inlining the string at a throw site.
212
+ */
213
+ const diagnosticCode = {
214
+ /**
215
+ * Fallback for an unstructured error with no specific code.
216
+ */
217
+ unknown: "KUBB_UNKNOWN",
218
+ /**
219
+ * The file or URL set as `input` could not be read.
220
+ */
221
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
222
+ /**
223
+ * An adapter was configured without an `input`.
224
+ */
225
+ inputRequired: "KUBB_INPUT_REQUIRED",
226
+ /**
227
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
228
+ */
229
+ refNotFound: "KUBB_REF_NOT_FOUND",
230
+ /**
231
+ * A server variable value is not allowed by its `enum`.
232
+ */
233
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
234
+ /**
235
+ * A required plugin is missing from the config.
236
+ */
237
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
238
+ /**
239
+ * A plugin threw while generating.
240
+ */
241
+ pluginFailed: "KUBB_PLUGIN_FAILED",
242
+ /**
243
+ * A plugin reported a non-fatal warning through `ctx.warn`.
244
+ */
245
+ pluginWarning: "KUBB_PLUGIN_WARNING",
246
+ /**
247
+ * A plugin reported an informational message through `ctx.info`.
248
+ */
249
+ pluginInfo: "KUBB_PLUGIN_INFO",
250
+ /**
251
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
252
+ * adapters to emit as a `warning`.
253
+ */
254
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
255
+ /**
256
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
257
+ * to emit as an `info`.
258
+ */
259
+ deprecated: "KUBB_DEPRECATED",
260
+ /**
261
+ * An adapter is required but the config has none. The build cannot read the input
262
+ * without one.
263
+ */
264
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
265
+ /**
266
+ * A resolved output path escapes the output directory, which can stem from a path
267
+ * traversal in the spec or a misconfigured `group.name`.
268
+ */
269
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
270
+ /**
271
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
272
+ */
273
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
274
+ /**
275
+ * A post-generate command (`output.postGenerate`) exited with a failure.
276
+ */
277
+ postGenerateFailed: "KUBB_POST_GENERATE_FAILED",
278
+ /**
279
+ * The formatter pass over the generated files failed.
280
+ */
281
+ formatFailed: "KUBB_FORMAT_FAILED",
282
+ /**
283
+ * The linter pass over the generated files failed.
284
+ */
285
+ lintFailed: "KUBB_LINT_FAILED",
286
+ /**
287
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
288
+ */
289
+ performance: "KUBB_PERFORMANCE",
290
+ /**
291
+ * Not a failure. A newer Kubb version is available on npm.
292
+ */
293
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
294
+ };
295
+ //#endregion
296
+ //#region src/Diagnostics.ts
297
+ /**
298
+ * Docs major version, derived from the package version so the link tracks the published major.
299
+ */
300
+ const docsMajor = version.split(".")[0] ?? "5";
301
+ /**
302
+ * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
303
+ * with no `kind` is treated as a `problem`.
304
+ */
305
+ function isKind(kind) {
306
+ return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
307
+ }
308
+ /**
309
+ * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
338
310
  *
339
311
  * @example
340
312
  * ```ts
341
- * isValidVarName('status') // true
342
- * isValidVarName('class') // false (reserved word)
343
- * isValidVarName('42foo') // false (starts with digit)
313
+ * if (isProblem(diagnostic)) {
314
+ * console.log(diagnostic.location)
315
+ * }
344
316
  * ```
345
317
  */
346
- function isValidVarName(name) {
347
- if (!name || reservedWords.has(name)) return false;
348
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
349
- }
350
- //#endregion
351
- //#region ../../internals/utils/src/urlPath.ts
318
+ const isProblem = isKind("problem");
319
+ /**
320
+ * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
321
+ *
322
+ * @example
323
+ * ```ts
324
+ * const timings = diagnostics.filter(isPerformance)
325
+ * ```
326
+ */
327
+ const isPerformance = isKind("performance");
352
328
  /**
353
- * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
329
+ * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
354
330
  *
355
331
  * @example
356
- * const p = new URLPath('/pet/{petId}')
357
- * p.URL // '/pet/:petId'
358
- * p.template // '`/pet/${petId}`'
332
+ * ```ts
333
+ * if (isUpdate(diagnostic)) {
334
+ * console.log(diagnostic.latestVersion)
335
+ * }
336
+ * ```
337
+ */
338
+ const isUpdate = isKind("update");
339
+ /**
340
+ * Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,
341
+ * blue info).
342
+ */
343
+ const severityStyle = {
344
+ error: "red",
345
+ warning: "yellow",
346
+ info: "blue"
347
+ };
348
+ /**
349
+ * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
350
+ * and `Diagnostics.docsUrl` for the matching kubb.dev page.
351
+ */
352
+ const diagnosticCatalog = {
353
+ [diagnosticCode.unknown]: {
354
+ title: "Unknown error",
355
+ cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
356
+ fix: "Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug."
357
+ },
358
+ [diagnosticCode.inputNotFound]: {
359
+ title: "Input not found",
360
+ cause: "The file or URL set as `input` (or passed as `kubb generate PATH`) could not be read.",
361
+ fix: "Check that the path or URL exists and is readable, then set it as `input` or pass it on the CLI."
362
+ },
363
+ [diagnosticCode.inputRequired]: {
364
+ title: "Input required",
365
+ cause: "An adapter is configured but no `input` was provided.",
366
+ fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
367
+ },
368
+ [diagnosticCode.refNotFound]: {
369
+ title: "Reference not found",
370
+ cause: "A `$ref` could not be resolved in the source document.",
371
+ fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
372
+ },
373
+ [diagnosticCode.invalidServerVariable]: {
374
+ title: "Invalid server variable",
375
+ cause: "A server variable value is not allowed by its `enum`.",
376
+ fix: "Use one of the values listed in the server variable `enum`, or update the spec."
377
+ },
378
+ [diagnosticCode.pluginNotFound]: {
379
+ title: "Plugin not found",
380
+ cause: "A plugin that another plugin depends on is missing from the config.",
381
+ fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
382
+ },
383
+ [diagnosticCode.pluginFailed]: {
384
+ title: "Plugin failed",
385
+ cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
386
+ fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
387
+ },
388
+ [diagnosticCode.pluginWarning]: {
389
+ title: "Plugin warning",
390
+ cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
391
+ fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
392
+ },
393
+ [diagnosticCode.pluginInfo]: {
394
+ title: "Plugin info",
395
+ cause: "A plugin reported an informational message through `ctx.info`.",
396
+ fix: "Informational only. No action is required."
397
+ },
398
+ [diagnosticCode.unsupportedFormat]: {
399
+ title: "Unsupported format",
400
+ cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
401
+ fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
402
+ },
403
+ [diagnosticCode.deprecated]: {
404
+ title: "Deprecated",
405
+ cause: "A referenced schema or operation is marked `deprecated`.",
406
+ fix: "Migrate off the deprecated definition if the warning is unwanted."
407
+ },
408
+ [diagnosticCode.adapterRequired]: {
409
+ title: "Adapter required",
410
+ cause: "An action needs an adapter but none is configured.",
411
+ fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
412
+ },
413
+ [diagnosticCode.pathTraversal]: {
414
+ title: "Path traversal",
415
+ cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
416
+ fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
417
+ },
418
+ [diagnosticCode.invalidPluginOptions]: {
419
+ title: "Invalid plugin options",
420
+ cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
421
+ fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
422
+ },
423
+ [diagnosticCode.postGenerateFailed]: {
424
+ title: "Post-generate command failed",
425
+ cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
426
+ fix: "Check the command is installed and correct, and run it manually to see the error."
427
+ },
428
+ [diagnosticCode.formatFailed]: {
429
+ title: "Format failed",
430
+ cause: "The formatter pass over the generated files failed.",
431
+ fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
432
+ },
433
+ [diagnosticCode.lintFailed]: {
434
+ title: "Lint failed",
435
+ cause: "The linter pass over the generated files failed.",
436
+ fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
437
+ },
438
+ [diagnosticCode.performance]: {
439
+ title: "Performance",
440
+ cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
441
+ fix: "No action. This is an informational metric."
442
+ },
443
+ [diagnosticCode.updateAvailable]: {
444
+ title: "Update available",
445
+ cause: "A newer Kubb version is published on npm than the one running.",
446
+ fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
447
+ }
448
+ };
449
+ /**
450
+ * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
451
+ * that lets deep code report a diagnostic without threading a callback.
452
+ *
453
+ * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
454
+ * `Diagnostics.scope` activates it for a run, so anything inside that run (the
455
+ * adapter parse, a generator) reports through `Diagnostics.report` and lands
456
+ * in the same run.
359
457
  */
360
- var URLPath = class {
458
+ var Diagnostics = class Diagnostics {
459
+ static #reporterStorage = new AsyncLocalStorage();
361
460
  /**
362
- * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.
461
+ * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
363
462
  */
364
- path;
365
- #options;
366
- constructor(path, options = {}) {
367
- this.path = path;
368
- this.#options = options;
369
- }
370
- /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.
463
+ static code = diagnosticCode;
464
+ /**
465
+ * Type guard for a build {@link ProblemDiagnostic}.
466
+ */
467
+ static isProblem = isProblem;
468
+ /**
469
+ * Type guard for a version-update {@link UpdateDiagnostic}.
470
+ */
471
+ static isUpdate = isUpdate;
472
+ /**
473
+ * Type guard for a per-plugin {@link PerformanceDiagnostic}.
474
+ */
475
+ static isPerformance = isPerformance;
476
+ /**
477
+ * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
478
+ * through the existing throw/catch paths while keeping their code and location.
371
479
  *
372
480
  * @example
373
481
  * ```ts
374
- * new URLPath('/pet/{petId}').URL // '/pet/:petId'
482
+ * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
375
483
  * ```
376
484
  */
377
- get URL() {
378
- return this.toURLPath();
485
+ static Error = class DiagnosticError extends Error {
486
+ diagnostic;
487
+ constructor(diagnostic) {
488
+ super(diagnostic.message, { cause: diagnostic.cause });
489
+ this.name = "DiagnosticError";
490
+ this.diagnostic = diagnostic;
491
+ }
492
+ };
493
+ /**
494
+ * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
495
+ * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
496
+ * that carries a `code`.
497
+ */
498
+ static isError(error) {
499
+ if (error instanceof Diagnostics.Error) return true;
500
+ return error instanceof Error && error.name === "DiagnosticError" && "diagnostic" in error && typeof error.diagnostic === "object" && error.diagnostic !== null && typeof error.diagnostic?.code === "string";
379
501
  }
380
- /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).
381
- *
382
- * @example
383
- * ```ts
384
- * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
385
- * new URLPath('/pet/{petId}').isURL // false
386
- * ```
502
+ /**
503
+ * Runs `fn` with `sink` as the active diagnostic sink for the whole async
504
+ * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
387
505
  */
388
- get isURL() {
389
- try {
390
- return !!new URL(this.path).href;
391
- } catch {
392
- return false;
506
+ static scope(sink, fn) {
507
+ return Diagnostics.#reporterStorage.run(sink, fn);
508
+ }
509
+ /**
510
+ * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
511
+ * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
512
+ * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
513
+ * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
514
+ */
515
+ static report(diagnostic) {
516
+ const sink = Diagnostics.#reporterStorage.getStore();
517
+ if (!sink) return false;
518
+ sink(diagnostic);
519
+ return true;
520
+ }
521
+ /**
522
+ * Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.
523
+ * Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a
524
+ * diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
525
+ */
526
+ static async emit(hooks, diagnostic) {
527
+ await hooks.callHook("kubb:diagnostic", { diagnostic });
528
+ }
529
+ /**
530
+ * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
531
+ * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
532
+ */
533
+ static from(error) {
534
+ const seen = /* @__PURE__ */ new Set();
535
+ let current = error;
536
+ let root;
537
+ while (current instanceof Error && !seen.has(current)) {
538
+ if (Diagnostics.isError(current)) return current.diagnostic;
539
+ seen.add(current);
540
+ root = current;
541
+ current = current.cause;
393
542
  }
543
+ return {
544
+ code: diagnosticCode.unknown,
545
+ severity: "error",
546
+ message: root ? root.message : getErrorMessage(error),
547
+ cause: root
548
+ };
394
549
  }
395
550
  /**
396
- * Converts the OpenAPI path to a TypeScript template literal string.
397
- *
398
- * @example
399
- * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
400
- * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
551
+ * Builds a per-plugin performance record. Reporters sum these into the run total.
401
552
  */
402
- get template() {
403
- return this.toTemplateString();
553
+ static performance({ plugin, duration }) {
554
+ return {
555
+ kind: "performance",
556
+ code: diagnosticCode.performance,
557
+ severity: "info",
558
+ message: `${plugin} generated in ${Math.round(duration)}ms`,
559
+ plugin,
560
+ duration
561
+ };
404
562
  }
405
- /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.
406
- *
407
- * @example
408
- * ```ts
409
- * new URLPath('/pet/{petId}').object
410
- * // { url: '/pet/:petId', params: { petId: 'petId' } }
411
- * ```
563
+ /**
564
+ * Builds the version-update notice shown when a newer Kubb is published on npm.
412
565
  */
413
- get object() {
414
- return this.toObject();
566
+ static update({ currentVersion, latestVersion }) {
567
+ return {
568
+ kind: "update",
569
+ code: diagnosticCode.updateAvailable,
570
+ severity: "info",
571
+ message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
572
+ currentVersion,
573
+ latestVersion
574
+ };
415
575
  }
416
- /** Returns a map of path parameter names, or `undefined` when the path has no parameters.
417
- *
418
- * @example
419
- * ```ts
420
- * new URLPath('/pet/{petId}').params // { petId: 'petId' }
421
- * new URLPath('/pet').params // undefined
422
- * ```
576
+ /**
577
+ * True when any diagnostic is an error, the severity that fails a build. Non-error
578
+ * diagnostics are ignored.
423
579
  */
424
- get params() {
425
- return this.getParams();
580
+ static hasError(diagnostics) {
581
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error");
426
582
  }
427
- #transformParam(raw) {
428
- const param = isValidVarName(raw) ? raw : camelCase(raw);
429
- return this.#options.casing === "camelcase" ? camelCase(param) : param;
583
+ /**
584
+ * Names of the plugins that failed, deduped, derived from the error diagnostics
585
+ * that carry a `plugin`.
586
+ */
587
+ static failedPlugins(diagnostics) {
588
+ const names = /* @__PURE__ */ new Set();
589
+ for (const diagnostic of diagnostics) if (diagnostic.severity === "error" && diagnostic.plugin) names.add(diagnostic.plugin);
590
+ return [...names];
430
591
  }
431
592
  /**
432
- * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.
593
+ * Counts `problem` diagnostics by severity for the run summary. `performance` and
594
+ * `update` diagnostics are ignored.
433
595
  */
434
- #eachParam(fn) {
435
- for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
436
- const raw = match[1];
437
- fn(raw, this.#transformParam(raw));
596
+ static count(diagnostics) {
597
+ let errors = 0;
598
+ let warnings = 0;
599
+ let infos = 0;
600
+ for (const diagnostic of diagnostics) {
601
+ if (!isProblem(diagnostic)) continue;
602
+ if (diagnostic.severity === "error") errors += 1;
603
+ else if (diagnostic.severity === "warning") warnings += 1;
604
+ else infos += 1;
438
605
  }
439
- }
440
- toObject({ type = "path", replacer, stringify } = {}) {
441
- const object = {
442
- url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
443
- params: this.getParams()
606
+ return {
607
+ errors,
608
+ warnings,
609
+ infos
444
610
  };
445
- if (stringify) {
446
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
447
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
448
- return `{ url: '${object.url}' }`;
611
+ }
612
+ /**
613
+ * Drops duplicate `problem` diagnostics that share a code, location pointer, and
614
+ * plugin, so the same issue reported across several passes is shown once. Non-problem
615
+ * diagnostics are always kept.
616
+ */
617
+ static dedupe(diagnostics) {
618
+ const seen = /* @__PURE__ */ new Set();
619
+ const result = [];
620
+ for (const diagnostic of diagnostics) {
621
+ if (!isProblem(diagnostic)) {
622
+ result.push(diagnostic);
623
+ continue;
624
+ }
625
+ const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
626
+ const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
627
+ if (seen.has(key)) continue;
628
+ seen.add(key);
629
+ result.push(diagnostic);
449
630
  }
450
- return object;
631
+ return result;
451
632
  }
452
633
  /**
453
- * Converts the OpenAPI path to a TypeScript template literal string.
454
- * An optional `replacer` can transform each extracted parameter name before interpolation.
455
- *
456
- * @example
457
- * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
634
+ * Builds the kubb.dev docs URL for a diagnostic code, e.g.
635
+ * `KUBB_REF_NOT_FOUND` `https://kubb.dev/docs/5.x/reference/diagnostics/kubb-ref-not-found`.
458
636
  */
459
- toTemplateString({ prefix = "", replacer } = {}) {
460
- return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
461
- if (i % 2 === 0) return part;
462
- const param = this.#transformParam(part);
463
- return `\${${replacer ? replacer(param) : param}}`;
464
- }).join("")}\``;
637
+ static docsUrl(code) {
638
+ const slug = code.toLowerCase().replaceAll("_", "-");
639
+ return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics/${slug}`;
465
640
  }
466
641
  /**
467
- * Extracts all `{param}` segments from the path and returns them as a key-value map.
468
- * An optional `replacer` transforms each parameter name in both key and value positions.
469
- * Returns `undefined` when no path parameters are found.
470
- *
471
- * @example
472
- * ```ts
473
- * new URLPath('/pet/{petId}/tag/{tagId}').getParams()
474
- * // { petId: 'petId', tagId: 'tagId' }
475
- * ```
642
+ * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
643
+ * `/diagnostics/<slug>` page.
476
644
  */
477
- getParams(replacer) {
478
- const params = {};
479
- this.#eachParam((_raw, param) => {
480
- const key = replacer ? replacer(param) : param;
481
- params[key] = key;
482
- });
483
- return Object.keys(params).length > 0 ? params : void 0;
645
+ static explain(code) {
646
+ return diagnosticCatalog[code];
484
647
  }
485
- /** Converts the OpenAPI path to Express-style colon syntax.
486
- *
487
- * @example
488
- * ```ts
489
- * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'
490
- * ```
648
+ /**
649
+ * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
650
+ * consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
651
+ * fields are omitted rather than set to `undefined`.
491
652
  */
492
- toURLPath() {
493
- return this.path.replace(/\{([^}]+)\}/g, ":$1");
653
+ static serialize(diagnostic) {
654
+ const problem = isProblem(diagnostic) ? diagnostic : void 0;
655
+ return {
656
+ code: diagnostic.code,
657
+ severity: diagnostic.severity,
658
+ message: diagnostic.message,
659
+ ...problem?.location ? { location: problem.location } : {},
660
+ ...problem?.help ? { help: problem.help } : {},
661
+ ...problem?.plugin ? { plugin: problem.plugin } : {},
662
+ ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
663
+ };
494
664
  }
495
- };
496
- //#endregion
497
- //#region src/createAdapter.ts
665
+ /**
666
+ * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
667
+ * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
668
+ * rows (`at:` pointer, `fix:` help, `see:` docs link).
669
+ *
670
+ * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
671
+ * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
672
+ */
673
+ static format(diagnostic) {
674
+ const { code, severity, message } = diagnostic;
675
+ const color = severityStyle[severity];
676
+ const problem = isProblem(diagnostic) ? diagnostic : void 0;
677
+ const tag = styleText(color, styleText("bold", `[${code}]`));
678
+ const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`;
679
+ const details = [];
680
+ if (problem?.location && "pointer" in problem.location) details.push(` ${styleText("dim", "at:")} ${styleText("cyan", problem.location.pointer)}`);
681
+ if (problem?.help) details.push(` ${styleText("cyan", "fix:")} ${problem.help}`);
682
+ if (code !== diagnosticCode.unknown) details.push(` ${styleText("dim", "see:")} ${styleText("cyan", Diagnostics.docsUrl(code))}`);
683
+ return {
684
+ headline,
685
+ details
686
+ };
687
+ }
688
+ /**
689
+ * The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
690
+ * indented detail rows. Used where there is no gutter (plain and file output).
691
+ */
692
+ static formatLines(diagnostic) {
693
+ const { headline, details } = Diagnostics.format(diagnostic);
694
+ return [headline, ...details];
695
+ }
696
+ };
697
+ //#endregion
698
+ //#region src/definePlugin.ts
498
699
  /**
499
- * Factory for implementing custom adapters that translate non-OpenAPI specs into Kubb's AST.
500
- *
501
- * Use this to support GraphQL schemas, gRPC definitions, AsyncAPI, or custom domain-specific languages.
502
- * Built-in adapters include `@kubb/adapter-oas` for OpenAPI and Swagger documents.
700
+ * Merges the `output.mode` default into the output config and validates the combination.
701
+ * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
702
+ * since a single-file output has nothing to group.
703
+ */
704
+ function normalizeOutput({ output, group, pluginName }) {
705
+ const mode = output.mode ?? "directory";
706
+ if (mode === "file" && group) throw new Diagnostics.Error({
707
+ code: diagnosticCode.invalidPluginOptions,
708
+ severity: "error",
709
+ message: `Plugin "${pluginName}" sets \`output.mode: 'file'\` but also configures a \`group\` option.`,
710
+ help: "A single-file output has nothing to group. Remove the `group` option, or use `output.mode: 'directory'` to organize files into subdirectories.",
711
+ location: { kind: "config" },
712
+ plugin: pluginName
713
+ });
714
+ return {
715
+ ...output,
716
+ mode
717
+ };
718
+ }
719
+ /**
720
+ * Wraps a plugin factory and returns a function that accepts user options and
721
+ * yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
503
722
  *
504
- * @note Adapters must parse their input format to Kubb's `InputNode` structure.
723
+ * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
724
+ * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
725
+ * convention (`plugin-react-query`, `plugin-zod`, ...).
505
726
  *
506
727
  * @example
507
728
  * ```ts
508
- * export const myAdapter = createAdapter<MyAdapter>((options) => {
509
- * return {
510
- * name: 'my-adapter',
511
- * options,
512
- * async parse(source) {
513
- * // Transform source format to InputNode
514
- * return { ... }
515
- * },
516
- * }
517
- * })
729
+ * import { definePlugin } from '@kubb/core'
518
730
  *
519
- * // Instantiate:
520
- * const adapter = myAdapter({ validate: true })
731
+ * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
732
+ * name: 'plugin-ts',
733
+ * hooks: {
734
+ * 'kubb:plugin:setup'(ctx) {
735
+ * ctx.setResolver(resolverTs)
736
+ * },
737
+ * },
738
+ * }))
521
739
  * ```
522
740
  */
523
- function createAdapter(build) {
524
- return (options) => build(options ?? {});
741
+ function definePlugin(factory) {
742
+ return (options) => factory(options ?? {});
525
743
  }
526
744
  //#endregion
527
- //#region package.json
528
- var version$1 = "5.0.0-beta.9";
745
+ //#region src/input.ts
746
+ /**
747
+ * Classifies an `input` value so callers branch on it once instead of repeating the checks.
748
+ *
749
+ * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
750
+ * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
751
+ * `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
752
+ */
753
+ function getInputKind(input) {
754
+ if (typeof input !== "string") return "object";
755
+ const trimmed = input.trimStart();
756
+ if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
757
+ if (URL.canParse(input)) return "url";
758
+ return "file";
759
+ }
760
+ /**
761
+ * Normalizes `config.input` into an `AdapterSource` the adapter can parse.
762
+ *
763
+ * A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
764
+ * local path is resolved against `config.root`, both as `{ type: 'path' }`.
765
+ */
766
+ function inputToAdapterSource(config) {
767
+ const input = config.input;
768
+ if (!input) throw new Diagnostics.Error({
769
+ code: Diagnostics.code.inputRequired,
770
+ severity: "error",
771
+ message: "An adapter is configured without an input.",
772
+ help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
773
+ location: { kind: "config" }
774
+ });
775
+ if (typeof input !== "string") return {
776
+ type: "data",
777
+ data: input
778
+ };
779
+ const kind = getInputKind(input);
780
+ if (kind === "inline") return {
781
+ type: "data",
782
+ data: input
783
+ };
784
+ if (kind === "url") return {
785
+ type: "path",
786
+ path: input
787
+ };
788
+ return {
789
+ type: "path",
790
+ path: resolve(config.root, input)
791
+ };
792
+ }
529
793
  //#endregion
530
- //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
531
- var Node$1 = class {
532
- static {
533
- __name(this, "Node");
794
+ //#region src/Resolver.ts
795
+ function isNamespace(value) {
796
+ return typeof value === "object" && value !== null && !Array.isArray(value);
797
+ }
798
+ /**
799
+ * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
800
+ * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
801
+ * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
802
+ * reachable and a `file` override is never dropped.
803
+ */
804
+ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
805
+ /**
806
+ * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
807
+ */
808
+ function toBaseName({ name, extname }) {
809
+ return `${toFilePath(name)}${extname}`;
810
+ }
811
+ /**
812
+ * Base constraint for all plugin resolver objects.
813
+ *
814
+ * The built-in machinery lives under `default`. Generators call the top-level `name` and
815
+ * `file`, and a plugin overrides them to set its conventions. Extend with top-level helpers
816
+ * (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
817
+ *
818
+ * @example Top-level helper
819
+ * ```ts
820
+ * type MyResolver = Resolver & {
821
+ * typeName(name: string): string
822
+ * }
823
+ * ```
824
+ *
825
+ * @example Grouped namespace
826
+ * ```ts
827
+ * type MyResolver = Resolver & {
828
+ * query: {
829
+ * name(node: OperationNode): string
830
+ * keyName(node: OperationNode): string
831
+ * }
832
+ * }
833
+ * ```
834
+ */
835
+ var Resolver = class Resolver {
836
+ static #patternCache = /* @__PURE__ */ new Map();
837
+ static #optionsCache = /* @__PURE__ */ new WeakMap();
838
+ pluginName;
839
+ #options;
840
+ #baseName;
841
+ #filePath;
842
+ constructor(options) {
843
+ this.pluginName = options.pluginName;
844
+ this.#options = options;
845
+ this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
846
+ this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
847
+ this.#apply(options);
534
848
  }
535
- value;
536
- next;
537
- constructor(value) {
538
- this.value = value;
849
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
850
+ get [resolverOptions]() {
851
+ return this.#options;
539
852
  }
540
- };
541
- var Queue = class {
542
- #head;
543
- #tail;
544
- #size;
545
- constructor() {
546
- this.clear();
547
- }
548
- enqueue(value) {
549
- const node = new Node$1(value);
550
- if (this.#head) {
551
- this.#tail.next = node;
552
- this.#tail = node;
553
- } else {
554
- this.#head = node;
555
- this.#tail = node;
853
+ /**
854
+ * The built-in resolution machinery. Always reaches the untouched defaults, even when a
855
+ * plugin overrides the top-level `name` or `file`.
856
+ */
857
+ get default() {
858
+ return {
859
+ name: camelCase,
860
+ options: this.#resolveOptions.bind(this),
861
+ path: this.#resolvePath.bind(this),
862
+ file: this.#resolveFile.bind(this),
863
+ banner: this.#resolveBanner.bind(this),
864
+ footer: this.#resolveFooter.bind(this)
865
+ };
866
+ }
867
+ name(name) {
868
+ return this.default.name(name);
869
+ }
870
+ file(options) {
871
+ return this.#resolveFile(options);
872
+ }
873
+ /**
874
+ * Merges `override` over `base` and returns a new resolver with helpers re-bound. Top-level
875
+ * keys replace, and a namespace (or `file`) merges per method, so overriding `query.name`
876
+ * keeps the base `query.keyName`. Used when applying `setResolver` partial overrides. Reads a
877
+ * resolver's options through the shared brand rather than `instanceof`, so a `file` override
878
+ * survives even when `base` and `override` come from different `@kubb/core` copies.
879
+ */
880
+ static merge(base, override) {
881
+ const patch = resolverOptions in override ? override[resolverOptions] : override;
882
+ const merged = { ...base[resolverOptions] };
883
+ for (const [key, value] of Object.entries(patch)) {
884
+ if (value === void 0) continue;
885
+ const current = merged[key];
886
+ merged[key] = isNamespace(value) && isNamespace(current) ? {
887
+ ...current,
888
+ ...value
889
+ } : value;
556
890
  }
557
- this.#size++;
558
- }
559
- dequeue() {
560
- const current = this.#head;
561
- if (!current) return;
562
- this.#head = this.#head.next;
563
- this.#size--;
564
- if (!this.#head) this.#tail = void 0;
565
- return current.value;
566
- }
567
- peek() {
568
- if (!this.#head) return;
569
- return this.#head.value;
570
- }
571
- clear() {
572
- this.#head = void 0;
573
- this.#tail = void 0;
574
- this.#size = 0;
575
- }
576
- get size() {
577
- return this.#size;
578
- }
579
- *[Symbol.iterator]() {
580
- let current = this.#head;
581
- while (current) {
582
- yield current.value;
583
- current = current.next;
891
+ return new Resolver(merged);
892
+ }
893
+ /**
894
+ * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
895
+ * `this.file` resolve there for top-level helpers and namespace methods alike. `default`
896
+ * is skipped so it can't be shadowed.
897
+ */
898
+ #apply(options) {
899
+ const root = this;
900
+ const bind = (value) => typeof value === "function" ? value.bind(root) : value;
901
+ for (const [key, value] of Object.entries(options)) {
902
+ if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
903
+ root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
584
904
  }
585
905
  }
586
- *drain() {
587
- while (this.#head) yield this.dequeue();
906
+ static #testPattern(value, pattern) {
907
+ if (typeof pattern === "string") {
908
+ let regex = Resolver.#patternCache.get(pattern);
909
+ regex ??= new RegExp(pattern);
910
+ Resolver.#patternCache.set(pattern, regex);
911
+ return regex.test(value);
912
+ }
913
+ return value.match(pattern) !== null;
588
914
  }
589
- };
590
- //#endregion
591
- //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
592
- function pLimit(concurrency) {
593
- let rejectOnClear = false;
594
- if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
595
- validateConcurrency(concurrency);
596
- if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
597
- const queue = new Queue();
598
- let activeCount = 0;
599
- const resumeNext = () => {
600
- if (activeCount < concurrency && queue.size > 0) {
601
- activeCount++;
602
- queue.dequeue().run();
915
+ static #matchesOperation(node, { type, pattern }) {
916
+ if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
917
+ if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
918
+ if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
919
+ if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
920
+ if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
921
+ return false;
922
+ }
923
+ /**
924
+ * Returns `null` when the filter type doesn't apply to schemas, so include rules built
925
+ * from operation filters (e.g. `tag`) don't exclude every schema.
926
+ */
927
+ static #matchesSchema(node, { type, pattern }) {
928
+ if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
929
+ return null;
930
+ }
931
+ static #computeOptions(node, { options, exclude = [], include, override = [] }) {
932
+ if (operationDef.is(node)) {
933
+ if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
934
+ if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
935
+ return {
936
+ ...options,
937
+ ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
938
+ };
603
939
  }
604
- };
605
- const next = () => {
606
- activeCount--;
607
- resumeNext();
608
- };
609
- const run = async (function_, resolve, arguments_) => {
610
- const result = (async () => function_(...arguments_))();
611
- resolve(result);
612
- try {
613
- await result;
614
- } catch {}
615
- next();
616
- };
617
- const enqueue = (function_, resolve, reject, arguments_) => {
618
- const queueItem = { reject };
619
- new Promise((internalResolve) => {
620
- queueItem.run = internalResolve;
621
- queue.enqueue(queueItem);
622
- }).then(run.bind(void 0, function_, resolve, arguments_));
623
- if (activeCount < concurrency) resumeNext();
624
- };
625
- const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
626
- enqueue(function_, resolve, reject, arguments_);
627
- });
628
- Object.defineProperties(generator, {
629
- activeCount: { get: () => activeCount },
630
- pendingCount: { get: () => queue.size },
631
- clearQueue: { value() {
632
- if (!rejectOnClear) {
633
- queue.clear();
634
- return;
635
- }
636
- const abortError = AbortSignal.abort().reason;
637
- while (queue.size > 0) queue.dequeue().reject(abortError);
638
- } },
639
- concurrency: {
640
- get: () => concurrency,
641
- set(newConcurrency) {
642
- validateConcurrency(newConcurrency);
643
- concurrency = newConcurrency;
644
- queueMicrotask(() => {
645
- while (activeCount < concurrency && queue.size > 0) resumeNext();
646
- });
940
+ if (schemaDef.is(node)) {
941
+ if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
942
+ if (include) {
943
+ const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
944
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
647
945
  }
648
- },
649
- map: { async value(iterable, function_) {
650
- const promises = Array.from(iterable, (value, index) => this(function_, value, index));
651
- return Promise.all(promises);
652
- } }
653
- });
654
- return generator;
655
- }
656
- function validateConcurrency(concurrency) {
657
- if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
658
- }
946
+ return {
947
+ ...options,
948
+ ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
949
+ };
950
+ }
951
+ return options;
952
+ }
953
+ /**
954
+ * Applies include/exclude filters and merges matching override options, caching the result
955
+ * per `(options, node)` pair. Returns `null` when the node is filtered out.
956
+ */
957
+ #resolveOptions(node, context) {
958
+ const { options } = context;
959
+ if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
960
+ let byOptions = Resolver.#optionsCache.get(options);
961
+ if (!byOptions) {
962
+ byOptions = /* @__PURE__ */ new WeakMap();
963
+ Resolver.#optionsCache.set(options, byOptions);
964
+ }
965
+ const cached = byOptions.get(node);
966
+ if (cached) return cached.value;
967
+ const result = Resolver.#computeOptions(node, context);
968
+ byOptions.set(node, { value: result });
969
+ return result;
970
+ }
971
+ /**
972
+ * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
973
+ * groups use the first non-traversal segment (`''` when none remain, placing the file in
974
+ * the output root, kept safe by the caller's boundary check).
975
+ */
976
+ static #resolveGroupDir(group, groupValue) {
977
+ if (group.name) return group.name({ group: groupValue });
978
+ if (group.type === "tag") return camelCase(groupValue);
979
+ const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
980
+ return segment ? camelCase(segment) : "";
981
+ }
982
+ /**
983
+ * `mode: 'file'` resolves directly to `output.path`. `mode: 'directory'` (default) resolves
984
+ * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
985
+ * are provided.
986
+ */
987
+ #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
988
+ if (output.mode === "file") return path.resolve(root, output.path);
989
+ const outputDir = path.resolve(root, output.path);
990
+ const result = group && (groupPath || tag) ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : path.resolve(outputDir, baseName);
991
+ const outputDirWithSep = outputDir.endsWith(path.sep) ? outputDir : `${outputDir}${path.sep}`;
992
+ if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Diagnostics.Error({
993
+ code: Diagnostics.code.pathTraversal,
994
+ severity: "error",
995
+ message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
996
+ help: "This can stem from a path traversal in the OpenAPI specification or a misconfigured `group.name` function. Keep generated paths within the output directory.",
997
+ location: { kind: "config" }
998
+ });
999
+ return result;
1000
+ }
1001
+ /**
1002
+ * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
1003
+ * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
1004
+ * spec-derived values from writing outside the project.
1005
+ */
1006
+ #resolveOverridePath(filePath, root) {
1007
+ const resolved = path.resolve(root, filePath);
1008
+ const rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
1009
+ if (resolved !== root && !resolved.startsWith(rootWithSep)) throw new Diagnostics.Error({
1010
+ code: Diagnostics.code.pathTraversal,
1011
+ severity: "error",
1012
+ message: `Resolved path "${resolved}" is outside the project root "${root}".`,
1013
+ help: "A resolver `file.path` must return a path inside the project root.",
1014
+ location: { kind: "config" }
1015
+ });
1016
+ return resolved;
1017
+ }
1018
+ /**
1019
+ * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
1020
+ * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
1021
+ * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
1022
+ * with empty `sources`, `imports`, and `exports`, which consumers populate separately.
1023
+ */
1024
+ #resolveFile(options) {
1025
+ const { name, extname, tag, path: groupPath, root, output, group } = options;
1026
+ const baseName = this.#baseName({
1027
+ name,
1028
+ extname
1029
+ });
1030
+ const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
1031
+ baseName,
1032
+ output
1033
+ }), root) : this.#resolvePath({
1034
+ baseName,
1035
+ tag,
1036
+ path: groupPath,
1037
+ root,
1038
+ output,
1039
+ group
1040
+ });
1041
+ return ast.factory.createFile({
1042
+ path: filePath,
1043
+ baseName: path.basename(filePath),
1044
+ meta: { pluginName: this.pluginName },
1045
+ sources: [],
1046
+ imports: [],
1047
+ exports: []
1048
+ });
1049
+ }
1050
+ /**
1051
+ * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
1052
+ * a caller (e.g. the barrel plugin) has no document metadata.
1053
+ */
1054
+ static #buildBannerMeta(meta, file) {
1055
+ return {
1056
+ title: meta?.title,
1057
+ description: meta?.description,
1058
+ version: meta?.version,
1059
+ baseURL: meta?.baseURL,
1060
+ circularNames: meta?.circularNames ?? [],
1061
+ enumNames: meta?.enumNames ?? [],
1062
+ filePath: file?.path ?? "",
1063
+ baseName: file?.baseName ?? "",
1064
+ isBarrel: file?.isBarrel ?? false,
1065
+ isAggregation: file?.isAggregation ?? false
1066
+ };
1067
+ }
1068
+ /**
1069
+ * Resolves a user-configured banner/footer value. `undefined` means not configured.
1070
+ */
1071
+ static #resolveUserText(value, meta, file) {
1072
+ if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
1073
+ if (typeof value === "string") return value;
1074
+ }
1075
+ static #buildDefaultBanner({ title, version, config }) {
1076
+ const lines = [
1077
+ "/**",
1078
+ "* Generated by Kubb (https://kubb.dev/).",
1079
+ "* Do not edit manually."
1080
+ ];
1081
+ if (config.output.defaultBanner !== "simple") {
1082
+ const input = config.input;
1083
+ let source = "";
1084
+ if (typeof input === "string") source = getInputKind(input) === "inline" ? "text content" : path.basename(input);
1085
+ else if (input) source = "text content";
1086
+ if (source) lines.push(`* Source: ${source}`);
1087
+ if (title) lines.push(`* Title: ${title}`);
1088
+ if (version) lines.push(`* OpenAPI spec version: ${version}`);
1089
+ }
1090
+ return `${lines.join("\n")}\n*/\n`;
1091
+ }
1092
+ /**
1093
+ * A user-supplied `output.banner` overrides the default Kubb notice. When
1094
+ * `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
1095
+ */
1096
+ #resolveBanner(meta, { output, config, file }) {
1097
+ const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
1098
+ if (userBanner !== void 0) return userBanner;
1099
+ if (config.output.defaultBanner === false) return null;
1100
+ return Resolver.#buildDefaultBanner({
1101
+ title: meta?.title,
1102
+ version: meta?.version,
1103
+ config
1104
+ });
1105
+ }
1106
+ #resolveFooter(meta, { output, file }) {
1107
+ return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
1108
+ }
1109
+ };
659
1110
  //#endregion
660
- //#region src/FileProcessor.ts
661
- function joinSources(file) {
662
- return file.sources.map((item) => extractStringsFromNodes(item.nodes)).filter(Boolean).join("\n\n");
1111
+ //#region src/createResolver.ts
1112
+ /**
1113
+ * Defines a plugin resolver, the object that decides what every generated symbol and file
1114
+ * path is called. Override the top-level `name` and `file` to set the plugin's conventions,
1115
+ * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
1116
+ * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
1117
+ * through `this.name`, `this.file`, and `this.default`.
1118
+ *
1119
+ * @example Custom identifier casing
1120
+ * ```ts
1121
+ * export const resolverTs = createResolver<PluginTs>({
1122
+ * pluginName: 'plugin-ts',
1123
+ * name(name) {
1124
+ * return ensureValidVarName(pascalCase(name))
1125
+ * },
1126
+ * })
1127
+ * ```
1128
+ *
1129
+ * @example Rename generated files with `file.baseName`
1130
+ * ```ts
1131
+ * export const resolverFaker = createResolver<PluginFaker>({
1132
+ * pluginName: 'plugin-faker',
1133
+ * name(name) {
1134
+ * return camelCase(name, { prefix: 'create' })
1135
+ * },
1136
+ * file: {
1137
+ * baseName({ name, extname }) {
1138
+ * return `${camelCase(name, { prefix: 'create' })}${extname}`
1139
+ * },
1140
+ * },
1141
+ * })
1142
+ * ```
1143
+ *
1144
+ * @example Own the full path with `file.path`
1145
+ * ```ts
1146
+ * export const resolverFaker = createResolver<PluginFaker>({
1147
+ * pluginName: 'plugin-faker',
1148
+ * file: {
1149
+ * path({ baseName, output }) {
1150
+ * return `${output.path}/mocks/${baseName}`
1151
+ * },
1152
+ * },
1153
+ * })
1154
+ * ```
1155
+ */
1156
+ function createResolver(options) {
1157
+ return new Resolver(options);
663
1158
  }
1159
+ //#endregion
1160
+ //#region src/Transform.ts
664
1161
  /**
665
- * Converts a single file to a string using the registered parsers.
666
- * Falls back to joining source values when no matching parser is found.
1162
+ * Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in
1163
+ * isolation on the original adapter node and are composed into a single `Visitor` that the
1164
+ * `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin
1165
+ * chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`
1166
+ * returns the original node reference, and `transform` does the same when the composed visitor
1167
+ * leaves the tree untouched, so callers can detect a no-op by identity.
667
1168
  *
668
- * @internal
1169
+ * Registration order matches the order setup hooks fire, which the driver has already sorted by
1170
+ * `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders
1171
+ * within a single plugin's list.
669
1172
  */
670
- var FileProcessor = class {
671
- #limit = pLimit(100);
672
- async parse(file, { parsers, extension } = {}) {
673
- const parseExtName = extension?.[file.extname] || void 0;
674
- if (!parsers || !file.extname) return joinSources(file);
675
- const parser = parsers.get(file.extname);
676
- if (!parser) return joinSources(file);
677
- return parser.parse(file, { extname: parseExtName });
678
- }
679
- async run(files, { parsers, mode = "sequential", extension, onStart, onEnd, onUpdate } = {}) {
680
- await onStart?.(files);
681
- const total = files.length;
682
- let processed = 0;
683
- const processOne = async (file) => {
684
- const source = await this.parse(file, {
685
- extension,
686
- parsers
1173
+ var Transform = class {
1174
+ #macros = /* @__PURE__ */ new Map();
1175
+ #composed = /* @__PURE__ */ new Map();
1176
+ #memo = /* @__PURE__ */ new Map();
1177
+ /**
1178
+ * Appends `macro` to the plugin's list, after any macros already registered.
1179
+ */
1180
+ add(pluginName, macro) {
1181
+ const list = this.#macros.get(pluginName);
1182
+ if (list) list.push(macro);
1183
+ else this.#macros.set(pluginName, [macro]);
1184
+ this.#invalidate(pluginName);
1185
+ }
1186
+ /**
1187
+ * Replaces the plugin's macro list with `macros`.
1188
+ */
1189
+ set(pluginName, macros) {
1190
+ this.#macros.set(pluginName, [...macros]);
1191
+ this.#invalidate(pluginName);
1192
+ }
1193
+ /**
1194
+ * Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no
1195
+ * macros, so callers can compare by identity to detect a no-op.
1196
+ */
1197
+ applyTo(pluginName, node) {
1198
+ const visitor = this.#visitorFor(pluginName);
1199
+ if (!visitor) return node;
1200
+ let memo = this.#memo.get(pluginName);
1201
+ if (!memo) {
1202
+ memo = /* @__PURE__ */ new WeakMap();
1203
+ this.#memo.set(pluginName, memo);
1204
+ }
1205
+ const cached = memo.get(node);
1206
+ if (cached) return cached;
1207
+ const result = transform(node, visitor);
1208
+ memo.set(node, result);
1209
+ return result;
1210
+ }
1211
+ /**
1212
+ * Clears every registration. Called from the driver's `dispose()` so macros do not leak across
1213
+ * builds.
1214
+ */
1215
+ dispose() {
1216
+ this.#macros.clear();
1217
+ this.#composed.clear();
1218
+ this.#memo.clear();
1219
+ }
1220
+ #invalidate(pluginName) {
1221
+ this.#composed.delete(pluginName);
1222
+ this.#memo.delete(pluginName);
1223
+ }
1224
+ #visitorFor(pluginName) {
1225
+ const macros = this.#macros.get(pluginName);
1226
+ if (!macros || macros.length === 0) return void 0;
1227
+ let composed = this.#composed.get(pluginName);
1228
+ if (!composed) {
1229
+ composed = composeMacros(macros);
1230
+ this.#composed.set(pluginName, composed);
1231
+ }
1232
+ return composed;
1233
+ }
1234
+ };
1235
+ //#endregion
1236
+ //#region src/KubbDriver.ts
1237
+ const ENFORCE_ORDER = {
1238
+ pre: -1,
1239
+ post: 1
1240
+ };
1241
+ const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
1242
+ var KubbDriver = class {
1243
+ config;
1244
+ options;
1245
+ /**
1246
+ * The `InputNode` produced by the adapter. Set after adapter setup.
1247
+ */
1248
+ inputNode = null;
1249
+ adapter = null;
1250
+ /**
1251
+ * Raw adapter source so `adapter.parse()` can run lazily.
1252
+ * Intentionally outlives the build, cleared by `dispose()`.
1253
+ */
1254
+ #adapterSource = null;
1255
+ /**
1256
+ * Central file store for all generated files.
1257
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1258
+ * add files. This property gives direct read/write access when needed.
1259
+ */
1260
+ fileManager = new FileManager();
1261
+ plugins = /* @__PURE__ */ new Map();
1262
+ /**
1263
+ * Tracks which plugins have generators registered via `addGenerator()` (hook-based path).
1264
+ * Used by the build loop to decide whether to emit generator hooks for a given plugin.
1265
+ */
1266
+ #hookGeneratorPlugins = /* @__PURE__ */ new Set();
1267
+ #resolvers = /* @__PURE__ */ new Map();
1268
+ #defaultResolvers = /* @__PURE__ */ new Map();
1269
+ /**
1270
+ * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
1271
+ * them in one pass. External `hooks.hook(...)` listeners are not tracked.
1272
+ */
1273
+ #unhooks = [];
1274
+ /**
1275
+ * Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,
1276
+ * and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.
1277
+ */
1278
+ #transforms = new Transform();
1279
+ constructor(config, options) {
1280
+ this.config = config;
1281
+ this.options = options;
1282
+ this.adapter = config.adapter ?? null;
1283
+ }
1284
+ /**
1285
+ * Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
1286
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1287
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1288
+ * so `run` can parse it later.
1289
+ */
1290
+ async setup() {
1291
+ const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
1292
+ return {
1293
+ name: rawPlugin.name,
1294
+ dependencies: rawPlugin.dependencies,
1295
+ enforce: rawPlugin.enforce,
1296
+ hooks: rawPlugin.hooks,
1297
+ options: rawPlugin.options ?? {
1298
+ output: {
1299
+ path: ".",
1300
+ mode: "directory"
1301
+ },
1302
+ exclude: [],
1303
+ override: []
1304
+ }
1305
+ };
1306
+ }));
1307
+ for (const plugin of normalized) {
1308
+ this.#registerPlugin(plugin);
1309
+ this.plugins.set(plugin.name, plugin);
1310
+ }
1311
+ if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
1312
+ }
1313
+ /**
1314
+ * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
1315
+ * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
1316
+ * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
1317
+ * at the comparator level, so a chain where A depends on B and B depends on C could come out
1318
+ * wrong when A and C are never compared directly. Dependencies on plugins missing from the
1319
+ * config are ignored here and surface later through `requirePlugin`.
1320
+ */
1321
+ #sortPlugins(plugins) {
1322
+ const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
1323
+ const names = new Set(queue.map((plugin) => plugin.name));
1324
+ const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]));
1325
+ const sorted = [];
1326
+ for (const _ of plugins) {
1327
+ const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
1328
+ if (index === -1) throw new Diagnostics.Error({
1329
+ code: Diagnostics.code.invalidPluginOptions,
1330
+ severity: "error",
1331
+ message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
1332
+ help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
1333
+ location: { kind: "config" }
1334
+ });
1335
+ const [plugin] = queue.splice(index, 1);
1336
+ if (!plugin) break;
1337
+ sorted.push(plugin);
1338
+ for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
1339
+ }
1340
+ return sorted;
1341
+ }
1342
+ get hooks() {
1343
+ return this.options.hooks;
1344
+ }
1345
+ /**
1346
+ * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
1347
+ * `run` do not re-parse.
1348
+ */
1349
+ async #parseInput() {
1350
+ if (this.inputNode || !this.adapter || !this.#adapterSource) return;
1351
+ this.inputNode = await this.adapter.parse(this.#adapterSource);
1352
+ }
1353
+ /**
1354
+ * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
1355
+ * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
1356
+ * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
1357
+ * plugin-scoped context.
1358
+ *
1359
+ * @internal
1360
+ */
1361
+ #registerPlugin(plugin) {
1362
+ const { hooks } = plugin;
1363
+ if (!hooks) return;
1364
+ const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
1365
+ this.#unhooks.push(this.hooks.addHooks(configHooks));
1366
+ }
1367
+ /**
1368
+ * Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
1369
+ * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
1370
+ * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
1371
+ * plugins can configure generators, resolvers, macros, and options before `buildStart`.
1372
+ */
1373
+ async setupHooks() {
1374
+ for (const plugin of this.plugins.values()) {
1375
+ const setup = plugin.hooks?.["kubb:plugin:setup"];
1376
+ if (!setup) continue;
1377
+ await setup({
1378
+ config: this.config,
1379
+ options: plugin.options ?? {},
1380
+ addGenerator: (...generators) => {
1381
+ for (const generator of generators) this.registerGenerator(plugin.name, generator);
1382
+ },
1383
+ setResolver: (resolver) => {
1384
+ this.setPluginResolver(plugin.name, resolver);
1385
+ },
1386
+ addMacro: (macro) => {
1387
+ this.#transforms.add(plugin.name, macro);
1388
+ },
1389
+ setMacros: (macros) => {
1390
+ this.#transforms.set(plugin.name, macros);
1391
+ },
1392
+ setOptions: (opts) => {
1393
+ plugin.options = {
1394
+ ...plugin.options,
1395
+ ...opts
1396
+ };
1397
+ if (plugin.options.output) {
1398
+ const group = "group" in plugin.options ? plugin.options.group : void 0;
1399
+ plugin.options.output = normalizeOutput({
1400
+ output: plugin.options.output,
1401
+ group,
1402
+ pluginName: plugin.name
1403
+ });
1404
+ }
1405
+ },
1406
+ injectFile: (userFileNode) => {
1407
+ this.fileManager.add(ast.factory.createFile(userFileNode));
1408
+ }
1409
+ });
1410
+ }
1411
+ }
1412
+ /**
1413
+ * Registers a generator for the given plugin on the shared hook emitter.
1414
+ *
1415
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1416
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1417
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1418
+ * so that generators from different plugins do not cross-fire.
1419
+ *
1420
+ * The renderer comes from `generator.renderer`. Set `generator.renderer = null` (or leave it
1421
+ * unset) to opt out of rendering.
1422
+ *
1423
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1424
+ */
1425
+ registerGenerator(pluginName, generator) {
1426
+ const wrap = (method) => {
1427
+ if (!method) return void 0;
1428
+ return async (node, ctx) => {
1429
+ if (ctx.plugin.name !== pluginName) return;
1430
+ const result = await method(node, ctx);
1431
+ await this.dispatch({
1432
+ result,
1433
+ renderer: generator.renderer
1434
+ });
1435
+ };
1436
+ };
1437
+ this.#unhooks.push(this.hooks.addHooks({
1438
+ "kubb:generate:schema": wrap(generator.schema),
1439
+ "kubb:generate:operation": wrap(generator.operation),
1440
+ "kubb:generate:operations": wrap(generator.operations)
1441
+ }));
1442
+ this.#hookGeneratorPlugins.add(pluginName);
1443
+ }
1444
+ /**
1445
+ * Returns `true` when at least one generator was registered for the given plugin
1446
+ * via `addGenerator()` in `kubb:plugin:setup`.
1447
+ *
1448
+ * Used by the build loop to decide whether to walk the AST and emit generator hooks
1449
+ * for a plugin.
1450
+ */
1451
+ hasHookGenerators(pluginName) {
1452
+ return this.#hookGeneratorPlugins.has(pluginName);
1453
+ }
1454
+ /**
1455
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
1456
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
1457
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
1458
+ * contributes a `timing` diagnostic for the run summary.
1459
+ */
1460
+ async run() {
1461
+ const { hooks, config, fileManager } = this;
1462
+ const diagnostics = [];
1463
+ const parsersMap = /* @__PURE__ */ new Map();
1464
+ for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
1465
+ const onWriteStart = async (files) => {
1466
+ await hooks.callHook("kubb:files:processing:start", { files });
1467
+ };
1468
+ const updateBuffer = [];
1469
+ const onWriteUpdate = (item) => {
1470
+ updateBuffer.push(item);
1471
+ };
1472
+ const onWriteEnd = async (files) => {
1473
+ await hooks.callHook("kubb:files:processing:update", { files: updateBuffer.map((item) => ({
1474
+ ...item,
1475
+ config
1476
+ })) });
1477
+ updateBuffer.length = 0;
1478
+ await hooks.callHook("kubb:files:processing:end", { files });
1479
+ };
1480
+ const unhookWrites = fileManager.hooks.addHooks({
1481
+ start: onWriteStart,
1482
+ update: onWriteUpdate,
1483
+ end: onWriteEnd
1484
+ });
1485
+ return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
1486
+ try {
1487
+ const outputRoot = resolve(config.root, config.output.path);
1488
+ await this.#parseInput();
1489
+ await this.setupHooks();
1490
+ if (this.adapter && this.inputNode) await hooks.callHook("kubb:build:start", Object.assign({
1491
+ config,
1492
+ adapter: this.adapter,
1493
+ meta: this.inputNode.meta,
1494
+ getPlugin: this.getPlugin.bind(this)
1495
+ }, this.#filesPayload()));
1496
+ const generatorPlugins = [];
1497
+ for (const plugin of this.plugins.values()) {
1498
+ const context = this.getContext(plugin);
1499
+ const hrStart = process.hrtime();
1500
+ try {
1501
+ await hooks.callHook("kubb:plugin:start", { plugin });
1502
+ } catch (caughtError) {
1503
+ const error = toError(caughtError);
1504
+ const duration = getElapsedMs(hrStart);
1505
+ await this.#emitPluginEnd({
1506
+ plugin,
1507
+ duration,
1508
+ success: false,
1509
+ error
1510
+ });
1511
+ diagnostics.push({
1512
+ ...Diagnostics.from(error),
1513
+ plugin: plugin.name
1514
+ }, Diagnostics.performance({
1515
+ plugin: plugin.name,
1516
+ duration
1517
+ }));
1518
+ continue;
1519
+ }
1520
+ if (this.hasHookGenerators(plugin.name)) {
1521
+ generatorPlugins.push({
1522
+ plugin,
1523
+ context,
1524
+ hrStart
1525
+ });
1526
+ continue;
1527
+ }
1528
+ const duration = getElapsedMs(hrStart);
1529
+ diagnostics.push(Diagnostics.performance({
1530
+ plugin: plugin.name,
1531
+ duration
1532
+ }));
1533
+ await this.#emitPluginEnd({
1534
+ plugin,
1535
+ duration,
1536
+ success: true
1537
+ });
1538
+ }
1539
+ diagnostics.push(...await this.#runGenerators(generatorPlugins));
1540
+ await hooks.callHook("kubb:plugins:end", Object.assign({ config }, this.#filesPayload()));
1541
+ await fileManager.write(fileManager.files, {
1542
+ storage: config.storage,
1543
+ parsers: parsersMap
1544
+ });
1545
+ await hooks.callHook("kubb:build:end", {
1546
+ files: this.fileManager.files,
1547
+ config,
1548
+ outputDir: outputRoot
1549
+ });
1550
+ return { diagnostics: Diagnostics.dedupe(diagnostics) };
1551
+ } catch (caughtError) {
1552
+ diagnostics.push(Diagnostics.from(caughtError));
1553
+ return { diagnostics: Diagnostics.dedupe(diagnostics) };
1554
+ } finally {
1555
+ unhookWrites();
1556
+ }
1557
+ });
1558
+ }
1559
+ #filesPayload() {
1560
+ const driver = this;
1561
+ return {
1562
+ get files() {
1563
+ return driver.fileManager.files;
1564
+ },
1565
+ upsertFile: (...files) => driver.fileManager.upsert(...files)
1566
+ };
1567
+ }
1568
+ #emitPluginEnd({ plugin, duration, success, error }) {
1569
+ return this.hooks.callHook("kubb:plugin:end", Object.assign({
1570
+ plugin,
1571
+ duration,
1572
+ success,
1573
+ ...error ? { error } : {},
1574
+ config: this.config
1575
+ }, this.#filesPayload()));
1576
+ }
1577
+ /**
1578
+ * Runs schemas and operations through every plugin's generators. Each node is run
1579
+ * through the plugin's macros (from `this.#transforms`) before the generator sees it,
1580
+ * so plugins stay isolated and the hot path stays per-node. Schemas run before operations
1581
+ * so file output stays deterministic across runs.
1582
+ * A failing plugin contributes an error diagnostic so the rest of the build continues.
1583
+ * Every plugin also contributes a `timing` diagnostic.
1584
+ *
1585
+ * Plugins are processed one at a time, in full, so `kubb:plugin:end` fires as each one
1586
+ * completes rather than all at once at the end. That ordering drives the CLI's
1587
+ * `Plugins N/M` counter.
1588
+ *
1589
+ * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
1590
+ * post-plugin listeners (the barrel writer and friends) complete.
1591
+ */
1592
+ async #runGenerators(entries) {
1593
+ const diagnostics = [];
1594
+ if (entries.length === 0) return diagnostics;
1595
+ if (!this.inputNode) {
1596
+ for (const { plugin, hrStart } of entries) {
1597
+ const duration = getElapsedMs(hrStart);
1598
+ diagnostics.push(Diagnostics.performance({
1599
+ plugin: plugin.name,
1600
+ duration
1601
+ }));
1602
+ await this.#emitPluginEnd({
1603
+ plugin,
1604
+ duration,
1605
+ success: true
1606
+ });
1607
+ }
1608
+ return diagnostics;
1609
+ }
1610
+ const transforms = this.#transforms;
1611
+ const { schemas, operations } = this.inputNode;
1612
+ const emitsSchemaHook = this.hooks.listenerCount("kubb:generate:schema") > 0;
1613
+ const emitsOperationHook = this.hooks.listenerCount("kubb:generate:operation") > 0;
1614
+ const emitsOperationsHook = this.hooks.listenerCount("kubb:generate:operations") > 0;
1615
+ const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
1616
+ for (const { plugin } of entries) {
1617
+ const { exclude, include, override } = plugin.options;
1618
+ if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
1619
+ const resolver = this.getResolver(plugin.name);
1620
+ const includedOps = operations.filter((operation) => resolver.default.options(operation, {
1621
+ options: plugin.options,
1622
+ exclude,
1623
+ include,
1624
+ override
1625
+ }) !== null);
1626
+ allowedSchemaNamesByPlugin.set(plugin.name, collectUsedSchemaNames(includedOps, schemas));
1627
+ }
1628
+ for (const { plugin, context, hrStart } of entries) {
1629
+ const generatorContext = {
1630
+ ...context,
1631
+ resolver: this.getResolver(plugin.name)
1632
+ };
1633
+ const { exclude, include, override } = plugin.options;
1634
+ const optionsAreStatic = !exclude?.length && !include?.length && !override?.length;
1635
+ const allowedSchemaNames = allowedSchemaNamesByPlugin.get(plugin.name) ?? null;
1636
+ let error = null;
1637
+ const resolveForPlugin = (node) => {
1638
+ const transformedNode = transforms.applyTo(plugin.name, node);
1639
+ if (optionsAreStatic) return {
1640
+ transformedNode,
1641
+ options: plugin.options
1642
+ };
1643
+ const options = generatorContext.resolver.default.options(transformedNode, {
1644
+ options: plugin.options,
1645
+ exclude,
1646
+ include,
1647
+ override
1648
+ });
1649
+ if (options === null) return null;
1650
+ return {
1651
+ transformedNode,
1652
+ options
1653
+ };
1654
+ };
1655
+ if (emitsSchemaHook) for (const node of schemas) {
1656
+ if (error) break;
1657
+ try {
1658
+ const resolved = resolveForPlugin(node);
1659
+ if (!resolved) continue;
1660
+ const { transformedNode, options } = resolved;
1661
+ if (allowedSchemaNames !== null && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) continue;
1662
+ await this.hooks.callHook("kubb:generate:schema", transformedNode, {
1663
+ ...generatorContext,
1664
+ options
1665
+ });
1666
+ } catch (caughtError) {
1667
+ error = toError(caughtError);
1668
+ }
1669
+ }
1670
+ if (emitsOperationHook) for (const node of operations) {
1671
+ if (error) break;
1672
+ try {
1673
+ const resolved = resolveForPlugin(node);
1674
+ if (!resolved) continue;
1675
+ await this.hooks.callHook("kubb:generate:operation", resolved.transformedNode, {
1676
+ ...generatorContext,
1677
+ options: resolved.options
1678
+ });
1679
+ } catch (caughtError) {
1680
+ error = toError(caughtError);
1681
+ }
1682
+ }
1683
+ if (!error && emitsOperationsHook) try {
1684
+ const ctx = {
1685
+ ...generatorContext,
1686
+ options: plugin.options
1687
+ };
1688
+ const pluginOperations = operations.reduce((acc, node) => {
1689
+ const resolved = resolveForPlugin(node);
1690
+ if (resolved) acc.push(resolved.transformedNode);
1691
+ return acc;
1692
+ }, []);
1693
+ await this.hooks.callHook("kubb:generate:operations", pluginOperations, ctx);
1694
+ } catch (caughtError) {
1695
+ error = toError(caughtError);
1696
+ }
1697
+ const duration = getElapsedMs(hrStart);
1698
+ await this.#emitPluginEnd({
1699
+ plugin,
1700
+ duration,
1701
+ success: !error,
1702
+ error: error ?? void 0
1703
+ });
1704
+ if (error) diagnostics.push({
1705
+ ...Diagnostics.from(error),
1706
+ plugin: plugin.name
687
1707
  });
688
- const currentProcessed = ++processed;
689
- const percentage = currentProcessed / total * 100;
690
- await onUpdate?.({
691
- file,
692
- source,
693
- processed: currentProcessed,
694
- percentage,
695
- total
1708
+ diagnostics.push(Diagnostics.performance({
1709
+ plugin: plugin.name,
1710
+ duration
1711
+ }));
1712
+ }
1713
+ return diagnostics;
1714
+ }
1715
+ /**
1716
+ * Stores whatever a generator method or `kubb:generate:*` hook returned.
1717
+ *
1718
+ * - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.
1719
+ * - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the
1720
+ * produced files go to `fileManager.upsert`.
1721
+ * - A falsy result is treated as a no-op. The generator wrote files itself via
1722
+ * `ctx.upsertFile`.
1723
+ *
1724
+ * Pass `renderer` when the result may be a renderer element. Generators that only return
1725
+ * `Array<FileNode>` do not need one.
1726
+ */
1727
+ async dispatch({ result, renderer }) {
1728
+ try {
1729
+ var _usingCtx$2 = _usingCtx();
1730
+ if (!result) return;
1731
+ if (Array.isArray(result)) {
1732
+ this.fileManager.upsert(...result);
1733
+ return;
1734
+ }
1735
+ if (!renderer) return;
1736
+ const instance = _usingCtx$2.u(renderer());
1737
+ await instance.render(result);
1738
+ this.fileManager.upsert(...instance.files);
1739
+ } catch (_) {
1740
+ _usingCtx$2.e = _;
1741
+ } finally {
1742
+ _usingCtx$2.d();
1743
+ }
1744
+ }
1745
+ /**
1746
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1747
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
1748
+ *
1749
+ * @internal
1750
+ */
1751
+ dispose() {
1752
+ for (const unhook of this.#unhooks) unhook();
1753
+ this.#unhooks.length = 0;
1754
+ this.#hookGeneratorPlugins.clear();
1755
+ this.#transforms.dispose();
1756
+ this.#resolvers.clear();
1757
+ this.#defaultResolvers.clear();
1758
+ this.fileManager.dispose();
1759
+ this.inputNode = null;
1760
+ this.#adapterSource = null;
1761
+ }
1762
+ [Symbol.dispose]() {
1763
+ this.dispose();
1764
+ }
1765
+ #getDefaultResolver = memoize(this.#defaultResolvers, (pluginName) => createResolver({ pluginName }));
1766
+ /**
1767
+ * Merges `partial` with the plugin's default resolver and stores the result.
1768
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
1769
+ * get the up-to-date resolver without going through `getResolver()`.
1770
+ */
1771
+ setPluginResolver(pluginName, partial) {
1772
+ const defaultResolver = this.#getDefaultResolver(pluginName);
1773
+ const merged = Resolver.merge(defaultResolver, partial);
1774
+ this.#resolvers.set(pluginName, merged);
1775
+ const plugin = this.plugins.get(pluginName);
1776
+ if (plugin) plugin.resolver = merged;
1777
+ }
1778
+ getResolver(pluginName) {
1779
+ return this.#resolvers.get(pluginName) ?? this.#getDefaultResolver(pluginName);
1780
+ }
1781
+ getContext(plugin) {
1782
+ const driver = this;
1783
+ const report = (diagnostic) => {
1784
+ Diagnostics.report({
1785
+ ...diagnostic,
1786
+ plugin: plugin.name
696
1787
  });
697
1788
  };
698
- if (mode === "sequential") for (const file of files) await processOne(file);
699
- else await Promise.all(files.map((file) => this.#limit(() => processOne(file))));
700
- await onEnd?.(files);
701
- return files;
1789
+ return {
1790
+ config: driver.config,
1791
+ get root() {
1792
+ return resolve(driver.config.root, driver.config.output.path);
1793
+ },
1794
+ hooks: driver.hooks,
1795
+ plugin,
1796
+ getPlugin: driver.getPlugin.bind(driver),
1797
+ requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
1798
+ getResolver: driver.getResolver.bind(driver),
1799
+ driver,
1800
+ addFile: async (...files) => {
1801
+ driver.fileManager.add(...files);
1802
+ },
1803
+ upsertFile: async (...files) => {
1804
+ driver.fileManager.upsert(...files);
1805
+ },
1806
+ get meta() {
1807
+ return driver.inputNode?.meta ?? {
1808
+ circularNames: [],
1809
+ enumNames: []
1810
+ };
1811
+ },
1812
+ get adapter() {
1813
+ return driver.adapter;
1814
+ },
1815
+ get resolver() {
1816
+ return driver.getResolver(plugin.name);
1817
+ },
1818
+ warn(message) {
1819
+ report({
1820
+ code: Diagnostics.code.pluginWarning,
1821
+ severity: "warning",
1822
+ message
1823
+ });
1824
+ },
1825
+ error(error) {
1826
+ const cause = typeof error === "string" ? void 0 : error;
1827
+ report({
1828
+ code: Diagnostics.code.pluginFailed,
1829
+ severity: "error",
1830
+ message: typeof error === "string" ? error : error.message,
1831
+ cause
1832
+ });
1833
+ },
1834
+ info(message) {
1835
+ report({
1836
+ code: Diagnostics.code.pluginInfo,
1837
+ severity: "info",
1838
+ message
1839
+ });
1840
+ }
1841
+ };
1842
+ }
1843
+ getPlugin(pluginName) {
1844
+ return this.plugins.get(pluginName);
1845
+ }
1846
+ requirePlugin(pluginName, context) {
1847
+ const plugin = this.getPlugin(pluginName);
1848
+ if (plugin) return plugin;
1849
+ const requiredBy = context?.requiredBy;
1850
+ const by = requiredBy ? ` by "${requiredBy}"` : "";
1851
+ const help = requiredBy ? ` (required by "${requiredBy}")` : "";
1852
+ throw new Diagnostics.Error({
1853
+ code: Diagnostics.code.pluginNotFound,
1854
+ severity: "error",
1855
+ message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
1856
+ help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
1857
+ location: { kind: "config" }
1858
+ });
702
1859
  }
703
1860
  };
704
1861
  //#endregion
705
1862
  //#region src/createStorage.ts
706
1863
  /**
707
- * Factory for implementing custom storage backends that control where generated files are written.
708
- *
709
- * Takes a builder function `(options: TOptions) => Storage` and returns a factory `(options?: TOptions) => Storage`.
710
- * Kubb provides filesystem and in-memory implementations out of the box.
1864
+ * Defines a custom storage backend. The builder receives user options and
1865
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
1866
+ * storages. A custom backend writes generated files elsewhere, such as cloud
1867
+ * storage or a database.
711
1868
  *
712
- * @note Call the returned factory with optional options to instantiate the storage adapter.
713
- *
714
- * @example
1869
+ * @example In-memory storage (the built-in implementation)
715
1870
  * ```ts
716
1871
  * import { createStorage } from '@kubb/core'
717
1872
  *
718
1873
  * export const memoryStorage = createStorage(() => {
719
1874
  * const store = new Map<string, string>()
1875
+ *
720
1876
  * return {
721
1877
  * name: 'memory',
722
- * async hasItem(key) { return store.has(key) },
723
- * async getItem(key) { return store.get(key) ?? null },
724
- * async setItem(key, value) { store.set(key, value) },
725
- * async removeItem(key) { store.delete(key) },
1878
+ * async hasItem(key) {
1879
+ * return store.has(key)
1880
+ * },
1881
+ * async getItem(key) {
1882
+ * return store.get(key) ?? null
1883
+ * },
1884
+ * async setItem(key, value) {
1885
+ * store.set(key, value)
1886
+ * },
1887
+ * async removeItem(key) {
1888
+ * store.delete(key)
1889
+ * },
726
1890
  * async getKeys(base) {
727
1891
  * const keys = [...store.keys()]
728
1892
  * return base ? keys.filter((k) => k.startsWith(base)) : keys
729
1893
  * },
730
- * async clear(base) { if (!base) store.clear() },
1894
+ * async clear(base) {
1895
+ * if (!base) store.clear()
1896
+ * },
731
1897
  * }
732
1898
  * })
733
- *
734
- * // Instantiate:
735
- * const storage = memoryStorage()
736
1899
  * ```
737
1900
  */
738
1901
  function createStorage(build) {
@@ -740,6 +1903,29 @@ function createStorage(build) {
740
1903
  }
741
1904
  //#endregion
742
1905
  //#region src/storages/fsStorage.ts
1906
+ const WRITE_CONCURRENCY = 50;
1907
+ function createLimiter(concurrency) {
1908
+ let active = 0;
1909
+ const queue = [];
1910
+ function next() {
1911
+ if (active >= concurrency) return;
1912
+ const run = queue.shift();
1913
+ if (!run) return;
1914
+ active++;
1915
+ run();
1916
+ }
1917
+ return function limit(task) {
1918
+ return new Promise((resolve, reject) => {
1919
+ queue.push(() => {
1920
+ task().then(resolve, reject).finally(() => {
1921
+ active--;
1922
+ next();
1923
+ });
1924
+ });
1925
+ next();
1926
+ });
1927
+ };
1928
+ }
743
1929
  /**
744
1930
  * Built-in filesystem storage driver.
745
1931
  *
@@ -747,642 +1933,540 @@ function createStorage(build) {
747
1933
  * Keys are resolved against `process.cwd()`, so root-relative paths such as
748
1934
  * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.
749
1935
  *
750
- * Internally uses the `write` utility from `@internals/utils`, which:
751
- * - trims leading/trailing whitespace before writing
752
- * - skips the write when file content is already identical (deduplication)
753
- * - creates missing parent directories automatically
754
- * - supports Bun's native file API when running under Bun
1936
+ * Writes are deduplicated and directory-safe:
1937
+ * - leading and trailing whitespace is trimmed before writing
1938
+ * - the write is skipped when the file content is already identical
1939
+ * - missing parent directories are created automatically
1940
+ * - Bun's native file API is used when running under Bun
1941
+ * - concurrent `setItem` calls are capped at {@link WRITE_CONCURRENCY} in flight, so a caller
1942
+ * can fire every file's write without pacing itself
755
1943
  *
756
1944
  * @example
757
1945
  * ```ts
758
1946
  * import { fsStorage } from '@kubb/core'
759
1947
  * import { defineConfig } from 'kubb'
760
- *
761
- * export default defineConfig({
762
- * input: { path: './petStore.yaml' },
763
- * output: { path: './src/gen' },
764
- * storage: fsStorage(),
765
- * })
766
- * ```
767
- */
768
- const fsStorage = createStorage(() => ({
769
- name: "fs",
770
- async hasItem(key) {
771
- try {
772
- await access(resolve(key));
773
- return true;
774
- } catch (_error) {
775
- return false;
776
- }
777
- },
778
- async getItem(key) {
779
- try {
780
- return await readFile(resolve(key), "utf8");
781
- } catch (_error) {
782
- return null;
783
- }
784
- },
785
- async setItem(key, value) {
786
- await write(resolve(key), value, { sanity: false });
787
- },
788
- async removeItem(key) {
789
- await rm(resolve(key), { force: true });
790
- },
791
- async getKeys(base) {
792
- const keys = [];
793
- const resolvedBase = resolve(base ?? process.cwd());
794
- async function walk(dir, prefix) {
795
- let entries;
1948
+ *
1949
+ * export default defineConfig({
1950
+ * input: './petStore.yaml',
1951
+ * output: { path: './src/gen' },
1952
+ * storage: fsStorage(),
1953
+ * })
1954
+ * ```
1955
+ */
1956
+ const fsStorage = createStorage(() => {
1957
+ const limit = createLimiter(WRITE_CONCURRENCY);
1958
+ return {
1959
+ name: "fs",
1960
+ async hasItem(key) {
796
1961
  try {
797
- entries = await readdir(dir, { withFileTypes: true });
1962
+ await access(resolve(key));
1963
+ return true;
798
1964
  } catch (_error) {
799
- return;
1965
+ return false;
800
1966
  }
801
- for (const entry of entries) {
802
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
803
- if (entry.isDirectory()) await walk(join(dir, entry.name), rel);
804
- else keys.push(rel);
1967
+ },
1968
+ async getItem(key) {
1969
+ try {
1970
+ return await readFile(resolve(key), "utf8");
1971
+ } catch (_error) {
1972
+ return null;
805
1973
  }
1974
+ },
1975
+ async setItem(key, value) {
1976
+ await limit(() => write(resolve(key), value, { sanity: false }));
1977
+ },
1978
+ async removeItem(key) {
1979
+ await rm(resolve(key), { force: true });
1980
+ },
1981
+ async getKeys(base) {
1982
+ const resolvedBase = resolve(base ?? process.cwd());
1983
+ const keys = [];
1984
+ try {
1985
+ for await (const entry of glob("**/*", {
1986
+ cwd: resolvedBase,
1987
+ withFileTypes: true
1988
+ })) if (entry.isFile()) keys.push(toPosixPath(relative(resolvedBase, join(entry.parentPath, entry.name))));
1989
+ } catch (_error) {}
1990
+ return keys;
1991
+ },
1992
+ async clear(base) {
1993
+ if (!base) return;
1994
+ await clean(resolve(base));
806
1995
  }
807
- await walk(resolvedBase, "");
808
- return keys;
809
- },
810
- async clear(base) {
811
- if (!base) return;
812
- await clean(resolve(base));
813
- }
814
- }));
1996
+ };
1997
+ });
815
1998
  //#endregion
816
1999
  //#region src/createKubb.ts
817
- async function setup(userConfig, options = {}) {
818
- const hooks = options.hooks ?? new AsyncEventEmitter();
819
- const config = {
2000
+ function resolveConfig(userConfig) {
2001
+ return {
820
2002
  ...userConfig,
821
2003
  root: userConfig.root || process.cwd(),
822
2004
  parsers: userConfig.parsers ?? [],
823
- adapter: userConfig.adapter,
824
2005
  output: {
825
2006
  format: false,
826
2007
  lint: false,
827
- extension: DEFAULT_EXTENSION,
828
- defaultBanner: DEFAULT_BANNER,
2008
+ defaultBanner: "simple",
829
2009
  ...userConfig.output
830
2010
  },
831
2011
  storage: userConfig.storage ?? fsStorage(),
832
- devtools: userConfig.devtools ? {
833
- studioUrl: DEFAULT_STUDIO_URL,
834
- ...typeof userConfig.devtools === "boolean" ? {} : userConfig.devtools
835
- } : void 0,
2012
+ reporters: userConfig.reporters ?? [],
836
2013
  plugins: userConfig.plugins ?? []
837
2014
  };
838
- const driver = new PluginDriver(config, { hooks });
839
- const sources = /* @__PURE__ */ new Map();
840
- const diagnosticInfo = getDiagnosticInfo();
841
- await hooks.emit("kubb:debug", {
842
- date: /* @__PURE__ */ new Date(),
843
- logs: [
844
- "Configuration:",
845
- ` • Name: ${userConfig.name || "unnamed"}`,
846
- ` • Root: ${userConfig.root || process.cwd()}`,
847
- ` • Output: ${userConfig.output?.path || "not specified"}`,
848
- ` • Plugins: ${userConfig.plugins?.length || 0}`,
849
- "Output Settings:",
850
- ` • Storage: ${config.storage.name}`,
851
- ` • Formatter: ${userConfig.output?.format || "none"}`,
852
- ` • Linter: ${userConfig.output?.lint || "none"}`,
853
- "Environment:",
854
- Object.entries(diagnosticInfo).map(([key, value]) => ` • ${key}: ${value}`).join("\n")
855
- ]
856
- });
857
- try {
858
- if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {
859
- await exists(userConfig.input.path);
860
- await hooks.emit("kubb:debug", {
861
- date: /* @__PURE__ */ new Date(),
862
- logs: [`✓ Input file validated: ${userConfig.input.path}`]
863
- });
864
- }
865
- } catch (caughtError) {
866
- if (isInputPath(userConfig)) {
867
- const error = caughtError;
868
- throw new Error(`Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${userConfig.input.path}`, { cause: error });
869
- }
870
- }
871
- if (config.output.clean) {
872
- await hooks.emit("kubb:debug", {
873
- date: /* @__PURE__ */ new Date(),
874
- logs: ["Cleaning output directories", ` • Output: ${config.output.path}`]
875
- });
876
- await config.storage.clear(resolve(config.root, config.output.path));
877
- }
878
- function registerMiddlewareHook(event, middlewareHooks) {
879
- const handler = middlewareHooks[event];
880
- if (handler) hooks.on(event, handler);
881
- }
882
- for (const middleware of config.middleware ?? []) for (const event of Object.keys(middleware.hooks)) registerMiddlewareHook(event, middleware.hooks);
883
- if (config.adapter) {
884
- const source = inputToAdapterSource(config);
885
- await hooks.emit("kubb:debug", {
886
- date: /* @__PURE__ */ new Date(),
887
- logs: [`Running adapter: ${config.adapter.name}`]
888
- });
889
- driver.adapter = config.adapter;
890
- driver.inputNode = await config.adapter.parse(source);
891
- await hooks.emit("kubb:debug", {
892
- date: /* @__PURE__ */ new Date(),
893
- logs: [
894
- `✓ Adapter '${config.adapter.name}' resolved InputNode`,
895
- ` • Schemas: ${driver.inputNode.schemas.length}`,
896
- ` • Operations: ${driver.inputNode.operations.length}`
897
- ]
898
- });
899
- }
900
- return {
901
- config,
902
- hooks,
903
- driver,
904
- sources
905
- };
906
2015
  }
907
2016
  /**
908
- * Walks the AST and dispatches nodes to a plugin's direct AST hooks
909
- * (`schema`, `operation`, `operations`).
2017
+ * Kubb code-generation instance bound to a single config entry. Resolves the user
2018
+ * config in the constructor, so `config` is available right away, and shares `hooks`,
2019
+ * `storage`, and `driver` across the `setup → build` lifecycle.
2020
+ *
2021
+ * `createKubb` takes a plain config object (the shape `defineConfig` produces),
2022
+ * not a fluent builder.
910
2023
  *
911
- * When `include` contains only operation-scoped filters (`tag`, `operationId`, `path`,
912
- * `method`, `contentType`) and no `schemaName` filter, the function pre-computes the set
913
- * of top-level schema names transitively reachable from the included operations and skips
914
- * schemas that fall outside that set. This ensures that component schemas referenced
915
- * exclusively by excluded operations are not generated.
2024
+ * Attach hook listeners to `.hooks` before calling `setup()` or `build()`.
2025
+ *
2026
+ * @example
2027
+ * ```ts
2028
+ * const kubb = createKubb(userConfig)
2029
+ * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))
2030
+ * const { files, diagnostics } = await kubb.safeBuild()
2031
+ * ```
916
2032
  */
917
- async function runPluginAstHooks(plugin, context) {
918
- const { adapter, inputNode, resolver, driver } = context;
919
- const { exclude, include, override } = plugin.options;
920
- if (!adapter || !inputNode) throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. adapterOas()) before this plugin in your Kubb config.`);
921
- function resolveRenderer(gen) {
922
- return gen.renderer === null ? void 0 : gen.renderer ?? plugin.renderer ?? context.config.renderer;
923
- }
924
- const generators = plugin.generators ?? [];
925
- const collectedOperations = [];
926
- const generatorContext = {
927
- ...context,
928
- resolver: driver.getResolver(plugin.name)
929
- };
930
- const operationFilterTypes = new Set([
931
- "tag",
932
- "operationId",
933
- "path",
934
- "method",
935
- "contentType"
936
- ]);
937
- const hasOperationBasedIncludes = include?.some(({ type }) => operationFilterTypes.has(type)) ?? false;
938
- const hasSchemaNameIncludes = include?.some(({ type }) => type === "schemaName") ?? false;
939
- let allowedSchemaNames;
940
- if (hasOperationBasedIncludes && !hasSchemaNameIncludes) allowedSchemaNames = collectUsedSchemaNames(inputNode.operations.filter((op) => resolver.resolveOptions(op, {
941
- options: plugin.options,
942
- exclude,
943
- include,
944
- override
945
- }) !== null), inputNode.schemas);
946
- await walk(inputNode, {
947
- depth: "shallow",
948
- async schema(node) {
949
- const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
950
- if (allowedSchemaNames !== void 0 && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) return;
951
- const options = resolver.resolveOptions(transformedNode, {
952
- options: plugin.options,
953
- exclude,
954
- include,
955
- override
956
- });
957
- if (options === null) return;
958
- const ctx = {
959
- ...generatorContext,
960
- options
961
- };
962
- for (const gen of generators) {
963
- if (!gen.schema) continue;
964
- await applyHookResult(await gen.schema(transformedNode, ctx), driver, resolveRenderer(gen));
965
- }
966
- await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
967
- },
968
- async operation(node) {
969
- const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
970
- const options = resolver.resolveOptions(transformedNode, {
971
- options: plugin.options,
972
- exclude,
973
- include,
974
- override
975
- });
976
- if (options !== null) {
977
- collectedOperations.push(transformedNode);
978
- const ctx = {
979
- ...generatorContext,
980
- options
981
- };
982
- for (const gen of generators) {
983
- if (!gen.operation) continue;
984
- await applyHookResult(await gen.operation(transformedNode, ctx), driver, resolveRenderer(gen));
985
- }
986
- await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
987
- }
988
- }
989
- });
990
- if (collectedOperations.length > 0) {
991
- const ctx = {
992
- ...generatorContext,
993
- options: plugin.options
994
- };
995
- for (const gen of generators) {
996
- if (!gen.operations) continue;
997
- await applyHookResult(await gen.operations(collectedOperations, ctx), driver, resolveRenderer(gen));
2033
+ var Kubb = class {
2034
+ hooks;
2035
+ config;
2036
+ #driver = null;
2037
+ #storage = null;
2038
+ constructor(userConfig, options = {}) {
2039
+ this.config = resolveConfig(userConfig);
2040
+ this.hooks = options.hooks ?? new Hookable();
2041
+ }
2042
+ get storage() {
2043
+ if (!this.#storage) throw new Error("[kubb] setup() must be called before accessing storage");
2044
+ return this.#storage;
2045
+ }
2046
+ get driver() {
2047
+ if (!this.#driver) throw new Error("[kubb] setup() must be called before accessing driver");
2048
+ return this.#driver;
2049
+ }
2050
+ /**
2051
+ * Initializes the driver and storage. `build()` calls this automatically.
2052
+ */
2053
+ async setup() {
2054
+ const config = this.config;
2055
+ const driver = new KubbDriver(config, { hooks: this.hooks });
2056
+ this.hooks.setMaxListeners(Math.max(10, config.plugins.length * 4));
2057
+ if (config.output.clean) await config.storage.clear(resolve(config.root, config.output.path));
2058
+ await driver.setup();
2059
+ this.#driver = driver;
2060
+ this.#storage = config.storage;
2061
+ }
2062
+ /**
2063
+ * Runs the full pipeline and throws on any plugin error.
2064
+ * Automatically calls `setup()` if needed.
2065
+ */
2066
+ async build() {
2067
+ const out = await this.safeBuild();
2068
+ if (Diagnostics.hasError(out.diagnostics)) {
2069
+ const errors = out.diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.cause ?? new Diagnostics.Error(diagnostic));
2070
+ throw new BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? "error" : "errors"}`, { errors });
998
2071
  }
999
- await driver.hooks.emit("kubb:generate:operations", collectedOperations, ctx);
2072
+ return out;
1000
2073
  }
1001
- }
1002
- async function safeBuild(setupResult) {
1003
- const { driver, hooks, sources } = setupResult;
1004
- const failedPlugins = /* @__PURE__ */ new Set();
1005
- const pluginTimings = /* @__PURE__ */ new Map();
1006
- const config = driver.config;
1007
- try {
1008
- await driver.emitSetupHooks();
1009
- if (driver.adapter && driver.inputNode) await hooks.emit("kubb:build:start", {
1010
- config,
1011
- adapter: driver.adapter,
1012
- inputNode: driver.inputNode,
1013
- getPlugin: driver.getPlugin.bind(driver),
1014
- get files() {
1015
- return driver.fileManager.files;
1016
- },
1017
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1018
- });
1019
- for (const plugin of driver.plugins.values()) {
1020
- const context = driver.getContext(plugin);
1021
- const hrStart = process.hrtime();
1022
- try {
1023
- const timestamp = /* @__PURE__ */ new Date();
1024
- await hooks.emit("kubb:plugin:start", { plugin });
1025
- await hooks.emit("kubb:debug", {
1026
- date: timestamp,
1027
- logs: ["Starting plugin...", ` • Plugin Name: ${plugin.name}`]
1028
- });
1029
- if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) await runPluginAstHooks(plugin, context);
1030
- const duration = getElapsedMs(hrStart);
1031
- pluginTimings.set(plugin.name, duration);
1032
- await hooks.emit("kubb:plugin:end", {
1033
- plugin,
1034
- duration,
1035
- success: true,
1036
- config,
1037
- get files() {
1038
- return driver.fileManager.files;
1039
- },
1040
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1041
- });
1042
- await hooks.emit("kubb:debug", {
1043
- date: /* @__PURE__ */ new Date(),
1044
- logs: [`✓ Plugin started successfully (${formatMs(duration)})`]
1045
- });
1046
- } catch (caughtError) {
1047
- const error = caughtError;
1048
- const errorTimestamp = /* @__PURE__ */ new Date();
1049
- const duration = getElapsedMs(hrStart);
1050
- await hooks.emit("kubb:plugin:end", {
1051
- plugin,
1052
- duration,
1053
- success: false,
1054
- error,
1055
- config,
1056
- get files() {
1057
- return driver.fileManager.files;
1058
- },
1059
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1060
- });
1061
- await hooks.emit("kubb:debug", {
1062
- date: errorTimestamp,
1063
- logs: [
1064
- "✗ Plugin start failed",
1065
- ` • Plugin Name: ${plugin.name}`,
1066
- ` • Error: ${error.constructor.name} - ${error.message}`,
1067
- " • Stack Trace:",
1068
- error.stack || "No stack trace available"
1069
- ]
1070
- });
1071
- failedPlugins.add({
1072
- plugin,
1073
- error
1074
- });
1075
- }
2074
+ /**
2075
+ * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.
2076
+ * Automatically calls `setup()` if needed. This is the canonical call: it never throws on
2077
+ * plugin errors, so callers stay in control of how failures surface.
2078
+ */
2079
+ async safeBuild() {
2080
+ try {
2081
+ var _usingCtx$1 = _usingCtx();
2082
+ if (!this.#driver) await this.setup();
2083
+ const self = _usingCtx$1.u(this);
2084
+ const driver = self.driver;
2085
+ const storage = self.storage;
2086
+ const { diagnostics } = await driver.run();
2087
+ return {
2088
+ diagnostics,
2089
+ files: driver.fileManager.files,
2090
+ driver,
2091
+ storage
2092
+ };
2093
+ } catch (_) {
2094
+ _usingCtx$1.e = _;
2095
+ } finally {
2096
+ _usingCtx$1.d();
1076
2097
  }
1077
- await hooks.emit("kubb:plugins:end", {
1078
- config,
1079
- get files() {
1080
- return driver.fileManager.files;
1081
- },
1082
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1083
- });
1084
- const files = driver.fileManager.files;
1085
- const parsersMap = /* @__PURE__ */ new Map();
1086
- for (const parser of config.parsers) if (parser.extNames) for (const extname of parser.extNames) parsersMap.set(extname, parser);
1087
- const fileProcessor = new FileProcessor();
1088
- await hooks.emit("kubb:debug", {
1089
- date: /* @__PURE__ */ new Date(),
1090
- logs: [`Writing ${files.length} files...`]
1091
- });
1092
- await fileProcessor.run(files, {
1093
- parsers: parsersMap,
1094
- mode: "parallel",
1095
- extension: config.output.extension,
1096
- onStart: async (processingFiles) => {
1097
- await hooks.emit("kubb:files:processing:start", { files: processingFiles });
1098
- },
1099
- onUpdate: async ({ file, source, processed, total, percentage }) => {
1100
- await hooks.emit("kubb:file:processing:update", {
1101
- file,
1102
- source,
1103
- processed,
1104
- total,
1105
- percentage,
1106
- config
1107
- });
1108
- if (source) {
1109
- await config.storage.setItem(file.path, source);
1110
- sources.set(file.path, source);
1111
- }
1112
- },
1113
- onEnd: async (processedFiles) => {
1114
- await hooks.emit("kubb:files:processing:end", { files: processedFiles });
1115
- await hooks.emit("kubb:debug", {
1116
- date: /* @__PURE__ */ new Date(),
1117
- logs: [`✓ File write process completed for ${processedFiles.length} files`]
1118
- });
1119
- }
1120
- });
1121
- await hooks.emit("kubb:build:end", {
1122
- files,
1123
- config,
1124
- outputDir: resolve(config.root, config.output.path)
1125
- });
1126
- return {
1127
- failedPlugins,
1128
- files,
1129
- driver,
1130
- pluginTimings,
1131
- sources
1132
- };
1133
- } catch (error) {
1134
- return {
1135
- failedPlugins,
1136
- files: [],
1137
- driver,
1138
- pluginTimings,
1139
- error,
1140
- sources
1141
- };
1142
- } finally {
1143
- driver.dispose();
1144
2098
  }
1145
- }
1146
- async function build(setupResult) {
1147
- const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult);
1148
- if (error) throw error;
1149
- if (failedPlugins.size > 0) {
1150
- const errors = [...failedPlugins].map(({ error }) => error);
1151
- throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors });
2099
+ dispose() {
2100
+ this.#driver?.dispose();
1152
2101
  }
1153
- return {
1154
- failedPlugins,
1155
- files,
1156
- driver,
1157
- pluginTimings,
1158
- error: void 0,
1159
- sources
1160
- };
1161
- }
1162
- /**
1163
- * Returns a snapshot of the current runtime environment.
1164
- *
1165
- * Useful for attaching context to debug logs and error reports so that
1166
- * issues can be reproduced without manual information gathering.
1167
- */
1168
- function getDiagnosticInfo() {
1169
- return {
1170
- nodeVersion: version,
1171
- KubbVersion: version$1,
1172
- platform: process.platform,
1173
- arch: process.arch,
1174
- cwd: process.cwd()
1175
- };
1176
- }
1177
- function isInputPath(config) {
1178
- return typeof config?.input === "object" && config.input !== null && "path" in config.input;
1179
- }
1180
- function inputToAdapterSource(config) {
1181
- const input = config.input;
1182
- if (!input) throw new Error("[kubb] input is required when using an adapter. Provide input.path or input.data in your config.");
1183
- if ("data" in input) return {
1184
- type: "data",
1185
- data: input.data
1186
- };
1187
- if (new URLPath(input.path).isURL) return {
1188
- type: "path",
1189
- path: input.path
1190
- };
1191
- return {
1192
- type: "path",
1193
- path: resolve(config.root, input.path)
1194
- };
1195
- }
2102
+ [Symbol.dispose]() {
2103
+ this.dispose();
2104
+ }
2105
+ };
1196
2106
  /**
1197
- * Creates a Kubb instance bound to a single config entry.
1198
- *
1199
- * Accepts a user-facing config shape and resolves it to a full {@link Config} during
1200
- * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
1201
- * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
1202
- * calling `setup()` or `build()`.
2107
+ * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent
2108
+ * to `new Kubb(userConfig, options)` and the canonical public entry point.
1203
2109
  *
1204
2110
  * @example
1205
2111
  * ```ts
1206
- * const kubb = createKubb(userConfig)
2112
+ * import { createKubb } from '@kubb/core'
2113
+ * import { adapterOas } from '@kubb/adapter-oas'
2114
+ * import { pluginTs } from '@kubb/plugin-ts'
1207
2115
  *
1208
- * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
1209
- * console.log(`${plugin.name} completed in ${duration}ms`)
2116
+ * const kubb = createKubb({
2117
+ * input: './petStore.yaml',
2118
+ * output: { path: './src/gen' },
2119
+ * adapter: adapterOas(),
2120
+ * plugins: [pluginTs()],
1210
2121
  * })
1211
2122
  *
1212
- * const { files, failedPlugins } = await kubb.safeBuild()
2123
+ * await kubb.build()
1213
2124
  * ```
1214
2125
  */
1215
2126
  function createKubb(userConfig, options = {}) {
1216
- const hooks = options.hooks ?? new AsyncEventEmitter();
1217
- let setupResult;
1218
- const instance = {
1219
- get hooks() {
1220
- return hooks;
1221
- },
1222
- get sources() {
1223
- return setupResult?.sources ?? /* @__PURE__ */ new Map();
1224
- },
1225
- get driver() {
1226
- return setupResult?.driver;
1227
- },
1228
- get config() {
1229
- return setupResult?.config;
1230
- },
1231
- async setup() {
1232
- setupResult = await setup(userConfig, { hooks });
1233
- },
1234
- async build() {
1235
- if (!setupResult) await instance.setup();
1236
- return build(setupResult);
1237
- },
1238
- async safeBuild() {
1239
- if (!setupResult) await instance.setup();
1240
- return safeBuild(setupResult);
1241
- }
1242
- };
1243
- return instance;
2127
+ return new Kubb(userConfig, options);
1244
2128
  }
1245
2129
  //#endregion
1246
- //#region src/createRenderer.ts
2130
+ //#region src/createReporter.ts
1247
2131
  /**
1248
- * Creates a renderer factory for use in generator definitions.
2132
+ * Numeric log-level thresholds used internally to compare verbosity.
1249
2133
  *
1250
- * Wrap your renderer factory function with this helper to register it as the
1251
- * renderer for a generator. Core will call this factory once per render cycle
1252
- * to obtain a fresh renderer instance.
2134
+ * Higher numbers are more verbose.
2135
+ */
2136
+ const logLevel = {
2137
+ silent: Number.NEGATIVE_INFINITY,
2138
+ error: 0,
2139
+ warn: 1,
2140
+ info: 3,
2141
+ verbose: 4
2142
+ };
2143
+ /**
2144
+ * Defines a reporter. When the definition has a `drain`, the returned reporter buffers each value
2145
+ * `report` returns and hands the array to `drain` once, then clears it. Without a `drain`, nothing
2146
+ * is buffered. Wiring the reporter onto the run's hooks is the host's job, so the reporter only
2147
+ * ever deals with a {@link GenerationResult}.
1253
2148
  *
1254
2149
  * @example
1255
2150
  * ```ts
1256
- * // packages/renderer-jsx/src/index.ts
1257
- * export const jsxRenderer = createRenderer(() => {
1258
- * const runtime = new Runtime()
1259
- * return {
1260
- * async render(element) { await runtime.render(element) },
1261
- * get files() { return runtime.nodes },
1262
- * unmount(error) { runtime.unmount(error) },
1263
- * }
1264
- * })
2151
+ * import { createReporter, Diagnostics } from '@kubb/core'
1265
2152
  *
1266
- * // packages/plugin-zod/src/generators/zodGenerator.tsx
1267
- * import { jsxRenderer } from '@kubb/renderer-jsx'
1268
- * export const zodGenerator = defineGenerator<PluginZod>({
1269
- * name: 'zod',
1270
- * renderer: jsxRenderer,
1271
- * schema(node, options) { return <File ...>...</File> },
2153
+ * export const jsonReporter = createReporter({
2154
+ * name: 'json',
2155
+ * report(result) {
2156
+ * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
2157
+ * },
2158
+ * drain(context, reports) {
2159
+ * process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
2160
+ * },
1272
2161
  * })
1273
2162
  * ```
1274
2163
  */
1275
- function createRenderer(factory) {
1276
- return factory;
2164
+ function createReporter(reporter) {
2165
+ const reports = /* @__PURE__ */ new Set();
2166
+ return {
2167
+ name: reporter.name,
2168
+ async report(result, context) {
2169
+ const report = await reporter.report(result, context);
2170
+ reports.add(report);
2171
+ },
2172
+ async drain(context) {
2173
+ await reporter.drain?.(context, Array.from(reports));
2174
+ reports.clear();
2175
+ },
2176
+ [Symbol.dispose]() {
2177
+ reports.clear();
2178
+ }
2179
+ };
1277
2180
  }
1278
2181
  //#endregion
1279
- //#region src/defineGenerator.ts
2182
+ //#region src/reporters/report.ts
1280
2183
  /**
1281
- * Defines a generator. Returns the object as-is with correct `this` typings.
1282
- * `applyHookResult` handles renderer elements and `File[]` uniformly using
1283
- * the generator's declared `renderer` factory.
2184
+ * Builds the normalized {@link Report} for one config from its {@link GenerationResult}. Splits the
2185
+ * diagnostics into problems and per-plugin timings (slowest first) and derives the plugin and issue
2186
+ * counts, so every reporter renders the same data.
1284
2187
  */
1285
- function defineGenerator(generator) {
1286
- return generator;
2188
+ function buildReport(result) {
2189
+ const { config, diagnostics, filesCreated, status, hrStart } = result;
2190
+ const failed = Diagnostics.failedPlugins(diagnostics);
2191
+ const total = config.plugins?.length ?? 0;
2192
+ const counts = Diagnostics.count(diagnostics);
2193
+ const problems = diagnostics.filter(Diagnostics.isProblem);
2194
+ const timings = diagnostics.filter(Diagnostics.isPerformance).sort((a, b) => b.duration - a.duration).map((diagnostic) => ({
2195
+ plugin: diagnostic.plugin,
2196
+ durationMs: diagnostic.duration
2197
+ }));
2198
+ return {
2199
+ name: config.name ?? "",
2200
+ status,
2201
+ plugins: {
2202
+ passed: total - failed.length,
2203
+ failed,
2204
+ total
2205
+ },
2206
+ counts,
2207
+ filesCreated,
2208
+ durationMs: getElapsedMs(hrStart),
2209
+ output: resolve(config.root, config.output.path),
2210
+ timings,
2211
+ diagnostics: problems.map((diagnostic) => Diagnostics.serialize(diagnostic))
2212
+ };
2213
+ }
2214
+ //#endregion
2215
+ //#region src/reporters/cliReporter.ts
2216
+ /**
2217
+ * Builds the vitest/jest-style summary for one {@link Report}: right-aligned dim labels with
2218
+ * `N passed (total)` counts, and a per-plugin `Timings` section when `showTimings`.
2219
+ */
2220
+ function buildSummaryLines(report, { showTimings }) {
2221
+ const { status, plugins, counts, filesCreated, durationMs, output, timings } = report;
2222
+ const rows = [];
2223
+ rows.push(["Plugins", status === "success" ? `${styleText("green", `${plugins.passed} passed`)} (${plugins.total})` : `${styleText("green", `${plugins.passed} passed`)} | ${styleText("red", `${plugins.failed.length} failed`)} (${plugins.total})`]);
2224
+ if (status === "failed" && plugins.failed.length > 0) rows.push(["Failed", plugins.failed.map((name) => randomCliColor(name)).join(", ")]);
2225
+ if (counts.errors > 0 || counts.warnings > 0) {
2226
+ const issues = [counts.errors > 0 ? styleText("red", `${counts.errors} ${counts.errors === 1 ? "error" : "errors"}`) : void 0, counts.warnings > 0 ? styleText("yellow", `${counts.warnings} ${counts.warnings === 1 ? "warning" : "warnings"}`) : void 0].filter(Boolean).join(" | ");
2227
+ rows.push(["Issues", issues]);
2228
+ }
2229
+ rows.push(["Files", `${styleText("green", String(filesCreated))} generated`]);
2230
+ rows.push(["Duration", styleText("green", formatMs(durationMs))]);
2231
+ rows.push(["Output", output]);
2232
+ const labelWidth = Math.max(...rows.map(([label]) => label.length), timings.length > 0 ? 7 : 0);
2233
+ const lines = rows.map(([label, value]) => `${styleText("dim", label.padStart(labelWidth))} ${value}`);
2234
+ if (showTimings && timings.length > 0) {
2235
+ const nameWidth = Math.max(0, ...timings.map((timing) => timing.plugin.length));
2236
+ const indent = " ".repeat(labelWidth + 2);
2237
+ lines.push(styleText("dim", "Timings".padStart(labelWidth)));
2238
+ for (const timing of timings) {
2239
+ const timeStr = formatMs(timing.durationMs);
2240
+ const barLength = Math.min(Math.ceil(timing.durationMs / 100), 10);
2241
+ const bar = styleText("dim", "█".repeat(barLength));
2242
+ lines.push(`${indent}${styleText("dim", "•")} ${timing.plugin.padEnd(nameWidth)} ${bar} ${timeStr}`);
2243
+ }
2244
+ }
2245
+ return lines;
2246
+ }
2247
+ /**
2248
+ * Renders the summary as plain `console.log` lines so it works in every CLI (no clack/TTY
2249
+ * dependency): a blank line, the config name colored by status, then the summary rows.
2250
+ */
2251
+ function renderSummary(lines, { title, status }) {
2252
+ console.log("");
2253
+ if (title) console.log(styleText(status === "failed" ? "red" : "green", title));
2254
+ for (const line of lines) console.log(line);
1287
2255
  }
2256
+ /**
2257
+ * The default `cli` reporter. Renders the {@link Report} for each config as it finishes, independent
2258
+ * of the live logger view. Suppressed at `silent`. The `verbose` level adds the per-plugin timings.
2259
+ */
2260
+ const cliReporter = createReporter({
2261
+ name: "cli",
2262
+ report(result, { logLevel: logLevel$1 }) {
2263
+ if (logLevel$1 <= logLevel.silent) return;
2264
+ const report = buildReport(result);
2265
+ renderSummary(buildSummaryLines(report, { showTimings: logLevel$1 >= logLevel.verbose }), {
2266
+ title: report.name,
2267
+ status: report.status
2268
+ });
2269
+ }
2270
+ });
1288
2271
  //#endregion
1289
- //#region src/defineLogger.ts
2272
+ //#region src/reporters/fileReporter.ts
2273
+ /**
2274
+ * Builds the `## Summary` section: the same counts the cli and json reporters expose, as a list of
2275
+ * `label value` rows with the labels padded to a common width.
2276
+ */
2277
+ function buildSummarySection(report) {
2278
+ const { status, plugins, counts, filesCreated, durationMs, output } = report;
2279
+ const rows = [["Status", status], ["Plugins", status === "success" ? `${plugins.passed} passed (${plugins.total})` : `${plugins.passed} passed | ${plugins.failed.length} failed (${plugins.total})`]];
2280
+ if (plugins.failed.length > 0) rows.push(["Failed", plugins.failed.join(", ")]);
2281
+ rows.push(["Issues", `${counts.errors} errors | ${counts.warnings} warnings | ${counts.infos} infos`]);
2282
+ rows.push(["Files", `${filesCreated} generated`]);
2283
+ rows.push(["Duration", formatMs(durationMs)]);
2284
+ rows.push(["Output", output]);
2285
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
2286
+ return [
2287
+ "## Summary",
2288
+ "",
2289
+ ...rows.map(([label, value]) => ` ${label.padEnd(labelWidth)} ${value}`)
2290
+ ];
2291
+ }
2292
+ /**
2293
+ * Builds the `## Problems` section: each problem rendered in the miette block format, blocks
2294
+ * separated by a blank line. Returns an empty array when there are no problems, so the caller
2295
+ * can drop the heading.
2296
+ */
2297
+ function buildProblemSection(diagnostics) {
2298
+ const problems = diagnostics.filter(Diagnostics.isProblem);
2299
+ if (problems.length === 0) return [];
2300
+ return [
2301
+ "## Problems",
2302
+ "",
2303
+ problems.map((diagnostic) => Diagnostics.formatLines(diagnostic).join("\n")).join("\n\n")
2304
+ ];
2305
+ }
1290
2306
  /**
1291
- * Wraps a logger definition into a typed {@link Logger}.
2307
+ * Builds the `## Timings` section from a {@link Report}: one `plugin duration` row per record,
2308
+ * slowest first with the plugin names left-aligned and the durations right-aligned. Returns an
2309
+ * empty array when there are no timings.
2310
+ */
2311
+ function buildTimingSection(report) {
2312
+ const { timings } = report;
2313
+ if (timings.length === 0) return [];
2314
+ const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length));
2315
+ const durations = timings.map((timing) => formatMs(timing.durationMs));
2316
+ const durationWidth = Math.max(...durations.map((duration) => duration.length));
2317
+ return [
2318
+ "## Timings",
2319
+ "",
2320
+ ...timings.map((timing, index) => ` ${timing.plugin.padEnd(nameWidth)} ${durations[index].padStart(durationWidth)}`)
2321
+ ];
2322
+ }
2323
+ /**
2324
+ * The `file` reporter. Writes a config's {@link Report} to `.kubb/kubb-<name>-<timestamp>.log` as a
2325
+ * plain-text document: a `# <name> — <timestamp>` header, a `## Summary` with the same counts the
2326
+ * cli and json reporters expose, a `## Problems` section in the miette block format, and a
2327
+ * `## Timings` section. Selected with `--reporter file` (or `reporters: ['file']`).
1292
2328
  *
1293
- * The optional second type parameter `TInstallReturn` allows loggers to return
1294
- * a value from `install` for example, a sink factory that the caller can
1295
- * forward to hook execution.
2329
+ * @note It captures the collected diagnostics once a config finishes, not the live
2330
+ * `kubb:info`/`kubb:plugin` hook stream. Color is stripped so the file stays plain text even when
2331
+ * the run is attached to a TTY.
2332
+ */
2333
+ const fileReporter = createReporter({
2334
+ name: "file",
2335
+ async report(result) {
2336
+ const { diagnostics, config } = result;
2337
+ if (diagnostics.length === 0) return;
2338
+ const report = buildReport(result);
2339
+ const content = stripVTControlCharacters([config.name ? `# ${config.name} — ${(/* @__PURE__ */ new Date()).toISOString()}` : `# ${(/* @__PURE__ */ new Date()).toISOString()}`, ...[
2340
+ buildSummarySection(report),
2341
+ buildProblemSection(diagnostics),
2342
+ buildTimingSection(report)
2343
+ ].filter((section) => section.length > 0).map((section) => section.join("\n"))].join("\n\n"));
2344
+ const baseName = `${[
2345
+ "kubb",
2346
+ config.name,
2347
+ Date.now()
2348
+ ].filter(Boolean).join("-")}.log`;
2349
+ const pathName = resolve(process$1.cwd(), ".kubb", baseName);
2350
+ await write(pathName, `${content}\n`);
2351
+ console.error(`Debug log written to ${relative(process$1.cwd(), pathName)}`);
2352
+ }
2353
+ });
2354
+ //#endregion
2355
+ //#region src/reporters/jsonReporter.ts
2356
+ /**
2357
+ * The `json` reporter. `report` returns one config's {@link Report}, which {@link createReporter}
2358
+ * buffers, and `drain` writes them as a single pretty-printed JSON array on `kubb:lifecycle:end`.
2359
+ * Buffering keeps a multi-config run one valid JSON document on stdout instead of concatenated
2360
+ * objects that would break `jq .`. The terminal reporter is suppressed while `json` is active so
2361
+ * stdout stays valid JSON.
2362
+ */
2363
+ const jsonReporter = createReporter({
2364
+ name: "json",
2365
+ report(result) {
2366
+ return buildReport(result);
2367
+ },
2368
+ drain(_context, reports) {
2369
+ process$1.stdout.write(`${JSON.stringify(reports, null, 2)}\n`);
2370
+ }
2371
+ });
2372
+ //#endregion
2373
+ //#region src/createRenderer.ts
2374
+ /**
2375
+ * Defines a renderer factory. Renderers turn the generator's return value
2376
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
2377
+ * written to disk.
1296
2378
  *
1297
- * @example Basic logger
1298
- * ```ts
1299
- * export const myLogger = defineLogger({
1300
- * name: 'my-logger',
1301
- * install(context, options) {
1302
- * context.on('kubb:info', (message) => console.log('ℹ', message))
1303
- * context.on('kubb:error', (error) => console.error('✗', error.message))
1304
- * },
1305
- * })
1306
- * ```
2379
+ * A renderer can target output formats beyond JSX, for instance a Handlebars
2380
+ * renderer or one that writes binary files. Plugins and generators pick the
2381
+ * renderer to use via the `renderer` field on `defineGenerator`.
1307
2382
  *
1308
- * @example Logger that returns a hook sink factory
2383
+ * @example A minimal renderer that wraps a custom runtime
1309
2384
  * ```ts
1310
- * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({
1311
- * name: 'my-logger',
1312
- * install(context, options) {
1313
- * // register event handlers …
1314
- * return (commandWithArgs) => ({ onStdout: console.log })
1315
- * },
2385
+ * import { createRenderer } from '@kubb/core'
2386
+ *
2387
+ * export const myRenderer = createRenderer(() => {
2388
+ * const runtime = new MyRuntime()
2389
+ * return {
2390
+ * async render(element) {
2391
+ * await runtime.render(element)
2392
+ * },
2393
+ * get files() {
2394
+ * return runtime.files
2395
+ * },
2396
+ * [Symbol.dispose]() {
2397
+ * runtime.dispose()
2398
+ * },
2399
+ * }
1316
2400
  * })
1317
2401
  * ```
1318
2402
  */
1319
- function defineLogger(logger) {
1320
- return logger;
2403
+ function createRenderer(factory) {
2404
+ return factory;
1321
2405
  }
1322
2406
  //#endregion
1323
- //#region src/defineMiddleware.ts
2407
+ //#region src/defineGenerator.ts
1324
2408
  /**
1325
- * Creates a middleware factory using the hook-style `hooks` API.
1326
- *
1327
- * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.
1328
- * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
2409
+ * Defines a generator: a unit of work that runs during the plugin's AST walk
2410
+ * and produces files. Plugins register generators via `ctx.addGenerator()`
2411
+ * inside `kubb:plugin:setup`.
1329
2412
  *
1330
- * @note The factory can accept typed options. See examples for using options and per-build state patterns.
2413
+ * The returned object is the input as-is, but with `this` types preserved so
2414
+ * `schema`/`operation`/`operations` methods are correctly typed against the
2415
+ * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
2416
+ * are both handled by the runtime, so pick whichever style fits.
1331
2417
  *
1332
- * @example
1333
- * ```ts
1334
- * import { defineMiddleware } from '@kubb/core'
2418
+ * @example JSX-based schema generator
2419
+ * ```tsx
2420
+ * import { defineGenerator } from '@kubb/core'
2421
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1335
2422
  *
1336
- * // Stateless middleware
1337
- * export const logMiddleware = defineMiddleware(() => ({
1338
- * name: 'log-middleware',
1339
- * hooks: {
1340
- * 'kubb:build:end'({ files }) {
1341
- * console.log(`Build complete with ${files.length} files`)
1342
- * },
2423
+ * export const typeGenerator = defineGenerator({
2424
+ * name: 'typescript',
2425
+ * renderer: jsxRenderer,
2426
+ * schema(node, ctx) {
2427
+ * return (
2428
+ * <File path={`${ctx.root}/${node.name}.ts`}>
2429
+ * <Type node={node} resolver={ctx.resolver} />
2430
+ * </File>
2431
+ * )
1343
2432
  * },
1344
- * }))
1345
- *
1346
- * // Middleware with options and per-build state
1347
- * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
1348
- * const seen = new Set<string>()
1349
- * return {
1350
- * name: 'prefix-middleware',
1351
- * hooks: {
1352
- * 'kubb:plugin:end'({ plugin }) {
1353
- * seen.add(`${options.prefix}${plugin.name}`)
1354
- * },
1355
- * },
1356
- * }
1357
2433
  * })
1358
2434
  * ```
1359
2435
  */
1360
- function defineMiddleware(factory) {
1361
- return (options) => factory(options ?? {});
2436
+ function defineGenerator(generator) {
2437
+ return generator;
1362
2438
  }
1363
2439
  //#endregion
1364
2440
  //#region src/defineParser.ts
1365
2441
  /**
1366
- * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.
2442
+ * Wraps a parser factory and returns a function that accepts user options and
2443
+ * yields a typed {@link Parser}. Mirrors {@link definePlugin}: the factory
2444
+ * receives the caller's options, and calling the returned function without
2445
+ * options passes an empty object.
1367
2446
  *
1368
- * @note Call the returned factory with optional options to instantiate the parser.
2447
+ * Register the result in the `parsers` array on `defineConfig`, calling it to
2448
+ * apply options (`parserTs({ extension: { '.ts': '.js' } })`).
1369
2449
  *
1370
2450
  * @example
1371
2451
  * ```ts
1372
2452
  * import { defineParser } from '@kubb/core'
2453
+ * import { extractStringsFromNodes } from '@kubb/ast'
1373
2454
  *
1374
- * export const jsonParser = defineParser({
2455
+ * export const parserJson = defineParser((options: { pretty?: boolean } = {}) => ({
1375
2456
  * name: 'json',
1376
2457
  * extNames: ['.json'],
1377
2458
  * parse(file) {
1378
- * const { extractStringsFromNodes } = await import('@kubb/ast')
1379
- * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
2459
+ * const source = file.sources.map((source) => extractStringsFromNodes(source.nodes ?? [])).join('\n')
2460
+ * return options.pretty ? JSON.stringify(JSON.parse(source), null, 2) : source
1380
2461
  * },
1381
- * })
2462
+ * print(...nodes) {
2463
+ * return nodes.map(String).join('\n')
2464
+ * },
2465
+ * }))
1382
2466
  * ```
1383
2467
  */
1384
- function defineParser(parser) {
1385
- return parser;
2468
+ function defineParser(factory) {
2469
+ return (options) => factory(options ?? {});
1386
2470
  }
1387
2471
  //#endregion
1388
2472
  //#region src/storages/memoryStorage.ts
@@ -1399,7 +2483,7 @@ function defineParser(parser) {
1399
2483
  * import { defineConfig } from 'kubb'
1400
2484
  *
1401
2485
  * export default defineConfig({
1402
- * input: { path: './petStore.yaml' },
2486
+ * input: './petStore.yaml',
1403
2487
  * output: { path: './src/gen' },
1404
2488
  * storage: memoryStorage(),
1405
2489
  * })
@@ -1435,6 +2519,6 @@ const memoryStorage = createStorage(() => {
1435
2519
  };
1436
2520
  });
1437
2521
  //#endregion
1438
- export { AsyncEventEmitter, FileManager, FileProcessor, PluginDriver, URLPath, ast, createAdapter, createKubb, createRenderer, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fsStorage, isInputPath, logLevel, memoryStorage };
2522
+ export { Diagnostics, Hookable, KubbDriver, Resolver, applyConfigDefaults, cliReporter, createAdapter, createKubb, createRenderer, createReporter, createResolver, createStorage, defineGenerator, defineParser, definePlugin, fileReporter, fsStorage, getInputKind, jsonReporter, logLevel, memoryStorage };
1439
2523
 
1440
2524
  //# sourceMappingURL=index.js.map