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

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