@kubb/core 5.0.0-alpha.5 → 5.0.0-alpha.50

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 (71) hide show
  1. package/README.md +3 -2
  2. package/dist/PluginDriver-DtwggkXg.cjs +1082 -0
  3. package/dist/PluginDriver-DtwggkXg.cjs.map +1 -0
  4. package/dist/PluginDriver-mXeqWp-U.js +979 -0
  5. package/dist/PluginDriver-mXeqWp-U.js.map +1 -0
  6. package/dist/index.cjs +1013 -1829
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +274 -265
  9. package/dist/index.js +1003 -1799
  10. package/dist/index.js.map +1 -1
  11. package/dist/mocks.cjs +138 -0
  12. package/dist/mocks.cjs.map +1 -0
  13. package/dist/mocks.d.ts +74 -0
  14. package/dist/mocks.js +133 -0
  15. package/dist/mocks.js.map +1 -0
  16. package/dist/types-DfEv9d_c.d.ts +1721 -0
  17. package/package.json +51 -57
  18. package/src/FileManager.ts +133 -0
  19. package/src/FileProcessor.ts +86 -0
  20. package/src/Kubb.ts +154 -101
  21. package/src/PluginDriver.ts +418 -0
  22. package/src/constants.ts +43 -47
  23. package/src/createAdapter.ts +25 -0
  24. package/src/createKubb.ts +614 -0
  25. package/src/createRenderer.ts +57 -0
  26. package/src/createStorage.ts +58 -0
  27. package/src/defineGenerator.ts +88 -100
  28. package/src/defineLogger.ts +13 -3
  29. package/src/defineParser.ts +45 -0
  30. package/src/definePlugin.ts +68 -7
  31. package/src/defineResolver.ts +501 -0
  32. package/src/devtools.ts +14 -14
  33. package/src/index.ts +12 -17
  34. package/src/mocks.ts +171 -0
  35. package/src/renderNode.ts +35 -0
  36. package/src/storages/fsStorage.ts +40 -11
  37. package/src/storages/memoryStorage.ts +4 -3
  38. package/src/types.ts +575 -205
  39. package/src/utils/TreeNode.ts +47 -9
  40. package/src/utils/diagnostics.ts +4 -1
  41. package/src/utils/getBarrelFiles.ts +94 -16
  42. package/src/utils/isInputPath.ts +10 -0
  43. package/src/utils/packageJSON.ts +99 -0
  44. package/dist/PluginManager-vZodFEMe.d.ts +0 -1056
  45. package/dist/chunk-ByKO4r7w.cjs +0 -38
  46. package/dist/hooks.cjs +0 -60
  47. package/dist/hooks.cjs.map +0 -1
  48. package/dist/hooks.d.ts +0 -56
  49. package/dist/hooks.js +0 -56
  50. package/dist/hooks.js.map +0 -1
  51. package/src/BarrelManager.ts +0 -74
  52. package/src/PackageManager.ts +0 -180
  53. package/src/PluginManager.ts +0 -667
  54. package/src/PromiseManager.ts +0 -40
  55. package/src/build.ts +0 -419
  56. package/src/config.ts +0 -56
  57. package/src/defineAdapter.ts +0 -22
  58. package/src/defineStorage.ts +0 -56
  59. package/src/errors.ts +0 -1
  60. package/src/hooks/index.ts +0 -4
  61. package/src/hooks/useKubb.ts +0 -46
  62. package/src/hooks/useMode.ts +0 -11
  63. package/src/hooks/usePlugin.ts +0 -11
  64. package/src/hooks/usePluginManager.ts +0 -11
  65. package/src/utils/FunctionParams.ts +0 -155
  66. package/src/utils/executeStrategies.ts +0 -81
  67. package/src/utils/formatters.ts +0 -56
  68. package/src/utils/getConfigs.ts +0 -30
  69. package/src/utils/getPlugins.ts +0 -23
  70. package/src/utils/linters.ts +0 -25
  71. package/src/utils/resolveOptions.ts +0 -93
@@ -0,0 +1,979 @@
1
+ import "./chunk--u3MIqq1.js";
2
+ import path, { extname, resolve } from "node:path";
3
+ import { createFile, isOperationNode, isSchemaNode } from "@kubb/ast";
4
+ import { deflateSync } from "fflate";
5
+ import { x } from "tinyexec";
6
+ //#region ../../internals/utils/src/casing.ts
7
+ /**
8
+ * Shared implementation for camelCase and PascalCase conversion.
9
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
10
+ * and capitalizes each word according to `pascal`.
11
+ *
12
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
13
+ */
14
+ function toCamelOrPascal(text, pascal) {
15
+ 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) => {
16
+ if (word.length > 1 && word === word.toUpperCase()) return word;
17
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
18
+ return word.charAt(0).toUpperCase() + word.slice(1);
19
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
20
+ }
21
+ /**
22
+ * Splits `text` on `.` and applies `transformPart` to each segment.
23
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
24
+ * Segments are joined with `/` to form a file path.
25
+ *
26
+ * Only splits on dots followed by a letter so that version numbers
27
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
28
+ *
29
+ * Empty segments are filtered before joining. They arise when the text starts with
30
+ * a dot followed immediately by a letter (e.g. `..Schema` splits into `['..', 'Schema']`
31
+ * and `'..'` transforms to an empty string). Without this filter the join would produce
32
+ * a leading `/`, which `path.resolve` would interpret as an absolute path, allowing
33
+ * generated files to escape the configured output directory.
34
+ */
35
+ function applyToFileParts(text, transformPart) {
36
+ const parts = text.split(/\.(?=[a-zA-Z])/);
37
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).filter(Boolean).join("/");
38
+ }
39
+ /**
40
+ * Converts `text` to camelCase.
41
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
42
+ *
43
+ * @example
44
+ * camelCase('hello-world') // 'helloWorld'
45
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
46
+ */
47
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
48
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
49
+ prefix,
50
+ suffix
51
+ } : {}));
52
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
53
+ }
54
+ /**
55
+ * Converts `text` to PascalCase.
56
+ * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
57
+ *
58
+ * @example
59
+ * pascalCase('hello-world') // 'HelloWorld'
60
+ * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
61
+ */
62
+ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
63
+ if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
64
+ prefix,
65
+ suffix
66
+ }) : camelCase(part));
67
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
68
+ }
69
+ //#endregion
70
+ //#region ../../internals/utils/src/string.ts
71
+ /**
72
+ * Strips the file extension from a path or file name.
73
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
74
+ *
75
+ * @example
76
+ * trimExtName('petStore.ts') // 'petStore'
77
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
78
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
79
+ * trimExtName('noExtension') // 'noExtension'
80
+ */
81
+ function trimExtName(text) {
82
+ const dotIndex = text.lastIndexOf(".");
83
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
84
+ return text;
85
+ }
86
+ //#endregion
87
+ //#region src/constants.ts
88
+ /**
89
+ * Base URL for the Kubb Studio web app.
90
+ */
91
+ const DEFAULT_STUDIO_URL = "https://studio.kubb.dev";
92
+ /**
93
+ * Basename (without extension) of generated barrel files.
94
+ *
95
+ * Used to detect whether a path already points at a barrel so the generator
96
+ * avoids re-creating one on top of it.
97
+ */
98
+ const BARREL_BASENAME = "index";
99
+ /**
100
+ * File name used for generated barrel (index) files.
101
+ */
102
+ const BARREL_FILENAME = `${BARREL_BASENAME}.ts`;
103
+ /**
104
+ * Default banner style written at the top of every generated file.
105
+ */
106
+ const DEFAULT_BANNER = "simple";
107
+ /**
108
+ * Default file-extension mapping used when no explicit mapping is configured.
109
+ */
110
+ const DEFAULT_EXTENSION = { ".ts": ".ts" };
111
+ /**
112
+ * Numeric log-level thresholds used internally to compare verbosity.
113
+ *
114
+ * Higher numbers are more verbose.
115
+ */
116
+ const logLevel = {
117
+ silent: Number.NEGATIVE_INFINITY,
118
+ error: 0,
119
+ warn: 1,
120
+ info: 3,
121
+ verbose: 4,
122
+ debug: 5
123
+ };
124
+ //#endregion
125
+ //#region src/defineResolver.ts
126
+ const stringPatternCache = /* @__PURE__ */ new Map();
127
+ function testPattern(value, pattern) {
128
+ if (typeof pattern === "string") {
129
+ let regex = stringPatternCache.get(pattern);
130
+ if (!regex) {
131
+ regex = new RegExp(pattern);
132
+ stringPatternCache.set(pattern, regex);
133
+ }
134
+ return regex.test(value);
135
+ }
136
+ return value.match(pattern) !== null;
137
+ }
138
+ /**
139
+ * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).
140
+ */
141
+ function matchesOperationPattern(node, type, pattern) {
142
+ switch (type) {
143
+ case "tag": return node.tags.some((tag) => testPattern(tag, pattern));
144
+ case "operationId": return testPattern(node.operationId, pattern);
145
+ case "path": return testPattern(node.path, pattern);
146
+ case "method": return testPattern(node.method.toLowerCase(), pattern);
147
+ case "contentType": return node.requestBody?.contentType ? testPattern(node.requestBody.contentType, pattern) : false;
148
+ default: return false;
149
+ }
150
+ }
151
+ /**
152
+ * Checks if a schema matches a pattern for a given filter type (`schemaName`).
153
+ *
154
+ * Returns `null` when the filter type doesn't apply to schemas.
155
+ */
156
+ function matchesSchemaPattern(node, type, pattern) {
157
+ switch (type) {
158
+ case "schemaName": return node.name ? testPattern(node.name, pattern) : false;
159
+ default: return null;
160
+ }
161
+ }
162
+ /**
163
+ * Default name resolver used by `defineResolver`.
164
+ *
165
+ * - `camelCase` for `function` and `file` types.
166
+ * - `PascalCase` for `type`.
167
+ * - `camelCase` for everything else.
168
+ */
169
+ function defaultResolver(name, type) {
170
+ let resolvedName = camelCase(name);
171
+ if (type === "file" || type === "function") resolvedName = camelCase(name, { isFile: type === "file" });
172
+ if (type === "type") resolvedName = pascalCase(name);
173
+ return resolvedName;
174
+ }
175
+ /**
176
+ * Default option resolver — applies include/exclude filters and merges matching override options.
177
+ *
178
+ * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.
179
+ *
180
+ * @example Include/exclude filtering
181
+ * ```ts
182
+ * const options = defaultResolveOptions(operationNode, {
183
+ * options: { output: 'types' },
184
+ * exclude: [{ type: 'tag', pattern: 'internal' }],
185
+ * })
186
+ * // → null when node has tag 'internal'
187
+ * ```
188
+ *
189
+ * @example Override merging
190
+ * ```ts
191
+ * const options = defaultResolveOptions(operationNode, {
192
+ * options: { enumType: 'asConst' },
193
+ * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],
194
+ * })
195
+ * // → { enumType: 'enum' } when operationId matches
196
+ * ```
197
+ */
198
+ function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
199
+ if (isOperationNode(node)) {
200
+ if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
201
+ if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
202
+ const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options;
203
+ return {
204
+ ...options,
205
+ ...overrideOptions
206
+ };
207
+ }
208
+ if (isSchemaNode(node)) {
209
+ if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null;
210
+ if (include) {
211
+ const applicable = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern)).filter((r) => r !== null);
212
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
213
+ }
214
+ const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options;
215
+ return {
216
+ ...options,
217
+ ...overrideOptions
218
+ };
219
+ }
220
+ return options;
221
+ }
222
+ /**
223
+ * Default path resolver used by `defineResolver`.
224
+ *
225
+ * - Returns the output directory in `single` mode.
226
+ * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.
227
+ * - Falls back to a flat `output/baseName` path otherwise.
228
+ *
229
+ * A custom `group.name` function overrides the default subdirectory naming.
230
+ * For `tag` groups the default is `${camelCase(tag)}Controller`.
231
+ * For `path` groups the default is the first path segment after `/`.
232
+ *
233
+ * @example Flat output
234
+ * ```ts
235
+ * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
236
+ * // → '/src/types/petTypes.ts'
237
+ * ```
238
+ *
239
+ * @example Tag-based grouping
240
+ * ```ts
241
+ * defaultResolvePath(
242
+ * { baseName: 'petTypes.ts', tag: 'pets' },
243
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
244
+ * )
245
+ * // → '/src/types/petsController/petTypes.ts'
246
+ * ```
247
+ *
248
+ * @example Path-based grouping
249
+ * ```ts
250
+ * defaultResolvePath(
251
+ * { baseName: 'petTypes.ts', path: '/pets/list' },
252
+ * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
253
+ * )
254
+ * // → '/src/types/pets/petTypes.ts'
255
+ * ```
256
+ *
257
+ * @example Single-file mode
258
+ * ```ts
259
+ * defaultResolvePath(
260
+ * { baseName: 'petTypes.ts', pathMode: 'single' },
261
+ * { root: '/src', output: { path: 'types' } },
262
+ * )
263
+ * // → '/src/types'
264
+ * ```
265
+ */
266
+ function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
267
+ if ((pathMode ?? PluginDriver.getMode(path.resolve(root, output.path))) === "single") return path.resolve(root, output.path);
268
+ let result;
269
+ if (group && (groupPath || tag)) {
270
+ const groupValue = group.type === "path" ? groupPath : tag;
271
+ const defaultName = group.type === "tag" ? ({ group: g }) => `${camelCase(g)}Controller` : ({ group: g }) => {
272
+ const segment = g.split("/").filter((s) => s !== "" && s !== "." && s !== "..")[0];
273
+ return segment ? camelCase(segment) : "";
274
+ };
275
+ const resolveName = group.name ?? defaultName;
276
+ result = path.resolve(root, output.path, resolveName({ group: groupValue }), baseName);
277
+ } else result = path.resolve(root, output.path, baseName);
278
+ const outputDir = path.resolve(root, output.path);
279
+ const outputDirWithSep = outputDir.endsWith(path.sep) ? outputDir : `${outputDir}${path.sep}`;
280
+ 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.`);
281
+ return result;
282
+ }
283
+ /**
284
+ * Default file resolver used by `defineResolver`.
285
+ *
286
+ * Resolves a `FileNode` by combining name resolution (`resolver.default`) with
287
+ * path resolution (`resolver.resolvePath`). The resolved file always has empty
288
+ * `sources`, `imports`, and `exports` arrays — consumers populate those separately.
289
+ *
290
+ * In `single` mode the name is omitted and the file sits directly in the output directory.
291
+ *
292
+ * @example Resolve a schema file
293
+ * ```ts
294
+ * const file = defaultResolveFile.call(resolver,
295
+ * { name: 'pet', extname: '.ts' },
296
+ * { root: '/src', output: { path: 'types' } },
297
+ * )
298
+ * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }
299
+ * ```
300
+ *
301
+ * @example Resolve an operation file with tag grouping
302
+ * ```ts
303
+ * const file = defaultResolveFile.call(resolver,
304
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
305
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
306
+ * )
307
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
308
+ * ```
309
+ */
310
+ function defaultResolveFile({ name, extname, tag, path: groupPath }, context) {
311
+ const pathMode = PluginDriver.getMode(path.resolve(context.root, context.output.path));
312
+ const baseName = `${pathMode === "single" ? "" : this.default(name, "file")}${extname}`;
313
+ const filePath = this.resolvePath({
314
+ baseName,
315
+ pathMode,
316
+ tag,
317
+ path: groupPath
318
+ }, context);
319
+ return createFile({
320
+ path: filePath,
321
+ baseName: path.basename(filePath),
322
+ meta: { pluginName: this.pluginName },
323
+ sources: [],
324
+ imports: [],
325
+ exports: []
326
+ });
327
+ }
328
+ /**
329
+ * Generates the default "Generated by Kubb" banner from config and optional node metadata.
330
+ */
331
+ function buildDefaultBanner({ title, description, version, config }) {
332
+ try {
333
+ let source = "";
334
+ if (Array.isArray(config.input)) {
335
+ const first = config.input[0];
336
+ if (first && "path" in first) source = path.basename(first.path);
337
+ } else if ("path" in config.input) source = path.basename(config.input.path);
338
+ else if ("data" in config.input) source = "text content";
339
+ let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
340
+ if (config.output.defaultBanner === "simple") {
341
+ banner += "*/\n";
342
+ return banner;
343
+ }
344
+ if (source) banner += `* Source: ${source}\n`;
345
+ if (title) banner += `* Title: ${title}\n`;
346
+ if (description) {
347
+ const formattedDescription = description.replace(/\n/gm, "\n* ");
348
+ banner += `* Description: ${formattedDescription}\n`;
349
+ }
350
+ if (version) banner += `* OpenAPI spec version: ${version}\n`;
351
+ banner += "*/\n";
352
+ return banner;
353
+ } catch (_error) {
354
+ return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
355
+ }
356
+ }
357
+ /**
358
+ * Default banner resolver — returns the banner string for a generated file.
359
+ *
360
+ * A user-supplied `output.banner` overrides the default Kubb "Generated by Kubb" notice.
361
+ * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`
362
+ * from the OAS spec when a `node` is provided).
363
+ *
364
+ * - When `output.banner` is a function and `node` is provided, returns `output.banner(node)`.
365
+ * - When `output.banner` is a function and `node` is absent, falls back to the Kubb notice.
366
+ * - When `output.banner` is a string, returns it directly.
367
+ * - When `config.output.defaultBanner` is `false`, returns `undefined`.
368
+ * - Otherwise returns the Kubb "Generated by Kubb" notice.
369
+ *
370
+ * @example String banner overrides default
371
+ * ```ts
372
+ * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })
373
+ * // → '// my banner'
374
+ * ```
375
+ *
376
+ * @example Function banner with node
377
+ * ```ts
378
+ * defaultResolveBanner(inputNode, { output: { banner: (node) => `// v${node.version}` }, config })
379
+ * // → '// v3.0.0'
380
+ * ```
381
+ *
382
+ * @example No user banner — Kubb notice with OAS metadata
383
+ * ```ts
384
+ * defaultResolveBanner(inputNode, { config })
385
+ * // → '/** Generated by Kubb ... Title: Pet Store ... *\/'
386
+ * ```
387
+ *
388
+ * @example Disabled default banner
389
+ * ```ts
390
+ * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })
391
+ * // → undefined
392
+ * ```
393
+ */
394
+ function defaultResolveBanner(node, { output, config }) {
395
+ if (typeof output?.banner === "function") return output.banner(node);
396
+ if (typeof output?.banner === "string") return output.banner;
397
+ if (config.output.defaultBanner === false) return;
398
+ return buildDefaultBanner({
399
+ title: node?.meta?.title,
400
+ version: node?.meta?.version,
401
+ config
402
+ });
403
+ }
404
+ /**
405
+ * Default footer resolver — returns the footer string for a generated file.
406
+ *
407
+ * - When `output.footer` is a function and `node` is provided, calls it with the node.
408
+ * - When `output.footer` is a function and `node` is absent, returns `undefined`.
409
+ * - When `output.footer` is a string, returns it directly.
410
+ * - Otherwise returns `undefined`.
411
+ *
412
+ * @example String footer
413
+ * ```ts
414
+ * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })
415
+ * // → '// end of file'
416
+ * ```
417
+ *
418
+ * @example Function footer with node
419
+ * ```ts
420
+ * defaultResolveFooter(inputNode, { output: { footer: (node) => `// ${node.title}` }, config })
421
+ * // → '// Pet Store'
422
+ * ```
423
+ */
424
+ function defaultResolveFooter(node, { output }) {
425
+ if (typeof output?.footer === "function") return node ? output.footer(node) : void 0;
426
+ if (typeof output?.footer === "string") return output.footer;
427
+ }
428
+ /**
429
+ * Defines a resolver for a plugin, injecting built-in defaults for name casing,
430
+ * include/exclude/override filtering, path resolution, and file construction.
431
+ *
432
+ * All four defaults can be overridden by providing them in the builder function:
433
+ * - `default` — name casing strategy (camelCase / PascalCase)
434
+ * - `resolveOptions` — include/exclude/override filtering
435
+ * - `resolvePath` — output path computation
436
+ * - `resolveFile` — full `FileNode` construction
437
+ *
438
+ * Methods in the builder have access to `this` (the full resolver object), so they
439
+ * can call other resolver methods without circular imports.
440
+ *
441
+ * @example Basic resolver with naming helpers
442
+ * ```ts
443
+ * export const resolver = defineResolver<PluginTs>(() => ({
444
+ * name: 'default',
445
+ * resolveName(node) {
446
+ * return this.default(node.name, 'function')
447
+ * },
448
+ * resolveTypedName(node) {
449
+ * return this.default(node.name, 'type')
450
+ * },
451
+ * }))
452
+ * ```
453
+ *
454
+ * @example Override resolvePath for a custom output structure
455
+ * ```ts
456
+ * export const resolver = defineResolver<PluginTs>(() => ({
457
+ * name: 'custom',
458
+ * resolvePath({ baseName }, { root, output }) {
459
+ * return path.resolve(root, output.path, 'generated', baseName)
460
+ * },
461
+ * }))
462
+ * ```
463
+ *
464
+ * @example Use this.default inside a helper
465
+ * ```ts
466
+ * export const resolver = defineResolver<PluginTs>(() => ({
467
+ * name: 'default',
468
+ * resolveParamName(node, param) {
469
+ * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')
470
+ * },
471
+ * }))
472
+ * ```
473
+ */
474
+ function defineResolver(build) {
475
+ return {
476
+ default: defaultResolver,
477
+ resolveOptions: defaultResolveOptions,
478
+ resolvePath: defaultResolvePath,
479
+ resolveFile: defaultResolveFile,
480
+ resolveBanner: defaultResolveBanner,
481
+ resolveFooter: defaultResolveFooter,
482
+ ...build()
483
+ };
484
+ }
485
+ //#endregion
486
+ //#region src/devtools.ts
487
+ /**
488
+ * Encodes an `InputNode` as a compressed, URL-safe string.
489
+ *
490
+ * The JSON representation is deflate-compressed with {@link deflateSync} before
491
+ * base64url encoding, which typically reduces payload size by 70–80 % and
492
+ * keeps URLs well within browser and server path-length limits.
493
+ *
494
+ * Use {@link decodeAst} to reverse.
495
+ */
496
+ function encodeAst(input) {
497
+ const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(input)));
498
+ return Buffer.from(compressed).toString("base64url");
499
+ }
500
+ /**
501
+ * Constructs the Kubb Studio URL for the given `InputNode`.
502
+ * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).
503
+ * The `input` is encoded and attached as the `?root=` query parameter so Studio
504
+ * can decode and render it without a round-trip to any server.
505
+ */
506
+ function getStudioUrl(input, studioUrl, options = {}) {
507
+ return `${studioUrl.replace(/\/$/, "")}${options.ast ? "/ast" : ""}?root=${encodeAst(input)}`;
508
+ }
509
+ /**
510
+ * Opens the Kubb Studio URL for the given `InputNode` in the default browser —
511
+ *
512
+ * Falls back to printing the URL if the browser cannot be launched.
513
+ */
514
+ async function openInStudio(input, studioUrl, options = {}) {
515
+ const url = getStudioUrl(input, studioUrl, options);
516
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
517
+ const args = process.platform === "win32" ? [
518
+ "/c",
519
+ "start",
520
+ "",
521
+ url
522
+ ] : [url];
523
+ try {
524
+ await x(cmd, args);
525
+ } catch {
526
+ console.log(`\n ${url}\n`);
527
+ }
528
+ }
529
+ //#endregion
530
+ //#region src/FileManager.ts
531
+ function mergeFile(a, b) {
532
+ return {
533
+ ...a,
534
+ sources: [...a.sources || [], ...b.sources || []],
535
+ imports: [...a.imports || [], ...b.imports || []],
536
+ exports: [...a.exports || [], ...b.exports || []]
537
+ };
538
+ }
539
+ /**
540
+ * In-memory file store for generated files.
541
+ *
542
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
543
+ * The `files` getter returns all stored files sorted by path length (shortest first).
544
+ *
545
+ * @example
546
+ * ```ts
547
+ * import { FileManager } from '@kubb/core'
548
+ *
549
+ * const manager = new FileManager()
550
+ * manager.upsert(myFile)
551
+ * console.log(manager.files) // all stored files
552
+ * ```
553
+ */
554
+ var FileManager = class {
555
+ #cache = /* @__PURE__ */ new Map();
556
+ #filesCache = null;
557
+ /**
558
+ * Adds one or more files. Files with the same path are merged — sources, imports,
559
+ * and exports from all calls with the same path are concatenated together.
560
+ */
561
+ add(...files) {
562
+ const resolvedFiles = [];
563
+ const mergedFiles = /* @__PURE__ */ new Map();
564
+ for (const file of files) {
565
+ const existing = mergedFiles.get(file.path);
566
+ mergedFiles.set(file.path, existing ? mergeFile(existing, file) : file);
567
+ }
568
+ for (const file of mergedFiles.values()) {
569
+ const resolvedFile = createFile(file);
570
+ this.#cache.set(resolvedFile.path, resolvedFile);
571
+ resolvedFiles.push(resolvedFile);
572
+ }
573
+ this.#filesCache = null;
574
+ return resolvedFiles;
575
+ }
576
+ /**
577
+ * Adds or merges one or more files.
578
+ * If a file with the same path already exists, its sources/imports/exports are merged together.
579
+ */
580
+ upsert(...files) {
581
+ const resolvedFiles = [];
582
+ const mergedFiles = /* @__PURE__ */ new Map();
583
+ for (const file of files) {
584
+ const existing = mergedFiles.get(file.path);
585
+ mergedFiles.set(file.path, existing ? mergeFile(existing, file) : file);
586
+ }
587
+ for (const file of mergedFiles.values()) {
588
+ const existing = this.#cache.get(file.path);
589
+ const resolvedFile = createFile(existing ? mergeFile(existing, file) : file);
590
+ this.#cache.set(resolvedFile.path, resolvedFile);
591
+ resolvedFiles.push(resolvedFile);
592
+ }
593
+ this.#filesCache = null;
594
+ return resolvedFiles;
595
+ }
596
+ getByPath(path) {
597
+ return this.#cache.get(path) ?? null;
598
+ }
599
+ deleteByPath(path) {
600
+ this.#cache.delete(path);
601
+ this.#filesCache = null;
602
+ }
603
+ clear() {
604
+ this.#cache.clear();
605
+ this.#filesCache = null;
606
+ }
607
+ /**
608
+ * All stored files, sorted by path length (shorter paths first).
609
+ * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
610
+ */
611
+ get files() {
612
+ if (this.#filesCache) return this.#filesCache;
613
+ const keys = [...this.#cache.keys()];
614
+ const meta = /* @__PURE__ */ new Map();
615
+ for (const key of keys) meta.set(key, {
616
+ length: key.length,
617
+ isIndex: trimExtName(key).endsWith(BARREL_BASENAME)
618
+ });
619
+ keys.sort((a, b) => {
620
+ const ma = meta.get(a);
621
+ const mb = meta.get(b);
622
+ if (ma.length !== mb.length) return ma.length - mb.length;
623
+ if (ma.isIndex !== mb.isIndex) return ma.isIndex ? 1 : -1;
624
+ return 0;
625
+ });
626
+ const files = [];
627
+ for (const key of keys) {
628
+ const file = this.#cache.get(key);
629
+ if (file) files.push(file);
630
+ }
631
+ this.#filesCache = files;
632
+ return files;
633
+ }
634
+ };
635
+ //#endregion
636
+ //#region src/renderNode.ts
637
+ /**
638
+ * Handles the return value of a plugin AST hook or generator method.
639
+ *
640
+ * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
641
+ * - `Array<FileNode>` → added directly into `driver.fileManager`
642
+ * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
643
+ *
644
+ * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
645
+ * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
646
+ */
647
+ async function applyHookResult(result, driver, rendererFactory) {
648
+ if (!result) return;
649
+ if (Array.isArray(result)) {
650
+ driver.fileManager.upsert(...result);
651
+ return;
652
+ }
653
+ if (!rendererFactory) return;
654
+ const renderer = rendererFactory();
655
+ await renderer.render(result);
656
+ driver.fileManager.upsert(...renderer.files);
657
+ renderer.unmount();
658
+ }
659
+ //#endregion
660
+ //#region src/PluginDriver.ts
661
+ var PluginDriver = class PluginDriver {
662
+ config;
663
+ options;
664
+ /**
665
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
666
+ *
667
+ * @example
668
+ * ```ts
669
+ * PluginDriver.getMode('src/gen/types.ts') // 'single'
670
+ * PluginDriver.getMode('src/gen/types') // 'split'
671
+ * ```
672
+ */
673
+ static getMode(fileOrFolder) {
674
+ if (!fileOrFolder) return "split";
675
+ return extname(fileOrFolder) ? "single" : "split";
676
+ }
677
+ /**
678
+ * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
679
+ * the build pipeline after the adapter's `parse()` resolves.
680
+ */
681
+ inputNode = void 0;
682
+ adapter = void 0;
683
+ #studioIsOpen = false;
684
+ /**
685
+ * Central file store for all generated files.
686
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
687
+ * add files; this property gives direct read/write access when needed.
688
+ */
689
+ fileManager = new FileManager();
690
+ plugins = /* @__PURE__ */ new Map();
691
+ /**
692
+ * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
693
+ * Used by the build loop to decide whether to emit generator events for a given plugin.
694
+ */
695
+ #pluginsWithEventGenerators = /* @__PURE__ */ new Set();
696
+ #resolvers = /* @__PURE__ */ new Map();
697
+ #defaultResolvers = /* @__PURE__ */ new Map();
698
+ #hookListeners = /* @__PURE__ */ new Map();
699
+ constructor(config, options) {
700
+ this.config = config;
701
+ this.options = options;
702
+ config.plugins.map((rawPlugin) => this.#normalizePlugin(rawPlugin)).filter((plugin) => {
703
+ if (typeof plugin.apply === "function") return plugin.apply(config);
704
+ return true;
705
+ }).sort((a, b) => {
706
+ if (b.dependencies?.includes(a.name)) return -1;
707
+ if (a.dependencies?.includes(b.name)) return 1;
708
+ return 0;
709
+ }).forEach((plugin) => {
710
+ this.plugins.set(plugin.name, plugin);
711
+ });
712
+ }
713
+ get hooks() {
714
+ return this.options.hooks;
715
+ }
716
+ /**
717
+ * Creates an `NormalizedPlugin` from a hook-style plugin and registers
718
+ * its lifecycle handlers on the `AsyncEventEmitter`.
719
+ */
720
+ #normalizePlugin(hookPlugin) {
721
+ const normalizedPlugin = {
722
+ name: hookPlugin.name,
723
+ dependencies: hookPlugin.dependencies,
724
+ options: {
725
+ output: { path: "." },
726
+ exclude: [],
727
+ override: []
728
+ }
729
+ };
730
+ this.registerPluginHooks(hookPlugin, normalizedPlugin);
731
+ return normalizedPlugin;
732
+ }
733
+ /**
734
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
735
+ *
736
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
737
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
738
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
739
+ *
740
+ * All other hooks are iterated and registered directly as pass-through listeners.
741
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
742
+ *
743
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
744
+ * the plugin lifecycle without modifying plugin behavior.
745
+ *
746
+ * @internal
747
+ */
748
+ registerPluginHooks(hookPlugin, normalizedPlugin) {
749
+ const { hooks } = hookPlugin;
750
+ if (hooks["kubb:plugin:setup"]) {
751
+ const setupHandler = (globalCtx) => {
752
+ const pluginCtx = {
753
+ ...globalCtx,
754
+ options: hookPlugin.options ?? {},
755
+ addGenerator: (gen) => {
756
+ this.registerGenerator(normalizedPlugin.name, gen);
757
+ },
758
+ setResolver: (resolver) => {
759
+ this.setPluginResolver(normalizedPlugin.name, resolver);
760
+ },
761
+ setTransformer: (visitor) => {
762
+ normalizedPlugin.transformer = visitor;
763
+ },
764
+ setRenderer: (renderer) => {
765
+ normalizedPlugin.renderer = renderer;
766
+ },
767
+ setOptions: (opts) => {
768
+ normalizedPlugin.options = {
769
+ ...normalizedPlugin.options,
770
+ ...opts
771
+ };
772
+ },
773
+ injectFile: ({ sources = [], ...rest }) => {
774
+ this.fileManager.add(createFile({
775
+ imports: [],
776
+ exports: [],
777
+ sources,
778
+ ...rest
779
+ }));
780
+ }
781
+ };
782
+ return hooks["kubb:plugin:setup"](pluginCtx);
783
+ };
784
+ this.hooks.on("kubb:plugin:setup", setupHandler);
785
+ this.#trackHookListener("kubb:plugin:setup", setupHandler);
786
+ }
787
+ for (const [event, handler] of Object.entries(hooks)) {
788
+ if (event === "kubb:plugin:setup" || !handler) continue;
789
+ this.hooks.on(event, handler);
790
+ this.#trackHookListener(event, handler);
791
+ }
792
+ }
793
+ /**
794
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
795
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
796
+ *
797
+ * Call this once from `safeBuild` before the plugin execution loop begins.
798
+ */
799
+ async emitSetupHooks() {
800
+ const noop = () => {};
801
+ await this.hooks.emit("kubb:plugin:setup", {
802
+ config: this.config,
803
+ options: {},
804
+ addGenerator: noop,
805
+ setResolver: noop,
806
+ setTransformer: noop,
807
+ setRenderer: noop,
808
+ setOptions: noop,
809
+ injectFile: noop,
810
+ updateConfig: noop
811
+ });
812
+ }
813
+ /**
814
+ * Registers a generator for the given plugin on the shared event emitter.
815
+ *
816
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
817
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
818
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
819
+ * so that generators from different plugins do not cross-fire.
820
+ *
821
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
822
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
823
+ * declares a renderer.
824
+ *
825
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
826
+ */
827
+ registerGenerator(pluginName, gen) {
828
+ const resolveRenderer = () => {
829
+ const plugin = this.plugins.get(pluginName);
830
+ return gen.renderer === null ? void 0 : gen.renderer ?? plugin?.renderer ?? this.config.renderer;
831
+ };
832
+ if (gen.schema) {
833
+ const schemaHandler = async (node, ctx) => {
834
+ if (ctx.plugin.name !== pluginName) return;
835
+ await applyHookResult(await gen.schema(node, ctx), this, resolveRenderer());
836
+ };
837
+ this.hooks.on("kubb:generate:schema", schemaHandler);
838
+ this.#trackHookListener("kubb:generate:schema", schemaHandler);
839
+ }
840
+ if (gen.operation) {
841
+ const operationHandler = async (node, ctx) => {
842
+ if (ctx.plugin.name !== pluginName) return;
843
+ await applyHookResult(await gen.operation(node, ctx), this, resolveRenderer());
844
+ };
845
+ this.hooks.on("kubb:generate:operation", operationHandler);
846
+ this.#trackHookListener("kubb:generate:operation", operationHandler);
847
+ }
848
+ if (gen.operations) {
849
+ const operationsHandler = async (nodes, ctx) => {
850
+ if (ctx.plugin.name !== pluginName) return;
851
+ await applyHookResult(await gen.operations(nodes, ctx), this, resolveRenderer());
852
+ };
853
+ this.hooks.on("kubb:generate:operations", operationsHandler);
854
+ this.#trackHookListener("kubb:generate:operations", operationsHandler);
855
+ }
856
+ this.#pluginsWithEventGenerators.add(pluginName);
857
+ }
858
+ /**
859
+ * Returns `true` when at least one generator was registered for the given plugin
860
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
861
+ *
862
+ * Used by the build loop to decide whether to walk the AST and emit generator events
863
+ * for a plugin that has no static `plugin.generators`.
864
+ */
865
+ hasRegisteredGenerators(pluginName) {
866
+ return this.#pluginsWithEventGenerators.has(pluginName);
867
+ }
868
+ /**
869
+ * Unregisters all plugin lifecycle listeners from the shared event emitter.
870
+ * Called at the end of a build to prevent listener leaks across repeated builds.
871
+ *
872
+ * @internal
873
+ */
874
+ dispose() {
875
+ for (const [event, handlers] of this.#hookListeners) for (const handler of handlers) this.hooks.off(event, handler);
876
+ this.#hookListeners.clear();
877
+ this.#pluginsWithEventGenerators.clear();
878
+ }
879
+ #trackHookListener(event, handler) {
880
+ let handlers = this.#hookListeners.get(event);
881
+ if (!handlers) {
882
+ handlers = /* @__PURE__ */ new Set();
883
+ this.#hookListeners.set(event, handlers);
884
+ }
885
+ handlers.add(handler);
886
+ }
887
+ #createDefaultResolver(pluginName) {
888
+ const existingResolver = this.#defaultResolvers.get(pluginName);
889
+ if (existingResolver) return existingResolver;
890
+ const resolver = defineResolver(() => ({
891
+ name: "default",
892
+ pluginName
893
+ }));
894
+ this.#defaultResolvers.set(pluginName, resolver);
895
+ return resolver;
896
+ }
897
+ /**
898
+ * Merges `partial` with the plugin's default resolver and stores the result.
899
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
900
+ * get the up-to-date resolver without going through `getResolver()`.
901
+ */
902
+ setPluginResolver(pluginName, partial) {
903
+ const merged = {
904
+ ...this.#createDefaultResolver(pluginName),
905
+ ...partial
906
+ };
907
+ this.#resolvers.set(pluginName, merged);
908
+ const plugin = this.plugins.get(pluginName);
909
+ if (plugin) plugin.resolver = merged;
910
+ }
911
+ getResolver(pluginName) {
912
+ return this.#resolvers.get(pluginName) ?? this.plugins.get(pluginName)?.resolver ?? this.#createDefaultResolver(pluginName);
913
+ }
914
+ getContext(plugin) {
915
+ const driver = this;
916
+ return {
917
+ config: driver.config,
918
+ get root() {
919
+ return resolve(driver.config.root, driver.config.output.path);
920
+ },
921
+ getMode(output) {
922
+ return PluginDriver.getMode(resolve(driver.config.root, driver.config.output.path, output.path));
923
+ },
924
+ hooks: driver.hooks,
925
+ plugin,
926
+ getPlugin: driver.getPlugin.bind(driver),
927
+ requirePlugin: driver.requirePlugin.bind(driver),
928
+ getResolver: driver.getResolver.bind(driver),
929
+ driver,
930
+ addFile: async (...files) => {
931
+ driver.fileManager.add(...files);
932
+ },
933
+ upsertFile: async (...files) => {
934
+ driver.fileManager.upsert(...files);
935
+ },
936
+ get inputNode() {
937
+ return driver.inputNode;
938
+ },
939
+ get adapter() {
940
+ return driver.adapter;
941
+ },
942
+ get resolver() {
943
+ return driver.getResolver(plugin.name);
944
+ },
945
+ get transformer() {
946
+ return plugin.transformer;
947
+ },
948
+ warn(message) {
949
+ driver.hooks.emit("kubb:warn", message);
950
+ },
951
+ error(error) {
952
+ driver.hooks.emit("kubb:error", typeof error === "string" ? new Error(error) : error);
953
+ },
954
+ info(message) {
955
+ driver.hooks.emit("kubb:info", message);
956
+ },
957
+ openInStudio(options) {
958
+ if (!driver.config.devtools || driver.#studioIsOpen) return;
959
+ if (typeof driver.config.devtools !== "object") throw new Error("Devtools must be an object");
960
+ if (!driver.inputNode || !driver.adapter) throw new Error("adapter is not defined, make sure you have set the parser in kubb.config.ts");
961
+ driver.#studioIsOpen = true;
962
+ const studioUrl = driver.config.devtools?.studioUrl ?? "https://studio.kubb.dev";
963
+ return openInStudio(driver.inputNode, studioUrl, options);
964
+ }
965
+ };
966
+ }
967
+ getPlugin(pluginName) {
968
+ return this.plugins.get(pluginName);
969
+ }
970
+ requirePlugin(pluginName) {
971
+ const plugin = this.plugins.get(pluginName);
972
+ if (!plugin) throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`);
973
+ return plugin;
974
+ }
975
+ };
976
+ //#endregion
977
+ export { BARREL_BASENAME as a, DEFAULT_EXTENSION as c, camelCase as d, defineResolver as i, DEFAULT_STUDIO_URL as l, applyHookResult as n, BARREL_FILENAME as o, FileManager as r, DEFAULT_BANNER as s, PluginDriver as t, logLevel as u };
978
+
979
+ //# sourceMappingURL=PluginDriver-mXeqWp-U.js.map