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

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