@kubb/core 5.0.0-alpha.36 → 5.0.0-alpha.39

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 (42) hide show
  1. package/dist/{PluginDriver-CCdkwR14.cjs → PluginDriver-BQwm8hDd.cjs} +70 -147
  2. package/dist/PluginDriver-BQwm8hDd.cjs.map +1 -0
  3. package/dist/{PluginDriver-B_65W4fv.js → PluginDriver-CgXFtmNP.js} +36 -96
  4. package/dist/PluginDriver-CgXFtmNP.js.map +1 -0
  5. package/dist/index.cjs +23 -341
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +5 -317
  8. package/dist/index.js +23 -311
  9. package/dist/index.js.map +1 -1
  10. package/dist/mocks.cjs +2 -3
  11. package/dist/mocks.cjs.map +1 -1
  12. package/dist/mocks.d.ts +2 -2
  13. package/dist/mocks.js +2 -2
  14. package/dist/mocks.js.map +1 -1
  15. package/dist/{PluginDriver-C9iBgYbk.d.ts → types-DUc5lEUp.d.ts} +596 -714
  16. package/package.json +4 -11
  17. package/src/PluginDriver.ts +18 -17
  18. package/src/constants.ts +0 -48
  19. package/src/createKubb.ts +1 -1
  20. package/src/defineResolver.ts +3 -3
  21. package/src/index.ts +3 -20
  22. package/src/mocks.ts +3 -3
  23. package/src/storages/fsStorage.ts +27 -7
  24. package/src/types.ts +3 -11
  25. package/src/utils/TreeNode.ts +3 -3
  26. package/src/utils/executeStrategies.ts +0 -16
  27. package/dist/PluginDriver-B_65W4fv.js.map +0 -1
  28. package/dist/PluginDriver-CCdkwR14.cjs.map +0 -1
  29. package/dist/chunk-ByKO4r7w.cjs +0 -38
  30. package/dist/hooks.cjs +0 -32
  31. package/dist/hooks.cjs.map +0 -1
  32. package/dist/hooks.d.ts +0 -23
  33. package/dist/hooks.js +0 -29
  34. package/dist/hooks.js.map +0 -1
  35. package/src/hooks/index.ts +0 -3
  36. package/src/hooks/useDriver.ts +0 -9
  37. package/src/hooks/useMode.ts +0 -8
  38. package/src/hooks/usePlugin.ts +0 -9
  39. package/src/utils/FunctionParams.ts +0 -155
  40. package/src/utils/formatters.ts +0 -45
  41. package/src/utils/getFunctionParams.ts +0 -254
  42. package/src/utils/linters.ts +0 -45
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#emitter","NodeEventEmitter","posix","#options","isValidVarName","camelCase","#transformParam","#eachParam","#limit","pLimit","#cachedLeaves","getMode","path","DEFAULT_EXTENSION","DEFAULT_BANNER","DEFAULT_STUDIO_URL","PluginDriver","applyHookResult","BARREL_FILENAME","#params"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/urlPath.ts","../src/createAdapter.ts","../src/FileProcessor.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/utils/TreeNode.ts","../src/utils/getBarrelFiles.ts","../src/utils/isInputPath.ts","../src/createKubb.ts","../src/createPlugin.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts","../src/utils/formatters.ts","../src/utils/getFunctionParams.ts","../src/utils/linters.ts","../src/utils/packageJSON.ts"],"sourcesContent":["/** Thrown when a plugin's configuration or input fails validation.\n *\n * @example\n * ```ts\n * throw new ValidationPluginError('Invalid config: \"output.path\" is required')\n * ```\n */\nexport class ValidationPluginError extends Error {}\n\n/**\n * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","import { EventEmitter as NodeEventEmitter } from 'node:events'\nimport { toError } from './errors.ts'\n\n/**\n * A function that can be registered as an event listener, synchronous or async.\n */\ntype AsyncListener<TArgs extends unknown[]> = (...args: TArgs) => void | Promise<void>\n\n/**\n * Typed `EventEmitter` that awaits all async listeners before resolving.\n * Wraps Node's `EventEmitter` with full TypeScript event-map inference.\n *\n * @example\n * ```ts\n * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()\n * emitter.on('build', async (name) => { console.log(name) })\n * await emitter.emit('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[] }> {\n /**\n * Maximum number of listeners per event before Node emits a memory-leak warning.\n * @default 10\n */\n constructor(maxListener = 10) {\n this.#emitter.setMaxListeners(maxListener)\n }\n\n #emitter = new NodeEventEmitter()\n\n /**\n * Emits `eventName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.\n *\n * @example\n * ```ts\n * await emitter.emit('build', 'petstore')\n * ```\n */\n async emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void> {\n const listeners = this.#emitter.listeners(eventName) as Array<AsyncListener<TEvents[TEventName]>>\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n try {\n await listener(...eventArgs)\n } catch (err) {\n let serializedArgs: string\n try {\n serializedArgs = JSON.stringify(eventArgs)\n } catch {\n serializedArgs = String(eventArgs)\n }\n throw new Error(`Error in async listener for \"${eventName}\" with eventArgs ${serializedArgs}`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', async (name) => { console.log(name) })\n * ```\n */\n on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.on(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Registers a one-shot listener that removes itself after the first invocation.\n *\n * @example\n * ```ts\n * emitter.onOnce('build', async (name) => { console.log(name) })\n * ```\n */\n onOnce<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n const wrapper: AsyncListener<TEvents[TEventName]> = (...args) => {\n this.off(eventName, wrapper)\n return handler(...args)\n }\n this.on(eventName, wrapper)\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * emitter.off('build', handler)\n * ```\n */\n off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.off(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Returns the number of listeners registered for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', handler)\n * emitter.listenerCount('build') // 1\n * ```\n */\n listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number {\n return this.#emitter.listenerCount(eventName)\n }\n\n /**\n * Removes all listeners from every event channel.\n *\n * @example\n * ```ts\n * emitter.removeAll()\n * ```\n */\n removeAll(): void {\n this.#emitter.removeAllListeners()\n }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n\n/**\n * Formats the elapsed time since `hrStart` as a human-readable string.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * formatHrtime(start) // '1.50s'\n * ```\n */\nexport function formatHrtime(hrStart: [number, number]): string {\n return formatMs(getElapsedMs(hrStart))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\n\n/**\n * Walks up the directory tree from `cwd` (defaults to `process.cwd()`) and\n * returns the absolute path of the nearest `package.json`, or `null` when none\n * is found before reaching the filesystem root.\n *\n * @example\n * ```ts\n * const pkgPath = findPackageJSON('/home/user/project/src') // '/home/user/project/package.json'\n * ```\n */\nexport function findPackageJSON(cwd?: string): string | null {\n let dir = cwd ? resolve(cwd) : process.cwd()\n while (true) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) return pkgPath\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Converts all backslashes to forward slashes.\n * Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n */\nfunction toSlash(p: string): string {\n if (p.startsWith('\\\\\\\\?\\\\')) return p\n return p.replaceAll('\\\\', '/')\n}\n\n/**\n * Returns the relative path from `rootDir` to `filePath`, always using forward slashes\n * and prefixed with `./` when not already traversing upward.\n *\n * @example\n * ```ts\n * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'\n * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'\n * ```\n */\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath))\n\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\n/**\n * Synchronous counterpart of `read`.\n *\n * @example\n * ```ts\n * const source = readSync('./src/Pet.ts')\n * ```\n */\nexport function readSync(path: string): string {\n return readFileSync(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (typeof Bun !== 'undefined') {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import type { Adapter, AdapterFactoryOptions } from './types.ts'\n\n/**\n * Builder type for an {@link Adapter} — takes options and returns the adapter instance.\n */\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Creates an adapter factory. Call the returned function with optional options to get the adapter instance.\n *\n * @example\n * export const myAdapter = createAdapter<MyAdapter>((options) => {\n * return {\n * name: 'my-adapter',\n * options,\n * async parse(source) { ... },\n * }\n * })\n *\n * // instantiate\n * const adapter = myAdapter({ validate: true })\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","import type { CodeNode, FileNode } from '@kubb/ast'\nimport { extractStringsFromNodes } from '@kubb/ast'\nimport pLimit from 'p-limit'\nimport { PARALLEL_CONCURRENCY_LIMIT } from './constants.ts'\nimport type { Parser } from './defineParser.ts'\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n}\n\ntype RunOptions = ParseOptions & {\n /**\n * @default 'sequential'\n */\n mode?: 'sequential' | 'parallel'\n onStart?: (files: Array<FileNode>) => Promise<void> | void\n onEnd?: (files: Array<FileNode>) => Promise<void> | void\n onUpdate?: (params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }) => Promise<void> | void\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((item) => extractStringsFromNodes(item.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/**\n * Converts a single file to a string using the registered parsers.\n * Falls back to joining source values when no matching parser is found.\n */\nexport class FileProcessor {\n readonly #limit = pLimit(PARALLEL_CONCURRENCY_LIMIT)\n\n async parse(file: FileNode, { parsers, extension }: ParseOptions = {}): Promise<string> {\n const parseExtName = extension?.[file.extname] || undefined\n\n if (!parsers || !file.extname) {\n return joinSources(file)\n }\n\n const parser = parsers.get(file.extname)\n\n if (!parser) {\n return joinSources(file)\n }\n\n return parser.parse(file, { extname: parseExtName })\n }\n\n async run(files: Array<FileNode>, { parsers, mode = 'sequential', extension, onStart, onEnd, onUpdate }: RunOptions = {}): Promise<Array<FileNode>> {\n await onStart?.(files)\n\n const total = files.length\n let processed = 0\n\n const processOne = async (file: FileNode) => {\n const source = await this.parse(file, { extension, parsers })\n const currentProcessed = ++processed\n const percentage = (currentProcessed / total) * 100\n\n await onUpdate?.({\n file,\n source,\n processed: currentProcessed,\n percentage,\n total,\n })\n }\n\n if (mode === 'sequential') {\n for (const file of files) {\n await processOne(file)\n }\n } else {\n await Promise.all(files.map((file) => this.#limit(() => processOne(file))))\n }\n\n await onEnd?.(files)\n\n return files\n }\n}\n","export type Storage = {\n /**\n * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists in storage.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Returns the stored string value, or `null` when `key` does not exist.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Persists `value` under `key`, creating any required structure.\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Removes the entry for `key`. No-ops when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns all keys, optionally filtered to those starting with `base`.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes all entries, optionally scoped to those starting with `base`.\n */\n clear(base?: string): Promise<void>\n /**\n * Optional teardown hook called after the build completes.\n */\n dispose?(): Promise<void>\n}\n\n/**\n * Creates a storage factory. Call the returned function with optional options to get the storage instance.\n *\n * @example\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n * return {\n * name: 'memory',\n * async hasItem(key) { return store.has(key) },\n * async getItem(key) { return store.get(key) ?? null },\n * async setItem(key, value) { store.set(key, value) },\n * async removeItem(key) { store.delete(key) },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) { if (!base) store.clear() },\n * }\n * })\n */\nexport function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {\n return (options) => build(options ?? ({} as TOptions))\n}\n","import type { Dirent } from 'node:fs'\nimport { access, readdir, readFile, rm } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { clean, write } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\n\n/**\n * Built-in filesystem storage driver.\n *\n * This is the default storage when no `storage` option is configured in `output`.\n * Keys are resolved against `process.cwd()`, so root-relative paths such as\n * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.\n *\n * Internally uses the `write` utility from `@internals/utils`, which:\n * - trims leading/trailing whitespace before writing\n * - skips the write when file content is already identical (deduplication)\n * - creates missing parent directories automatically\n * - supports Bun's native file API when running under Bun\n *\n * @example\n * ```ts\n * import { defineConfig, fsStorage } from '@kubb/core'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen', storage: fsStorage() },\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch {\n return false\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch {\n return null\n }\n },\n async setItem(key: string, value: string) {\n await write(resolve(key), value, { sanity: false })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async getKeys(base?: string) {\n const keys: Array<string> = []\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, { withFileTypes: true })) as Array<Dirent>\n } catch {\n return\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n await walk(join(dir, entry.name), rel)\n } else {\n keys.push(rel)\n }\n }\n }\n\n await walk(resolve(base ?? process.cwd()), '')\n\n return keys\n },\n async clear(base?: string) {\n if (!base) {\n return\n }\n\n await clean(resolve(base))\n },\n}))\n","","import { version as nodeVersion } from 'node:process'\nimport { version as KubbVersion } from '../../package.json'\n\n/**\n * Returns a snapshot of the current runtime environment.\n *\n * Useful for attaching context to debug logs and error reports so that\n * issues can be reproduced without manual information gathering.\n */\nexport function getDiagnosticInfo() {\n return {\n nodeVersion,\n KubbVersion,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n } as const\n}\n","import path from 'node:path'\nimport type { FileNode } from '@kubb/ast'\nimport { getMode } from '../PluginDriver.ts'\n\ntype BarrelData = {\n file?: FileNode\n /**\n * @deprecated use file instead\n */\n type: 'single' | 'split'\n path: string\n name: string\n}\n\n/**\n * Tree structure used to build per-directory barrel (`index.ts`) files from a\n * flat list of generated {@link FileNode} entries.\n *\n * Each node represents either a directory or a file within the output tree.\n * Use {@link TreeNode.build} to construct a root node from a file list, then\n * traverse with {@link TreeNode.forEach}, {@link TreeNode.leaves}, or the\n * `*Deep` helpers.\n */\nexport class TreeNode {\n data: BarrelData\n parent?: TreeNode\n children: Array<TreeNode> = []\n #cachedLeaves?: Array<TreeNode> = undefined\n\n constructor(data: BarrelData, parent?: TreeNode) {\n this.data = data\n this.parent = parent\n }\n\n addChild(data: BarrelData): TreeNode {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n /**\n * Returns the root ancestor of this node, walking up via `parent` links.\n */\n get root(): TreeNode {\n if (!this.parent) {\n return this\n }\n return this.parent.root\n }\n\n /**\n * Returns all leaf descendants (nodes with no children) of this node.\n *\n * Results are cached after the first traversal.\n */\n get leaves(): Array<TreeNode> {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n if (this.#cachedLeaves) {\n return this.#cachedLeaves\n }\n\n const leaves: TreeNode[] = []\n for (const child of this.children) {\n leaves.push(...child.leaves)\n }\n\n this.#cachedLeaves = leaves\n\n return leaves\n }\n\n /**\n * Visits this node and every descendant in depth-first order.\n */\n forEach(callback: (treeNode: TreeNode) => void): this {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n callback(this)\n\n for (const child of this.children) {\n child.forEach(callback)\n }\n\n return this\n }\n\n /**\n * Finds the first leaf that satisfies `predicate`, or `undefined` when none match.\n */\n findDeep(predicate?: (value: TreeNode, index: number, obj: TreeNode[]) => boolean): TreeNode | undefined {\n if (typeof predicate !== 'function') {\n throw new TypeError('find() predicate must be a function')\n }\n\n return this.leaves.find(predicate)\n }\n\n /**\n * Calls `callback` for every leaf of this node.\n */\n forEachDeep(callback: (treeNode: TreeNode) => void): void {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n this.leaves.forEach(callback)\n }\n\n /**\n * Returns all leaves that satisfy `callback`.\n */\n filterDeep(callback: (treeNode: TreeNode) => boolean): Array<TreeNode> {\n if (typeof callback !== 'function') {\n throw new TypeError('filter() callback must be a function')\n }\n\n return this.leaves.filter(callback)\n }\n\n /**\n * Maps every leaf through `callback` and returns the resulting array.\n */\n mapDeep<T>(callback: (treeNode: TreeNode) => T): Array<T> {\n if (typeof callback !== 'function') {\n throw new TypeError('map() callback must be a function')\n }\n\n return this.leaves.map(callback)\n }\n\n /**\n * Builds a {@link TreeNode} tree from a flat list of files.\n *\n * - Filters to files under `root` (when provided) and skips `.json` files.\n * - Returns `null` when no files match.\n */\n public static build(files: FileNode[], root?: string): TreeNode | null {\n try {\n const filteredTree = buildDirectoryTree(files, root)\n\n if (!filteredTree) {\n return null\n }\n\n const treeNode = new TreeNode({\n name: filteredTree.name,\n path: filteredTree.path,\n file: filteredTree.file,\n type: getMode(filteredTree.path),\n })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({\n name: item.name,\n path: item.path,\n file: item.file,\n type: getMode(item.path),\n })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => {\n recurse(treeNode, child)\n })\n\n return treeNode\n } catch (error) {\n throw new Error('Something went wrong with creating barrel files with the TreeNode class', { cause: error })\n }\n }\n}\n\ntype DirectoryTree = {\n name: string\n path: string\n file?: FileNode\n children: Array<DirectoryTree>\n}\n\nconst normalizePath = (p: string): string => p.replaceAll('\\\\', '/')\n\nfunction buildDirectoryTree(files: Array<FileNode>, rootFolder = ''): DirectoryTree | null {\n const normalizedRootFolder = normalizePath(rootFolder)\n const rootPrefix = normalizedRootFolder.endsWith('/') ? normalizedRootFolder : `${normalizedRootFolder}/`\n\n const filteredFiles = files.filter((file) => {\n const normalizedFilePath = normalizePath(file.path)\n return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith('.json') : !normalizedFilePath.endsWith('.json')\n })\n\n if (filteredFiles.length === 0) {\n return null // No files match the root folder\n }\n\n const root: DirectoryTree = {\n name: rootFolder || '',\n path: rootFolder || '',\n children: [],\n }\n\n filteredFiles.forEach((file) => {\n const relativePath = file.path.slice(rootFolder.length)\n const parts = relativePath.split('/').filter(Boolean)\n let currentLevel: DirectoryTree[] = root.children\n let currentPath = normalizePath(rootFolder)\n\n parts.forEach((part, index) => {\n currentPath = path.posix.join(currentPath, part)\n\n let existingNode = currentLevel.find((node) => node.name === part)\n\n if (!existingNode) {\n if (index === parts.length - 1) {\n // If its the last part, its a file\n existingNode = {\n name: part,\n file,\n path: currentPath,\n } as DirectoryTree\n } else {\n // Otherwise, its a folder\n existingNode = {\n name: part,\n path: currentPath,\n children: [],\n } as DirectoryTree\n }\n currentLevel.push(existingNode)\n }\n\n // Move to the next level if its a folder\n if (!existingNode.file) {\n currentLevel = existingNode.children\n }\n })\n })\n\n return root\n}\n","/** biome-ignore-all lint/suspicious/useIterableCallbackReturn: not needed */\nimport { join } from 'node:path'\nimport { getRelativePath } from '@internals/utils'\nimport type { FileNode } from '@kubb/ast'\nimport { createExport, createFile, createSource } from '@kubb/ast'\nimport type { BarrelType } from '../types.ts'\nimport { TreeNode } from './TreeNode.ts'\n\nexport type FileMetaBase = {\n pluginName?: string\n}\n\ntype AddIndexesProps = {\n type: BarrelType | false | undefined\n /**\n * Absolute output root derived from config `root` and `output.path`.\n */\n root: string\n /**\n * Output settings for the plugin.\n */\n output: {\n path: string\n }\n group?: {\n output: string\n exportAs: string\n }\n\n meta?: FileMetaBase\n}\n\nfunction getBarrelFilesByRoot(root: string | undefined, files: Array<FileNode>): Array<FileNode> {\n const cachedFiles = new Map<string, FileNode>()\n\n TreeNode.build(files, root)?.forEach((treeNode) => {\n if (!treeNode?.children || !treeNode.parent?.data.path) {\n return\n }\n\n const barrelFilePath = join(treeNode.parent?.data.path, 'index.ts')\n const barrelFile = createFile({\n path: barrelFilePath,\n baseName: 'index.ts',\n exports: [],\n imports: [],\n sources: [],\n })\n const previousBarrelFile = cachedFiles.get(barrelFile.path)\n const leaves = treeNode.leaves\n\n leaves.forEach((item) => {\n if (!item.data.name) {\n return\n }\n\n const sources = item.data.file?.sources || []\n\n sources.forEach((source) => {\n if (!item.data.file?.path || !source.isIndexable || !source.name) {\n return\n }\n const alreadyContainInPreviousBarrelFile = previousBarrelFile?.sources.some(\n (item) => item.name === source.name && item.isTypeOnly === source.isTypeOnly,\n )\n\n if (alreadyContainInPreviousBarrelFile) {\n return\n }\n\n barrelFile.exports.push(\n createExport({\n name: [source.name],\n path: getRelativePath(treeNode.parent?.data.path, item.data.path),\n isTypeOnly: source.isTypeOnly,\n }),\n )\n\n barrelFile.sources.push(\n createSource({\n name: source.name,\n isTypeOnly: source.isTypeOnly,\n isExportable: false,\n isIndexable: false,\n }),\n )\n })\n })\n\n if (previousBarrelFile) {\n previousBarrelFile.sources.push(...barrelFile.sources)\n previousBarrelFile.exports.push(...barrelFile.exports)\n } else {\n cachedFiles.set(barrelFile.path, barrelFile)\n }\n })\n\n return [...cachedFiles.values()]\n}\n\nfunction trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n // Only strip when the dot is found and no path separator follows it\n // (guards against stripping dots that are part of a directory name like /project.v2/gen)\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Generates `index.ts` barrel files for all directories under `root/output.path`.\n *\n * - Returns an empty array when `type` is falsy or `'propagate'`.\n * - Skips generation when the output path itself ends with `index` (already a barrel).\n * - When `type` is `'all'`, strips named exports so every re-export becomes a wildcard (`export * from`).\n * - Attaches `meta` to each barrel file for downstream plugin identification.\n */\nexport async function getBarrelFiles(files: Array<FileNode>, { type, meta = {}, root, output }: AddIndexesProps): Promise<Array<FileNode>> {\n if (!type || type === 'propagate') {\n return []\n }\n\n const pathToBuildFrom = join(root, output.path)\n\n if (trimExtName(pathToBuildFrom).endsWith('index')) {\n return []\n }\n\n const barrelFiles = getBarrelFilesByRoot(pathToBuildFrom, files)\n\n if (type === 'all') {\n return barrelFiles.map((file) => {\n return {\n ...file,\n exports: file.exports.map((exportItem) => {\n return {\n ...exportItem,\n name: undefined,\n }\n }),\n } as FileNode\n })\n }\n\n return barrelFiles.map((indexFile) => {\n return {\n ...indexFile,\n meta,\n } as FileNode\n })\n}\n","import type { Config, InputPath } from '../types'\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: Config | undefined): config is Config<InputPath> {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n","import { dirname, resolve } from 'node:path'\nimport { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, getRelativePath, URLPath } from '@internals/utils'\nimport type { ExportNode, FileNode, OperationNode } from '@kubb/ast'\nimport { createExport, createFile, transform, walk } from '@kubb/ast'\nimport { BARREL_FILENAME, DEFAULT_BANNER, DEFAULT_CONCURRENCY, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Generator } from './defineGenerator.ts'\nimport type { Parser } from './defineParser.ts'\nimport { FileProcessor } from './FileProcessor.ts'\nimport type { Kubb } from './Kubb.ts'\nimport { PluginDriver } from './PluginDriver.ts'\nimport { applyHookResult } from './renderNode.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, GeneratorContext, KubbHooks, Plugin, PluginContext, Storage } from './types.ts'\nimport { getDiagnosticInfo } from './utils/diagnostics.ts'\nimport type { FileMetaBase } from './utils/getBarrelFiles.ts'\nimport { getBarrelFiles } from './utils/getBarrelFiles.ts'\nimport { isInputPath } from './utils/isInputPath.ts'\n\ntype BuildOptions = {\n config: Config\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Full output produced by a successful or failed build.\n */\nexport type BuildOutput = {\n /**\n * Plugins that threw during installation, paired with the caught error.\n */\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n files: Array<FileNode>\n driver: PluginDriver\n /**\n * Elapsed time in milliseconds for each plugin, keyed by plugin name.\n */\n pluginTimings: Map<string, number>\n error?: Error\n /**\n * Raw generated source, keyed by absolute file path.\n */\n sources: Map<string, string>\n}\n\ntype SetupResult = {\n hooks: AsyncEventEmitter<KubbHooks>\n driver: PluginDriver\n sources: Map<string, string>\n config: Config\n storage: Storage | null\n}\n\nasync function setup(options: BuildOptions): Promise<SetupResult> {\n const { config: userConfig } = options\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n\n const sources: Map<string, string> = new Map<string, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n if (Array.isArray(userConfig.input)) {\n await hooks.emit('kubb:warn', 'This feature is still under development — use with caution')\n }\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n 'Configuration:',\n ` • Name: ${userConfig.name || 'unnamed'}`,\n ` • Root: ${userConfig.root || process.cwd()}`,\n ` • Output: ${userConfig.output?.path || 'not specified'}`,\n ` • Plugins: ${userConfig.plugins?.length || 0}`,\n 'Output Settings:',\n ` • Storage: ${userConfig.output?.storage ? `custom(${userConfig.output.storage.name})` : userConfig.output?.write === false ? 'disabled' : 'filesystem (default)'}`,\n ` • Formatter: ${userConfig.output?.format || 'none'}`,\n ` • Linter: ${userConfig.output?.lint || 'none'}`,\n 'Environment:',\n Object.entries(diagnosticInfo)\n .map(([key, value]) => ` • ${key}: ${value}`)\n .join('\\n'),\n ],\n })\n\n try {\n if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {\n await exists(userConfig.input.path)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Input file validated: ${userConfig.input.path}`],\n })\n }\n } catch (caughtError) {\n if (isInputPath(userConfig)) {\n const error = caughtError as Error\n\n throw new Error(\n `Cannot read file/URL defined in \\`input.path\\` or set with \\`kubb generate PATH\\` in the CLI of your Kubb config ${userConfig.input.path}`,\n {\n cause: error,\n },\n )\n }\n }\n\n if (!userConfig.adapter) {\n throw new Error('Adapter should be defined')\n }\n\n const config: Config = {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n adapter: userConfig.adapter,\n output: {\n write: true,\n barrelType: 'named',\n extension: DEFAULT_EXTENSION,\n defaultBanner: DEFAULT_BANNER,\n ...userConfig.output,\n },\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: userConfig.plugins as unknown as Config['plugins'],\n }\n\n const storage: Storage | null = config.output.write === false ? null : (config.output.storage ?? fsStorage())\n\n if (config.output.clean) {\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],\n })\n await storage?.clear(resolve(config.root, config.output.path))\n }\n\n const driver = new PluginDriver(config, {\n hooks,\n concurrency: DEFAULT_CONCURRENCY,\n })\n\n const adapter = config.adapter\n if (!adapter) {\n throw new Error('No adapter configured. Please provide an adapter in your kubb.config.ts.')\n }\n const source = inputToAdapterSource(config)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Running adapter: ${adapter.name}`],\n })\n\n driver.adapter = adapter\n driver.inputNode = await adapter.parse(source)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n `✓ Adapter '${adapter.name}' resolved InputNode`,\n ` • Schemas: ${driver.inputNode.schemas.length}`,\n ` • Operations: ${driver.inputNode.operations.length}`,\n ],\n })\n\n return {\n config,\n hooks,\n driver,\n sources,\n storage,\n }\n}\n\n/**\n * Walks the AST and dispatches nodes to a plugin's direct AST hooks\n * (`schema`, `operation`, `operations`).\n */\nasync function runPluginAstHooks(plugin: Plugin, context: PluginContext): Promise<void> {\n const { adapter, inputNode, resolver, driver } = context\n const { exclude, include, override } = plugin.options\n\n if (!adapter || !inputNode) {\n throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. pluginOas()) before this plugin in your Kubb config.`)\n }\n\n function resolveRenderer(gen: Generator<any>): RendererFactory | undefined {\n return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)\n }\n\n const generators = plugin.generators ?? []\n const collectedOperations: Array<OperationNode> = []\n\n const baseGeneratorContext = context as GeneratorContext\n const generatorContext = {\n ...baseGeneratorContext,\n resolver: driver.getResolver(plugin.name),\n }\n\n await walk(inputNode, {\n depth: 'shallow',\n async schema(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, { options: plugin.options, exclude, include, override })\n if (options === null) return\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.schema) continue\n const result = await gen.schema(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)\n },\n async operation(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, { options: plugin.options, exclude, include, override })\n if (options !== null) {\n collectedOperations.push(transformedNode)\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.operation) continue\n const result = await gen.operation(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)\n }\n },\n })\n\n if (collectedOperations.length > 0) {\n const ctx = { ...generatorContext, options: plugin.options }\n\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations(collectedOperations, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)\n }\n}\n\nasync function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {\n const { driver, hooks, sources, storage } = setupResult\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\n await driver.emitSetupHooks()\n\n if (driver.adapter && driver.inputNode) {\n await hooks.emit('kubb:build:start', {\n config,\n adapter: driver.adapter,\n inputNode: driver.inputNode,\n getPlugin: (name) => driver.getPlugin(name),\n })\n }\n\n for (const plugin of driver.plugins.values()) {\n const context = driver.getContext(plugin)\n const hrStart = process.hrtime()\n const { output } = plugin.options ?? {}\n const root = resolve(config.root, config.output.path)\n\n try {\n const timestamp = new Date()\n\n await hooks.emit('kubb:plugin:start', plugin)\n\n await hooks.emit('kubb:debug', {\n date: timestamp,\n logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n await plugin.buildStart.call(context)\n\n if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {\n await runPluginAstHooks(plugin, context)\n }\n\n if (output) {\n const barrelFiles = await getBarrelFiles(driver.fileManager.files, {\n type: output.barrelType ?? 'named',\n root,\n output,\n meta: { pluginName: plugin.name },\n })\n await context.upsertFile(...barrelFiles)\n }\n\n const duration = getElapsedMs(hrStart)\n pluginTimings.set(plugin.name, duration)\n\n await hooks.emit('kubb:plugin:end', plugin, { duration, success: true })\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Plugin started successfully (${formatMs(duration)})`],\n })\n } catch (caughtError) {\n const error = caughtError as Error\n const errorTimestamp = new Date()\n const duration = getElapsedMs(hrStart)\n\n await hooks.emit('kubb:plugin:end', plugin, {\n duration,\n success: false,\n error,\n })\n\n await hooks.emit('kubb:debug', {\n date: errorTimestamp,\n logs: [\n '✗ Plugin start failed',\n ` • Plugin Name: ${plugin.name}`,\n ` • Error: ${error.constructor.name} - ${error.message}`,\n ' • Stack Trace:',\n error.stack || 'No stack trace available',\n ],\n })\n\n failedPlugins.add({ plugin, error })\n }\n }\n\n if (config.output.barrelType) {\n const root = resolve(config.root)\n const rootPath = resolve(root, config.output.path, BARREL_FILENAME)\n const rootDir = dirname(rootPath)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: ['Generating barrel file', ` • Type: ${config.output.barrelType}`, ` • Path: ${rootPath}`],\n })\n\n const barrelFiles = driver.fileManager.files.filter((file) => {\n return file.sources.some((source) => source.isIndexable)\n })\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Found ${barrelFiles.length} indexable files for barrel export`],\n })\n\n const existingBarrel = driver.fileManager.files.find((f) => f.path === rootPath)\n const existingExports = new Set(\n existingBarrel?.exports?.flatMap((e) => (Array.isArray(e.name) ? e.name : [e.name])).filter((n): n is string => Boolean(n)) ?? [],\n )\n\n const rootFile = createFile<object>({\n path: rootPath,\n baseName: BARREL_FILENAME,\n exports: buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }).map((e) => createExport(e)),\n sources: [],\n imports: [],\n meta: {},\n })\n\n driver.fileManager.upsert(rootFile)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Generated barrel file (${rootFile.exports?.length || 0} exports)`],\n })\n }\n\n const files = driver.fileManager.files\n\n const parsersMap = new Map<FileNode['extname'], Parser>()\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const extname of parser.extNames) {\n parsersMap.set(extname, parser)\n }\n }\n }\n\n const fileProcessor = new FileProcessor()\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Writing ${files.length} files...`],\n })\n\n await fileProcessor.run(files, {\n parsers: parsersMap,\n extension: config.output.extension,\n onStart: async (processingFiles) => {\n await hooks.emit('kubb:files:processing:start', processingFiles)\n },\n onUpdate: async ({ file, source, processed, total, percentage }) => {\n await hooks.emit('kubb:file:processing:update', {\n file,\n source,\n processed,\n total,\n percentage,\n config,\n })\n if (source) {\n await storage?.setItem(file.path, source)\n sources.set(file.path, source)\n }\n },\n onEnd: async (processedFiles) => {\n await hooks.emit('kubb:files:processing:end', processedFiles)\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${processedFiles.length} files`],\n })\n },\n })\n\n for (const plugin of driver.plugins.values()) {\n if (plugin.buildEnd) {\n const context = driver.getContext(plugin)\n await plugin.buildEnd.call(context)\n }\n }\n\n await hooks.emit('kubb:build:end', {\n files,\n config,\n outputDir: resolve(config.root, config.output.path),\n })\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n files: [],\n driver,\n pluginTimings,\n error: error as Error,\n sources,\n }\n } finally {\n driver.dispose()\n }\n}\n\nasync function build(setupResult: SetupResult): Promise<BuildOutput> {\n const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)\n\n if (error) {\n throw error\n }\n\n if (failedPlugins.size > 0) {\n const errors = [...failedPlugins].map(({ error }) => error)\n\n throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })\n }\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\ntype BuildBarrelExportsParams = {\n barrelFiles: FileNode[]\n rootDir: string\n existingExports: Set<string>\n config: Config\n driver: PluginDriver\n}\n\nfunction buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }: BuildBarrelExportsParams): ExportNode[] {\n const pluginNameMap = new Map<string, Plugin>()\n for (const plugin of driver.plugins.values()) {\n pluginNameMap.set(plugin.name, plugin)\n }\n\n return barrelFiles.flatMap((file) => {\n const containsOnlyTypes = file.sources?.every((source) => source.isTypeOnly)\n\n return (file.sources ?? []).flatMap((source) => {\n if (!file.path || !source.isIndexable) {\n return []\n }\n\n const meta = file.meta as FileMetaBase | undefined\n const plugin = meta?.pluginName ? pluginNameMap.get(meta.pluginName) : undefined\n const pluginOptions = plugin?.options\n\n if (!pluginOptions || pluginOptions.output?.barrelType === false) {\n return []\n }\n\n const exportName = config.output.barrelType === 'all' ? undefined : source.name ? [source.name] : undefined\n if (exportName?.some((n) => existingExports.has(n))) {\n return []\n }\n\n return [\n createExport({\n name: exportName,\n path: getRelativePath(rootDir, file.path),\n isTypeOnly: config.output.barrelType === 'all' ? containsOnlyTypes : source.isTypeOnly,\n }),\n ]\n })\n })\n}\n\nfunction inputToAdapterSource(config: Config): AdapterSource {\n if (Array.isArray(config.input)) {\n return {\n type: 'paths',\n paths: config.input.map((i) => (new URLPath(i.path).isURL ? i.path : resolve(config.root, i.path))),\n }\n }\n\n if ('data' in config.input) {\n return { type: 'data', data: config.input.data }\n }\n\n if (new URLPath(config.input.path).isURL) {\n return { type: 'path', path: config.input.path }\n }\n\n const resolved = resolve(config.root, config.input.path)\n return { type: 'path', path: resolved }\n}\n\ntype KubbOptions = {\n config: Config\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Creates a Kubb instance bound to a single config entry.\n *\n * The instance holds shared state (`hooks`, `sources`, `driver`, `config`) across the\n * `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before\n * calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb({ config })\n *\n * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {\n * console.log(`${plugin.name} completed in ${duration}ms`)\n * })\n *\n * const { files, failedPlugins } = await kubb.safeBuild()\n * ```\n */\nexport function createKubb(options: KubbOptions): Kubb {\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n let setupResult: SetupResult | undefined\n\n const instance: Kubb = {\n get hooks() {\n return hooks\n },\n get sources() {\n return setupResult?.sources ?? new Map()\n },\n get driver() {\n return setupResult?.driver\n },\n get config() {\n return setupResult?.config\n },\n async setup() {\n setupResult = await setup({ config: options.config, hooks })\n },\n async build() {\n if (!setupResult) {\n await instance.setup()\n }\n return build(setupResult!)\n },\n async safeBuild() {\n if (!setupResult) {\n await instance.setup()\n }\n return safeBuild(setupResult!)\n },\n }\n\n return instance\n}\n","import type { PluginFactoryOptions, UserPluginWithLifeCycle } from './types.ts'\n\n/**\n * Builder type for a {@link UserPluginWithLifeCycle} — takes options and returns the plugin instance.\n */\ntype PluginBuilder<T extends PluginFactoryOptions = PluginFactoryOptions> = (options: T['options']) => UserPluginWithLifeCycle<T>\n\n/**\n * Creates a plugin factory. Call the returned function with optional options to get the plugin instance.\n *\n * @example\n * ```ts\n * export const myPlugin = createPlugin<MyPlugin>((options) => {\n * return {\n * name: 'my-plugin',\n * get options() { return options },\n * resolvePath(baseName) { ... },\n * resolveName(name, type) { ... },\n * }\n * })\n *\n * // instantiate\n * const plugin = myPlugin({ output: { path: 'src/gen' } })\n * ```\n * @deprecated use definePlugin instead\n */\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(\n build: PluginBuilder<T>,\n): (options?: T['options']) => UserPluginWithLifeCycle<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * The generic `TElement` is the type of the element the renderer accepts —\n * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for\n * your own renderer. Defaults to `unknown` so that generators which do not\n * care about the element type continue to work without specifying it.\n *\n * This allows core to drive rendering without a hard dependency on\n * `@kubb/renderer-jsx` or any specific renderer implementation.\n */\nexport type Renderer<TElement = unknown> = {\n render(element: TElement): Promise<void>\n unmount(error?: Error | number | null): void\n readonly files: Array<FileNode>\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Creates a renderer factory for use in generator definitions.\n *\n * Wrap your renderer factory function with this helper to register it as the\n * renderer for a generator. Core will call this factory once per render cycle\n * to obtain a fresh renderer instance.\n *\n * @example\n * ```ts\n * // packages/renderer-jsx/src/index.ts\n * export const jsxRenderer = createRenderer(() => {\n * const runtime = new Runtime()\n * return {\n * async render(element) { await runtime.render(element) },\n * get files() { return runtime.nodes },\n * unmount(error) { runtime.unmount(error) },\n * }\n * })\n *\n * // packages/plugin-zod/src/generators/zodGenerator.tsx\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const zodGenerator = defineGenerator<PluginZod>({\n * name: 'zod',\n * renderer: jsxRenderer,\n * schema(node, options) { return <File ...>...</File> },\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { FileNode, OperationNode, SchemaNode } from '@kubb/ast'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { GeneratorContext, PluginFactoryOptions } from './types.ts'\n\nexport type { GeneratorContext } from './types.ts'\n\n/**\n * A generator is a named object with optional `schema`, `operation`, and `operations`\n * methods. Each method receives the AST node as the first argument and a typed\n * `ctx` object as the second, giving access to `ctx.config`, `ctx.resolver`,\n * `ctx.adapter`, `ctx.options`, `ctx.upsertFile`, etc.\n *\n * Generators that return renderer elements (e.g. JSX) must declare a `renderer`\n * factory so that core knows how to process the output without coupling core\n * to any specific renderer package.\n *\n * Return a renderer element, an array of `FileNode`, or `void` to handle file\n * writing manually via `ctx.upsertFile`.\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator<PluginTs>({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * operation(node, ctx) {\n * const { options } = ctx\n * return <File ...><OperationType node={node} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin\n * declares a `renderer` (overrides the plugin-level fallback).\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n}\n\n/**\n * Defines a generator. Returns the object as-is with correct `this` typings.\n * `applyHookResult` handles renderer elements and `File[]` uniformly using\n * the generator's declared `renderer` factory.\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { Logger, LoggerOptions, UserLogger } from './types.ts'\n\n/**\n * Wraps a logger definition into a typed {@link Logger}.\n *\n * @example\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context, options) {\n * context.on('kubb:info', (message) => console.log('ℹ', message))\n * context.on('kubb:error', (error) => console.error('✗', error.message))\n * },\n * })\n */\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions>(logger: UserLogger<Options>): Logger<Options> {\n return logger\n}\n","import type { FileNode } from '@kubb/ast'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\nexport type Parser<TMeta extends object = any> = {\n name: string\n /**\n * File extensions this parser handles.\n * Use `undefined` to create a catch-all fallback parser.\n *\n * @example Handled extensions\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Convert a resolved file to a string.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string\n}\n\n/**\n * Defines a parser with type safety.\n *\n * Use this function to create parsers that transform generated files to strings\n * based on their extension.\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * const { extractStringsFromNodes } = await import('@kubb/ast')\n * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta> {\n return parser\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { defineConfig, memoryStorage } from '@kubb/core'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen', storage: memoryStorage() },\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n","import { x } from 'tinyexec'\nimport type { formatters } from '../constants.ts'\n\ntype Formatter = keyof typeof formatters\n\n/**\n * Returns `true` when the given formatter is installed and callable.\n *\n * Availability is detected by running `<formatter> --version` and checking\n * that the process exits without error.\n */\nasync function isFormatterAvailable(formatter: Formatter): Promise<boolean> {\n try {\n await x(formatter, ['--version'], { nodeOptions: { stdio: 'ignore' } })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Detects the first available code formatter on the current system.\n *\n * - Checks in preference order: `biome`, `oxfmt`, `prettier`.\n * - Returns `null` when none are found.\n *\n * @example\n * ```ts\n * const formatter = await detectFormatter()\n * if (formatter) {\n * console.log(`Using ${formatter} for formatting`)\n * }\n * ```\n */\nexport async function detectFormatter(): Promise<Formatter | null> {\n const formatterNames = new Set(['biome', 'oxfmt', 'prettier'] as const)\n\n for (const formatter of formatterNames) {\n if (await isFormatterAvailable(formatter)) {\n return formatter\n }\n }\n\n return null\n}\n","import { sortBy } from 'remeda'\n\nexport type Param = {\n /**\n * Controls how path parameters are emitted in the function signature.\n * - `'object'` groups them as a single destructured parameter.\n * - `'inline'` spreads them as individual comma-separated parameters.\n * - `'inlineSpread'` emits a single rest parameter.\n *\n * @default 'inline'\n * @internal\n */\n mode?: 'object' | 'inline' | 'inlineSpread'\n type?: 'string' | 'number' | (string & {})\n optional?: boolean\n /**\n * Default value expression for the parameter.\n *\n * @example Assignment syntax\n * `test = \"default\"`\n */\n default?: string\n /**\n * Used for no TypeScript (with mode object).\n *\n * @example Value syntax\n * `test: \"default\"`\n */\n value?: string\n children?: Params\n}\n\ntype ParamItem =\n | (Pick<Param, 'mode' | 'type' | 'value'> & {\n optional?: true\n default?: never\n children?: Params\n })\n | (Pick<Param, 'mode' | 'type' | 'value'> & {\n optional?: false\n default?: string\n children?: Params\n })\n\nexport type Params = Record<string, Param | undefined>\n\ntype Options = {\n type: 'constructor' | 'call' | 'object' | 'objectValue'\n transformName?: (name: string) => string\n transformType?: (type: string) => string\n}\n\nfunction order(items: Array<[key: string, item?: ParamItem]>) {\n return sortBy(items.filter(Boolean) as Array<[key: string, item?: ParamItem]>, ([_key, item]) => {\n if (item?.children) {\n return 0 // Treat items with children as required (they'll get = {} if all children are optional)\n }\n // Priority order: required (0) → optional (1) → default-only (2)\n if (item?.optional) {\n return 1 // Optional parameters (with or without default)\n }\n if (item?.default) {\n // Parameters with default only (not marked as optional)\n // Note: While the ParamItem type suggests optional and default are mutually exclusive,\n // this handles the case where a parameter has a default value but isn't explicitly marked as optional\n return 2\n }\n return 0 // Required parameters\n })\n}\n\nfunction parseChild(key: string, item: ParamItem, options: Options): string | null {\n // @ts-expect-error\n const entries = order(Object.entries(item.children))\n\n const types: string[] = []\n const names: string[] = []\n\n const optional = entries.every(([_key, item]) => item?.optional || !!item?.default)\n\n entries.forEach(([key, entryItem]) => {\n if (entryItem) {\n const name = parseItem(key, { ...entryItem, type: undefined }, options)\n if (entryItem.children) {\n const subTypes = Object.entries(entryItem.children)\n .map(([key]) => {\n return key\n })\n .join(', ')\n\n if (subTypes) {\n names.push(`${name}: { ${subTypes} }`)\n } else {\n names.push(name)\n }\n } else {\n if (options.type === 'call' && options.transformName) {\n names.push(`${key}: ${name}`)\n } else {\n names.push(name)\n }\n }\n\n if (entries.some(([_key, item]) => item?.type)) {\n types.push(parseItem(key, { ...entryItem, default: undefined }, options))\n }\n }\n })\n\n const name = item.mode === 'inline' ? key : names.length ? `{ ${names.join(', ')} }` : undefined\n const type = item.type ? item.type : types.length ? `{ ${types.join('; ')} }` : undefined\n\n if (!name) {\n return null\n }\n\n return parseItem(\n name,\n {\n type,\n default: item.default,\n optional: !item.default ? optional : undefined,\n } as ParamItem,\n options,\n )\n}\n\nfunction parseItem(name: string, item: ParamItem, options: Options): string {\n const acc: string[] = []\n const transformedName = options.transformName ? options.transformName(name) : name\n const transformedType = options.transformType && item.type ? options.transformType(item.type) : item.type\n\n if (options.type === 'object') {\n return transformedName\n }\n\n if (options.type === 'objectValue') {\n return item.value ? `${transformedName}: ${item.value}` : transformedName\n }\n\n //LEGACY\n if (item.type && options.type === 'constructor') {\n if (item.optional) {\n // Check if this is a destructured parameter (object mode)\n const isDestructured = transformedName.startsWith('{')\n if (isDestructured) {\n // For destructured parameters, use \": type = {}\" syntax to make it optional\n acc.push(`${transformedName}: ${transformedType} = {}`)\n } else {\n // For inline parameters, use \"?: type\" syntax\n acc.push(`${transformedName}?: ${transformedType}`)\n }\n } else {\n acc.push(`${transformedName}: ${transformedType}${item.default ? ` = ${item.default}` : ''}`)\n }\n } else if (item.default && options.type === 'constructor') {\n acc.push(`${transformedName} = ${item.default}`)\n } else if (item.value) {\n acc.push(`${transformedName} : ${item.value}`)\n } else if (item.mode === 'inlineSpread') {\n acc.push(`... ${transformedName}`)\n } else {\n acc.push(transformedName)\n }\n\n return acc[0] as string\n}\n\nexport function getFunctionParams(params: Params, options: Options): string {\n const entries = order(Object.entries(params as Record<string, ParamItem | undefined>))\n\n return entries\n .reduce((acc, [key, item]) => {\n if (!item) {\n return acc\n }\n\n if (item.children) {\n if (Object.keys(item.children).length === 0) {\n return acc\n }\n\n if (item.mode === 'inlineSpread') {\n return [...acc, getFunctionParams(item.children, options)]\n }\n\n const parsedItem = parseChild(key, item, options)\n if (!parsedItem) {\n return acc\n }\n\n return [...acc, parsedItem]\n }\n\n const parsedItem = parseItem(key, item, options)\n\n return [...acc, parsedItem]\n }, [] as string[])\n .join(', ')\n}\n\n/**\n * @deprecated use @kubb/ast\n */\nexport function createFunctionParams(params: Params): Params {\n return params\n}\n\n/**\n * @deprecated use @kubb/ast\n */\nexport class FunctionParams {\n #params: Params\n\n static factory(params: Params) {\n return new FunctionParams(params)\n }\n constructor(params: Params) {\n this.#params = params\n }\n\n get params(): Params {\n return this.#params\n }\n\n get flatParams(): Params {\n const flatter = (acc: Params, [key, item]: [key: string, item?: Param]): Params => {\n if (item?.children) {\n return Object.entries(item.children).reduce(flatter, acc)\n }\n if (item) {\n acc[key] = item\n }\n\n return acc\n }\n return Object.entries(this.#params).reduce(flatter, {} as Params)\n }\n\n toCall({ transformName, transformType }: Pick<Options, 'transformName' | 'transformType'> = {}): string {\n return getFunctionParams(this.#params, { type: 'call', transformName, transformType })\n }\n\n toObject(): string {\n return getFunctionParams(this.#params, { type: 'object' })\n }\n toObjectValue(): string {\n return getFunctionParams(this.#params, { type: 'objectValue' })\n }\n\n toConstructor(): string {\n return getFunctionParams(this.#params, { type: 'constructor' })\n }\n}\n","import { x } from 'tinyexec'\nimport type { linters } from '../constants.ts'\n\ntype Linter = keyof typeof linters\n\n/**\n * Returns `true` when the given linter is installed and callable.\n *\n * Availability is detected by running `<linter> --version` and checking\n * that the process exits without error.\n */\nasync function isLinterAvailable(linter: Linter): Promise<boolean> {\n try {\n await x(linter, ['--version'], { nodeOptions: { stdio: 'ignore' } })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Detects the first available linter on the current system.\n *\n * - Checks in preference order: `biome`, `oxlint`, `eslint`.\n * - Returns `null` when none are found.\n *\n * @example\n * ```ts\n * const linter = await detectLinter()\n * if (linter) {\n * console.log(`Using ${linter} for linting`)\n * }\n * ```\n */\nexport async function detectLinter(): Promise<Linter | null> {\n const linterNames = new Set(['biome', 'oxlint', 'eslint'] as const)\n\n for (const linter of linterNames) {\n if (await isLinterAvailable(linter)) {\n return linter\n }\n }\n\n return null\n}\n","import { findPackageJSON, readSync } from '@internals/utils'\nimport { coerce, satisfies } from 'semver'\n\ntype PackageJSON = {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n}\n\ntype DependencyName = string\ntype DependencyVersion = string\n\nfunction getPackageJSONSync(cwd?: string): PackageJSON | null {\n const pkgPath = findPackageJSON(cwd)\n if (!pkgPath) {\n return null\n }\n\n return JSON.parse(readSync(pkgPath)) as PackageJSON\n}\n\nfunction match(packageJSON: PackageJSON, dependency: DependencyName | RegExp): string | null {\n const dependencies = {\n ...(packageJSON.dependencies || {}),\n ...(packageJSON.devDependencies || {}),\n }\n\n if (typeof dependency === 'string' && dependencies[dependency]) {\n return dependencies[dependency]\n }\n\n const matched = Object.keys(dependencies).find((dep) => dep.match(dependency))\n\n return matched ? (dependencies[matched] ?? null) : null\n}\n\nfunction getVersionSync(dependency: DependencyName | RegExp, cwd?: string): DependencyVersion | null {\n const packageJSON = getPackageJSONSync(cwd)\n\n return packageJSON ? match(packageJSON, dependency) : null\n}\n\n/**\n * Returns `true` when the nearest `package.json` declares a dependency that\n * satisfies the given semver range.\n *\n * - Searches both `dependencies` and `devDependencies`.\n * - Accepts a string package name or a `RegExp` to match scoped/pattern packages.\n * - Uses `semver.satisfies` for range comparison; returns `false` when the\n * version string cannot be coerced into a valid semver.\n *\n * @example\n * ```ts\n * satisfiesDependency('react', '>=18') // true when react@18.x is installed\n * satisfiesDependency(/^@tanstack\\//, '>=5') // true when any @tanstack/* >=5 is found\n * ```\n */\nexport function satisfiesDependency(dependency: DependencyName | RegExp, version: DependencyVersion, cwd?: string): boolean {\n const packageVersion = getVersionSync(dependency, cwd)\n\n if (!packageVersion) {\n return false\n }\n\n if (packageVersion === version) {\n return true\n }\n\n const semVer = coerce(packageVersion)\n\n if (!semVer) {\n return false\n }\n\n return satisfies(semVer, version)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,aAAb,cAAgC,MAAM;CACpC;CAEA,YAAY,SAAiB,SAAkD;AAC7E,QAAM,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AACxC,OAAK,OAAO;AACZ,OAAK,SAAS,QAAQ;;;;;;;;;;;;;;AAe1B,SAAgB,QAAQ,OAAuB;AAC7C,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;;;;;;;;;;;;;;;ACrBlE,IAAa,oBAAb,MAAoF;;;;;CAKlF,YAAY,cAAc,IAAI;AAC5B,QAAA,QAAc,gBAAgB,YAAY;;CAG5C,WAAW,IAAIC,YAAAA,cAAkB;;;;;;;;;;CAWjC,MAAM,KAAgD,WAAuB,GAAG,WAA+C;EAC7H,MAAM,YAAY,MAAA,QAAc,UAAU,UAAU;AAEpD,MAAI,UAAU,WAAW,EACvB;AAGF,OAAK,MAAM,YAAY,UACrB,KAAI;AACF,SAAM,SAAS,GAAG,UAAU;WACrB,KAAK;GACZ,IAAI;AACJ,OAAI;AACF,qBAAiB,KAAK,UAAU,UAAU;WACpC;AACN,qBAAiB,OAAO,UAAU;;AAEpC,SAAM,IAAI,MAAM,gCAAgC,UAAU,mBAAmB,kBAAkB,EAAE,OAAO,QAAQ,IAAI,EAAE,CAAC;;;;;;;;;;;CAa7H,GAA8C,WAAuB,SAAmD;AACtH,QAAA,QAAc,GAAG,WAAW,QAAoC;;;;;;;;;;CAWlE,OAAkD,WAAuB,SAAmD;EAC1H,MAAM,WAA+C,GAAG,SAAS;AAC/D,QAAK,IAAI,WAAW,QAAQ;AAC5B,UAAO,QAAQ,GAAG,KAAK;;AAEzB,OAAK,GAAG,WAAW,QAAQ;;;;;;;;;;CAW7B,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mB,EAAE;EACtC;AAED,KAAI,OAAO,eAAe,YAAY,aAAa,YACjD,QAAO,aAAa;CAGtB,MAAM,UAAU,OAAO,KAAK,aAAa,CAAC,MAAM,QAAQ,IAAI,MAAM,WAAW,CAAC;AAE9E,QAAO,UAAW,aAAa,YAAY,OAAQ;;AAGrD,SAAS,eAAe,YAAqC,KAAwC;CACnG,MAAM,cAAc,mBAAmB,IAAI;AAE3C,QAAO,cAAc,MAAM,aAAa,WAAW,GAAG;;;;;;;;;;;;;;;;;AAkBxD,SAAgB,oBAAoB,YAAqC,SAA4B,KAAuB;CAC1H,MAAM,iBAAiB,eAAe,YAAY,IAAI;AAEtD,KAAI,CAAC,eACH,QAAO;AAGT,KAAI,mBAAmB,QACrB,QAAO;CAGT,MAAM,UAAA,GAAA,OAAA,QAAgB,eAAe;AAErC,KAAI,CAAC,OACH,QAAO;AAGT,SAAA,GAAA,OAAA,WAAiB,QAAQ,QAAQ"}
1
+ {"version":3,"file":"index.cjs","names":["#emitter","NodeEventEmitter","posix","#options","isValidVarName","camelCase","#transformParam","#eachParam","#limit","pLimit","#cachedLeaves","PluginDriver","path","DEFAULT_EXTENSION","DEFAULT_BANNER","DEFAULT_STUDIO_URL","PluginDriver","applyHookResult","BARREL_FILENAME"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/urlPath.ts","../src/createAdapter.ts","../src/FileProcessor.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/utils/TreeNode.ts","../src/utils/getBarrelFiles.ts","../src/utils/isInputPath.ts","../src/createKubb.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts"],"sourcesContent":["/**\n * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","import { EventEmitter as NodeEventEmitter } from 'node:events'\nimport { toError } from './errors.ts'\n\n/**\n * A function that can be registered as an event listener, synchronous or async.\n */\ntype AsyncListener<TArgs extends unknown[]> = (...args: TArgs) => void | Promise<void>\n\n/**\n * Typed `EventEmitter` that awaits all async listeners before resolving.\n * Wraps Node's `EventEmitter` with full TypeScript event-map inference.\n *\n * @example\n * ```ts\n * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()\n * emitter.on('build', async (name) => { console.log(name) })\n * await emitter.emit('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[] }> {\n /**\n * Maximum number of listeners per event before Node emits a memory-leak warning.\n * @default 10\n */\n constructor(maxListener = 10) {\n this.#emitter.setMaxListeners(maxListener)\n }\n\n #emitter = new NodeEventEmitter()\n\n /**\n * Emits `eventName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.\n *\n * @example\n * ```ts\n * await emitter.emit('build', 'petstore')\n * ```\n */\n async emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void> {\n const listeners = this.#emitter.listeners(eventName) as Array<AsyncListener<TEvents[TEventName]>>\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n try {\n await listener(...eventArgs)\n } catch (err) {\n let serializedArgs: string\n try {\n serializedArgs = JSON.stringify(eventArgs)\n } catch {\n serializedArgs = String(eventArgs)\n }\n throw new Error(`Error in async listener for \"${eventName}\" with eventArgs ${serializedArgs}`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', async (name) => { console.log(name) })\n * ```\n */\n on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.on(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Registers a one-shot listener that removes itself after the first invocation.\n *\n * @example\n * ```ts\n * emitter.onOnce('build', async (name) => { console.log(name) })\n * ```\n */\n onOnce<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n const wrapper: AsyncListener<TEvents[TEventName]> = (...args) => {\n this.off(eventName, wrapper)\n return handler(...args)\n }\n this.on(eventName, wrapper)\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * emitter.off('build', handler)\n * ```\n */\n off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.off(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Returns the number of listeners registered for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', handler)\n * emitter.listenerCount('build') // 1\n * ```\n */\n listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number {\n return this.#emitter.listenerCount(eventName)\n }\n\n /**\n * Removes all listeners from every event channel.\n *\n * @example\n * ```ts\n * emitter.removeAll()\n * ```\n */\n removeAll(): void {\n this.#emitter.removeAllListeners()\n }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n\n/**\n * Formats the elapsed time since `hrStart` as a human-readable string.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * formatHrtime(start) // '1.50s'\n * ```\n */\nexport function formatHrtime(hrStart: [number, number]): string {\n return formatMs(getElapsedMs(hrStart))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\n\n/**\n * Walks up the directory tree from `cwd` (defaults to `process.cwd()`) and\n * returns the absolute path of the nearest `package.json`, or `null` when none\n * is found before reaching the filesystem root.\n *\n * @example\n * ```ts\n * const pkgPath = findPackageJSON('/home/user/project/src') // '/home/user/project/package.json'\n * ```\n */\nexport function findPackageJSON(cwd?: string): string | null {\n let dir = cwd ? resolve(cwd) : process.cwd()\n while (true) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) return pkgPath\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Converts all backslashes to forward slashes.\n * Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n */\nfunction toSlash(p: string): string {\n if (p.startsWith('\\\\\\\\?\\\\')) return p\n return p.replaceAll('\\\\', '/')\n}\n\n/**\n * Returns the relative path from `rootDir` to `filePath`, always using forward slashes\n * and prefixed with `./` when not already traversing upward.\n *\n * @example\n * ```ts\n * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'\n * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'\n * ```\n */\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath))\n\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\n/**\n * Synchronous counterpart of `read`.\n *\n * @example\n * ```ts\n * const source = readSync('./src/Pet.ts')\n * ```\n */\nexport function readSync(path: string): string {\n return readFileSync(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (typeof Bun !== 'undefined') {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import type { Adapter, AdapterFactoryOptions } from './types.ts'\n\n/**\n * Builder type for an {@link Adapter} — takes options and returns the adapter instance.\n */\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Creates an adapter factory. Call the returned function with optional options to get the adapter instance.\n *\n * @example\n * export const myAdapter = createAdapter<MyAdapter>((options) => {\n * return {\n * name: 'my-adapter',\n * options,\n * async parse(source) { ... },\n * }\n * })\n *\n * // instantiate\n * const adapter = myAdapter({ validate: true })\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","import type { CodeNode, FileNode } from '@kubb/ast'\nimport { extractStringsFromNodes } from '@kubb/ast'\nimport pLimit from 'p-limit'\nimport { PARALLEL_CONCURRENCY_LIMIT } from './constants.ts'\nimport type { Parser } from './defineParser.ts'\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n}\n\ntype RunOptions = ParseOptions & {\n /**\n * @default 'sequential'\n */\n mode?: 'sequential' | 'parallel'\n onStart?: (files: Array<FileNode>) => Promise<void> | void\n onEnd?: (files: Array<FileNode>) => Promise<void> | void\n onUpdate?: (params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }) => Promise<void> | void\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((item) => extractStringsFromNodes(item.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/**\n * Converts a single file to a string using the registered parsers.\n * Falls back to joining source values when no matching parser is found.\n */\nexport class FileProcessor {\n readonly #limit = pLimit(PARALLEL_CONCURRENCY_LIMIT)\n\n async parse(file: FileNode, { parsers, extension }: ParseOptions = {}): Promise<string> {\n const parseExtName = extension?.[file.extname] || undefined\n\n if (!parsers || !file.extname) {\n return joinSources(file)\n }\n\n const parser = parsers.get(file.extname)\n\n if (!parser) {\n return joinSources(file)\n }\n\n return parser.parse(file, { extname: parseExtName })\n }\n\n async run(files: Array<FileNode>, { parsers, mode = 'sequential', extension, onStart, onEnd, onUpdate }: RunOptions = {}): Promise<Array<FileNode>> {\n await onStart?.(files)\n\n const total = files.length\n let processed = 0\n\n const processOne = async (file: FileNode) => {\n const source = await this.parse(file, { extension, parsers })\n const currentProcessed = ++processed\n const percentage = (currentProcessed / total) * 100\n\n await onUpdate?.({\n file,\n source,\n processed: currentProcessed,\n percentage,\n total,\n })\n }\n\n if (mode === 'sequential') {\n for (const file of files) {\n await processOne(file)\n }\n } else {\n await Promise.all(files.map((file) => this.#limit(() => processOne(file))))\n }\n\n await onEnd?.(files)\n\n return files\n }\n}\n","export type Storage = {\n /**\n * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists in storage.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Returns the stored string value, or `null` when `key` does not exist.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Persists `value` under `key`, creating any required structure.\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Removes the entry for `key`. No-ops when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns all keys, optionally filtered to those starting with `base`.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes all entries, optionally scoped to those starting with `base`.\n */\n clear(base?: string): Promise<void>\n /**\n * Optional teardown hook called after the build completes.\n */\n dispose?(): Promise<void>\n}\n\n/**\n * Creates a storage factory. Call the returned function with optional options to get the storage instance.\n *\n * @example\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n * return {\n * name: 'memory',\n * async hasItem(key) { return store.has(key) },\n * async getItem(key) { return store.get(key) ?? null },\n * async setItem(key, value) { store.set(key, value) },\n * async removeItem(key) { store.delete(key) },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) { if (!base) store.clear() },\n * }\n * })\n */\nexport function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {\n return (options) => build(options ?? ({} as TOptions))\n}\n","import type { Dirent } from 'node:fs'\nimport { access, readdir, readFile, rm } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { clean, write } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\n\n/**\n * Detects the filesystem error used to indicate that a path does not exist.\n */\nfunction isMissingPathError(error: unknown): error is NodeJS.ErrnoException {\n return typeof error === 'object' && error !== null && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT'\n}\n\n/**\n * Built-in filesystem storage driver.\n *\n * This is the default storage when no `storage` option is configured in `output`.\n * Keys are resolved against `process.cwd()`, so root-relative paths such as\n * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.\n *\n * Internally uses the `write` utility from `@internals/utils`, which:\n * - trims leading/trailing whitespace before writing\n * - skips the write when file content is already identical (deduplication)\n * - creates missing parent directories automatically\n * - supports Bun's native file API when running under Bun\n *\n * @example\n * ```ts\n * import { defineConfig, fsStorage } from '@kubb/core'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen', storage: fsStorage() },\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch (error) {\n if (isMissingPathError(error)) {\n return false\n }\n\n throw new Error(`Failed to access storage item \"${key}\"`, { cause: error as Error })\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch (error) {\n if (isMissingPathError(error)) {\n return null\n }\n\n throw new Error(`Failed to read storage item \"${key}\"`, { cause: error as Error })\n }\n },\n async setItem(key: string, value: string) {\n await write(resolve(key), value, { sanity: false })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async getKeys(base?: string) {\n const keys: Array<string> = []\n const resolvedBase = resolve(base ?? process.cwd())\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, { withFileTypes: true })) as Array<Dirent>\n } catch (error) {\n if (isMissingPathError(error)) {\n return\n }\n\n throw new Error(`Failed to list storage keys under \"${resolvedBase}\"`, { cause: error as Error })\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n await walk(join(dir, entry.name), rel)\n } else {\n keys.push(rel)\n }\n }\n }\n\n await walk(resolvedBase, '')\n\n return keys\n },\n async clear(base?: string) {\n if (!base) {\n return\n }\n\n await clean(resolve(base))\n },\n}))\n","","import { version as nodeVersion } from 'node:process'\nimport { version as KubbVersion } from '../../package.json'\n\n/**\n * Returns a snapshot of the current runtime environment.\n *\n * Useful for attaching context to debug logs and error reports so that\n * issues can be reproduced without manual information gathering.\n */\nexport function getDiagnosticInfo() {\n return {\n nodeVersion,\n KubbVersion,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n } as const\n}\n","import path from 'node:path'\nimport type { FileNode } from '@kubb/ast'\nimport { PluginDriver } from '../PluginDriver.ts'\n\ntype BarrelData = {\n file?: FileNode\n /**\n * @deprecated use file instead\n */\n type: 'single' | 'split'\n path: string\n name: string\n}\n\n/**\n * Tree structure used to build per-directory barrel (`index.ts`) files from a\n * flat list of generated {@link FileNode} entries.\n *\n * Each node represents either a directory or a file within the output tree.\n * Use {@link TreeNode.build} to construct a root node from a file list, then\n * traverse with {@link TreeNode.forEach}, {@link TreeNode.leaves}, or the\n * `*Deep` helpers.\n */\nexport class TreeNode {\n data: BarrelData\n parent?: TreeNode\n children: Array<TreeNode> = []\n #cachedLeaves?: Array<TreeNode> = undefined\n\n constructor(data: BarrelData, parent?: TreeNode) {\n this.data = data\n this.parent = parent\n }\n\n addChild(data: BarrelData): TreeNode {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n /**\n * Returns the root ancestor of this node, walking up via `parent` links.\n */\n get root(): TreeNode {\n if (!this.parent) {\n return this\n }\n return this.parent.root\n }\n\n /**\n * Returns all leaf descendants (nodes with no children) of this node.\n *\n * Results are cached after the first traversal.\n */\n get leaves(): Array<TreeNode> {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n if (this.#cachedLeaves) {\n return this.#cachedLeaves\n }\n\n const leaves: TreeNode[] = []\n for (const child of this.children) {\n leaves.push(...child.leaves)\n }\n\n this.#cachedLeaves = leaves\n\n return leaves\n }\n\n /**\n * Visits this node and every descendant in depth-first order.\n */\n forEach(callback: (treeNode: TreeNode) => void): this {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n callback(this)\n\n for (const child of this.children) {\n child.forEach(callback)\n }\n\n return this\n }\n\n /**\n * Finds the first leaf that satisfies `predicate`, or `undefined` when none match.\n */\n findDeep(predicate?: (value: TreeNode, index: number, obj: TreeNode[]) => boolean): TreeNode | undefined {\n if (typeof predicate !== 'function') {\n throw new TypeError('find() predicate must be a function')\n }\n\n return this.leaves.find(predicate)\n }\n\n /**\n * Calls `callback` for every leaf of this node.\n */\n forEachDeep(callback: (treeNode: TreeNode) => void): void {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n this.leaves.forEach(callback)\n }\n\n /**\n * Returns all leaves that satisfy `callback`.\n */\n filterDeep(callback: (treeNode: TreeNode) => boolean): Array<TreeNode> {\n if (typeof callback !== 'function') {\n throw new TypeError('filter() callback must be a function')\n }\n\n return this.leaves.filter(callback)\n }\n\n /**\n * Maps every leaf through `callback` and returns the resulting array.\n */\n mapDeep<T>(callback: (treeNode: TreeNode) => T): Array<T> {\n if (typeof callback !== 'function') {\n throw new TypeError('map() callback must be a function')\n }\n\n return this.leaves.map(callback)\n }\n\n /**\n * Builds a {@link TreeNode} tree from a flat list of files.\n *\n * - Filters to files under `root` (when provided) and skips `.json` files.\n * - Returns `null` when no files match.\n */\n public static build(files: FileNode[], root?: string): TreeNode | null {\n try {\n const filteredTree = buildDirectoryTree(files, root)\n\n if (!filteredTree) {\n return null\n }\n\n const treeNode = new TreeNode({\n name: filteredTree.name,\n path: filteredTree.path,\n file: filteredTree.file,\n type: PluginDriver.getMode(filteredTree.path),\n })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({\n name: item.name,\n path: item.path,\n file: item.file,\n type: PluginDriver.getMode(item.path),\n })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => {\n recurse(treeNode, child)\n })\n\n return treeNode\n } catch (error) {\n throw new Error('Something went wrong with creating barrel files with the TreeNode class', { cause: error })\n }\n }\n}\n\ntype DirectoryTree = {\n name: string\n path: string\n file?: FileNode\n children: Array<DirectoryTree>\n}\n\nconst normalizePath = (p: string): string => p.replaceAll('\\\\', '/')\n\nfunction buildDirectoryTree(files: Array<FileNode>, rootFolder = ''): DirectoryTree | null {\n const normalizedRootFolder = normalizePath(rootFolder)\n const rootPrefix = normalizedRootFolder.endsWith('/') ? normalizedRootFolder : `${normalizedRootFolder}/`\n\n const filteredFiles = files.filter((file) => {\n const normalizedFilePath = normalizePath(file.path)\n return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith('.json') : !normalizedFilePath.endsWith('.json')\n })\n\n if (filteredFiles.length === 0) {\n return null // No files match the root folder\n }\n\n const root: DirectoryTree = {\n name: rootFolder || '',\n path: rootFolder || '',\n children: [],\n }\n\n filteredFiles.forEach((file) => {\n const relativePath = file.path.slice(rootFolder.length)\n const parts = relativePath.split('/').filter(Boolean)\n let currentLevel: DirectoryTree[] = root.children\n let currentPath = normalizePath(rootFolder)\n\n parts.forEach((part, index) => {\n currentPath = path.posix.join(currentPath, part)\n\n let existingNode = currentLevel.find((node) => node.name === part)\n\n if (!existingNode) {\n if (index === parts.length - 1) {\n // If its the last part, its a file\n existingNode = {\n name: part,\n file,\n path: currentPath,\n } as DirectoryTree\n } else {\n // Otherwise, its a folder\n existingNode = {\n name: part,\n path: currentPath,\n children: [],\n } as DirectoryTree\n }\n currentLevel.push(existingNode)\n }\n\n // Move to the next level if its a folder\n if (!existingNode.file) {\n currentLevel = existingNode.children\n }\n })\n })\n\n return root\n}\n","/** biome-ignore-all lint/suspicious/useIterableCallbackReturn: not needed */\nimport { join } from 'node:path'\nimport { getRelativePath } from '@internals/utils'\nimport type { FileNode } from '@kubb/ast'\nimport { createExport, createFile, createSource } from '@kubb/ast'\nimport type { BarrelType } from '../types.ts'\nimport { TreeNode } from './TreeNode.ts'\n\nexport type FileMetaBase = {\n pluginName?: string\n}\n\ntype AddIndexesProps = {\n type: BarrelType | false | undefined\n /**\n * Absolute output root derived from config `root` and `output.path`.\n */\n root: string\n /**\n * Output settings for the plugin.\n */\n output: {\n path: string\n }\n group?: {\n output: string\n exportAs: string\n }\n\n meta?: FileMetaBase\n}\n\nfunction getBarrelFilesByRoot(root: string | undefined, files: Array<FileNode>): Array<FileNode> {\n const cachedFiles = new Map<string, FileNode>()\n\n TreeNode.build(files, root)?.forEach((treeNode) => {\n if (!treeNode?.children || !treeNode.parent?.data.path) {\n return\n }\n\n const barrelFilePath = join(treeNode.parent?.data.path, 'index.ts')\n const barrelFile = createFile({\n path: barrelFilePath,\n baseName: 'index.ts',\n exports: [],\n imports: [],\n sources: [],\n })\n const previousBarrelFile = cachedFiles.get(barrelFile.path)\n const leaves = treeNode.leaves\n\n leaves.forEach((item) => {\n if (!item.data.name) {\n return\n }\n\n const sources = item.data.file?.sources || []\n\n sources.forEach((source) => {\n if (!item.data.file?.path || !source.isIndexable || !source.name) {\n return\n }\n const alreadyContainInPreviousBarrelFile = previousBarrelFile?.sources.some(\n (item) => item.name === source.name && item.isTypeOnly === source.isTypeOnly,\n )\n\n if (alreadyContainInPreviousBarrelFile) {\n return\n }\n\n barrelFile.exports.push(\n createExport({\n name: [source.name],\n path: getRelativePath(treeNode.parent?.data.path, item.data.path),\n isTypeOnly: source.isTypeOnly,\n }),\n )\n\n barrelFile.sources.push(\n createSource({\n name: source.name,\n isTypeOnly: source.isTypeOnly,\n isExportable: false,\n isIndexable: false,\n }),\n )\n })\n })\n\n if (previousBarrelFile) {\n previousBarrelFile.sources.push(...barrelFile.sources)\n previousBarrelFile.exports.push(...barrelFile.exports)\n } else {\n cachedFiles.set(barrelFile.path, barrelFile)\n }\n })\n\n return [...cachedFiles.values()]\n}\n\nfunction trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n // Only strip when the dot is found and no path separator follows it\n // (guards against stripping dots that are part of a directory name like /project.v2/gen)\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Generates `index.ts` barrel files for all directories under `root/output.path`.\n *\n * - Returns an empty array when `type` is falsy or `'propagate'`.\n * - Skips generation when the output path itself ends with `index` (already a barrel).\n * - When `type` is `'all'`, strips named exports so every re-export becomes a wildcard (`export * from`).\n * - Attaches `meta` to each barrel file for downstream plugin identification.\n */\nexport async function getBarrelFiles(files: Array<FileNode>, { type, meta = {}, root, output }: AddIndexesProps): Promise<Array<FileNode>> {\n if (!type || type === 'propagate') {\n return []\n }\n\n const pathToBuildFrom = join(root, output.path)\n\n if (trimExtName(pathToBuildFrom).endsWith('index')) {\n return []\n }\n\n const barrelFiles = getBarrelFilesByRoot(pathToBuildFrom, files)\n\n if (type === 'all') {\n return barrelFiles.map((file) => {\n return {\n ...file,\n exports: file.exports.map((exportItem) => {\n return {\n ...exportItem,\n name: undefined,\n }\n }),\n } as FileNode\n })\n }\n\n return barrelFiles.map((indexFile) => {\n return {\n ...indexFile,\n meta,\n } as FileNode\n })\n}\n","import type { Config, InputPath } from '../types'\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: Config | undefined): config is Config<InputPath> {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n","import { dirname, resolve } from 'node:path'\nimport { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, getRelativePath, URLPath } from '@internals/utils'\nimport type { ExportNode, FileNode, OperationNode } from '@kubb/ast'\nimport { createExport, createFile, transform, walk } from '@kubb/ast'\nimport { BARREL_FILENAME, DEFAULT_BANNER, DEFAULT_CONCURRENCY, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Generator } from './defineGenerator.ts'\nimport type { Parser } from './defineParser.ts'\nimport { FileProcessor } from './FileProcessor.ts'\nimport type { Kubb } from './Kubb.ts'\nimport { PluginDriver } from './PluginDriver.ts'\nimport { applyHookResult } from './renderNode.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, GeneratorContext, KubbHooks, Plugin, PluginContext, Storage } from './types.ts'\nimport { getDiagnosticInfo } from './utils/diagnostics.ts'\nimport type { FileMetaBase } from './utils/getBarrelFiles.ts'\nimport { getBarrelFiles } from './utils/getBarrelFiles.ts'\nimport { isInputPath } from './utils/isInputPath.ts'\n\ntype BuildOptions = {\n config: Config\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Full output produced by a successful or failed build.\n */\nexport type BuildOutput = {\n /**\n * Plugins that threw during installation, paired with the caught error.\n */\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n files: Array<FileNode>\n driver: PluginDriver\n /**\n * Elapsed time in milliseconds for each plugin, keyed by plugin name.\n */\n pluginTimings: Map<string, number>\n error?: Error\n /**\n * Raw generated source, keyed by absolute file path.\n */\n sources: Map<string, string>\n}\n\ntype SetupResult = {\n hooks: AsyncEventEmitter<KubbHooks>\n driver: PluginDriver\n sources: Map<string, string>\n config: Config\n storage: Storage | null\n}\n\nasync function setup(options: BuildOptions): Promise<SetupResult> {\n const { config: userConfig } = options\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n\n const sources: Map<string, string> = new Map<string, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n if (Array.isArray(userConfig.input)) {\n await hooks.emit('kubb:warn', 'This feature is still under development — use with caution')\n }\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n 'Configuration:',\n ` • Name: ${userConfig.name || 'unnamed'}`,\n ` • Root: ${userConfig.root || process.cwd()}`,\n ` • Output: ${userConfig.output?.path || 'not specified'}`,\n ` • Plugins: ${userConfig.plugins?.length || 0}`,\n 'Output Settings:',\n ` • Storage: ${userConfig.output?.storage ? `custom(${userConfig.output.storage.name})` : userConfig.output?.write === false ? 'disabled' : 'filesystem (default)'}`,\n ` • Formatter: ${userConfig.output?.format || 'none'}`,\n ` • Linter: ${userConfig.output?.lint || 'none'}`,\n 'Environment:',\n Object.entries(diagnosticInfo)\n .map(([key, value]) => ` • ${key}: ${value}`)\n .join('\\n'),\n ],\n })\n\n try {\n if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {\n await exists(userConfig.input.path)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Input file validated: ${userConfig.input.path}`],\n })\n }\n } catch (caughtError) {\n if (isInputPath(userConfig)) {\n const error = caughtError as Error\n\n throw new Error(\n `Cannot read file/URL defined in \\`input.path\\` or set with \\`kubb generate PATH\\` in the CLI of your Kubb config ${userConfig.input.path}`,\n {\n cause: error,\n },\n )\n }\n }\n\n if (!userConfig.adapter) {\n throw new Error('Adapter should be defined')\n }\n\n const config: Config = {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n adapter: userConfig.adapter,\n output: {\n write: true,\n barrelType: 'named',\n extension: DEFAULT_EXTENSION,\n defaultBanner: DEFAULT_BANNER,\n ...userConfig.output,\n },\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: userConfig.plugins as unknown as Config['plugins'],\n }\n\n const storage: Storage | null = config.output.write === false ? null : (config.output.storage ?? fsStorage())\n\n if (config.output.clean) {\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],\n })\n await storage?.clear(resolve(config.root, config.output.path))\n }\n\n const driver = new PluginDriver(config, {\n hooks,\n concurrency: DEFAULT_CONCURRENCY,\n })\n\n const adapter = config.adapter\n if (!adapter) {\n throw new Error('No adapter configured. Please provide an adapter in your kubb.config.ts.')\n }\n const source = inputToAdapterSource(config)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Running adapter: ${adapter.name}`],\n })\n\n driver.adapter = adapter\n driver.inputNode = await adapter.parse(source)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n `✓ Adapter '${adapter.name}' resolved InputNode`,\n ` • Schemas: ${driver.inputNode.schemas.length}`,\n ` • Operations: ${driver.inputNode.operations.length}`,\n ],\n })\n\n return {\n config,\n hooks,\n driver,\n sources,\n storage,\n }\n}\n\n/**\n * Walks the AST and dispatches nodes to a plugin's direct AST hooks\n * (`schema`, `operation`, `operations`).\n */\nasync function runPluginAstHooks(plugin: Plugin, context: PluginContext): Promise<void> {\n const { adapter, inputNode, resolver, driver } = context\n const { exclude, include, override } = plugin.options\n\n if (!adapter || !inputNode) {\n throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. pluginOas()) before this plugin in your Kubb config.`)\n }\n\n function resolveRenderer(gen: Generator): RendererFactory | undefined {\n return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)\n }\n\n const generators = plugin.generators ?? []\n const collectedOperations: Array<OperationNode> = []\n\n const baseGeneratorContext = context as GeneratorContext\n const generatorContext = {\n ...baseGeneratorContext,\n resolver: driver.getResolver(plugin.name),\n }\n\n await walk(inputNode, {\n depth: 'shallow',\n async schema(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, { options: plugin.options, exclude, include, override })\n if (options === null) return\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.schema) continue\n const result = await gen.schema(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)\n },\n async operation(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, { options: plugin.options, exclude, include, override })\n if (options !== null) {\n collectedOperations.push(transformedNode)\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.operation) continue\n const result = await gen.operation(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)\n }\n },\n })\n\n if (collectedOperations.length > 0) {\n const ctx = { ...generatorContext, options: plugin.options }\n\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations(collectedOperations, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)\n }\n}\n\nasync function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {\n const { driver, hooks, sources, storage } = setupResult\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\n await driver.emitSetupHooks()\n\n if (driver.adapter && driver.inputNode) {\n await hooks.emit('kubb:build:start', {\n config,\n adapter: driver.adapter,\n inputNode: driver.inputNode,\n getPlugin: (name) => driver.getPlugin(name),\n })\n }\n\n for (const plugin of driver.plugins.values()) {\n const context = driver.getContext(plugin)\n const hrStart = process.hrtime()\n const { output } = plugin.options ?? {}\n const root = resolve(config.root, config.output.path)\n\n try {\n const timestamp = new Date()\n\n await hooks.emit('kubb:plugin:start', plugin)\n\n await hooks.emit('kubb:debug', {\n date: timestamp,\n logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n await plugin.buildStart.call(context)\n\n if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {\n await runPluginAstHooks(plugin, context)\n }\n\n if (output) {\n const barrelFiles = await getBarrelFiles(driver.fileManager.files, {\n type: output.barrelType ?? 'named',\n root,\n output,\n meta: { pluginName: plugin.name },\n })\n await context.upsertFile(...barrelFiles)\n }\n\n const duration = getElapsedMs(hrStart)\n pluginTimings.set(plugin.name, duration)\n\n await hooks.emit('kubb:plugin:end', plugin, { duration, success: true })\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Plugin started successfully (${formatMs(duration)})`],\n })\n } catch (caughtError) {\n const error = caughtError as Error\n const errorTimestamp = new Date()\n const duration = getElapsedMs(hrStart)\n\n await hooks.emit('kubb:plugin:end', plugin, {\n duration,\n success: false,\n error,\n })\n\n await hooks.emit('kubb:debug', {\n date: errorTimestamp,\n logs: [\n '✗ Plugin start failed',\n ` • Plugin Name: ${plugin.name}`,\n ` • Error: ${error.constructor.name} - ${error.message}`,\n ' • Stack Trace:',\n error.stack || 'No stack trace available',\n ],\n })\n\n failedPlugins.add({ plugin, error })\n }\n }\n\n if (config.output.barrelType) {\n const root = resolve(config.root)\n const rootPath = resolve(root, config.output.path, BARREL_FILENAME)\n const rootDir = dirname(rootPath)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: ['Generating barrel file', ` • Type: ${config.output.barrelType}`, ` • Path: ${rootPath}`],\n })\n\n const barrelFiles = driver.fileManager.files.filter((file) => {\n return file.sources.some((source) => source.isIndexable)\n })\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Found ${barrelFiles.length} indexable files for barrel export`],\n })\n\n const existingBarrel = driver.fileManager.files.find((f) => f.path === rootPath)\n const existingExports = new Set(\n existingBarrel?.exports?.flatMap((e) => (Array.isArray(e.name) ? e.name : [e.name])).filter((n): n is string => Boolean(n)) ?? [],\n )\n\n const rootFile = createFile<object>({\n path: rootPath,\n baseName: BARREL_FILENAME,\n exports: buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }).map((e) => createExport(e)),\n sources: [],\n imports: [],\n meta: {},\n })\n\n driver.fileManager.upsert(rootFile)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Generated barrel file (${rootFile.exports?.length || 0} exports)`],\n })\n }\n\n const files = driver.fileManager.files\n\n const parsersMap = new Map<FileNode['extname'], Parser>()\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const extname of parser.extNames) {\n parsersMap.set(extname, parser)\n }\n }\n }\n\n const fileProcessor = new FileProcessor()\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Writing ${files.length} files...`],\n })\n\n await fileProcessor.run(files, {\n parsers: parsersMap,\n extension: config.output.extension,\n onStart: async (processingFiles) => {\n await hooks.emit('kubb:files:processing:start', processingFiles)\n },\n onUpdate: async ({ file, source, processed, total, percentage }) => {\n await hooks.emit('kubb:file:processing:update', {\n file,\n source,\n processed,\n total,\n percentage,\n config,\n })\n if (source) {\n await storage?.setItem(file.path, source)\n sources.set(file.path, source)\n }\n },\n onEnd: async (processedFiles) => {\n await hooks.emit('kubb:files:processing:end', processedFiles)\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${processedFiles.length} files`],\n })\n },\n })\n\n for (const plugin of driver.plugins.values()) {\n if (plugin.buildEnd) {\n const context = driver.getContext(plugin)\n await plugin.buildEnd.call(context)\n }\n }\n\n await hooks.emit('kubb:build:end', {\n files,\n config,\n outputDir: resolve(config.root, config.output.path),\n })\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n files: [],\n driver,\n pluginTimings,\n error: error as Error,\n sources,\n }\n } finally {\n driver.dispose()\n }\n}\n\nasync function build(setupResult: SetupResult): Promise<BuildOutput> {\n const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)\n\n if (error) {\n throw error\n }\n\n if (failedPlugins.size > 0) {\n const errors = [...failedPlugins].map(({ error }) => error)\n\n throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })\n }\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\ntype BuildBarrelExportsParams = {\n barrelFiles: FileNode[]\n rootDir: string\n existingExports: Set<string>\n config: Config\n driver: PluginDriver\n}\n\nfunction buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }: BuildBarrelExportsParams): ExportNode[] {\n const pluginNameMap = new Map<string, Plugin>()\n for (const plugin of driver.plugins.values()) {\n pluginNameMap.set(plugin.name, plugin)\n }\n\n return barrelFiles.flatMap((file) => {\n const containsOnlyTypes = file.sources?.every((source) => source.isTypeOnly)\n\n return (file.sources ?? []).flatMap((source) => {\n if (!file.path || !source.isIndexable) {\n return []\n }\n\n const meta = file.meta as FileMetaBase | undefined\n const plugin = meta?.pluginName ? pluginNameMap.get(meta.pluginName) : undefined\n const pluginOptions = plugin?.options\n\n if (!pluginOptions || pluginOptions.output?.barrelType === false) {\n return []\n }\n\n const exportName = config.output.barrelType === 'all' ? undefined : source.name ? [source.name] : undefined\n if (exportName?.some((n) => existingExports.has(n))) {\n return []\n }\n\n return [\n createExport({\n name: exportName,\n path: getRelativePath(rootDir, file.path),\n isTypeOnly: config.output.barrelType === 'all' ? containsOnlyTypes : source.isTypeOnly,\n }),\n ]\n })\n })\n}\n\nfunction inputToAdapterSource(config: Config): AdapterSource {\n if (Array.isArray(config.input)) {\n return {\n type: 'paths',\n paths: config.input.map((i) => (new URLPath(i.path).isURL ? i.path : resolve(config.root, i.path))),\n }\n }\n\n if ('data' in config.input) {\n return { type: 'data', data: config.input.data }\n }\n\n if (new URLPath(config.input.path).isURL) {\n return { type: 'path', path: config.input.path }\n }\n\n const resolved = resolve(config.root, config.input.path)\n return { type: 'path', path: resolved }\n}\n\ntype KubbOptions = {\n config: Config\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Creates a Kubb instance bound to a single config entry.\n *\n * The instance holds shared state (`hooks`, `sources`, `driver`, `config`) across the\n * `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before\n * calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb({ config })\n *\n * kubb.hooks.on('kubb:plugin:end', (plugin, { duration }) => {\n * console.log(`${plugin.name} completed in ${duration}ms`)\n * })\n *\n * const { files, failedPlugins } = await kubb.safeBuild()\n * ```\n */\nexport function createKubb(options: KubbOptions): Kubb {\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n let setupResult: SetupResult | undefined\n\n const instance: Kubb = {\n get hooks() {\n return hooks\n },\n get sources() {\n return setupResult?.sources ?? new Map()\n },\n get driver() {\n return setupResult?.driver\n },\n get config() {\n return setupResult?.config\n },\n async setup() {\n setupResult = await setup({ config: options.config, hooks })\n },\n async build() {\n if (!setupResult) {\n await instance.setup()\n }\n return build(setupResult!)\n },\n async safeBuild() {\n if (!setupResult) {\n await instance.setup()\n }\n return safeBuild(setupResult!)\n },\n }\n\n return instance\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * The generic `TElement` is the type of the element the renderer accepts —\n * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for\n * your own renderer. Defaults to `unknown` so that generators which do not\n * care about the element type continue to work without specifying it.\n *\n * This allows core to drive rendering without a hard dependency on\n * `@kubb/renderer-jsx` or any specific renderer implementation.\n */\nexport type Renderer<TElement = unknown> = {\n render(element: TElement): Promise<void>\n unmount(error?: Error | number | null): void\n readonly files: Array<FileNode>\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Creates a renderer factory for use in generator definitions.\n *\n * Wrap your renderer factory function with this helper to register it as the\n * renderer for a generator. Core will call this factory once per render cycle\n * to obtain a fresh renderer instance.\n *\n * @example\n * ```ts\n * // packages/renderer-jsx/src/index.ts\n * export const jsxRenderer = createRenderer(() => {\n * const runtime = new Runtime()\n * return {\n * async render(element) { await runtime.render(element) },\n * get files() { return runtime.nodes },\n * unmount(error) { runtime.unmount(error) },\n * }\n * })\n *\n * // packages/plugin-zod/src/generators/zodGenerator.tsx\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const zodGenerator = defineGenerator<PluginZod>({\n * name: 'zod',\n * renderer: jsxRenderer,\n * schema(node, options) { return <File ...>...</File> },\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { FileNode, OperationNode, SchemaNode } from '@kubb/ast'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { GeneratorContext, PluginFactoryOptions } from './types.ts'\n\nexport type { GeneratorContext } from './types.ts'\n\n/**\n * A generator is a named object with optional `schema`, `operation`, and `operations`\n * methods. Each method receives the AST node as the first argument and a typed\n * `ctx` object as the second, giving access to `ctx.config`, `ctx.resolver`,\n * `ctx.adapter`, `ctx.options`, `ctx.upsertFile`, etc.\n *\n * Generators that return renderer elements (e.g. JSX) must declare a `renderer`\n * factory so that core knows how to process the output without coupling core\n * to any specific renderer package.\n *\n * Return a renderer element, an array of `FileNode`, or `void` to handle file\n * writing manually via `ctx.upsertFile`.\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator<PluginTs>({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * operation(node, ctx) {\n * const { options } = ctx\n * return <File ...><OperationType node={node} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin\n * declares a `renderer` (overrides the plugin-level fallback).\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n}\n\n/**\n * Defines a generator. Returns the object as-is with correct `this` typings.\n * `applyHookResult` handles renderer elements and `File[]` uniformly using\n * the generator's declared `renderer` factory.\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { Logger, LoggerOptions, UserLogger } from './types.ts'\n\n/**\n * Wraps a logger definition into a typed {@link Logger}.\n *\n * @example\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context, options) {\n * context.on('kubb:info', (message) => console.log('ℹ', message))\n * context.on('kubb:error', (error) => console.error('✗', error.message))\n * },\n * })\n */\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions>(logger: UserLogger<Options>): Logger<Options> {\n return logger\n}\n","import type { FileNode } from '@kubb/ast'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\nexport type Parser<TMeta extends object = any> = {\n name: string\n /**\n * File extensions this parser handles.\n * Use `undefined` to create a catch-all fallback parser.\n *\n * @example Handled extensions\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Convert a resolved file to a string.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string\n}\n\n/**\n * Defines a parser with type safety.\n *\n * Use this function to create parsers that transform generated files to strings\n * based on their extension.\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * const { extractStringsFromNodes } = await import('@kubb/ast')\n * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta> {\n return parser\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { defineConfig, memoryStorage } from '@kubb/core'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen', storage: memoryStorage() },\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;AASA,IAAa,aAAb,cAAgC,MAAM;CACpC;CAEA,YAAY,SAAiB,SAAkD;AAC7E,QAAM,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AACxC,OAAK,OAAO;AACZ,OAAK,SAAS,QAAQ;;;;;;;;;;;;;;AAe1B,SAAgB,QAAQ,OAAuB;AAC7C,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;;;;;;;;;;;;;;;ACZlE,IAAa,oBAAb,MAAoF;;;;;CAKlF,YAAY,cAAc,IAAI;AAC5B,QAAA,QAAc,gBAAgB,YAAY;;CAG5C,WAAW,IAAIC,YAAAA,cAAkB;;;;;;;;;;CAWjC,MAAM,KAAgD,WAAuB,GAAG,WAA+C;EAC7H,MAAM,YAAY,MAAA,QAAc,UAAU,UAAU;AAE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