@kubb/core 5.0.0-alpha.35 → 5.0.0-alpha.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1729 @@
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_path = require("node:path");
28
+ node_path = __toESM(node_path, 1);
29
+ let _kubb_ast = require("@kubb/ast");
30
+ let node_perf_hooks = require("node:perf_hooks");
31
+ let fflate = require("fflate");
32
+ let tinyexec = require("tinyexec");
33
+ //#region ../../internals/utils/src/casing.ts
34
+ /**
35
+ * Shared implementation for camelCase and PascalCase conversion.
36
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
37
+ * and capitalizes each word according to `pascal`.
38
+ *
39
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
40
+ */
41
+ function toCamelOrPascal(text, pascal) {
42
+ 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) => {
43
+ if (word.length > 1 && word === word.toUpperCase()) return word;
44
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
45
+ return word.charAt(0).toUpperCase() + word.slice(1);
46
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
47
+ }
48
+ /**
49
+ * Splits `text` on `.` and applies `transformPart` to each segment.
50
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
51
+ * Segments are joined with `/` to form a file path.
52
+ *
53
+ * Only splits on dots followed by a letter so that version numbers
54
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
55
+ */
56
+ function applyToFileParts(text, transformPart) {
57
+ const parts = text.split(/\.(?=[a-zA-Z])/);
58
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
59
+ }
60
+ /**
61
+ * Converts `text` to camelCase.
62
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
63
+ *
64
+ * @example
65
+ * camelCase('hello-world') // 'helloWorld'
66
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
67
+ */
68
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
69
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
70
+ prefix,
71
+ suffix
72
+ } : {}));
73
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
74
+ }
75
+ /**
76
+ * Converts `text` to PascalCase.
77
+ * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
78
+ *
79
+ * @example
80
+ * pascalCase('hello-world') // 'HelloWorld'
81
+ * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
82
+ */
83
+ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
84
+ if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
85
+ prefix,
86
+ suffix
87
+ }) : camelCase(part));
88
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
89
+ }
90
+ //#endregion
91
+ //#region ../../internals/utils/src/promise.ts
92
+ /** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * const results = await Promise.allSettled([p1, p2])
97
+ * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)
98
+ * ```
99
+ */
100
+ function isPromiseRejectedResult(result) {
101
+ return result.status === "rejected";
102
+ }
103
+ //#endregion
104
+ //#region ../../internals/utils/src/reserved.ts
105
+ /**
106
+ * JavaScript and Java reserved words.
107
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
108
+ */
109
+ const reservedWords = new Set([
110
+ "abstract",
111
+ "arguments",
112
+ "boolean",
113
+ "break",
114
+ "byte",
115
+ "case",
116
+ "catch",
117
+ "char",
118
+ "class",
119
+ "const",
120
+ "continue",
121
+ "debugger",
122
+ "default",
123
+ "delete",
124
+ "do",
125
+ "double",
126
+ "else",
127
+ "enum",
128
+ "eval",
129
+ "export",
130
+ "extends",
131
+ "false",
132
+ "final",
133
+ "finally",
134
+ "float",
135
+ "for",
136
+ "function",
137
+ "goto",
138
+ "if",
139
+ "implements",
140
+ "import",
141
+ "in",
142
+ "instanceof",
143
+ "int",
144
+ "interface",
145
+ "let",
146
+ "long",
147
+ "native",
148
+ "new",
149
+ "null",
150
+ "package",
151
+ "private",
152
+ "protected",
153
+ "public",
154
+ "return",
155
+ "short",
156
+ "static",
157
+ "super",
158
+ "switch",
159
+ "synchronized",
160
+ "this",
161
+ "throw",
162
+ "throws",
163
+ "transient",
164
+ "true",
165
+ "try",
166
+ "typeof",
167
+ "var",
168
+ "void",
169
+ "volatile",
170
+ "while",
171
+ "with",
172
+ "yield",
173
+ "Array",
174
+ "Date",
175
+ "hasOwnProperty",
176
+ "Infinity",
177
+ "isFinite",
178
+ "isNaN",
179
+ "isPrototypeOf",
180
+ "length",
181
+ "Math",
182
+ "name",
183
+ "NaN",
184
+ "Number",
185
+ "Object",
186
+ "prototype",
187
+ "String",
188
+ "toString",
189
+ "undefined",
190
+ "valueOf"
191
+ ]);
192
+ /**
193
+ * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * transformReservedWord('class') // '_class'
198
+ * transformReservedWord('42foo') // '_42foo'
199
+ * transformReservedWord('status') // 'status'
200
+ * ```
201
+ */
202
+ function transformReservedWord(word) {
203
+ const firstChar = word.charCodeAt(0);
204
+ if (word && (reservedWords.has(word) || firstChar >= 48 && firstChar <= 57)) return `_${word}`;
205
+ return word;
206
+ }
207
+ /**
208
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * isValidVarName('status') // true
213
+ * isValidVarName('class') // false (reserved word)
214
+ * isValidVarName('42foo') // false (starts with digit)
215
+ * ```
216
+ */
217
+ function isValidVarName(name) {
218
+ try {
219
+ new Function(`var ${name}`);
220
+ } catch {
221
+ return false;
222
+ }
223
+ return true;
224
+ }
225
+ //#endregion
226
+ //#region ../../internals/utils/src/string.ts
227
+ /**
228
+ * Strips the file extension from a path or file name.
229
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
230
+ *
231
+ * @example
232
+ * trimExtName('petStore.ts') // 'petStore'
233
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
234
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
235
+ * trimExtName('noExtension') // 'noExtension'
236
+ */
237
+ function trimExtName(text) {
238
+ const dotIndex = text.lastIndexOf(".");
239
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
240
+ return text;
241
+ }
242
+ //#endregion
243
+ //#region src/constants.ts
244
+ /**
245
+ * Base URL for the Kubb Studio web app.
246
+ */
247
+ const DEFAULT_STUDIO_URL = "https://studio.kubb.dev";
248
+ /**
249
+ * File name used for generated barrel (index) files.
250
+ */
251
+ const BARREL_FILENAME = "index.ts";
252
+ /**
253
+ * Default banner style written at the top of every generated file.
254
+ */
255
+ const DEFAULT_BANNER = "simple";
256
+ /**
257
+ * Default file-extension mapping used when no explicit mapping is configured.
258
+ */
259
+ const DEFAULT_EXTENSION = { ".ts": ".ts" };
260
+ /**
261
+ * Numeric log-level thresholds used internally to compare verbosity.
262
+ *
263
+ * Higher numbers are more verbose.
264
+ */
265
+ const logLevel = {
266
+ silent: Number.NEGATIVE_INFINITY,
267
+ error: 0,
268
+ warn: 1,
269
+ info: 3,
270
+ verbose: 4,
271
+ debug: 5
272
+ };
273
+ //#endregion
274
+ //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
275
+ var Node = class {
276
+ value;
277
+ next;
278
+ constructor(value) {
279
+ this.value = value;
280
+ }
281
+ };
282
+ var Queue = class {
283
+ #head;
284
+ #tail;
285
+ #size;
286
+ constructor() {
287
+ this.clear();
288
+ }
289
+ enqueue(value) {
290
+ const node = new Node(value);
291
+ if (this.#head) {
292
+ this.#tail.next = node;
293
+ this.#tail = node;
294
+ } else {
295
+ this.#head = node;
296
+ this.#tail = node;
297
+ }
298
+ this.#size++;
299
+ }
300
+ dequeue() {
301
+ const current = this.#head;
302
+ if (!current) return;
303
+ this.#head = this.#head.next;
304
+ this.#size--;
305
+ if (!this.#head) this.#tail = void 0;
306
+ return current.value;
307
+ }
308
+ peek() {
309
+ if (!this.#head) return;
310
+ return this.#head.value;
311
+ }
312
+ clear() {
313
+ this.#head = void 0;
314
+ this.#tail = void 0;
315
+ this.#size = 0;
316
+ }
317
+ get size() {
318
+ return this.#size;
319
+ }
320
+ *[Symbol.iterator]() {
321
+ let current = this.#head;
322
+ while (current) {
323
+ yield current.value;
324
+ current = current.next;
325
+ }
326
+ }
327
+ *drain() {
328
+ while (this.#head) yield this.dequeue();
329
+ }
330
+ };
331
+ //#endregion
332
+ //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
333
+ function pLimit(concurrency) {
334
+ let rejectOnClear = false;
335
+ if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
336
+ validateConcurrency(concurrency);
337
+ if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
338
+ const queue = new Queue();
339
+ let activeCount = 0;
340
+ const resumeNext = () => {
341
+ if (activeCount < concurrency && queue.size > 0) {
342
+ activeCount++;
343
+ queue.dequeue().run();
344
+ }
345
+ };
346
+ const next = () => {
347
+ activeCount--;
348
+ resumeNext();
349
+ };
350
+ const run = async (function_, resolve, arguments_) => {
351
+ const result = (async () => function_(...arguments_))();
352
+ resolve(result);
353
+ try {
354
+ await result;
355
+ } catch {}
356
+ next();
357
+ };
358
+ const enqueue = (function_, resolve, reject, arguments_) => {
359
+ const queueItem = { reject };
360
+ new Promise((internalResolve) => {
361
+ queueItem.run = internalResolve;
362
+ queue.enqueue(queueItem);
363
+ }).then(run.bind(void 0, function_, resolve, arguments_));
364
+ if (activeCount < concurrency) resumeNext();
365
+ };
366
+ const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
367
+ enqueue(function_, resolve, reject, arguments_);
368
+ });
369
+ Object.defineProperties(generator, {
370
+ activeCount: { get: () => activeCount },
371
+ pendingCount: { get: () => queue.size },
372
+ clearQueue: { value() {
373
+ if (!rejectOnClear) {
374
+ queue.clear();
375
+ return;
376
+ }
377
+ const abortError = AbortSignal.abort().reason;
378
+ while (queue.size > 0) queue.dequeue().reject(abortError);
379
+ } },
380
+ concurrency: {
381
+ get: () => concurrency,
382
+ set(newConcurrency) {
383
+ validateConcurrency(newConcurrency);
384
+ concurrency = newConcurrency;
385
+ queueMicrotask(() => {
386
+ while (activeCount < concurrency && queue.size > 0) resumeNext();
387
+ });
388
+ }
389
+ },
390
+ map: { async value(iterable, function_) {
391
+ const promises = Array.from(iterable, (value, index) => this(function_, value, index));
392
+ return Promise.all(promises);
393
+ } }
394
+ });
395
+ return generator;
396
+ }
397
+ function validateConcurrency(concurrency) {
398
+ if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
399
+ }
400
+ //#endregion
401
+ //#region src/definePlugin.ts
402
+ /**
403
+ * Returns `true` when `plugin` is a hook-style plugin created with `definePlugin`.
404
+ *
405
+ * Used by `PluginDriver` to distinguish hook-style plugins from legacy `createPlugin` plugins
406
+ * so it can normalize them and register their handlers on the `AsyncEventEmitter`.
407
+ */
408
+ function isHookStylePlugin(plugin) {
409
+ return typeof plugin === "object" && plugin !== null && "hooks" in plugin;
410
+ }
411
+ /**
412
+ * Creates a plugin factory using the new hook-style (`hooks:`) API.
413
+ *
414
+ * The returned factory is called with optional options and produces a `HookStylePlugin`
415
+ * that coexists with plugins created via the legacy `createPlugin` API in the same
416
+ * `kubb.config.ts`.
417
+ *
418
+ * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
419
+ * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
420
+ *
421
+ * @example
422
+ * ```ts
423
+ * // With PluginFactoryOptions (recommended for real plugins)
424
+ * export const pluginTs = definePlugin<PluginTs>((options) => ({
425
+ * name: 'plugin-ts',
426
+ * hooks: {
427
+ * 'kubb:plugin:setup'(ctx) {
428
+ * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
429
+ * },
430
+ * },
431
+ * }))
432
+ * ```
433
+ */
434
+ function definePlugin(factory) {
435
+ return (options) => factory(options ?? {});
436
+ }
437
+ //#endregion
438
+ //#region src/defineResolver.ts
439
+ /**
440
+ * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).
441
+ */
442
+ function matchesOperationPattern(node, type, pattern) {
443
+ switch (type) {
444
+ case "tag": return node.tags.some((tag) => !!tag.match(pattern));
445
+ case "operationId": return !!node.operationId.match(pattern);
446
+ case "path": return !!node.path.match(pattern);
447
+ case "method": return !!node.method.toLowerCase().match(pattern);
448
+ case "contentType": return !!node.requestBody?.contentType?.match(pattern);
449
+ default: return false;
450
+ }
451
+ }
452
+ /**
453
+ * Checks if a schema matches a pattern for a given filter type (`schemaName`).
454
+ *
455
+ * Returns `null` when the filter type doesn't apply to schemas.
456
+ */
457
+ function matchesSchemaPattern(node, type, pattern) {
458
+ switch (type) {
459
+ case "schemaName": return node.name ? !!node.name.match(pattern) : false;
460
+ default: return null;
461
+ }
462
+ }
463
+ /**
464
+ * Default name resolver used by `defineResolver`.
465
+ *
466
+ * - `camelCase` for `function` and `file` types.
467
+ * - `PascalCase` for `type`.
468
+ * - `camelCase` for everything else.
469
+ */
470
+ function defaultResolver(name, type) {
471
+ let resolvedName = camelCase(name);
472
+ if (type === "file" || type === "function") resolvedName = camelCase(name, { isFile: type === "file" });
473
+ if (type === "type") resolvedName = pascalCase(name);
474
+ return resolvedName;
475
+ }
476
+ /**
477
+ * Default option resolver — applies include/exclude filters and merges matching override options.
478
+ *
479
+ * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.
480
+ *
481
+ * @example Include/exclude filtering
482
+ * ```ts
483
+ * const options = defaultResolveOptions(operationNode, {
484
+ * options: { output: 'types' },
485
+ * exclude: [{ type: 'tag', pattern: 'internal' }],
486
+ * })
487
+ * // → null when node has tag 'internal'
488
+ * ```
489
+ *
490
+ * @example Override merging
491
+ * ```ts
492
+ * const options = defaultResolveOptions(operationNode, {
493
+ * options: { enumType: 'asConst' },
494
+ * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],
495
+ * })
496
+ * // → { enumType: 'enum' } when operationId matches
497
+ * ```
498
+ */
499
+ function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
500
+ if ((0, _kubb_ast.isOperationNode)(node)) {
501
+ if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
502
+ if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
503
+ const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options;
504
+ return {
505
+ ...options,
506
+ ...overrideOptions
507
+ };
508
+ }
509
+ if ((0, _kubb_ast.isSchemaNode)(node)) {
510
+ if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null;
511
+ if (include) {
512
+ const applicable = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern)).filter((r) => r !== null);
513
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
514
+ }
515
+ const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options;
516
+ return {
517
+ ...options,
518
+ ...overrideOptions
519
+ };
520
+ }
521
+ return options;
522
+ }
523
+ /**
524
+ * Default path resolver used by `defineResolver`.
525
+ *
526
+ * - Returns the output directory in `single` mode.
527
+ * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.
528
+ * - Falls back to a flat `output/baseName` path otherwise.
529
+ *
530
+ * A custom `group.name` function overrides the default subdirectory naming.
531
+ * For `tag` groups the default is `${camelCase(tag)}Controller`.
532
+ * For `path` groups the default is the first path segment after `/`.
533
+ *
534
+ * @example Flat output
535
+ * ```ts
536
+ * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
537
+ * // → '/src/types/petTypes.ts'
538
+ * ```
539
+ *
540
+ * @example Tag-based grouping
541
+ * ```ts
542
+ * defaultResolvePath(
543
+ * { baseName: 'petTypes.ts', tag: 'pets' },
544
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
545
+ * )
546
+ * // → '/src/types/petsController/petTypes.ts'
547
+ * ```
548
+ *
549
+ * @example Path-based grouping
550
+ * ```ts
551
+ * defaultResolvePath(
552
+ * { baseName: 'petTypes.ts', path: '/pets/list' },
553
+ * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
554
+ * )
555
+ * // → '/src/types/pets/petTypes.ts'
556
+ * ```
557
+ *
558
+ * @example Single-file mode
559
+ * ```ts
560
+ * defaultResolvePath(
561
+ * { baseName: 'petTypes.ts', pathMode: 'single' },
562
+ * { root: '/src', output: { path: 'types' } },
563
+ * )
564
+ * // → '/src/types'
565
+ * ```
566
+ */
567
+ function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
568
+ if ((pathMode ?? PluginDriver.getMode(node_path.default.resolve(root, output.path))) === "single") return node_path.default.resolve(root, output.path);
569
+ if (group && (groupPath || tag)) return node_path.default.resolve(root, output.path, group.name({ group: group.type === "path" ? groupPath : tag }), baseName);
570
+ return node_path.default.resolve(root, output.path, baseName);
571
+ }
572
+ /**
573
+ * Default file resolver used by `defineResolver`.
574
+ *
575
+ * Resolves a `FileNode` by combining name resolution (`resolver.default`) with
576
+ * path resolution (`resolver.resolvePath`). The resolved file always has empty
577
+ * `sources`, `imports`, and `exports` arrays — consumers populate those separately.
578
+ *
579
+ * In `single` mode the name is omitted and the file sits directly in the output directory.
580
+ *
581
+ * @example Resolve a schema file
582
+ * ```ts
583
+ * const file = defaultResolveFile.call(resolver,
584
+ * { name: 'pet', extname: '.ts' },
585
+ * { root: '/src', output: { path: 'types' } },
586
+ * )
587
+ * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }
588
+ * ```
589
+ *
590
+ * @example Resolve an operation file with tag grouping
591
+ * ```ts
592
+ * const file = defaultResolveFile.call(resolver,
593
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
594
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
595
+ * )
596
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
597
+ * ```
598
+ */
599
+ function defaultResolveFile({ name, extname, tag, path: groupPath }, context) {
600
+ const pathMode = PluginDriver.getMode(node_path.default.resolve(context.root, context.output.path));
601
+ const baseName = `${pathMode === "single" ? "" : this.default(name, "file")}${extname}`;
602
+ const filePath = this.resolvePath({
603
+ baseName,
604
+ pathMode,
605
+ tag,
606
+ path: groupPath
607
+ }, context);
608
+ return (0, _kubb_ast.createFile)({
609
+ path: filePath,
610
+ baseName: node_path.default.basename(filePath),
611
+ meta: { pluginName: this.pluginName },
612
+ sources: [],
613
+ imports: [],
614
+ exports: []
615
+ });
616
+ }
617
+ /**
618
+ * Generates the default "Generated by Kubb" banner from config and optional node metadata.
619
+ */
620
+ function buildDefaultBanner({ title, description, version, config }) {
621
+ try {
622
+ let source = "";
623
+ if (Array.isArray(config.input)) {
624
+ const first = config.input[0];
625
+ if (first && "path" in first) source = node_path.default.basename(first.path);
626
+ } else if ("path" in config.input) source = node_path.default.basename(config.input.path);
627
+ else if ("data" in config.input) source = "text content";
628
+ let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
629
+ if (config.output.defaultBanner === "simple") {
630
+ banner += "*/\n";
631
+ return banner;
632
+ }
633
+ if (source) banner += `* Source: ${source}\n`;
634
+ if (title) banner += `* Title: ${title}\n`;
635
+ if (description) {
636
+ const formattedDescription = description.replace(/\n/gm, "\n* ");
637
+ banner += `* Description: ${formattedDescription}\n`;
638
+ }
639
+ if (version) banner += `* OpenAPI spec version: ${version}\n`;
640
+ banner += "*/\n";
641
+ return banner;
642
+ } catch (_error) {
643
+ return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
644
+ }
645
+ }
646
+ /**
647
+ * Default banner resolver — returns the banner string for a generated file.
648
+ *
649
+ * A user-supplied `output.banner` overrides the default Kubb "Generated by Kubb" notice.
650
+ * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`
651
+ * from the OAS spec when a `node` is provided).
652
+ *
653
+ * - When `output.banner` is a function and `node` is provided, returns `output.banner(node)`.
654
+ * - When `output.banner` is a function and `node` is absent, falls back to the Kubb notice.
655
+ * - When `output.banner` is a string, returns it directly.
656
+ * - When `config.output.defaultBanner` is `false`, returns `undefined`.
657
+ * - Otherwise returns the Kubb "Generated by Kubb" notice.
658
+ *
659
+ * @example String banner overrides default
660
+ * ```ts
661
+ * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })
662
+ * // → '// my banner'
663
+ * ```
664
+ *
665
+ * @example Function banner with node
666
+ * ```ts
667
+ * defaultResolveBanner(inputNode, { output: { banner: (node) => `// v${node.version}` }, config })
668
+ * // → '// v3.0.0'
669
+ * ```
670
+ *
671
+ * @example No user banner — Kubb notice with OAS metadata
672
+ * ```ts
673
+ * defaultResolveBanner(inputNode, { config })
674
+ * // → '/** Generated by Kubb ... Title: Pet Store ... *\/'
675
+ * ```
676
+ *
677
+ * @example Disabled default banner
678
+ * ```ts
679
+ * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })
680
+ * // → undefined
681
+ * ```
682
+ */
683
+ function defaultResolveBanner(node, { output, config }) {
684
+ if (typeof output?.banner === "function") return output.banner(node);
685
+ if (typeof output?.banner === "string") return output.banner;
686
+ if (config.output.defaultBanner === false) return;
687
+ return buildDefaultBanner({
688
+ title: node?.meta?.title,
689
+ version: node?.meta?.version,
690
+ config
691
+ });
692
+ }
693
+ /**
694
+ * Default footer resolver — returns the footer string for a generated file.
695
+ *
696
+ * - When `output.footer` is a function and `node` is provided, calls it with the node.
697
+ * - When `output.footer` is a function and `node` is absent, returns `undefined`.
698
+ * - When `output.footer` is a string, returns it directly.
699
+ * - Otherwise returns `undefined`.
700
+ *
701
+ * @example String footer
702
+ * ```ts
703
+ * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })
704
+ * // → '// end of file'
705
+ * ```
706
+ *
707
+ * @example Function footer with node
708
+ * ```ts
709
+ * defaultResolveFooter(inputNode, { output: { footer: (node) => `// ${node.title}` }, config })
710
+ * // → '// Pet Store'
711
+ * ```
712
+ */
713
+ function defaultResolveFooter(node, { output }) {
714
+ if (typeof output?.footer === "function") return node ? output.footer(node) : void 0;
715
+ if (typeof output?.footer === "string") return output.footer;
716
+ }
717
+ /**
718
+ * Defines a resolver for a plugin, injecting built-in defaults for name casing,
719
+ * include/exclude/override filtering, path resolution, and file construction.
720
+ *
721
+ * All four defaults can be overridden by providing them in the builder function:
722
+ * - `default` — name casing strategy (camelCase / PascalCase)
723
+ * - `resolveOptions` — include/exclude/override filtering
724
+ * - `resolvePath` — output path computation
725
+ * - `resolveFile` — full `FileNode` construction
726
+ *
727
+ * Methods in the builder have access to `this` (the full resolver object), so they
728
+ * can call other resolver methods without circular imports.
729
+ *
730
+ * @example Basic resolver with naming helpers
731
+ * ```ts
732
+ * export const resolver = defineResolver<PluginTs>(() => ({
733
+ * name: 'default',
734
+ * resolveName(node) {
735
+ * return this.default(node.name, 'function')
736
+ * },
737
+ * resolveTypedName(node) {
738
+ * return this.default(node.name, 'type')
739
+ * },
740
+ * }))
741
+ * ```
742
+ *
743
+ * @example Override resolvePath for a custom output structure
744
+ * ```ts
745
+ * export const resolver = defineResolver<PluginTs>(() => ({
746
+ * name: 'custom',
747
+ * resolvePath({ baseName }, { root, output }) {
748
+ * return path.resolve(root, output.path, 'generated', baseName)
749
+ * },
750
+ * }))
751
+ * ```
752
+ *
753
+ * @example Use this.default inside a helper
754
+ * ```ts
755
+ * export const resolver = defineResolver<PluginTs>(() => ({
756
+ * name: 'default',
757
+ * resolveParamName(node, param) {
758
+ * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')
759
+ * },
760
+ * }))
761
+ * ```
762
+ */
763
+ function defineResolver(build) {
764
+ return {
765
+ default: defaultResolver,
766
+ resolveOptions: defaultResolveOptions,
767
+ resolvePath: defaultResolvePath,
768
+ resolveFile: defaultResolveFile,
769
+ resolveBanner: defaultResolveBanner,
770
+ resolveFooter: defaultResolveFooter,
771
+ ...build()
772
+ };
773
+ }
774
+ //#endregion
775
+ //#region src/devtools.ts
776
+ /**
777
+ * Encodes an `InputNode` as a compressed, URL-safe string.
778
+ *
779
+ * The JSON representation is deflate-compressed with {@link deflateSync} before
780
+ * base64url encoding, which typically reduces payload size by 70–80 % and
781
+ * keeps URLs well within browser and server path-length limits.
782
+ *
783
+ * Use {@link decodeAst} to reverse.
784
+ */
785
+ function encodeAst(input) {
786
+ const compressed = (0, fflate.deflateSync)(new TextEncoder().encode(JSON.stringify(input)));
787
+ return Buffer.from(compressed).toString("base64url");
788
+ }
789
+ /**
790
+ * Constructs the Kubb Studio URL for the given `InputNode`.
791
+ * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).
792
+ * The `input` is encoded and attached as the `?root=` query parameter so Studio
793
+ * can decode and render it without a round-trip to any server.
794
+ */
795
+ function getStudioUrl(input, studioUrl, options = {}) {
796
+ return `${studioUrl.replace(/\/$/, "")}${options.ast ? "/ast" : ""}?root=${encodeAst(input)}`;
797
+ }
798
+ /**
799
+ * Opens the Kubb Studio URL for the given `InputNode` in the default browser —
800
+ *
801
+ * Falls back to printing the URL if the browser cannot be launched.
802
+ */
803
+ async function openInStudio(input, studioUrl, options = {}) {
804
+ const url = getStudioUrl(input, studioUrl, options);
805
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
806
+ const args = process.platform === "win32" ? [
807
+ "/c",
808
+ "start",
809
+ "",
810
+ url
811
+ ] : [url];
812
+ try {
813
+ await (0, tinyexec.x)(cmd, args);
814
+ } catch {
815
+ console.log(`\n ${url}\n`);
816
+ }
817
+ }
818
+ //#endregion
819
+ //#region src/FileManager.ts
820
+ function mergeFile(a, b) {
821
+ return {
822
+ ...a,
823
+ sources: [...a.sources || [], ...b.sources || []],
824
+ imports: [...a.imports || [], ...b.imports || []],
825
+ exports: [...a.exports || [], ...b.exports || []]
826
+ };
827
+ }
828
+ /**
829
+ * In-memory file store for generated files.
830
+ *
831
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
832
+ * The `files` getter returns all stored files sorted by path length (shortest first).
833
+ *
834
+ * @example
835
+ * ```ts
836
+ * import { FileManager } from '@kubb/core'
837
+ *
838
+ * const manager = new FileManager()
839
+ * manager.upsert(myFile)
840
+ * console.log(manager.files) // all stored files
841
+ * ```
842
+ */
843
+ var FileManager = class {
844
+ #cache = /* @__PURE__ */ new Map();
845
+ #filesCache = null;
846
+ /**
847
+ * Adds one or more files. Files with the same path are merged — sources, imports,
848
+ * and exports from all calls with the same path are concatenated together.
849
+ */
850
+ add(...files) {
851
+ const resolvedFiles = [];
852
+ const mergedFiles = /* @__PURE__ */ new Map();
853
+ files.forEach((file) => {
854
+ const existing = mergedFiles.get(file.path);
855
+ if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
856
+ else mergedFiles.set(file.path, file);
857
+ });
858
+ for (const file of mergedFiles.values()) {
859
+ const resolvedFile = (0, _kubb_ast.createFile)(file);
860
+ this.#cache.set(resolvedFile.path, resolvedFile);
861
+ this.#filesCache = null;
862
+ resolvedFiles.push(resolvedFile);
863
+ }
864
+ return resolvedFiles;
865
+ }
866
+ /**
867
+ * Adds or merges one or more files.
868
+ * If a file with the same path already exists, its sources/imports/exports are merged together.
869
+ */
870
+ upsert(...files) {
871
+ const resolvedFiles = [];
872
+ const mergedFiles = /* @__PURE__ */ new Map();
873
+ files.forEach((file) => {
874
+ const existing = mergedFiles.get(file.path);
875
+ if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
876
+ else mergedFiles.set(file.path, file);
877
+ });
878
+ for (const file of mergedFiles.values()) {
879
+ const existing = this.#cache.get(file.path);
880
+ const resolvedFile = (0, _kubb_ast.createFile)(existing ? mergeFile(existing, file) : file);
881
+ this.#cache.set(resolvedFile.path, resolvedFile);
882
+ this.#filesCache = null;
883
+ resolvedFiles.push(resolvedFile);
884
+ }
885
+ return resolvedFiles;
886
+ }
887
+ getByPath(path) {
888
+ return this.#cache.get(path) ?? null;
889
+ }
890
+ deleteByPath(path) {
891
+ this.#cache.delete(path);
892
+ this.#filesCache = null;
893
+ }
894
+ clear() {
895
+ this.#cache.clear();
896
+ this.#filesCache = null;
897
+ }
898
+ /**
899
+ * All stored files, sorted by path length (shorter paths first).
900
+ * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
901
+ */
902
+ get files() {
903
+ if (this.#filesCache) return this.#filesCache;
904
+ const keys = [...this.#cache.keys()].sort((a, b) => {
905
+ if (a.length !== b.length) return a.length - b.length;
906
+ const aIsIndex = trimExtName(a).endsWith("index");
907
+ if (aIsIndex !== trimExtName(b).endsWith("index")) return aIsIndex ? 1 : -1;
908
+ return 0;
909
+ });
910
+ const files = [];
911
+ for (const key of keys) {
912
+ const file = this.#cache.get(key);
913
+ if (file) files.push(file);
914
+ }
915
+ this.#filesCache = files;
916
+ return files;
917
+ }
918
+ };
919
+ //#endregion
920
+ //#region src/renderNode.ts
921
+ /**
922
+ * Handles the return value of a plugin AST hook or generator method.
923
+ *
924
+ * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
925
+ * - `Array<FileNode>` → added directly into `driver.fileManager`
926
+ * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
927
+ *
928
+ * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
929
+ * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
930
+ */
931
+ async function applyHookResult(result, driver, rendererFactory) {
932
+ if (!result) return;
933
+ if (Array.isArray(result)) {
934
+ driver.fileManager.upsert(...result);
935
+ return;
936
+ }
937
+ if (!rendererFactory) return;
938
+ const renderer = rendererFactory();
939
+ await renderer.render(result);
940
+ driver.fileManager.upsert(...renderer.files);
941
+ renderer.unmount();
942
+ }
943
+ //#endregion
944
+ //#region src/utils/executeStrategies.ts
945
+ /**
946
+ * Runs promise functions in sequence, threading each result into the next call.
947
+ *
948
+ * - Each function receives the accumulated state from the previous call.
949
+ * - Skips functions that return a falsy value (acts as a no-op for that step).
950
+ * - Returns an array of all individual results.
951
+ * @deprecated
952
+ */
953
+ function hookSeq(promises) {
954
+ return promises.filter(Boolean).reduce((promise, func) => {
955
+ if (typeof func !== "function") throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
956
+ return promise.then((state) => {
957
+ const calledFunc = func(state);
958
+ if (calledFunc) return calledFunc.then(Array.prototype.concat.bind(state));
959
+ return state;
960
+ });
961
+ }, Promise.resolve([]));
962
+ }
963
+ /**
964
+ * Runs promise functions in sequence and returns the first non-null result.
965
+ *
966
+ * - Stops as soon as `nullCheck` passes for a result (default: `!== null`).
967
+ * - Subsequent functions are skipped once a match is found.
968
+ * @deprecated
969
+ */
970
+ function hookFirst(promises, nullCheck = (state) => state !== null) {
971
+ let promise = Promise.resolve(null);
972
+ for (const func of promises.filter(Boolean)) promise = promise.then((state) => {
973
+ if (nullCheck(state)) return state;
974
+ return func(state);
975
+ });
976
+ return promise;
977
+ }
978
+ /**
979
+ * Runs promise functions concurrently and returns all settled results.
980
+ *
981
+ * - Limits simultaneous executions to `concurrency` (default: unlimited).
982
+ * - Uses `Promise.allSettled` so individual failures do not cancel other tasks.
983
+ * @deprecated
984
+ */
985
+ function hookParallel(promises, concurrency = Number.POSITIVE_INFINITY) {
986
+ const limit = pLimit(concurrency);
987
+ const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()));
988
+ return Promise.allSettled(tasks);
989
+ }
990
+ //#endregion
991
+ //#region src/PluginDriver.ts
992
+ const hookFirstNullCheck = (state) => !!state?.result;
993
+ var PluginDriver = class PluginDriver {
994
+ config;
995
+ options;
996
+ /**
997
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
998
+ *
999
+ * @example
1000
+ * ```ts
1001
+ * PluginDriver.getMode('src/gen/types.ts') // 'single'
1002
+ * PluginDriver.getMode('src/gen/types') // 'split'
1003
+ * ```
1004
+ */
1005
+ static getMode(fileOrFolder) {
1006
+ if (!fileOrFolder) return "split";
1007
+ return (0, node_path.extname)(fileOrFolder) ? "single" : "split";
1008
+ }
1009
+ /**
1010
+ * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
1011
+ * the build pipeline after the adapter's `parse()` resolves.
1012
+ */
1013
+ inputNode = void 0;
1014
+ adapter = void 0;
1015
+ #studioIsOpen = false;
1016
+ /**
1017
+ * Central file store for all generated files.
1018
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1019
+ * add files; this property gives direct read/write access when needed.
1020
+ */
1021
+ fileManager = new FileManager();
1022
+ plugins = /* @__PURE__ */ new Map();
1023
+ /**
1024
+ * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
1025
+ * Used by the build loop to decide whether to emit generator events for a given plugin.
1026
+ */
1027
+ #pluginsWithEventGenerators = /* @__PURE__ */ new Set();
1028
+ #resolvers = /* @__PURE__ */ new Map();
1029
+ #defaultResolvers = /* @__PURE__ */ new Map();
1030
+ #hookListeners = /* @__PURE__ */ new Map();
1031
+ constructor(config, options) {
1032
+ this.config = config;
1033
+ this.options = {
1034
+ ...options,
1035
+ hooks: options.hooks
1036
+ };
1037
+ config.plugins.map((rawPlugin) => {
1038
+ if (isHookStylePlugin(rawPlugin)) return this.#normalizeHookStylePlugin(rawPlugin);
1039
+ return {
1040
+ ...rawPlugin,
1041
+ buildStart: rawPlugin.buildStart ?? (() => {}),
1042
+ buildEnd: rawPlugin.buildEnd ?? (() => {})
1043
+ };
1044
+ }).filter((plugin) => {
1045
+ if (typeof plugin.apply === "function") return plugin.apply(config);
1046
+ return true;
1047
+ }).sort((a, b) => {
1048
+ if (b.dependencies?.includes(a.name)) return -1;
1049
+ if (a.dependencies?.includes(b.name)) return 1;
1050
+ return 0;
1051
+ }).forEach((plugin) => {
1052
+ this.plugins.set(plugin.name, plugin);
1053
+ });
1054
+ }
1055
+ get hooks() {
1056
+ if (!this.options.hooks) throw new Error("hooks are not defined");
1057
+ return this.options.hooks;
1058
+ }
1059
+ /**
1060
+ * Creates a `Plugin`-compatible object from a hook-style plugin and registers
1061
+ * its lifecycle handlers on the `AsyncEventEmitter`.
1062
+ *
1063
+ * The normalized plugin has an empty `buildStart` — generators registered via
1064
+ * `addGenerator()` in `kubb:plugin:setup` are stored on `normalizedPlugin.generators`
1065
+ * and used by `runPluginAstHooks` during the build.
1066
+ */
1067
+ #normalizeHookStylePlugin(hookPlugin) {
1068
+ const generators = [];
1069
+ const driver = this;
1070
+ const normalizedPlugin = {
1071
+ name: hookPlugin.name,
1072
+ dependencies: hookPlugin.dependencies,
1073
+ options: {
1074
+ output: { path: "." },
1075
+ exclude: [],
1076
+ override: []
1077
+ },
1078
+ generators,
1079
+ inject: () => void 0,
1080
+ resolveName(name, type) {
1081
+ return driver.getResolver(hookPlugin.name).default(name, type);
1082
+ },
1083
+ resolvePath(baseName, pathMode, resolveOptions) {
1084
+ const resolver = driver.getResolver(hookPlugin.name);
1085
+ const opts = normalizedPlugin.options;
1086
+ const group = resolveOptions?.group;
1087
+ return resolver.resolvePath({
1088
+ baseName,
1089
+ pathMode,
1090
+ tag: group?.tag,
1091
+ path: group?.path
1092
+ }, {
1093
+ root: (0, node_path.resolve)(driver.config.root, driver.config.output.path),
1094
+ output: opts.output,
1095
+ group: opts.group
1096
+ });
1097
+ },
1098
+ buildStart() {},
1099
+ buildEnd() {}
1100
+ };
1101
+ this.registerPluginHooks(hookPlugin, normalizedPlugin);
1102
+ return normalizedPlugin;
1103
+ }
1104
+ /**
1105
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
1106
+ *
1107
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
1108
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
1109
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
1110
+ *
1111
+ * All other hooks are iterated and registered directly as pass-through listeners.
1112
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
1113
+ *
1114
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
1115
+ * the plugin lifecycle without modifying plugin behavior.
1116
+ */
1117
+ registerPluginHooks(hookPlugin, normalizedPlugin) {
1118
+ const { hooks } = hookPlugin;
1119
+ if (hooks["kubb:plugin:setup"]) {
1120
+ const setupHandler = (globalCtx) => {
1121
+ const pluginCtx = {
1122
+ ...globalCtx,
1123
+ options: hookPlugin.options ?? {},
1124
+ addGenerator: (gen) => {
1125
+ this.registerGenerator(normalizedPlugin.name, gen);
1126
+ },
1127
+ setResolver: (resolver) => {
1128
+ this.setPluginResolver(normalizedPlugin.name, resolver);
1129
+ },
1130
+ setTransformer: (visitor) => {
1131
+ normalizedPlugin.transformer = visitor;
1132
+ },
1133
+ setRenderer: (renderer) => {
1134
+ normalizedPlugin.renderer = renderer;
1135
+ },
1136
+ setOptions: (opts) => {
1137
+ normalizedPlugin.options = {
1138
+ ...normalizedPlugin.options,
1139
+ ...opts
1140
+ };
1141
+ },
1142
+ injectFile: (file) => {
1143
+ const fileNode = (0, _kubb_ast.createFile)({
1144
+ baseName: file.baseName,
1145
+ path: file.path,
1146
+ sources: file.sources ?? [],
1147
+ imports: [],
1148
+ exports: []
1149
+ });
1150
+ this.fileManager.add(fileNode);
1151
+ }
1152
+ };
1153
+ return hooks["kubb:plugin:setup"](pluginCtx);
1154
+ };
1155
+ this.hooks.on("kubb:plugin:setup", setupHandler);
1156
+ this.#trackHookListener("kubb:plugin:setup", setupHandler);
1157
+ }
1158
+ for (const [event, handler] of Object.entries(hooks)) {
1159
+ if (event === "kubb:plugin:setup" || !handler) continue;
1160
+ this.hooks.on(event, handler);
1161
+ this.#trackHookListener(event, handler);
1162
+ }
1163
+ }
1164
+ /**
1165
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
1166
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
1167
+ *
1168
+ * Call this once from `safeBuild` before the plugin execution loop begins.
1169
+ */
1170
+ async emitSetupHooks() {
1171
+ await this.hooks.emit("kubb:plugin:setup", {
1172
+ config: this.config,
1173
+ addGenerator: () => {},
1174
+ setResolver: () => {},
1175
+ setTransformer: () => {},
1176
+ setRenderer: () => {},
1177
+ setOptions: () => {},
1178
+ injectFile: () => {},
1179
+ updateConfig: () => {},
1180
+ options: {}
1181
+ });
1182
+ }
1183
+ /**
1184
+ * Registers a generator for the given plugin on the shared event emitter.
1185
+ *
1186
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1187
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1188
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1189
+ * so that generators from different plugins do not cross-fire.
1190
+ *
1191
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
1192
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
1193
+ * declares a renderer.
1194
+ *
1195
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1196
+ */
1197
+ registerGenerator(pluginName, gen) {
1198
+ const resolveRenderer = () => {
1199
+ const plugin = this.plugins.get(pluginName);
1200
+ return gen.renderer === null ? void 0 : gen.renderer ?? plugin?.renderer ?? this.config.renderer;
1201
+ };
1202
+ if (gen.schema) {
1203
+ const schemaHandler = async (node, ctx) => {
1204
+ if (ctx.plugin.name !== pluginName) return;
1205
+ await applyHookResult(await gen.schema(node, ctx), this, resolveRenderer());
1206
+ };
1207
+ this.hooks.on("kubb:generate:schema", schemaHandler);
1208
+ this.#trackHookListener("kubb:generate:schema", schemaHandler);
1209
+ }
1210
+ if (gen.operation) {
1211
+ const operationHandler = async (node, ctx) => {
1212
+ if (ctx.plugin.name !== pluginName) return;
1213
+ await applyHookResult(await gen.operation(node, ctx), this, resolveRenderer());
1214
+ };
1215
+ this.hooks.on("kubb:generate:operation", operationHandler);
1216
+ this.#trackHookListener("kubb:generate:operation", operationHandler);
1217
+ }
1218
+ if (gen.operations) {
1219
+ const operationsHandler = async (nodes, ctx) => {
1220
+ if (ctx.plugin.name !== pluginName) return;
1221
+ await applyHookResult(await gen.operations(nodes, ctx), this, resolveRenderer());
1222
+ };
1223
+ this.hooks.on("kubb:generate:operations", operationsHandler);
1224
+ this.#trackHookListener("kubb:generate:operations", operationsHandler);
1225
+ }
1226
+ this.#pluginsWithEventGenerators.add(pluginName);
1227
+ }
1228
+ /**
1229
+ * Returns `true` when at least one generator was registered for the given plugin
1230
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
1231
+ *
1232
+ * Used by the build loop to decide whether to walk the AST and emit generator events
1233
+ * for a plugin that has no static `plugin.generators`.
1234
+ */
1235
+ hasRegisteredGenerators(pluginName) {
1236
+ return this.#pluginsWithEventGenerators.has(pluginName);
1237
+ }
1238
+ dispose() {
1239
+ for (const [event, handlers] of this.#hookListeners) for (const handler of handlers) this.hooks.off(event, handler);
1240
+ this.#hookListeners.clear();
1241
+ this.#pluginsWithEventGenerators.clear();
1242
+ }
1243
+ #trackHookListener(event, handler) {
1244
+ let handlers = this.#hookListeners.get(event);
1245
+ if (!handlers) {
1246
+ handlers = /* @__PURE__ */ new Set();
1247
+ this.#hookListeners.set(event, handlers);
1248
+ }
1249
+ handlers.add(handler);
1250
+ }
1251
+ #createDefaultResolver(pluginName) {
1252
+ const existingResolver = this.#defaultResolvers.get(pluginName);
1253
+ if (existingResolver) return existingResolver;
1254
+ const resolver = defineResolver(() => ({
1255
+ name: "default",
1256
+ pluginName
1257
+ }));
1258
+ this.#defaultResolvers.set(pluginName, resolver);
1259
+ return resolver;
1260
+ }
1261
+ setPluginResolver(pluginName, partial) {
1262
+ const merged = {
1263
+ ...this.#createDefaultResolver(pluginName),
1264
+ ...partial
1265
+ };
1266
+ this.#resolvers.set(pluginName, merged);
1267
+ const plugin = this.plugins.get(pluginName);
1268
+ if (plugin) plugin.resolver = merged;
1269
+ }
1270
+ getResolver(pluginName) {
1271
+ const dynamicResolver = this.#resolvers.get(pluginName);
1272
+ if (dynamicResolver) return dynamicResolver;
1273
+ const pluginResolver = this.plugins.get(pluginName)?.resolver;
1274
+ if (pluginResolver) return pluginResolver;
1275
+ return this.#createDefaultResolver(pluginName);
1276
+ }
1277
+ getContext(plugin) {
1278
+ const driver = this;
1279
+ const baseContext = {
1280
+ config: driver.config,
1281
+ get root() {
1282
+ return (0, node_path.resolve)(driver.config.root, driver.config.output.path);
1283
+ },
1284
+ getMode(output) {
1285
+ return PluginDriver.getMode((0, node_path.resolve)(driver.config.root, driver.config.output.path, output.path));
1286
+ },
1287
+ hooks: driver.hooks,
1288
+ plugin,
1289
+ getPlugin: driver.getPlugin.bind(driver),
1290
+ requirePlugin: driver.requirePlugin.bind(driver),
1291
+ driver,
1292
+ addFile: async (...files) => {
1293
+ driver.fileManager.add(...files);
1294
+ },
1295
+ upsertFile: async (...files) => {
1296
+ driver.fileManager.upsert(...files);
1297
+ },
1298
+ get inputNode() {
1299
+ return driver.inputNode;
1300
+ },
1301
+ get adapter() {
1302
+ return driver.adapter;
1303
+ },
1304
+ get resolver() {
1305
+ return driver.getResolver(plugin.name);
1306
+ },
1307
+ get transformer() {
1308
+ return plugin.transformer;
1309
+ },
1310
+ warn(message) {
1311
+ driver.hooks.emit("kubb:warn", message);
1312
+ },
1313
+ error(error) {
1314
+ driver.hooks.emit("kubb:error", typeof error === "string" ? new Error(error) : error);
1315
+ },
1316
+ info(message) {
1317
+ driver.hooks.emit("kubb:info", message);
1318
+ },
1319
+ openInStudio(options) {
1320
+ if (!driver.config.devtools || driver.#studioIsOpen) return;
1321
+ if (typeof driver.config.devtools !== "object") throw new Error("Devtools must be an object");
1322
+ if (!driver.inputNode || !driver.adapter) throw new Error("adapter is not defined, make sure you have set the parser in kubb.config.ts");
1323
+ driver.#studioIsOpen = true;
1324
+ const studioUrl = driver.config.devtools?.studioUrl ?? "https://studio.kubb.dev";
1325
+ return openInStudio(driver.inputNode, studioUrl, options);
1326
+ }
1327
+ };
1328
+ let mergedExtras = {};
1329
+ for (const p of this.plugins.values()) if (typeof p.inject === "function") {
1330
+ const result = p.inject.call(baseContext);
1331
+ if (result !== null && typeof result === "object") mergedExtras = {
1332
+ ...mergedExtras,
1333
+ ...result
1334
+ };
1335
+ }
1336
+ return {
1337
+ ...baseContext,
1338
+ ...mergedExtras
1339
+ };
1340
+ }
1341
+ /**
1342
+ * @deprecated use resolvers context instead
1343
+ */
1344
+ getFile({ name, mode, extname, pluginName, options }) {
1345
+ const resolvedName = mode ? mode === "single" ? "" : this.resolveName({
1346
+ name,
1347
+ pluginName,
1348
+ type: "file"
1349
+ }) : name;
1350
+ const path = this.resolvePath({
1351
+ baseName: `${resolvedName}${extname}`,
1352
+ mode,
1353
+ pluginName,
1354
+ options
1355
+ });
1356
+ if (!path) throw new Error(`Filepath should be defined for resolvedName "${resolvedName}" and pluginName "${pluginName}"`);
1357
+ return (0, _kubb_ast.createFile)({
1358
+ path,
1359
+ baseName: (0, node_path.basename)(path),
1360
+ meta: { pluginName },
1361
+ sources: [],
1362
+ imports: [],
1363
+ exports: []
1364
+ });
1365
+ }
1366
+ /**
1367
+ * @deprecated use resolvers context instead
1368
+ */
1369
+ resolvePath = (params) => {
1370
+ const defaultPath = (0, node_path.resolve)((0, node_path.resolve)(this.config.root, this.config.output.path), params.baseName);
1371
+ if (params.pluginName) return this.hookForPluginSync({
1372
+ pluginName: params.pluginName,
1373
+ hookName: "resolvePath",
1374
+ parameters: [
1375
+ params.baseName,
1376
+ params.mode,
1377
+ params.options
1378
+ ]
1379
+ })?.at(0) || defaultPath;
1380
+ return this.hookFirstSync({
1381
+ hookName: "resolvePath",
1382
+ parameters: [
1383
+ params.baseName,
1384
+ params.mode,
1385
+ params.options
1386
+ ]
1387
+ })?.result || defaultPath;
1388
+ };
1389
+ /**
1390
+ * @deprecated use resolvers context instead
1391
+ */
1392
+ resolveName = (params) => {
1393
+ if (params.pluginName) return transformReservedWord(this.hookForPluginSync({
1394
+ pluginName: params.pluginName,
1395
+ hookName: "resolveName",
1396
+ parameters: [params.name.trim(), params.type]
1397
+ })?.at(0) ?? params.name);
1398
+ const name = this.hookFirstSync({
1399
+ hookName: "resolveName",
1400
+ parameters: [params.name.trim(), params.type]
1401
+ })?.result;
1402
+ return transformReservedWord(name ?? params.name);
1403
+ };
1404
+ /**
1405
+ * Run a specific hookName for plugin x.
1406
+ */
1407
+ async hookForPlugin({ pluginName, hookName, parameters }) {
1408
+ const plugin = this.plugins.get(pluginName);
1409
+ if (!plugin) return [null];
1410
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1411
+ hookName,
1412
+ plugins: [plugin]
1413
+ });
1414
+ const result = await this.#execute({
1415
+ strategy: "hookFirst",
1416
+ hookName,
1417
+ parameters,
1418
+ plugin
1419
+ });
1420
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1421
+ return [result];
1422
+ }
1423
+ /**
1424
+ * Run a specific hookName for plugin x.
1425
+ */
1426
+ hookForPluginSync({ pluginName, hookName, parameters }) {
1427
+ const plugin = this.plugins.get(pluginName);
1428
+ if (!plugin) return null;
1429
+ const result = this.#executeSync({
1430
+ strategy: "hookFirst",
1431
+ hookName,
1432
+ parameters,
1433
+ plugin
1434
+ });
1435
+ return result !== null ? [result] : [];
1436
+ }
1437
+ /**
1438
+ * Returns the first non-null result.
1439
+ */
1440
+ async hookFirst({ hookName, parameters, skipped }) {
1441
+ const plugins = [];
1442
+ for (const plugin of this.plugins.values()) if (hookName in plugin && (skipped ? !skipped.has(plugin) : true)) plugins.push(plugin);
1443
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1444
+ hookName,
1445
+ plugins
1446
+ });
1447
+ const result = await hookFirst(plugins.map((plugin) => {
1448
+ return async () => {
1449
+ const value = await this.#execute({
1450
+ strategy: "hookFirst",
1451
+ hookName,
1452
+ parameters,
1453
+ plugin
1454
+ });
1455
+ return Promise.resolve({
1456
+ plugin,
1457
+ result: value
1458
+ });
1459
+ };
1460
+ }), hookFirstNullCheck);
1461
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1462
+ return result;
1463
+ }
1464
+ /**
1465
+ * Returns the first non-null result.
1466
+ */
1467
+ hookFirstSync({ hookName, parameters, skipped }) {
1468
+ let parseResult = null;
1469
+ for (const plugin of this.plugins.values()) {
1470
+ if (!(hookName in plugin)) continue;
1471
+ if (skipped?.has(plugin)) continue;
1472
+ parseResult = {
1473
+ result: this.#executeSync({
1474
+ strategy: "hookFirst",
1475
+ hookName,
1476
+ parameters,
1477
+ plugin
1478
+ }),
1479
+ plugin
1480
+ };
1481
+ if (parseResult.result != null) break;
1482
+ }
1483
+ return parseResult;
1484
+ }
1485
+ /**
1486
+ * Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
1487
+ */
1488
+ async hookParallel({ hookName, parameters }) {
1489
+ const plugins = [];
1490
+ for (const plugin of this.plugins.values()) if (hookName in plugin) plugins.push(plugin);
1491
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1492
+ hookName,
1493
+ plugins
1494
+ });
1495
+ const pluginStartTimes = /* @__PURE__ */ new Map();
1496
+ const results = await hookParallel(plugins.map((plugin) => {
1497
+ return () => {
1498
+ pluginStartTimes.set(plugin, node_perf_hooks.performance.now());
1499
+ return this.#execute({
1500
+ strategy: "hookParallel",
1501
+ hookName,
1502
+ parameters,
1503
+ plugin
1504
+ });
1505
+ };
1506
+ }), this.options.concurrency);
1507
+ results.forEach((result, index) => {
1508
+ if (isPromiseRejectedResult(result)) {
1509
+ const plugin = plugins[index];
1510
+ if (plugin) {
1511
+ const startTime = pluginStartTimes.get(plugin) ?? node_perf_hooks.performance.now();
1512
+ this.hooks.emit("kubb:error", result.reason, {
1513
+ plugin,
1514
+ hookName,
1515
+ strategy: "hookParallel",
1516
+ duration: Math.round(node_perf_hooks.performance.now() - startTime),
1517
+ parameters
1518
+ });
1519
+ }
1520
+ }
1521
+ });
1522
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1523
+ return results.reduce((acc, result) => {
1524
+ if (result.status === "fulfilled") acc.push(result.value);
1525
+ return acc;
1526
+ }, []);
1527
+ }
1528
+ /**
1529
+ * Execute a lifecycle hook sequentially for all plugins that implement it.
1530
+ */
1531
+ async hookSeq({ hookName, parameters }) {
1532
+ const plugins = [];
1533
+ for (const plugin of this.plugins.values()) if (hookName in plugin) plugins.push(plugin);
1534
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1535
+ hookName,
1536
+ plugins
1537
+ });
1538
+ await hookSeq(plugins.map((plugin) => {
1539
+ return () => this.#execute({
1540
+ strategy: "hookSeq",
1541
+ hookName,
1542
+ parameters,
1543
+ plugin
1544
+ });
1545
+ }));
1546
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1547
+ }
1548
+ getPlugin(pluginName) {
1549
+ return this.plugins.get(pluginName);
1550
+ }
1551
+ requirePlugin(pluginName) {
1552
+ const plugin = this.plugins.get(pluginName);
1553
+ if (!plugin) throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`);
1554
+ return plugin;
1555
+ }
1556
+ /**
1557
+ * Emit hook-processing completion metadata after a plugin hook resolves.
1558
+ */
1559
+ #emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters }) {
1560
+ this.hooks.emit("kubb:plugins:hook:processing:end", {
1561
+ duration: Math.round(node_perf_hooks.performance.now() - startTime),
1562
+ parameters,
1563
+ output,
1564
+ strategy,
1565
+ hookName,
1566
+ plugin
1567
+ });
1568
+ }
1569
+ #execute({ strategy, hookName, parameters, plugin }) {
1570
+ const hook = plugin[hookName];
1571
+ if (!hook) return null;
1572
+ this.hooks.emit("kubb:plugins:hook:processing:start", {
1573
+ strategy,
1574
+ hookName,
1575
+ parameters,
1576
+ plugin
1577
+ });
1578
+ const startTime = node_perf_hooks.performance.now();
1579
+ return (async () => {
1580
+ try {
1581
+ const output = typeof hook === "function" ? await Promise.resolve(hook.apply(this.getContext(plugin), parameters ?? [])) : hook;
1582
+ this.#emitProcessingEnd({
1583
+ startTime,
1584
+ output,
1585
+ strategy,
1586
+ hookName,
1587
+ plugin,
1588
+ parameters
1589
+ });
1590
+ return output;
1591
+ } catch (error) {
1592
+ this.hooks.emit("kubb:error", error, {
1593
+ plugin,
1594
+ hookName,
1595
+ strategy,
1596
+ duration: Math.round(node_perf_hooks.performance.now() - startTime)
1597
+ });
1598
+ return null;
1599
+ }
1600
+ })();
1601
+ }
1602
+ /**
1603
+ * Execute a plugin lifecycle hook synchronously and return its output.
1604
+ */
1605
+ #executeSync({ strategy, hookName, parameters, plugin }) {
1606
+ const hook = plugin[hookName];
1607
+ if (!hook) return null;
1608
+ this.hooks.emit("kubb:plugins:hook:processing:start", {
1609
+ strategy,
1610
+ hookName,
1611
+ parameters,
1612
+ plugin
1613
+ });
1614
+ const startTime = node_perf_hooks.performance.now();
1615
+ try {
1616
+ const output = typeof hook === "function" ? hook.apply(this.getContext(plugin), parameters) : hook;
1617
+ this.#emitProcessingEnd({
1618
+ startTime,
1619
+ output,
1620
+ strategy,
1621
+ hookName,
1622
+ plugin,
1623
+ parameters
1624
+ });
1625
+ return output;
1626
+ } catch (error) {
1627
+ this.hooks.emit("kubb:error", error, {
1628
+ plugin,
1629
+ hookName,
1630
+ strategy,
1631
+ duration: Math.round(node_perf_hooks.performance.now() - startTime)
1632
+ });
1633
+ return null;
1634
+ }
1635
+ }
1636
+ };
1637
+ //#endregion
1638
+ Object.defineProperty(exports, "BARREL_FILENAME", {
1639
+ enumerable: true,
1640
+ get: function() {
1641
+ return BARREL_FILENAME;
1642
+ }
1643
+ });
1644
+ Object.defineProperty(exports, "DEFAULT_BANNER", {
1645
+ enumerable: true,
1646
+ get: function() {
1647
+ return DEFAULT_BANNER;
1648
+ }
1649
+ });
1650
+ Object.defineProperty(exports, "DEFAULT_EXTENSION", {
1651
+ enumerable: true,
1652
+ get: function() {
1653
+ return DEFAULT_EXTENSION;
1654
+ }
1655
+ });
1656
+ Object.defineProperty(exports, "DEFAULT_STUDIO_URL", {
1657
+ enumerable: true,
1658
+ get: function() {
1659
+ return DEFAULT_STUDIO_URL;
1660
+ }
1661
+ });
1662
+ Object.defineProperty(exports, "FileManager", {
1663
+ enumerable: true,
1664
+ get: function() {
1665
+ return FileManager;
1666
+ }
1667
+ });
1668
+ Object.defineProperty(exports, "PluginDriver", {
1669
+ enumerable: true,
1670
+ get: function() {
1671
+ return PluginDriver;
1672
+ }
1673
+ });
1674
+ Object.defineProperty(exports, "__name", {
1675
+ enumerable: true,
1676
+ get: function() {
1677
+ return __name;
1678
+ }
1679
+ });
1680
+ Object.defineProperty(exports, "__toESM", {
1681
+ enumerable: true,
1682
+ get: function() {
1683
+ return __toESM;
1684
+ }
1685
+ });
1686
+ Object.defineProperty(exports, "applyHookResult", {
1687
+ enumerable: true,
1688
+ get: function() {
1689
+ return applyHookResult;
1690
+ }
1691
+ });
1692
+ Object.defineProperty(exports, "camelCase", {
1693
+ enumerable: true,
1694
+ get: function() {
1695
+ return camelCase;
1696
+ }
1697
+ });
1698
+ Object.defineProperty(exports, "definePlugin", {
1699
+ enumerable: true,
1700
+ get: function() {
1701
+ return definePlugin;
1702
+ }
1703
+ });
1704
+ Object.defineProperty(exports, "defineResolver", {
1705
+ enumerable: true,
1706
+ get: function() {
1707
+ return defineResolver;
1708
+ }
1709
+ });
1710
+ Object.defineProperty(exports, "isValidVarName", {
1711
+ enumerable: true,
1712
+ get: function() {
1713
+ return isValidVarName;
1714
+ }
1715
+ });
1716
+ Object.defineProperty(exports, "logLevel", {
1717
+ enumerable: true,
1718
+ get: function() {
1719
+ return logLevel;
1720
+ }
1721
+ });
1722
+ Object.defineProperty(exports, "pLimit", {
1723
+ enumerable: true,
1724
+ get: function() {
1725
+ return pLimit;
1726
+ }
1727
+ });
1728
+
1729
+ //# sourceMappingURL=PluginDriver-BQwm8hDd.cjs.map