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