@kubb/core 5.0.0-alpha.9 → 5.0.0-beta.10

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