@kubb/core 5.0.0-beta.2 → 5.0.0-beta.21

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 (45) hide show
  1. package/README.md +8 -38
  2. package/dist/KubbDriver-BBRa5CH2.cjs +2231 -0
  3. package/dist/KubbDriver-BBRa5CH2.cjs.map +1 -0
  4. package/dist/KubbDriver-Cq1isv2P.js +2110 -0
  5. package/dist/KubbDriver-Cq1isv2P.js.map +1 -0
  6. package/dist/{types-CC09VtBt.d.ts → createKubb-CYrw_xaR.d.ts} +1414 -1255
  7. package/dist/index.cjs +221 -1074
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +2 -185
  10. package/dist/index.js +211 -1068
  11. package/dist/index.js.map +1 -1
  12. package/dist/mocks.cjs +30 -21
  13. package/dist/mocks.cjs.map +1 -1
  14. package/dist/mocks.d.ts +5 -5
  15. package/dist/mocks.js +29 -20
  16. package/dist/mocks.js.map +1 -1
  17. package/package.json +6 -18
  18. package/src/FileManager.ts +75 -58
  19. package/src/FileProcessor.ts +48 -38
  20. package/src/KubbDriver.ts +915 -0
  21. package/src/constants.ts +11 -6
  22. package/src/createAdapter.ts +84 -1
  23. package/src/createKubb.ts +1022 -485
  24. package/src/createRenderer.ts +33 -22
  25. package/src/defineGenerator.ts +96 -7
  26. package/src/defineLogger.ts +42 -3
  27. package/src/defineMiddleware.ts +1 -1
  28. package/src/defineParser.ts +1 -1
  29. package/src/definePlugin.ts +304 -8
  30. package/src/defineResolver.ts +271 -150
  31. package/src/devtools.ts +8 -1
  32. package/src/index.ts +2 -2
  33. package/src/mocks.ts +11 -14
  34. package/src/storages/fsStorage.ts +13 -37
  35. package/src/types.ts +39 -1292
  36. package/dist/PluginDriver-BXibeQk-.cjs +0 -1036
  37. package/dist/PluginDriver-BXibeQk-.cjs.map +0 -1
  38. package/dist/PluginDriver-DV3p2Hky.js +0 -945
  39. package/dist/PluginDriver-DV3p2Hky.js.map +0 -1
  40. package/src/Kubb.ts +0 -300
  41. package/src/PluginDriver.ts +0 -424
  42. package/src/renderNode.ts +0 -35
  43. package/src/utils/diagnostics.ts +0 -18
  44. package/src/utils/isInputPath.ts +0 -10
  45. package/src/utils/packageJSON.ts +0 -99
@@ -0,0 +1,2231 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __name = (target, value) => __defProp(target, "name", {
5
+ value,
6
+ configurable: true
7
+ });
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let node_events = require("node:events");
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path, 1);
30
+ let _kubb_ast = require("@kubb/ast");
31
+ let fflate = require("fflate");
32
+ let tinyexec = require("tinyexec");
33
+ //#region ../../internals/utils/src/errors.ts
34
+ /**
35
+ * Thrown when one or more errors occur during a Kubb build.
36
+ * Carries the full list of underlying errors on `errors`.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * throw new BuildError('Build failed', { errors: [err1, err2] })
41
+ * ```
42
+ */
43
+ var BuildError = class extends Error {
44
+ errors;
45
+ constructor(message, options) {
46
+ super(message, { cause: options.cause });
47
+ this.name = "BuildError";
48
+ this.errors = options.errors;
49
+ }
50
+ };
51
+ /**
52
+ * Coerces an unknown thrown value to an `Error` instance.
53
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * try { ... } catch(err) {
58
+ * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
59
+ * }
60
+ * ```
61
+ */
62
+ function toError(value) {
63
+ return value instanceof Error ? value : new Error(String(value));
64
+ }
65
+ //#endregion
66
+ //#region ../../internals/utils/src/asyncEventEmitter.ts
67
+ /**
68
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
69
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
74
+ * emitter.on('build', async (name) => { console.log(name) })
75
+ * await emitter.emit('build', 'petstore') // all listeners awaited
76
+ * ```
77
+ */
78
+ var AsyncEventEmitter = class {
79
+ /**
80
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
81
+ * @default 10
82
+ */
83
+ constructor(maxListener = 10) {
84
+ this.#emitter.setMaxListeners(maxListener);
85
+ }
86
+ #emitter = new node_events.EventEmitter();
87
+ /**
88
+ * Emits `eventName` and awaits all registered listeners sequentially.
89
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * await emitter.emit('build', 'petstore')
94
+ * ```
95
+ */
96
+ emit(eventName, ...eventArgs) {
97
+ const listeners = this.#emitter.listeners(eventName);
98
+ if (listeners.length === 0) return;
99
+ return this.#emitAll(eventName, listeners, eventArgs);
100
+ }
101
+ async #emitAll(eventName, listeners, eventArgs) {
102
+ for (const listener of listeners) try {
103
+ await listener(...eventArgs);
104
+ } catch (err) {
105
+ let serializedArgs;
106
+ try {
107
+ serializedArgs = JSON.stringify(eventArgs);
108
+ } catch {
109
+ serializedArgs = String(eventArgs);
110
+ }
111
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
112
+ }
113
+ }
114
+ /**
115
+ * Registers a persistent listener for `eventName`.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * emitter.on('build', async (name) => { console.log(name) })
120
+ * ```
121
+ */
122
+ on(eventName, handler) {
123
+ this.#emitter.on(eventName, handler);
124
+ }
125
+ /**
126
+ * Registers a one-shot listener that removes itself after the first invocation.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * emitter.onOnce('build', async (name) => { console.log(name) })
131
+ * ```
132
+ */
133
+ onOnce(eventName, handler) {
134
+ const wrapper = (...args) => {
135
+ this.off(eventName, wrapper);
136
+ return handler(...args);
137
+ };
138
+ this.on(eventName, wrapper);
139
+ }
140
+ /**
141
+ * Removes a previously registered listener.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * emitter.off('build', handler)
146
+ * ```
147
+ */
148
+ off(eventName, handler) {
149
+ this.#emitter.off(eventName, handler);
150
+ }
151
+ /**
152
+ * Returns the number of listeners registered for `eventName`.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * emitter.on('build', handler)
157
+ * emitter.listenerCount('build') // 1
158
+ * ```
159
+ */
160
+ listenerCount(eventName) {
161
+ return this.#emitter.listenerCount(eventName);
162
+ }
163
+ /**
164
+ * Removes all listeners from every event channel.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * emitter.removeAll()
169
+ * ```
170
+ */
171
+ removeAll() {
172
+ this.#emitter.removeAllListeners();
173
+ }
174
+ };
175
+ //#endregion
176
+ //#region ../../internals/utils/src/casing.ts
177
+ /**
178
+ * Shared implementation for camelCase and PascalCase conversion.
179
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
180
+ * and capitalizes each word according to `pascal`.
181
+ *
182
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
183
+ */
184
+ function toCamelOrPascal(text, pascal) {
185
+ 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) => {
186
+ if (word.length > 1 && word === word.toUpperCase()) return word;
187
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
188
+ return word.charAt(0).toUpperCase() + word.slice(1);
189
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
190
+ }
191
+ /**
192
+ * Splits `text` on `.` and applies `transformPart` to each segment.
193
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
194
+ * Segments are joined with `/` to form a file path.
195
+ *
196
+ * Only splits on dots followed by a letter so that version numbers
197
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
198
+ *
199
+ * Empty segments are filtered before joining. They arise when the text starts with
200
+ * a dot followed immediately by a letter (e.g. `..Schema` splits into `['..', 'Schema']`
201
+ * and `'..'` transforms to an empty string). Without this filter the join would produce
202
+ * a leading `/`, which `path.resolve` would interpret as an absolute path, allowing
203
+ * generated files to escape the configured output directory.
204
+ */
205
+ function applyToFileParts(text, transformPart) {
206
+ const parts = text.split(/\.(?=[a-zA-Z])/);
207
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).filter(Boolean).join("/");
208
+ }
209
+ /**
210
+ * Converts `text` to camelCase.
211
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
212
+ *
213
+ * @example
214
+ * camelCase('hello-world') // 'helloWorld'
215
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
216
+ */
217
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
218
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
219
+ prefix,
220
+ suffix
221
+ } : {}));
222
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
223
+ }
224
+ /**
225
+ * Converts `text` to PascalCase.
226
+ * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
227
+ *
228
+ * @example
229
+ * pascalCase('hello-world') // 'HelloWorld'
230
+ * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
231
+ */
232
+ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
233
+ if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
234
+ prefix,
235
+ suffix
236
+ }) : camelCase(part));
237
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
238
+ }
239
+ //#endregion
240
+ //#region ../../internals/utils/src/time.ts
241
+ /**
242
+ * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
243
+ * Rounds to 2 decimal places for sub-millisecond precision without noise.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * const start = process.hrtime()
248
+ * doWork()
249
+ * getElapsedMs(start) // 42.35
250
+ * ```
251
+ */
252
+ function getElapsedMs(hrStart) {
253
+ const [seconds, nanoseconds] = process.hrtime(hrStart);
254
+ const ms = seconds * 1e3 + nanoseconds / 1e6;
255
+ return Math.round(ms * 100) / 100;
256
+ }
257
+ /**
258
+ * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * formatMs(250) // '250ms'
263
+ * formatMs(1500) // '1.50s'
264
+ * formatMs(90000) // '1m 30.0s'
265
+ * ```
266
+ */
267
+ function formatMs(ms) {
268
+ if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
269
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
270
+ return `${Math.round(ms)}ms`;
271
+ }
272
+ //#endregion
273
+ //#region ../../internals/utils/src/promise.ts
274
+ function* chunks(arr, size) {
275
+ for (let i = 0; i < arr.length; i += size) yield arr.slice(i, i + size);
276
+ }
277
+ /**
278
+ * Slices `source` into batches of `concurrency` items and awaits `process` for each batch.
279
+ * Accepts both plain arrays (sync) and `AsyncIterable` (streaming).
280
+ *
281
+ * `process` controls whether items inside a batch run in parallel; this helper only
282
+ * controls batch size and per-batch flushing.
283
+ *
284
+ * @example
285
+ * ```ts
286
+ * // parallel dispatch inside each batch
287
+ * await forBatches(schemas, (batch) => Promise.all(batch.map(process)), { concurrency: 8 })
288
+ *
289
+ * // async iterable with a flush after every batch
290
+ * await forBatches(stream.schemas, (batch) => dispatch(batch), { concurrency: 8, flush })
291
+ * ```
292
+ */
293
+ async function forBatches(source, process, options) {
294
+ const { concurrency, flush } = options;
295
+ if (Array.isArray(source)) {
296
+ for (const batch of chunks(source, concurrency)) {
297
+ await process(batch);
298
+ if (flush) await flush();
299
+ }
300
+ return;
301
+ }
302
+ const batch = [];
303
+ for await (const item of source) {
304
+ batch.push(item);
305
+ if (batch.length >= concurrency) {
306
+ await process(batch.splice(0));
307
+ if (flush) await flush();
308
+ }
309
+ }
310
+ if (batch.length > 0) {
311
+ await process(batch.splice(0));
312
+ if (flush) await flush();
313
+ }
314
+ }
315
+ /** Returns `true` when `result` is a thenable `Promise`.
316
+ *
317
+ * @example
318
+ * ```ts
319
+ * isPromise(Promise.resolve(1)) // true
320
+ * isPromise(42) // false
321
+ * ```
322
+ */
323
+ function isPromise(result) {
324
+ return result !== null && result !== void 0 && typeof result["then"] === "function";
325
+ }
326
+ /**
327
+ * Wraps `factory` with a keyed cache backed by the provided store.
328
+ *
329
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
330
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
331
+ * nest two `memoize` calls — the outer keyed by the first argument, the
332
+ * inner (created once per outer miss) keyed by the second.
333
+ *
334
+ * Because the cache is owned by the caller, it can be shared, inspected, or
335
+ * cleared independently of the memoized function.
336
+ *
337
+ * @example Single WeakMap key
338
+ * ```ts
339
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
340
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
341
+ * ```
342
+ *
343
+ * @example Single Map key (primitive)
344
+ * ```ts
345
+ * const cache = new Map<string, Resolver>()
346
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
347
+ * ```
348
+ *
349
+ * @example Two-level (object + primitive)
350
+ * ```ts
351
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
352
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
353
+ * fn(params)('camelcase')
354
+ * ```
355
+ */
356
+ function memoize(store, factory) {
357
+ return (key) => {
358
+ if (store.has(key)) return store.get(key);
359
+ const value = factory(key);
360
+ store.set(key, value);
361
+ return value;
362
+ };
363
+ }
364
+ /**
365
+ * Wraps a plain array in a reusable `AsyncIterable`.
366
+ * Each `[Symbol.asyncIterator]()` call returns a fresh generator so the
367
+ * iterable can be consumed multiple times (e.g. once per plugin pre-scan).
368
+ *
369
+ * @example
370
+ * ```ts
371
+ * const stream = arrayToAsyncIterable([1, 2, 3])
372
+ * for await (const n of stream) console.log(n) // 1, 2, 3
373
+ * ```
374
+ */
375
+ function arrayToAsyncIterable(arr) {
376
+ return { [Symbol.asyncIterator]() {
377
+ return (async function* () {
378
+ yield* arr;
379
+ })();
380
+ } };
381
+ }
382
+ //#endregion
383
+ //#region ../../internals/utils/src/reserved.ts
384
+ /**
385
+ * JavaScript and Java reserved words.
386
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
387
+ */
388
+ const reservedWords = new Set([
389
+ "abstract",
390
+ "arguments",
391
+ "boolean",
392
+ "break",
393
+ "byte",
394
+ "case",
395
+ "catch",
396
+ "char",
397
+ "class",
398
+ "const",
399
+ "continue",
400
+ "debugger",
401
+ "default",
402
+ "delete",
403
+ "do",
404
+ "double",
405
+ "else",
406
+ "enum",
407
+ "eval",
408
+ "export",
409
+ "extends",
410
+ "false",
411
+ "final",
412
+ "finally",
413
+ "float",
414
+ "for",
415
+ "function",
416
+ "goto",
417
+ "if",
418
+ "implements",
419
+ "import",
420
+ "in",
421
+ "instanceof",
422
+ "int",
423
+ "interface",
424
+ "let",
425
+ "long",
426
+ "native",
427
+ "new",
428
+ "null",
429
+ "package",
430
+ "private",
431
+ "protected",
432
+ "public",
433
+ "return",
434
+ "short",
435
+ "static",
436
+ "super",
437
+ "switch",
438
+ "synchronized",
439
+ "this",
440
+ "throw",
441
+ "throws",
442
+ "transient",
443
+ "true",
444
+ "try",
445
+ "typeof",
446
+ "var",
447
+ "void",
448
+ "volatile",
449
+ "while",
450
+ "with",
451
+ "yield",
452
+ "Array",
453
+ "Date",
454
+ "hasOwnProperty",
455
+ "Infinity",
456
+ "isFinite",
457
+ "isNaN",
458
+ "isPrototypeOf",
459
+ "length",
460
+ "Math",
461
+ "name",
462
+ "NaN",
463
+ "Number",
464
+ "Object",
465
+ "prototype",
466
+ "String",
467
+ "toString",
468
+ "undefined",
469
+ "valueOf"
470
+ ]);
471
+ /**
472
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
473
+ *
474
+ * @example
475
+ * ```ts
476
+ * isValidVarName('status') // true
477
+ * isValidVarName('class') // false (reserved word)
478
+ * isValidVarName('42foo') // false (starts with digit)
479
+ * ```
480
+ */
481
+ function isValidVarName(name) {
482
+ if (!name || reservedWords.has(name)) return false;
483
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
484
+ }
485
+ //#endregion
486
+ //#region ../../internals/utils/src/urlPath.ts
487
+ /**
488
+ * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
489
+ *
490
+ * @example
491
+ * const p = new URLPath('/pet/{petId}')
492
+ * p.URL // '/pet/:petId'
493
+ * p.template // '`/pet/${petId}`'
494
+ */
495
+ var URLPath = class {
496
+ /**
497
+ * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.
498
+ */
499
+ path;
500
+ #options;
501
+ constructor(path, options = {}) {
502
+ this.path = path;
503
+ this.#options = options;
504
+ }
505
+ /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.
506
+ *
507
+ * @example
508
+ * ```ts
509
+ * new URLPath('/pet/{petId}').URL // '/pet/:petId'
510
+ * ```
511
+ */
512
+ get URL() {
513
+ return this.toURLPath();
514
+ }
515
+ /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).
516
+ *
517
+ * @example
518
+ * ```ts
519
+ * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
520
+ * new URLPath('/pet/{petId}').isURL // false
521
+ * ```
522
+ */
523
+ get isURL() {
524
+ try {
525
+ return !!new URL(this.path).href;
526
+ } catch {
527
+ return false;
528
+ }
529
+ }
530
+ /**
531
+ * Converts the OpenAPI path to a TypeScript template literal string.
532
+ *
533
+ * @example
534
+ * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
535
+ * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
536
+ */
537
+ get template() {
538
+ return this.toTemplateString();
539
+ }
540
+ /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.
541
+ *
542
+ * @example
543
+ * ```ts
544
+ * new URLPath('/pet/{petId}').object
545
+ * // { url: '/pet/:petId', params: { petId: 'petId' } }
546
+ * ```
547
+ */
548
+ get object() {
549
+ return this.toObject();
550
+ }
551
+ /** Returns a map of path parameter names, or `undefined` when the path has no parameters.
552
+ *
553
+ * @example
554
+ * ```ts
555
+ * new URLPath('/pet/{petId}').params // { petId: 'petId' }
556
+ * new URLPath('/pet').params // undefined
557
+ * ```
558
+ */
559
+ get params() {
560
+ return this.getParams();
561
+ }
562
+ #transformParam(raw) {
563
+ const param = isValidVarName(raw) ? raw : camelCase(raw);
564
+ return this.#options.casing === "camelcase" ? camelCase(param) : param;
565
+ }
566
+ /**
567
+ * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.
568
+ */
569
+ #eachParam(fn) {
570
+ for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
571
+ const raw = match[1];
572
+ fn(raw, this.#transformParam(raw));
573
+ }
574
+ }
575
+ toObject({ type = "path", replacer, stringify } = {}) {
576
+ const object = {
577
+ url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
578
+ params: this.getParams()
579
+ };
580
+ if (stringify) {
581
+ if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
582
+ if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
583
+ return `{ url: '${object.url}' }`;
584
+ }
585
+ return object;
586
+ }
587
+ /**
588
+ * Converts the OpenAPI path to a TypeScript template literal string.
589
+ * An optional `replacer` can transform each extracted parameter name before interpolation.
590
+ *
591
+ * @example
592
+ * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
593
+ */
594
+ toTemplateString({ prefix = "", replacer } = {}) {
595
+ return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
596
+ if (i % 2 === 0) return part;
597
+ const param = this.#transformParam(part);
598
+ return `\${${replacer ? replacer(param) : param}}`;
599
+ }).join("")}\``;
600
+ }
601
+ /**
602
+ * Extracts all `{param}` segments from the path and returns them as a key-value map.
603
+ * An optional `replacer` transforms each parameter name in both key and value positions.
604
+ * Returns `undefined` when no path parameters are found.
605
+ *
606
+ * @example
607
+ * ```ts
608
+ * new URLPath('/pet/{petId}/tag/{tagId}').getParams()
609
+ * // { petId: 'petId', tagId: 'tagId' }
610
+ * ```
611
+ */
612
+ getParams(replacer) {
613
+ const params = {};
614
+ this.#eachParam((_raw, param) => {
615
+ const key = replacer ? replacer(param) : param;
616
+ params[key] = key;
617
+ });
618
+ return Object.keys(params).length > 0 ? params : void 0;
619
+ }
620
+ /** Converts the OpenAPI path to Express-style colon syntax.
621
+ *
622
+ * @example
623
+ * ```ts
624
+ * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'
625
+ * ```
626
+ */
627
+ toURLPath() {
628
+ return this.path.replace(/\{([^}]+)\}/g, ":$1");
629
+ }
630
+ };
631
+ //#endregion
632
+ //#region src/constants.ts
633
+ /**
634
+ * Base URL for the Kubb Studio web app.
635
+ */
636
+ const DEFAULT_STUDIO_URL = "https://kubb.studio";
637
+ /**
638
+ * Default banner style written at the top of every generated file.
639
+ */
640
+ const DEFAULT_BANNER = "simple";
641
+ /**
642
+ * Default file-extension mapping used when no explicit mapping is configured.
643
+ */
644
+ const DEFAULT_EXTENSION = { ".ts": ".ts" };
645
+ /**
646
+ * Numeric log-level thresholds used internally to compare verbosity.
647
+ *
648
+ * Higher numbers are more verbose.
649
+ */
650
+ const logLevel = {
651
+ silent: Number.NEGATIVE_INFINITY,
652
+ error: 0,
653
+ warn: 1,
654
+ info: 3,
655
+ verbose: 4,
656
+ debug: 5
657
+ };
658
+ //#endregion
659
+ //#region src/definePlugin.ts
660
+ /**
661
+ * Wraps a factory function and returns a typed `Plugin` with lifecycle handlers grouped under `hooks`.
662
+ *
663
+ * Handlers live in a single `hooks` object (inspired by Astro integrations).
664
+ * All lifecycle events from `KubbHooks` are available for subscription.
665
+ *
666
+ * @note For real plugins, use a `PluginFactoryOptions` type parameter to get type-safe context in `kubb:plugin:setup`.
667
+ * Plugin names should follow the convention `plugin-<feature>` (e.g., `plugin-react-query`, `plugin-zod`).
668
+ *
669
+ * @example
670
+ * ```ts
671
+ * import { definePlugin } from '@kubb/core'
672
+ *
673
+ * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
674
+ * name: 'plugin-ts',
675
+ * hooks: {
676
+ * 'kubb:plugin:setup'(ctx) {
677
+ * ctx.setResolver(resolverTs)
678
+ * },
679
+ * },
680
+ * }))
681
+ * ```
682
+ */
683
+ function definePlugin(factory) {
684
+ return (options) => factory(options ?? {});
685
+ }
686
+ /**
687
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
688
+ * Used to determine whether an output path targets a single file or a directory.
689
+ */
690
+ function getMode(fileOrFolder) {
691
+ if (!fileOrFolder) return "split";
692
+ return (0, node_path.extname)(fileOrFolder) ? "single" : "split";
693
+ }
694
+ //#endregion
695
+ //#region src/defineResolver.ts
696
+ const stringPatternCache = /* @__PURE__ */ new Map();
697
+ function testPattern(value, pattern) {
698
+ if (typeof pattern === "string") {
699
+ let regex = stringPatternCache.get(pattern);
700
+ if (!regex) {
701
+ regex = new RegExp(pattern);
702
+ stringPatternCache.set(pattern, regex);
703
+ }
704
+ return regex.test(value);
705
+ }
706
+ return value.match(pattern) !== null;
707
+ }
708
+ /**
709
+ * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).
710
+ */
711
+ function matchesOperationPattern(node, type, pattern) {
712
+ if (type === "tag") return node.tags.some((tag) => testPattern(tag, pattern));
713
+ if (type === "operationId") return testPattern(node.operationId, pattern);
714
+ if (type === "path") return testPattern(node.path, pattern);
715
+ if (type === "method") return testPattern(node.method.toLowerCase(), pattern);
716
+ if (type === "contentType") return node.requestBody?.content?.some((c) => testPattern(c.contentType, pattern)) ?? false;
717
+ return false;
718
+ }
719
+ /**
720
+ * Checks if a schema matches a pattern for a given filter type (`schemaName`).
721
+ *
722
+ * Returns `null` when the filter type doesn't apply to schemas.
723
+ */
724
+ function matchesSchemaPattern(node, type, pattern) {
725
+ if (type === "schemaName") return node.name ? testPattern(node.name, pattern) : false;
726
+ return null;
727
+ }
728
+ /**
729
+ * Default name resolver used by `defineResolver`.
730
+ *
731
+ * - `camelCase` for `function` and `file` types.
732
+ * - `PascalCase` for `type`.
733
+ * - `camelCase` for everything else.
734
+ */
735
+ function defaultResolver(name, type) {
736
+ if (type === "file" || type === "function") return camelCase(name, { isFile: type === "file" });
737
+ if (type === "type") return pascalCase(name);
738
+ return camelCase(name);
739
+ }
740
+ /**
741
+ * Default option resolver — applies include/exclude filters and merges matching override options.
742
+ *
743
+ * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.
744
+ *
745
+ * @example Include/exclude filtering
746
+ * ```ts
747
+ * const options = defaultResolveOptions(operationNode, {
748
+ * options: { output: 'types' },
749
+ * exclude: [{ type: 'tag', pattern: 'internal' }],
750
+ * })
751
+ * // → null when node has tag 'internal'
752
+ * ```
753
+ *
754
+ * @example Override merging
755
+ * ```ts
756
+ * const options = defaultResolveOptions(operationNode, {
757
+ * options: { enumType: 'asConst' },
758
+ * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],
759
+ * })
760
+ * // → { enumType: 'enum' } when operationId matches
761
+ * ```
762
+ */
763
+ const resolveOptionsCache = /* @__PURE__ */ new WeakMap();
764
+ function computeOptions(node, options, exclude, include, override) {
765
+ if ((0, _kubb_ast.isOperationNode)(node)) {
766
+ if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
767
+ if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
768
+ const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options;
769
+ return {
770
+ ...options,
771
+ ...overrideOptions
772
+ };
773
+ }
774
+ if ((0, _kubb_ast.isSchemaNode)(node)) {
775
+ if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null;
776
+ if (include) {
777
+ const applicable = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern)).filter((r) => r !== null);
778
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
779
+ }
780
+ const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options;
781
+ return {
782
+ ...options,
783
+ ...overrideOptions
784
+ };
785
+ }
786
+ return options;
787
+ }
788
+ function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
789
+ const optionsKey = options;
790
+ let byOptions = resolveOptionsCache.get(optionsKey);
791
+ if (!byOptions) {
792
+ byOptions = /* @__PURE__ */ new WeakMap();
793
+ resolveOptionsCache.set(optionsKey, byOptions);
794
+ }
795
+ const cached = byOptions.get(node);
796
+ if (cached !== void 0) return cached.value;
797
+ const result = computeOptions(node, options, exclude, include, override);
798
+ byOptions.set(node, { value: result });
799
+ return result;
800
+ }
801
+ /**
802
+ * Default path resolver used by `defineResolver`.
803
+ *
804
+ * - Returns the output directory in `single` mode.
805
+ * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.
806
+ * - Falls back to a flat `output/baseName` path otherwise.
807
+ *
808
+ * A custom `group.name` function overrides the default subdirectory naming.
809
+ * For `tag` groups the default is `${camelCase(tag)}Controller`.
810
+ * For `path` groups the default is the first path segment after `/`.
811
+ *
812
+ * @example Flat output
813
+ * ```ts
814
+ * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
815
+ * // → '/src/types/petTypes.ts'
816
+ * ```
817
+ *
818
+ * @example Tag-based grouping
819
+ * ```ts
820
+ * defaultResolvePath(
821
+ * { baseName: 'petTypes.ts', tag: 'pets' },
822
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
823
+ * )
824
+ * // → '/src/types/petsController/petTypes.ts'
825
+ * ```
826
+ *
827
+ * @example Path-based grouping
828
+ * ```ts
829
+ * defaultResolvePath(
830
+ * { baseName: 'petTypes.ts', path: '/pets/list' },
831
+ * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
832
+ * )
833
+ * // → '/src/types/pets/petTypes.ts'
834
+ * ```
835
+ *
836
+ * @example Single-file mode
837
+ * ```ts
838
+ * defaultResolvePath(
839
+ * { baseName: 'petTypes.ts', pathMode: 'single' },
840
+ * { root: '/src', output: { path: 'types' } },
841
+ * )
842
+ * // → '/src/types'
843
+ * ```
844
+ */
845
+ function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
846
+ if ((pathMode ?? getMode(node_path.default.resolve(root, output.path))) === "single") return node_path.default.resolve(root, output.path);
847
+ const result = (() => {
848
+ if (group && (groupPath || tag)) {
849
+ const groupValue = group.type === "path" ? groupPath : tag;
850
+ const defaultName = group.type === "tag" ? ({ group: g }) => `${camelCase(g)}Controller` : ({ group: g }) => {
851
+ const segment = g.split("/").filter((s) => s !== "" && s !== "." && s !== "..")[0];
852
+ return segment ? camelCase(segment) : "";
853
+ };
854
+ const resolveName = group.name ?? defaultName;
855
+ return node_path.default.resolve(root, output.path, resolveName({ group: groupValue }), baseName);
856
+ }
857
+ return node_path.default.resolve(root, output.path, baseName);
858
+ })();
859
+ const outputDir = node_path.default.resolve(root, output.path);
860
+ const outputDirWithSep = outputDir.endsWith(node_path.default.sep) ? outputDir : `${outputDir}${node_path.default.sep}`;
861
+ if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Error(`[Kubb] Resolved path "${result}" is outside the output directory "${outputDir}". This may indicate a path traversal attempt in the OpenAPI specification or a misconfigured group.name function.`);
862
+ return result;
863
+ }
864
+ /**
865
+ * Default file resolver used by `defineResolver`.
866
+ *
867
+ * Resolves a `FileNode` by combining name resolution (`resolver.default`) with
868
+ * path resolution (`resolver.resolvePath`). The resolved file always has empty
869
+ * `sources`, `imports`, and `exports` arrays — consumers populate those separately.
870
+ *
871
+ * In `single` mode the name is omitted and the file sits directly in the output directory.
872
+ *
873
+ * @example Resolve a schema file
874
+ * ```ts
875
+ * const file = defaultResolveFile.call(
876
+ * resolver,
877
+ * { name: 'pet', extname: '.ts' },
878
+ * { root: '/src', output: { path: 'types' } },
879
+ * )
880
+ * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }
881
+ * ```
882
+ *
883
+ * @example Resolve an operation file with tag grouping
884
+ * ```ts
885
+ * const file = defaultResolveFile.call(
886
+ * resolver,
887
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
888
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
889
+ * )
890
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
891
+ * ```
892
+ */
893
+ function defaultResolveFile({ name, extname, tag, path: groupPath }, context) {
894
+ const pathMode = getMode(node_path.default.resolve(context.root, context.output.path));
895
+ const baseName = `${pathMode === "single" ? "" : this.default(name, "file")}${extname}`;
896
+ const filePath = this.resolvePath({
897
+ baseName,
898
+ pathMode,
899
+ tag,
900
+ path: groupPath
901
+ }, context);
902
+ return (0, _kubb_ast.createFile)({
903
+ path: filePath,
904
+ baseName: node_path.default.basename(filePath),
905
+ meta: { pluginName: this.pluginName },
906
+ sources: [],
907
+ imports: [],
908
+ exports: []
909
+ });
910
+ }
911
+ /**
912
+ * Generates the default "Generated by Kubb" banner from config and optional node metadata.
913
+ */
914
+ function buildDefaultBanner({ title, description, version, config }) {
915
+ try {
916
+ const source = (() => {
917
+ if (Array.isArray(config.input)) {
918
+ const first = config.input[0];
919
+ if (first && "path" in first) return node_path.default.basename(first.path);
920
+ return "";
921
+ }
922
+ if (config.input && "path" in config.input) return node_path.default.basename(config.input.path);
923
+ if (config.input && "data" in config.input) return "text content";
924
+ return "";
925
+ })();
926
+ let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
927
+ if (config.output.defaultBanner === "simple") {
928
+ banner += "*/\n";
929
+ return banner;
930
+ }
931
+ if (source) banner += `* Source: ${source}\n`;
932
+ if (title) banner += `* Title: ${title}\n`;
933
+ if (description) {
934
+ const formattedDescription = description.replace(/\n/gm, "\n* ");
935
+ banner += `* Description: ${formattedDescription}\n`;
936
+ }
937
+ if (version) banner += `* OpenAPI spec version: ${version}\n`;
938
+ banner += "*/\n";
939
+ return banner;
940
+ } catch (_error) {
941
+ return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
942
+ }
943
+ }
944
+ /**
945
+ * Default banner resolver — returns the banner string for a generated file.
946
+ *
947
+ * A user-supplied `output.banner` overrides the default Kubb "Generated by Kubb" notice.
948
+ * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`
949
+ * from the document metadata when `meta` is provided).
950
+ *
951
+ * - When `output.banner` is a function, calls it with `meta` and returns the result.
952
+ * - When `output.banner` is a string, returns it directly.
953
+ * - When `config.output.defaultBanner` is `false`, returns `undefined`.
954
+ * - Otherwise returns the Kubb "Generated by Kubb" notice.
955
+ *
956
+ * @example String banner overrides default
957
+ * ```ts
958
+ * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })
959
+ * // → '// my banner'
960
+ * ```
961
+ *
962
+ * @example Function banner with metadata
963
+ * ```ts
964
+ * defaultResolveBanner(meta, { output: { banner: (m) => `// v${m?.version}` }, config })
965
+ * // → '// v3.0.0'
966
+ * ```
967
+ *
968
+ * @example No user banner — Kubb notice with OAS metadata
969
+ * ```ts
970
+ * defaultResolveBanner(meta, { config })
971
+ * // → '/** Generated by Kubb ... Title: Pet Store ... *\/'
972
+ * ```
973
+ *
974
+ * @example Disabled default banner
975
+ * ```ts
976
+ * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })
977
+ * // → null
978
+ * ```
979
+ */
980
+ function defaultResolveBanner(meta, { output, config }) {
981
+ if (typeof output?.banner === "function") return output.banner(meta);
982
+ if (typeof output?.banner === "string") return output.banner;
983
+ if (config.output.defaultBanner === false) return null;
984
+ return buildDefaultBanner({
985
+ title: meta?.title,
986
+ version: meta?.version,
987
+ config
988
+ });
989
+ }
990
+ /**
991
+ * Default footer resolver — returns the footer string for a generated file.
992
+ *
993
+ * - When `output.footer` is a function, calls it with `meta` and returns the result.
994
+ * - When `output.footer` is a string, returns it directly.
995
+ * - Otherwise returns `undefined`.
996
+ *
997
+ * @example String footer
998
+ * ```ts
999
+ * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })
1000
+ * // → '// end of file'
1001
+ * ```
1002
+ *
1003
+ * @example Function footer with metadata
1004
+ * ```ts
1005
+ * defaultResolveFooter(meta, { output: { footer: (m) => `// ${m?.title}` }, config })
1006
+ * // → '// Pet Store'
1007
+ * ```
1008
+ */
1009
+ function defaultResolveFooter(meta, { output }) {
1010
+ if (typeof output?.footer === "function") return output.footer(meta);
1011
+ if (typeof output?.footer === "string") return output.footer;
1012
+ return null;
1013
+ }
1014
+ /**
1015
+ * Defines a resolver for a plugin, injecting built-in defaults for name casing,
1016
+ * include/exclude/override filtering, path resolution, and file construction.
1017
+ *
1018
+ * All four defaults can be overridden by providing them in the builder function:
1019
+ * - `default` — name casing strategy (camelCase / PascalCase)
1020
+ * - `resolveOptions` — include/exclude/override filtering
1021
+ * - `resolvePath` — output path computation
1022
+ * - `resolveFile` — full `FileNode` construction
1023
+ *
1024
+ * Methods in the returned object can call sibling resolver methods via `this`.
1025
+ *
1026
+ * @example Basic resolver with naming helpers
1027
+ * ```ts
1028
+ * export const resolver = defineResolver<PluginTs>(() => ({
1029
+ * name: 'default',
1030
+ * resolveName(node) {
1031
+ * return this.default(node.name, 'function')
1032
+ * },
1033
+ * resolveTypedName(node) {
1034
+ * return this.default(node.name, 'type')
1035
+ * },
1036
+ * }))
1037
+ * ```
1038
+ *
1039
+ * @example Override resolvePath for a custom output structure
1040
+ * ```ts
1041
+ * export const resolver = defineResolver<PluginTs>(() => ({
1042
+ * name: 'custom',
1043
+ * resolvePath({ baseName }, { root, output }) {
1044
+ * return path.resolve(root, output.path, 'generated', baseName)
1045
+ * },
1046
+ * }))
1047
+ * ```
1048
+ *
1049
+ * @example Use this.default inside a helper
1050
+ * ```ts
1051
+ * export const resolver = defineResolver<PluginTs>(() => ({
1052
+ * name: 'default',
1053
+ * resolveParamName(node, param) {
1054
+ * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')
1055
+ * },
1056
+ * }))
1057
+ * ```
1058
+ */
1059
+ function defineResolver(build) {
1060
+ let resolver;
1061
+ resolver = {
1062
+ default: defaultResolver,
1063
+ resolveOptions: defaultResolveOptions,
1064
+ resolvePath: defaultResolvePath,
1065
+ resolveFile: (params, context) => defaultResolveFile.call(resolver, params, context),
1066
+ resolveBanner: defaultResolveBanner,
1067
+ resolveFooter: defaultResolveFooter,
1068
+ ...build()
1069
+ };
1070
+ return resolver;
1071
+ }
1072
+ //#endregion
1073
+ //#region src/devtools.ts
1074
+ /**
1075
+ * Encodes an `InputNode` as a compressed, URL-safe string.
1076
+ *
1077
+ * The JSON representation is deflate-compressed with {@link deflateSync} before
1078
+ * base64url encoding, which typically reduces payload size by 70–80 % and
1079
+ * keeps URLs well within browser and server path-length limits.
1080
+ *
1081
+ * Use {@link decodeAst} to reverse.
1082
+ */
1083
+ function encodeAst(input) {
1084
+ const compressed = (0, fflate.deflateSync)(new TextEncoder().encode(JSON.stringify(input)));
1085
+ return Buffer.from(compressed).toString("base64url");
1086
+ }
1087
+ /**
1088
+ * Constructs the Kubb Studio URL for the given `InputNode`.
1089
+ * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).
1090
+ * The `input` is encoded and attached as the `?root=` query parameter so Studio
1091
+ * can decode and render it without a round-trip to any server.
1092
+ */
1093
+ function getStudioUrl(input, studioUrl, options = {}) {
1094
+ return `${studioUrl.replace(/\/$/, "")}${options.ast ? "/ast" : ""}?root=${encodeAst(input)}`;
1095
+ }
1096
+ /**
1097
+ * Opens the Kubb Studio URL for the given `InputNode` in the default browser —
1098
+ *
1099
+ * Falls back to printing the URL if the browser cannot be launched.
1100
+ */
1101
+ async function openInStudio(input, studioUrl, options = {}) {
1102
+ const url = getStudioUrl(input, studioUrl, options);
1103
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
1104
+ const args = process.platform === "win32" ? [
1105
+ "/c",
1106
+ "start",
1107
+ "",
1108
+ url
1109
+ ] : [url];
1110
+ try {
1111
+ await (0, tinyexec.x)(cmd, args);
1112
+ } catch {
1113
+ console.log(`\n ${url}\n`);
1114
+ }
1115
+ }
1116
+ //#endregion
1117
+ //#region src/FileManager.ts
1118
+ function mergeFile(a, b) {
1119
+ return {
1120
+ ...a,
1121
+ banner: b.banner,
1122
+ footer: b.footer,
1123
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
1124
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
1125
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
1126
+ };
1127
+ }
1128
+ function isIndexPath(path) {
1129
+ return path.endsWith("/index.ts") || path === "index.ts";
1130
+ }
1131
+ function compareFiles(a, b) {
1132
+ const lenDiff = a.path.length - b.path.length;
1133
+ if (lenDiff !== 0) return lenDiff;
1134
+ const aIsIndex = isIndexPath(a.path);
1135
+ const bIsIndex = isIndexPath(b.path);
1136
+ if (aIsIndex && !bIsIndex) return 1;
1137
+ if (!aIsIndex && bIsIndex) return -1;
1138
+ return 0;
1139
+ }
1140
+ /**
1141
+ * In-memory file store for generated files. Files sharing a `path` are merged
1142
+ * (sources/imports/exports concatenated). The `files` getter is sorted by
1143
+ * path length (barrel `index.ts` last within a bucket).
1144
+ *
1145
+ * @example
1146
+ * ```ts
1147
+ * const manager = new FileManager()
1148
+ * manager.upsert(myFile)
1149
+ * manager.files // sorted view
1150
+ * ```
1151
+ */
1152
+ var FileManager = class {
1153
+ #cache = /* @__PURE__ */ new Map();
1154
+ #sorted = null;
1155
+ #onUpsert = null;
1156
+ /**
1157
+ * Registers a callback invoked with the resolved {@link FileNode} on every
1158
+ * `add` / `upsert`. Used by the build loop to track newly written files
1159
+ * without keeping its own scan-based diff. Single subscriber by design —
1160
+ * setting again replaces the previous callback. Pass `null` to detach.
1161
+ */
1162
+ setOnUpsert(callback) {
1163
+ this.#onUpsert = callback;
1164
+ }
1165
+ add(...files) {
1166
+ return this.#store(files, false);
1167
+ }
1168
+ upsert(...files) {
1169
+ return this.#store(files, true);
1170
+ }
1171
+ #store(files, mergeExisting) {
1172
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
1173
+ const resolved = [];
1174
+ for (const file of batch) {
1175
+ const existing = this.#cache.get(file.path);
1176
+ const merged = existing && mergeExisting ? (0, _kubb_ast.createFile)(mergeFile(existing, file)) : file;
1177
+ this.#cache.set(merged.path, merged);
1178
+ resolved.push(merged);
1179
+ this.#onUpsert?.(merged);
1180
+ }
1181
+ if (resolved.length > 0) this.#sorted = null;
1182
+ return resolved;
1183
+ }
1184
+ #dedupe(files) {
1185
+ const seen = /* @__PURE__ */ new Map();
1186
+ for (const file of files) {
1187
+ const prev = seen.get(file.path);
1188
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
1189
+ }
1190
+ return [...seen.values()];
1191
+ }
1192
+ getByPath(path) {
1193
+ return this.#cache.get(path) ?? null;
1194
+ }
1195
+ deleteByPath(path) {
1196
+ if (!this.#cache.delete(path)) return;
1197
+ this.#sorted = null;
1198
+ }
1199
+ clear() {
1200
+ this.#cache.clear();
1201
+ this.#sorted = null;
1202
+ }
1203
+ /**
1204
+ * Releases all stored files. Called by the core after `kubb:build:end`.
1205
+ */
1206
+ dispose() {
1207
+ this.clear();
1208
+ this.#onUpsert = null;
1209
+ }
1210
+ [Symbol.dispose]() {
1211
+ this.dispose();
1212
+ }
1213
+ /**
1214
+ * All stored files in stable sort order (shortest path first, barrel files
1215
+ * last within a length bucket). Returns a cached view — do not mutate.
1216
+ */
1217
+ get files() {
1218
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
1219
+ }
1220
+ };
1221
+ //#endregion
1222
+ //#region src/FileProcessor.ts
1223
+ function joinSources(file) {
1224
+ const sources = file.sources;
1225
+ if (sources.length === 0) return "";
1226
+ const parts = [];
1227
+ for (const source of sources) {
1228
+ const s = (0, _kubb_ast.extractStringsFromNodes)(source.nodes);
1229
+ if (s) parts.push(s);
1230
+ }
1231
+ return parts.join("\n\n");
1232
+ }
1233
+ /**
1234
+ * Converts a single file to a string using the registered parsers.
1235
+ * Falls back to joining source values when no matching parser is found.
1236
+ *
1237
+ * @internal
1238
+ */
1239
+ var FileProcessor = class {
1240
+ events = new AsyncEventEmitter();
1241
+ parse(file, { parsers, extension } = {}) {
1242
+ const parseExtName = extension?.[file.extname] || void 0;
1243
+ if (!parsers || !file.extname) return joinSources(file);
1244
+ const parser = parsers.get(file.extname);
1245
+ if (!parser) return joinSources(file);
1246
+ return parser.parse(file, { extname: parseExtName });
1247
+ }
1248
+ *stream(files, options = {}) {
1249
+ const total = files.length;
1250
+ if (total === 0) return;
1251
+ let processed = 0;
1252
+ for (const file of files) {
1253
+ const source = this.parse(file, options);
1254
+ processed++;
1255
+ yield {
1256
+ file,
1257
+ source,
1258
+ processed,
1259
+ total,
1260
+ percentage: processed / total * 100
1261
+ };
1262
+ }
1263
+ }
1264
+ async run(files, options = {}) {
1265
+ await this.events.emit("start", files);
1266
+ for (const { file, source, processed, total, percentage } of this.stream(files, options)) await this.events.emit("update", {
1267
+ file,
1268
+ source,
1269
+ processed,
1270
+ percentage,
1271
+ total
1272
+ });
1273
+ await this.events.emit("end", files);
1274
+ return files;
1275
+ }
1276
+ /**
1277
+ * Clears all registered event listeners.
1278
+ */
1279
+ dispose() {
1280
+ this.events.removeAll();
1281
+ }
1282
+ [Symbol.dispose]() {
1283
+ this.dispose();
1284
+ }
1285
+ };
1286
+ //#endregion
1287
+ //#region \0@oxc-project+runtime@0.129.0/helpers/usingCtx.js
1288
+ function _usingCtx() {
1289
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
1290
+ var n = Error();
1291
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
1292
+ };
1293
+ var e = {};
1294
+ var n = [];
1295
+ function using(r, e) {
1296
+ if (null != e) {
1297
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
1298
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
1299
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
1300
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
1301
+ t && (o = function o() {
1302
+ try {
1303
+ t.call(e);
1304
+ } catch (r) {
1305
+ return Promise.reject(r);
1306
+ }
1307
+ }), n.push({
1308
+ v: e,
1309
+ d: o,
1310
+ a: r
1311
+ });
1312
+ } else r && n.push({
1313
+ d: e,
1314
+ a: r
1315
+ });
1316
+ return e;
1317
+ }
1318
+ return {
1319
+ e,
1320
+ u: using.bind(null, !1),
1321
+ a: using.bind(null, !0),
1322
+ d: function d() {
1323
+ var o;
1324
+ var t = this.e;
1325
+ var s = 0;
1326
+ function next() {
1327
+ for (; o = n.pop();) try {
1328
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
1329
+ if (o.d) {
1330
+ var r = o.d.call(o.v);
1331
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
1332
+ } else s |= 1;
1333
+ } catch (r) {
1334
+ return err(r);
1335
+ }
1336
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
1337
+ if (t !== e) throw t;
1338
+ }
1339
+ function err(n) {
1340
+ return t = t !== e ? new r(n, t) : n, next();
1341
+ }
1342
+ return next();
1343
+ }
1344
+ };
1345
+ }
1346
+ //#endregion
1347
+ //#region src/KubbDriver.ts
1348
+ function enforceOrder(enforce) {
1349
+ return enforce === "pre" ? -1 : enforce === "post" ? 1 : 0;
1350
+ }
1351
+ const OPERATION_FILTER_TYPES = new Set([
1352
+ "tag",
1353
+ "operationId",
1354
+ "path",
1355
+ "method",
1356
+ "contentType"
1357
+ ]);
1358
+ var KubbDriver = class KubbDriver {
1359
+ config;
1360
+ options;
1361
+ /**
1362
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
1363
+ *
1364
+ * @example
1365
+ * ```ts
1366
+ * KubbDriver.getMode('src/gen/types.ts') // 'single'
1367
+ * KubbDriver.getMode('src/gen/types') // 'split'
1368
+ * ```
1369
+ */
1370
+ static getMode(fileOrFolder) {
1371
+ return getMode(fileOrFolder);
1372
+ }
1373
+ /**
1374
+ * The streaming `InputStreamNode` produced by the adapter.
1375
+ * Always set after adapter setup — parse-only adapters are wrapped automatically.
1376
+ */
1377
+ inputNode = null;
1378
+ adapter = null;
1379
+ /**
1380
+ * Studio session state, kept together so `dispose()` can reset it atomically.
1381
+ *
1382
+ * - `source` holds the raw adapter source so `adapter.parse()` can be called lazily.
1383
+ * Intentionally outlives the build; cleared by `dispose()`.
1384
+ * - `isOpen` prevents opening the studio more than once per build.
1385
+ * - `inputNode` caches the parse promise so `adapter.parse()` is called at most once
1386
+ * per studio session, even when `openInStudio()` is called multiple times.
1387
+ */
1388
+ #studio = {
1389
+ source: null,
1390
+ isOpen: false,
1391
+ inputNode: null
1392
+ };
1393
+ #middlewareListeners = [];
1394
+ /**
1395
+ * Central file store for all generated files.
1396
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1397
+ * add files; this property gives direct read/write access when needed.
1398
+ */
1399
+ fileManager = new FileManager();
1400
+ #fileProcessor = new FileProcessor();
1401
+ plugins = /* @__PURE__ */ new Map();
1402
+ /**
1403
+ * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
1404
+ * Used by the build loop to decide whether to emit generator events for a given plugin.
1405
+ */
1406
+ #eventGeneratorPlugins = /* @__PURE__ */ new Set();
1407
+ #resolvers = /* @__PURE__ */ new Map();
1408
+ #defaultResolvers = /* @__PURE__ */ new Map();
1409
+ #hookListeners = /* @__PURE__ */ new Map();
1410
+ constructor(config, options) {
1411
+ this.config = config;
1412
+ this.options = options;
1413
+ this.adapter = config.adapter ?? null;
1414
+ }
1415
+ async setup() {
1416
+ const normalized = this.config.plugins.map((rawPlugin) => this.#normalizePlugin(rawPlugin));
1417
+ normalized.sort((a, b) => {
1418
+ if (b.dependencies?.includes(a.name)) return -1;
1419
+ if (a.dependencies?.includes(b.name)) return 1;
1420
+ return enforceOrder(a.enforce) - enforceOrder(b.enforce);
1421
+ });
1422
+ for (const plugin of normalized) {
1423
+ if (plugin.apply) plugin.apply(this.config);
1424
+ this.#registerPlugin(plugin);
1425
+ this.plugins.set(plugin.name, plugin);
1426
+ }
1427
+ if (this.config.middleware) for (const middleware of this.config.middleware) for (const event of Object.keys(middleware.hooks)) this.#registerMiddleware(event, middleware.hooks);
1428
+ if (this.config.adapter) await this.#registerAdapter(this.config.adapter);
1429
+ }
1430
+ get hooks() {
1431
+ return this.options.hooks;
1432
+ }
1433
+ /**
1434
+ * Creates an `NormalizedPlugin` from a hook-style plugin and registers
1435
+ * its lifecycle handlers on the `AsyncEventEmitter`.
1436
+ */
1437
+ #normalizePlugin(plugin) {
1438
+ const normalized = {
1439
+ name: plugin.name,
1440
+ dependencies: plugin.dependencies,
1441
+ enforce: plugin.enforce,
1442
+ hooks: plugin.hooks,
1443
+ options: plugin.options ?? {
1444
+ output: { path: "." },
1445
+ exclude: [],
1446
+ override: []
1447
+ }
1448
+ };
1449
+ if ("apply" in plugin && typeof plugin.apply === "function") normalized.apply = plugin.apply;
1450
+ return normalized;
1451
+ }
1452
+ async #registerAdapter(adapter) {
1453
+ const source = inputToAdapterSource(this.config);
1454
+ this.#studio.source = source;
1455
+ if (adapter.stream) {
1456
+ this.inputNode = await adapter.stream(source);
1457
+ await this.hooks.emit("kubb:debug", {
1458
+ date: /* @__PURE__ */ new Date(),
1459
+ logs: [`✓ Adapter '${adapter.name}' producing input stream`]
1460
+ });
1461
+ } else {
1462
+ const inputNode = await adapter.parse(source);
1463
+ this.inputNode = (0, _kubb_ast.createStreamInput)(arrayToAsyncIterable(inputNode.schemas), arrayToAsyncIterable(inputNode.operations), inputNode.meta);
1464
+ await this.hooks.emit("kubb:debug", {
1465
+ date: /* @__PURE__ */ new Date(),
1466
+ logs: [
1467
+ `✓ Adapter '${adapter.name}' resolved InputNode (wrapped as stream)`,
1468
+ ` • Schemas: ${inputNode.schemas.length}`,
1469
+ ` • Operations: ${inputNode.operations.length}`
1470
+ ]
1471
+ });
1472
+ }
1473
+ }
1474
+ #registerMiddleware(event, middlewareHooks) {
1475
+ const handler = middlewareHooks[event];
1476
+ if (!handler) return;
1477
+ this.hooks.on(event, handler);
1478
+ this.#middlewareListeners.push([event, handler]);
1479
+ }
1480
+ /**
1481
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
1482
+ *
1483
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
1484
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
1485
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
1486
+ *
1487
+ * All other hooks are iterated and registered directly as pass-through listeners.
1488
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
1489
+ *
1490
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
1491
+ * the plugin lifecycle without modifying plugin behavior.
1492
+ *
1493
+ * @internal
1494
+ */
1495
+ #registerPlugin(plugin) {
1496
+ const { hooks } = plugin;
1497
+ if (!hooks) return;
1498
+ if (hooks["kubb:plugin:setup"]) {
1499
+ const setupHandler = (globalCtx) => {
1500
+ const pluginCtx = {
1501
+ ...globalCtx,
1502
+ options: plugin.options ?? {},
1503
+ addGenerator: (gen) => {
1504
+ this.registerGenerator(plugin.name, gen);
1505
+ },
1506
+ setResolver: (resolver) => {
1507
+ this.setPluginResolver(plugin.name, resolver);
1508
+ },
1509
+ setTransformer: (visitor) => {
1510
+ plugin.transformer = visitor;
1511
+ },
1512
+ setRenderer: (renderer) => {
1513
+ plugin.renderer = renderer;
1514
+ },
1515
+ setOptions: (opts) => {
1516
+ plugin.options = {
1517
+ ...plugin.options,
1518
+ ...opts
1519
+ };
1520
+ },
1521
+ injectFile: (userFileNode) => {
1522
+ this.fileManager.add((0, _kubb_ast.createFile)(userFileNode));
1523
+ }
1524
+ };
1525
+ return hooks["kubb:plugin:setup"](pluginCtx);
1526
+ };
1527
+ this.hooks.on("kubb:plugin:setup", setupHandler);
1528
+ this.#trackHookListener("kubb:plugin:setup", setupHandler);
1529
+ }
1530
+ for (const [event, handler] of Object.entries(hooks)) {
1531
+ if (event === "kubb:plugin:setup" || !handler) continue;
1532
+ this.hooks.on(event, handler);
1533
+ this.#trackHookListener(event, handler);
1534
+ }
1535
+ }
1536
+ /**
1537
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
1538
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
1539
+ *
1540
+ * Call this once from `safeBuild` before the plugin execution loop begins.
1541
+ */
1542
+ async emitSetupHooks() {
1543
+ const noop = () => {};
1544
+ await this.hooks.emit("kubb:plugin:setup", {
1545
+ config: this.config,
1546
+ options: {},
1547
+ addGenerator: noop,
1548
+ setResolver: noop,
1549
+ setTransformer: noop,
1550
+ setRenderer: noop,
1551
+ setOptions: noop,
1552
+ injectFile: noop,
1553
+ updateConfig: noop
1554
+ });
1555
+ }
1556
+ /**
1557
+ * Registers a generator for the given plugin on the shared event emitter.
1558
+ *
1559
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1560
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1561
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1562
+ * so that generators from different plugins do not cross-fire.
1563
+ *
1564
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
1565
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
1566
+ * declares a renderer.
1567
+ *
1568
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1569
+ */
1570
+ registerGenerator(pluginName, gen) {
1571
+ const resolveRenderer = () => {
1572
+ const plugin = this.plugins.get(pluginName);
1573
+ return gen.renderer === null ? void 0 : gen.renderer ?? plugin?.renderer ?? this.config.renderer;
1574
+ };
1575
+ if (gen.schema) {
1576
+ const schemaHandler = async (node, ctx) => {
1577
+ if (ctx.plugin.name !== pluginName) return;
1578
+ await applyHookResult({
1579
+ result: await gen.schema(node, ctx),
1580
+ driver: this,
1581
+ rendererFactory: resolveRenderer()
1582
+ });
1583
+ };
1584
+ this.hooks.on("kubb:generate:schema", schemaHandler);
1585
+ this.#trackHookListener("kubb:generate:schema", schemaHandler);
1586
+ }
1587
+ if (gen.operation) {
1588
+ const operationHandler = async (node, ctx) => {
1589
+ if (ctx.plugin.name !== pluginName) return;
1590
+ await applyHookResult({
1591
+ result: await gen.operation(node, ctx),
1592
+ driver: this,
1593
+ rendererFactory: resolveRenderer()
1594
+ });
1595
+ };
1596
+ this.hooks.on("kubb:generate:operation", operationHandler);
1597
+ this.#trackHookListener("kubb:generate:operation", operationHandler);
1598
+ }
1599
+ if (gen.operations) {
1600
+ const operationsHandler = async (nodes, ctx) => {
1601
+ if (ctx.plugin.name !== pluginName) return;
1602
+ await applyHookResult({
1603
+ result: await gen.operations(nodes, ctx),
1604
+ driver: this,
1605
+ rendererFactory: resolveRenderer()
1606
+ });
1607
+ };
1608
+ this.hooks.on("kubb:generate:operations", operationsHandler);
1609
+ this.#trackHookListener("kubb:generate:operations", operationsHandler);
1610
+ }
1611
+ this.#eventGeneratorPlugins.add(pluginName);
1612
+ }
1613
+ /**
1614
+ * Returns `true` when at least one generator was registered for the given plugin
1615
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
1616
+ *
1617
+ * Used by the build loop to decide whether to walk the AST and emit generator events
1618
+ * for a plugin that has no static `plugin.generators`.
1619
+ */
1620
+ hasEventGenerators(pluginName) {
1621
+ return this.#eventGeneratorPlugins.has(pluginName);
1622
+ }
1623
+ /**
1624
+ * Runs the full plugin pipeline. Returns timings/failures collected so far even
1625
+ * when an outer hook throws — the orchestrator preserves partial state by capturing
1626
+ * the error into `error` instead of propagating.
1627
+ */
1628
+ async run({ storage }) {
1629
+ const hooks = this.hooks;
1630
+ const config = this.config;
1631
+ const failedPlugins = /* @__PURE__ */ new Set();
1632
+ const pluginTimings = /* @__PURE__ */ new Map();
1633
+ const parsersMap = /* @__PURE__ */ new Map();
1634
+ for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
1635
+ const pendingFiles = /* @__PURE__ */ new Map();
1636
+ this.fileManager.setOnUpsert((file) => {
1637
+ pendingFiles.set(file.path, file);
1638
+ });
1639
+ try {
1640
+ const flushPending = async () => {
1641
+ if (pendingFiles.size === 0) return;
1642
+ const files = [...pendingFiles.values()];
1643
+ pendingFiles.clear();
1644
+ await hooks.emit("kubb:debug", {
1645
+ date: /* @__PURE__ */ new Date(),
1646
+ logs: [`Writing ${files.length} files...`]
1647
+ });
1648
+ await hooks.emit("kubb:files:processing:start", { files });
1649
+ const items = [...this.#fileProcessor.stream(files, {
1650
+ parsers: parsersMap,
1651
+ extension: config.output.extension
1652
+ })];
1653
+ await hooks.emit("kubb:files:processing:update", { files: items.map(({ file, source, processed, total, percentage }) => ({
1654
+ file,
1655
+ source,
1656
+ processed,
1657
+ total,
1658
+ percentage,
1659
+ config
1660
+ })) });
1661
+ const queue = [];
1662
+ for (const { file, source } of items) if (source) {
1663
+ queue.push(storage.setItem(file.path, source));
1664
+ if (queue.length >= 50) await Promise.all(queue.splice(0));
1665
+ }
1666
+ await Promise.all(queue);
1667
+ await hooks.emit("kubb:files:processing:end", { files });
1668
+ await hooks.emit("kubb:debug", {
1669
+ date: /* @__PURE__ */ new Date(),
1670
+ logs: [`✓ File write process completed for ${files.length} files`]
1671
+ });
1672
+ };
1673
+ await this.emitSetupHooks();
1674
+ if (this.adapter && this.inputNode) await hooks.emit("kubb:build:start", Object.assign({
1675
+ config,
1676
+ adapter: this.adapter,
1677
+ meta: this.inputNode.meta,
1678
+ getPlugin: this.getPlugin.bind(this)
1679
+ }, this.#filesPayload()));
1680
+ const generatorPlugins = [];
1681
+ for (const plugin of this.plugins.values()) {
1682
+ const context = this.getContext(plugin);
1683
+ const hrStart = process.hrtime();
1684
+ try {
1685
+ await hooks.emit("kubb:plugin:start", { plugin });
1686
+ await hooks.emit("kubb:debug", {
1687
+ date: /* @__PURE__ */ new Date(),
1688
+ logs: ["Starting plugin...", ` • Plugin Name: ${plugin.name}`]
1689
+ });
1690
+ } catch (caughtError) {
1691
+ const error = caughtError;
1692
+ const duration = getElapsedMs(hrStart);
1693
+ pluginTimings.set(plugin.name, duration);
1694
+ await this.#emitPluginEnd({
1695
+ plugin,
1696
+ duration,
1697
+ success: false,
1698
+ error
1699
+ });
1700
+ failedPlugins.add({
1701
+ plugin,
1702
+ error
1703
+ });
1704
+ continue;
1705
+ }
1706
+ if (plugin.generators?.length || this.hasEventGenerators(plugin.name)) {
1707
+ generatorPlugins.push({
1708
+ plugin,
1709
+ context,
1710
+ hrStart
1711
+ });
1712
+ continue;
1713
+ }
1714
+ const duration = getElapsedMs(hrStart);
1715
+ pluginTimings.set(plugin.name, duration);
1716
+ await this.#emitPluginEnd({
1717
+ plugin,
1718
+ duration,
1719
+ success: true
1720
+ });
1721
+ await hooks.emit("kubb:debug", {
1722
+ date: /* @__PURE__ */ new Date(),
1723
+ logs: [`✓ Plugin started successfully (${formatMs(duration)})`]
1724
+ });
1725
+ }
1726
+ if (generatorPlugins.length > 0) if (this.inputNode) {
1727
+ const { timings, failed } = await this.#runGenerators(generatorPlugins, flushPending);
1728
+ await flushPending();
1729
+ for (const [name, duration] of timings) pluginTimings.set(name, duration);
1730
+ for (const entry of failed) failedPlugins.add(entry);
1731
+ } else for (const { plugin, hrStart } of generatorPlugins) {
1732
+ const duration = getElapsedMs(hrStart);
1733
+ pluginTimings.set(plugin.name, duration);
1734
+ await this.#emitPluginEnd({
1735
+ plugin,
1736
+ duration,
1737
+ success: true
1738
+ });
1739
+ }
1740
+ await hooks.emit("kubb:plugins:end", Object.assign({ config }, this.#filesPayload()));
1741
+ await flushPending();
1742
+ const files = this.fileManager.files;
1743
+ await hooks.emit("kubb:build:end", {
1744
+ files,
1745
+ config,
1746
+ outputDir: (0, node_path.resolve)(config.root, config.output.path)
1747
+ });
1748
+ return {
1749
+ failedPlugins,
1750
+ pluginTimings
1751
+ };
1752
+ } catch (caughtError) {
1753
+ return {
1754
+ failedPlugins,
1755
+ pluginTimings,
1756
+ error: caughtError
1757
+ };
1758
+ } finally {
1759
+ this.fileManager.setOnUpsert(null);
1760
+ }
1761
+ }
1762
+ #filesPayload() {
1763
+ const driver = this;
1764
+ return {
1765
+ get files() {
1766
+ return driver.fileManager.files;
1767
+ },
1768
+ upsertFile: (...files) => driver.fileManager.upsert(...files)
1769
+ };
1770
+ }
1771
+ #emitPluginEnd({ plugin, duration, success, error }) {
1772
+ return this.hooks.emit("kubb:plugin:end", Object.assign({
1773
+ plugin,
1774
+ duration,
1775
+ success,
1776
+ ...error ? { error } : {},
1777
+ config: this.config
1778
+ }, this.#filesPayload()));
1779
+ }
1780
+ async #runGenerators(entries, flushPending) {
1781
+ const timings = /* @__PURE__ */ new Map();
1782
+ const failed = /* @__PURE__ */ new Set();
1783
+ const driver = this;
1784
+ const { schemas, operations } = this.inputNode;
1785
+ const states = entries.map(({ plugin, context, hrStart }) => {
1786
+ const { exclude, include, override } = plugin.options;
1787
+ const hasExclude = Array.isArray(exclude) && exclude.length > 0;
1788
+ const hasInclude = Array.isArray(include) && include.length > 0;
1789
+ const hasOverride = Array.isArray(override) && override.length > 0;
1790
+ return {
1791
+ plugin,
1792
+ generatorContext: {
1793
+ ...context,
1794
+ resolver: this.getResolver(plugin.name)
1795
+ },
1796
+ generators: plugin.generators ?? [],
1797
+ hrStart,
1798
+ failed: false,
1799
+ error: null,
1800
+ optionsAreStatic: !hasExclude && !hasInclude && !hasOverride,
1801
+ allowedSchemaNames: null
1802
+ };
1803
+ });
1804
+ const emitsSchemaHook = this.hooks.listenerCount("kubb:generate:schema") > 0;
1805
+ const emitsOperationHook = this.hooks.listenerCount("kubb:generate:operation") > 0;
1806
+ const pruningStates = states.filter(({ plugin }) => {
1807
+ const { include } = plugin.options;
1808
+ return (include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false);
1809
+ });
1810
+ if (pruningStates.length > 0) {
1811
+ const allSchemas = [];
1812
+ for await (const schema of schemas) allSchemas.push(schema);
1813
+ const includedOpsByState = new Map(pruningStates.map((s) => [s, []]));
1814
+ for await (const operation of operations) for (const state of pruningStates) {
1815
+ const { exclude, include, override } = state.plugin.options;
1816
+ if (state.generatorContext.resolver.resolveOptions(operation, {
1817
+ options: state.plugin.options,
1818
+ exclude,
1819
+ include,
1820
+ override
1821
+ }) !== null) includedOpsByState.get(state)?.push(operation);
1822
+ }
1823
+ for (const state of pruningStates) {
1824
+ state.allowedSchemaNames = (0, _kubb_ast.collectUsedSchemaNames)(includedOpsByState.get(state) ?? [], allSchemas);
1825
+ includedOpsByState.delete(state);
1826
+ }
1827
+ }
1828
+ const resolveRendererFor = (gen, state) => gen.renderer === null ? void 0 : gen.renderer ?? state.plugin.renderer ?? state.generatorContext.config.renderer;
1829
+ const dispatchSchema = async (state, node) => {
1830
+ if (state.failed) return;
1831
+ try {
1832
+ const { plugin, generatorContext, generators } = state;
1833
+ const transformedNode = plugin.transformer ? (0, _kubb_ast.transform)(node, plugin.transformer) : node;
1834
+ if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) return;
1835
+ const { exclude, include, override } = plugin.options;
1836
+ const options = state.optionsAreStatic ? plugin.options : generatorContext.resolver.resolveOptions(transformedNode, {
1837
+ options: plugin.options,
1838
+ exclude,
1839
+ include,
1840
+ override
1841
+ });
1842
+ if (options === null) return;
1843
+ const ctx = {
1844
+ ...generatorContext,
1845
+ options
1846
+ };
1847
+ for (const gen of generators) {
1848
+ if (!gen.schema) continue;
1849
+ const raw = gen.schema(transformedNode, ctx);
1850
+ const applied = applyHookResult({
1851
+ result: isPromise(raw) ? await raw : raw,
1852
+ driver,
1853
+ rendererFactory: resolveRendererFor(gen, state)
1854
+ });
1855
+ if (isPromise(applied)) await applied;
1856
+ }
1857
+ if (emitsSchemaHook) await this.hooks.emit("kubb:generate:schema", transformedNode, ctx);
1858
+ } catch (caughtError) {
1859
+ state.failed = true;
1860
+ state.error = caughtError;
1861
+ }
1862
+ };
1863
+ const dispatchOperation = async (state, node) => {
1864
+ if (state.failed) return;
1865
+ try {
1866
+ const { plugin, generatorContext, generators } = state;
1867
+ const transformedNode = plugin.transformer ? (0, _kubb_ast.transform)(node, plugin.transformer) : node;
1868
+ const { exclude, include, override } = plugin.options;
1869
+ const options = state.optionsAreStatic ? plugin.options : generatorContext.resolver.resolveOptions(transformedNode, {
1870
+ options: plugin.options,
1871
+ exclude,
1872
+ include,
1873
+ override
1874
+ });
1875
+ if (options === null) return;
1876
+ const ctx = {
1877
+ ...generatorContext,
1878
+ options
1879
+ };
1880
+ for (const gen of generators) {
1881
+ if (!gen.operation) continue;
1882
+ const raw = gen.operation(transformedNode, ctx);
1883
+ const applied = applyHookResult({
1884
+ result: isPromise(raw) ? await raw : raw,
1885
+ driver,
1886
+ rendererFactory: resolveRendererFor(gen, state)
1887
+ });
1888
+ if (isPromise(applied)) await applied;
1889
+ }
1890
+ if (emitsOperationHook) await this.hooks.emit("kubb:generate:operation", transformedNode, ctx);
1891
+ } catch (caughtError) {
1892
+ state.failed = true;
1893
+ state.error = caughtError;
1894
+ }
1895
+ };
1896
+ const needsCollectedOperations = this.hooks.listenerCount("kubb:generate:operations") > 0 || states.some((s) => s.generators.some((g) => !!g.operations));
1897
+ const collectedOperations = needsCollectedOperations ? [] : void 0;
1898
+ await forBatches(schemas, (nodes) => Promise.all(nodes.flatMap((n) => states.map((state) => dispatchSchema(state, n)))), {
1899
+ concurrency: 8,
1900
+ flush: flushPending
1901
+ });
1902
+ await forBatches(operations, (nodes) => {
1903
+ if (needsCollectedOperations) collectedOperations.push(...nodes);
1904
+ return Promise.all(nodes.flatMap((n) => states.map((state) => dispatchOperation(state, n))));
1905
+ }, {
1906
+ concurrency: 8,
1907
+ flush: flushPending
1908
+ });
1909
+ for (const state of states) {
1910
+ if (!state.failed && needsCollectedOperations) try {
1911
+ const { plugin, generatorContext, generators } = state;
1912
+ const ctx = {
1913
+ ...generatorContext,
1914
+ options: plugin.options
1915
+ };
1916
+ for (const gen of generators) {
1917
+ if (!gen.operations) continue;
1918
+ await applyHookResult({
1919
+ result: await gen.operations(collectedOperations, ctx),
1920
+ driver,
1921
+ rendererFactory: resolveRendererFor(gen, state)
1922
+ });
1923
+ }
1924
+ await this.hooks.emit("kubb:generate:operations", collectedOperations, ctx);
1925
+ } catch (caughtError) {
1926
+ state.failed = true;
1927
+ state.error = caughtError;
1928
+ }
1929
+ const duration = getElapsedMs(state.hrStart);
1930
+ timings.set(state.plugin.name, duration);
1931
+ await this.#emitPluginEnd({
1932
+ plugin: state.plugin,
1933
+ duration,
1934
+ success: !state.failed,
1935
+ error: state.failed && state.error ? state.error : void 0
1936
+ });
1937
+ if (state.failed && state.error) failed.add({
1938
+ plugin: state.plugin,
1939
+ error: state.error
1940
+ });
1941
+ await this.hooks.emit("kubb:debug", {
1942
+ date: /* @__PURE__ */ new Date(),
1943
+ logs: [state.failed ? "✗ Plugin start failed" : `✓ Plugin started successfully (${formatMs(duration)})`]
1944
+ });
1945
+ }
1946
+ return {
1947
+ timings,
1948
+ failed
1949
+ };
1950
+ }
1951
+ /**
1952
+ * Unregisters all plugin lifecycle listeners from the shared event emitter.
1953
+ * Called at the end of a build to prevent listener leaks across repeated builds.
1954
+ *
1955
+ * @internal
1956
+ */
1957
+ dispose() {
1958
+ for (const [event, handlers] of this.#hookListeners) for (const handler of handlers) this.hooks.off(event, handler);
1959
+ this.#hookListeners.clear();
1960
+ this.#eventGeneratorPlugins.clear();
1961
+ this.#resolvers.clear();
1962
+ this.#defaultResolvers.clear();
1963
+ this.fileManager.dispose();
1964
+ this.#fileProcessor.dispose();
1965
+ this.inputNode = null;
1966
+ this.#studio = {
1967
+ source: null,
1968
+ isOpen: false,
1969
+ inputNode: null
1970
+ };
1971
+ for (const [event, handler] of this.#middlewareListeners) this.hooks.off(event, handler);
1972
+ }
1973
+ [Symbol.dispose]() {
1974
+ this.dispose();
1975
+ }
1976
+ #trackHookListener(event, handler) {
1977
+ let handlers = this.#hookListeners.get(event);
1978
+ if (!handlers) {
1979
+ handlers = /* @__PURE__ */ new Set();
1980
+ this.#hookListeners.set(event, handlers);
1981
+ }
1982
+ handlers.add(handler);
1983
+ }
1984
+ #getDefaultResolver = memoize(this.#defaultResolvers, (pluginName) => defineResolver(() => ({
1985
+ name: "default",
1986
+ pluginName
1987
+ })));
1988
+ /**
1989
+ * Merges `partial` with the plugin's default resolver and stores the result.
1990
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
1991
+ * get the up-to-date resolver without going through `getResolver()`.
1992
+ */
1993
+ setPluginResolver(pluginName, partial) {
1994
+ const merged = {
1995
+ ...this.#getDefaultResolver(pluginName),
1996
+ ...partial
1997
+ };
1998
+ this.#resolvers.set(pluginName, merged);
1999
+ const plugin = this.plugins.get(pluginName);
2000
+ if (plugin) plugin.resolver = merged;
2001
+ }
2002
+ getResolver(pluginName) {
2003
+ return this.#resolvers.get(pluginName) ?? this.plugins.get(pluginName)?.resolver ?? this.#getDefaultResolver(pluginName);
2004
+ }
2005
+ getContext(plugin) {
2006
+ const driver = this;
2007
+ return {
2008
+ config: driver.config,
2009
+ get root() {
2010
+ return (0, node_path.resolve)(driver.config.root, driver.config.output.path);
2011
+ },
2012
+ getMode(output) {
2013
+ return KubbDriver.getMode((0, node_path.resolve)(driver.config.root, driver.config.output.path, output.path));
2014
+ },
2015
+ hooks: driver.hooks,
2016
+ plugin,
2017
+ getPlugin: driver.getPlugin.bind(driver),
2018
+ requirePlugin: driver.requirePlugin.bind(driver),
2019
+ getResolver: driver.getResolver.bind(driver),
2020
+ driver,
2021
+ addFile: async (...files) => {
2022
+ driver.fileManager.add(...files);
2023
+ },
2024
+ upsertFile: async (...files) => {
2025
+ driver.fileManager.upsert(...files);
2026
+ },
2027
+ get meta() {
2028
+ return driver.inputNode?.meta ?? {
2029
+ circularNames: [],
2030
+ enumNames: []
2031
+ };
2032
+ },
2033
+ get adapter() {
2034
+ return driver.adapter;
2035
+ },
2036
+ get resolver() {
2037
+ return driver.getResolver(plugin.name);
2038
+ },
2039
+ get transformer() {
2040
+ return plugin.transformer;
2041
+ },
2042
+ warn(message) {
2043
+ driver.hooks.emit("kubb:warn", { message });
2044
+ },
2045
+ error(error) {
2046
+ driver.hooks.emit("kubb:error", { error: typeof error === "string" ? new Error(error) : error });
2047
+ },
2048
+ info(message) {
2049
+ driver.hooks.emit("kubb:info", { message });
2050
+ },
2051
+ async openInStudio(options) {
2052
+ if (!driver.config.devtools || driver.#studio.isOpen) return;
2053
+ if (typeof driver.config.devtools !== "object") throw new Error("Devtools must be an object");
2054
+ if (!driver.adapter || !driver.#studio.source) throw new Error("adapter is not defined, make sure you have set the parser in kubb.config.ts");
2055
+ driver.#studio.isOpen = true;
2056
+ const studioUrl = driver.config.devtools?.studioUrl ?? "https://kubb.studio";
2057
+ driver.#studio.inputNode ??= Promise.resolve(driver.adapter.parse(driver.#studio.source));
2058
+ return openInStudio(await driver.#studio.inputNode, studioUrl, options);
2059
+ }
2060
+ };
2061
+ }
2062
+ getPlugin(pluginName) {
2063
+ return this.plugins.get(pluginName);
2064
+ }
2065
+ requirePlugin(pluginName) {
2066
+ const plugin = this.plugins.get(pluginName);
2067
+ if (!plugin) throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`);
2068
+ return plugin;
2069
+ }
2070
+ };
2071
+ /**
2072
+ * Handles the return value of a plugin AST hook or generator method.
2073
+ *
2074
+ * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
2075
+ * - `Array<FileNode>` → added directly into `driver.fileManager`
2076
+ * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
2077
+ *
2078
+ * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
2079
+ * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
2080
+ */
2081
+ function applyHookResult({ result, driver, rendererFactory }) {
2082
+ if (!result) return;
2083
+ if (Array.isArray(result)) {
2084
+ driver.fileManager.upsert(...result);
2085
+ return;
2086
+ }
2087
+ if (!rendererFactory) return;
2088
+ const renderer = rendererFactory();
2089
+ if (renderer.stream) try {
2090
+ var _usingCtx$1 = _usingCtx();
2091
+ const r = _usingCtx$1.u(renderer);
2092
+ for (const file of r.stream(result)) driver.fileManager.upsert(file);
2093
+ return;
2094
+ } catch (_) {
2095
+ _usingCtx$1.e = _;
2096
+ } finally {
2097
+ _usingCtx$1.d();
2098
+ }
2099
+ return applyAsyncRender({
2100
+ renderer,
2101
+ result,
2102
+ driver
2103
+ });
2104
+ }
2105
+ async function applyAsyncRender({ renderer, result, driver }) {
2106
+ try {
2107
+ var _usingCtx3 = _usingCtx();
2108
+ const r = _usingCtx3.u(renderer);
2109
+ await r.render(result);
2110
+ driver.fileManager.upsert(...r.files);
2111
+ } catch (_) {
2112
+ _usingCtx3.e = _;
2113
+ } finally {
2114
+ _usingCtx3.d();
2115
+ }
2116
+ }
2117
+ function inputToAdapterSource(config) {
2118
+ const input = config.input;
2119
+ if (!input) throw new Error("[kubb] input is required when using an adapter. Provide input.path or input.data in your config.");
2120
+ if ("data" in input) return {
2121
+ type: "data",
2122
+ data: input.data
2123
+ };
2124
+ if (new URLPath(input.path).isURL) return {
2125
+ type: "path",
2126
+ path: input.path
2127
+ };
2128
+ return {
2129
+ type: "path",
2130
+ path: (0, node_path.resolve)(config.root, input.path)
2131
+ };
2132
+ }
2133
+ //#endregion
2134
+ Object.defineProperty(exports, "AsyncEventEmitter", {
2135
+ enumerable: true,
2136
+ get: function() {
2137
+ return AsyncEventEmitter;
2138
+ }
2139
+ });
2140
+ Object.defineProperty(exports, "BuildError", {
2141
+ enumerable: true,
2142
+ get: function() {
2143
+ return BuildError;
2144
+ }
2145
+ });
2146
+ Object.defineProperty(exports, "DEFAULT_BANNER", {
2147
+ enumerable: true,
2148
+ get: function() {
2149
+ return DEFAULT_BANNER;
2150
+ }
2151
+ });
2152
+ Object.defineProperty(exports, "DEFAULT_EXTENSION", {
2153
+ enumerable: true,
2154
+ get: function() {
2155
+ return DEFAULT_EXTENSION;
2156
+ }
2157
+ });
2158
+ Object.defineProperty(exports, "DEFAULT_STUDIO_URL", {
2159
+ enumerable: true,
2160
+ get: function() {
2161
+ return DEFAULT_STUDIO_URL;
2162
+ }
2163
+ });
2164
+ Object.defineProperty(exports, "FileManager", {
2165
+ enumerable: true,
2166
+ get: function() {
2167
+ return FileManager;
2168
+ }
2169
+ });
2170
+ Object.defineProperty(exports, "FileProcessor", {
2171
+ enumerable: true,
2172
+ get: function() {
2173
+ return FileProcessor;
2174
+ }
2175
+ });
2176
+ Object.defineProperty(exports, "KubbDriver", {
2177
+ enumerable: true,
2178
+ get: function() {
2179
+ return KubbDriver;
2180
+ }
2181
+ });
2182
+ Object.defineProperty(exports, "URLPath", {
2183
+ enumerable: true,
2184
+ get: function() {
2185
+ return URLPath;
2186
+ }
2187
+ });
2188
+ Object.defineProperty(exports, "__name", {
2189
+ enumerable: true,
2190
+ get: function() {
2191
+ return __name;
2192
+ }
2193
+ });
2194
+ Object.defineProperty(exports, "__toESM", {
2195
+ enumerable: true,
2196
+ get: function() {
2197
+ return __toESM;
2198
+ }
2199
+ });
2200
+ Object.defineProperty(exports, "_usingCtx", {
2201
+ enumerable: true,
2202
+ get: function() {
2203
+ return _usingCtx;
2204
+ }
2205
+ });
2206
+ Object.defineProperty(exports, "applyHookResult", {
2207
+ enumerable: true,
2208
+ get: function() {
2209
+ return applyHookResult;
2210
+ }
2211
+ });
2212
+ Object.defineProperty(exports, "definePlugin", {
2213
+ enumerable: true,
2214
+ get: function() {
2215
+ return definePlugin;
2216
+ }
2217
+ });
2218
+ Object.defineProperty(exports, "defineResolver", {
2219
+ enumerable: true,
2220
+ get: function() {
2221
+ return defineResolver;
2222
+ }
2223
+ });
2224
+ Object.defineProperty(exports, "logLevel", {
2225
+ enumerable: true,
2226
+ get: function() {
2227
+ return logLevel;
2228
+ }
2229
+ });
2230
+
2231
+ //# sourceMappingURL=KubbDriver-BBRa5CH2.cjs.map