@kubb/core 5.0.0-beta.4 → 5.0.0-beta.41

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