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

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