@kubb/core 5.6.2 → 5.6.3

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