@kubb/core 5.0.0-alpha.30 → 5.0.0-alpha.32

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#emitter","NodeEventEmitter","#options","#transformParam","#eachParam","#head","#tail","#size","#studioIsOpen","openInStudioFn","#execute","#executeSync","#emitProcessingEnd","#cachedLeaves","#items","#orderItems","#addParams","composeTransformers"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/config.ts","../src/constants.ts","../src/devtools.ts","../../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js","../../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js","../src/utils/executeStrategies.ts","../src/PluginDriver.ts","../src/renderNode.tsx","../src/createStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/utils/TreeNode.ts","../src/utils/getBarrelFiles.ts","../src/build.ts","../src/createAdapter.ts","../src/createPlugin.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/definePresets.ts","../src/defineResolver.ts","../src/storages/memoryStorage.ts","../src/utils/FunctionParams.ts","../src/utils/formatters.ts","../src/utils/getConfigs.ts","../src/utils/getPreset.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 * 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","type Options = {\n /**\n * When `true`, dot-separated segments are split on `.` and joined with `/` after casing.\n */\n isFile?: boolean\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Splits `text` on `.` and applies `transformPart` to each segment.\n * The last segment receives `isLast = true`, all earlier segments receive `false`.\n * Segments are joined with `/` to form a file path.\n *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\n\n/**\n * Converts `text` to camelCase.\n * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n *\n * @example\n * camelCase('hello-world') // 'helloWorld'\n * camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n *\n * @example\n * pascalCase('hello-world') // 'HelloWorld'\n * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\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 { readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, posix, resolve } from 'node:path'\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","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\n/** Returns `true` when `result` is a fulfilled `Promise.allSettled` result.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseFulfilledResult).map((r) => r.value)\n * ```\n */\nexport function isPromiseFulfilledResult<T = unknown>(result: PromiseSettledResult<unknown>): result is PromiseFulfilledResult<T> {\n return result.status === 'fulfilled'\n}\n\n/** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)\n * ```\n */\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return 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 { PossiblePromise } from '@internals/utils'\nimport type { InputPath, UserConfig } from './types.ts'\n\n/**\n * CLI options derived from command-line flags.\n */\nexport type CLIOptions = {\n /**\n * Path to `kubb.config.js`.\n */\n config?: string\n /**\n * Enable watch mode for input files.\n */\n watch?: boolean\n /**\n * Logging verbosity for CLI usage.\n *\n * - `silent`: hide non-essential logs\n * - `info`: show general logs (non-plugin-related)\n * - `debug`: include detailed plugin lifecycle logs\n * @default 'silent'\n */\n logLevel?: 'silent' | 'info' | 'debug'\n}\n\n/**\n * All accepted forms of a Kubb configuration.\n */\nexport type ConfigInput = PossiblePromise<UserConfig | UserConfig[]> | ((cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>)\n\n/**\n * Helper for defining a Kubb configuration.\n *\n * Accepts either:\n * - A config object or array of configs\n * - A function returning the config(s), optionally async,\n * receiving the CLI options as argument\n *\n * @example\n * export default defineConfig(({ logLevel }) => ({\n * root: 'src',\n * plugins: [myPlugin()],\n * }))\n */\nexport function defineConfig(config: (cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>): typeof config\nexport function defineConfig(config: PossiblePromise<UserConfig | UserConfig[]>): typeof config\nexport function defineConfig(config: ConfigInput): ConfigInput {\n return config\n}\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: UserConfig | undefined): config is UserConfig<InputPath> {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n","import type { FabricFile } from '@kubb/fabric-core/types'\n\n/**\n * Base URL for the Kubb Studio web app.\n */\nexport const DEFAULT_STUDIO_URL = 'https://studio.kubb.dev' as const\n\n/**\n * Default number of plugins that may run concurrently during a build.\n */\nexport const DEFAULT_CONCURRENCY = 15\n\n/**\n * File name used for generated barrel (index) files.\n */\nexport const BARREL_FILENAME = 'index.ts' as const\n\n/**\n * Default banner style written at the top of every generated file.\n */\nexport const DEFAULT_BANNER = 'simple' as const\n\n/**\n * Default file-extension mapping used when no explicit mapping is configured.\n */\nexport const DEFAULT_EXTENSION: Record<FabricFile.Extname, FabricFile.Extname | ''> = { '.ts': '.ts' }\n\n/**\n * Characters recognized as path separators on both POSIX and Windows.\n */\nexport const PATH_SEPARATORS = new Set(['/', '\\\\'] as const)\n\n/**\n * Numeric log-level thresholds used internally to compare verbosity.\n *\n * Higher numbers are more verbose.\n */\nexport const logLevel = {\n silent: Number.NEGATIVE_INFINITY,\n error: 0,\n warn: 1,\n info: 3,\n verbose: 4,\n debug: 5,\n} as const\n\n/**\n * CLI command descriptors for each supported linter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the linter is not found.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n args: (outputPath: string) => ['--fix', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const\n\n/**\n * CLI command descriptors for each supported code formatter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the formatter is not found.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const\n","import type { RootNode } from '@kubb/ast/types'\nimport { deflateSync, inflateSync } from 'fflate'\nimport { x } from 'tinyexec'\nimport type { DevtoolsOptions } from './types.ts'\n\n/**\n * Encodes a `RootNode` as a compressed, URL-safe string.\n *\n * The JSON representation is deflate-compressed with {@link deflateSync} before\n * base64url encoding, which typically reduces payload size by 70–80 % and\n * keeps URLs well within browser and server path-length limits.\n *\n * Use {@link decodeAst} to reverse.\n */\nexport function encodeAst(root: RootNode): string {\n const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(root)))\n return Buffer.from(compressed).toString('base64url')\n}\n\n/**\n * Decodes a `RootNode` from a string produced by {@link encodeAst}.\n *\n * Works in both Node.js and the browser — no streaming APIs required.\n */\nexport function decodeAst(encoded: string): RootNode {\n const bytes = Buffer.from(encoded, 'base64url')\n return JSON.parse(new TextDecoder().decode(inflateSync(bytes))) as RootNode\n}\n\n/**\n * Constructs the Kubb Studio URL for the given `RootNode`.\n * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).\n * The `root` is encoded and attached as the `?root=` query parameter so Studio\n * can decode and render it without a round-trip to any server.\n */\nexport function getStudioUrl(root: RootNode, studioUrl: string, options: DevtoolsOptions = {}): string {\n const baseUrl = studioUrl.replace(/\\/$/, '')\n const path = options.ast ? '/ast' : ''\n\n return `${baseUrl}${path}?root=${encodeAst(root)}`\n}\n\n/**\n * Opens the Kubb Studio URL for the given `RootNode` in the default browser —\n *\n * Falls back to printing the URL if the browser cannot be launched.\n */\nexport async function openInStudio(root: RootNode, studioUrl: string, options: DevtoolsOptions = {}): Promise<void> {\n const url = getStudioUrl(root, studioUrl, options)\n\n const cmd = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open'\n const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]\n\n try {\n await x(cmd, args)\n } catch {\n console.log(`\\n ${url}\\n`)\n }\n}\n","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tlet rejectOnClear = false;\n\n\tif (typeof concurrency === 'object') {\n\t\t({concurrency, rejectOnClear = false} = concurrency);\n\t}\n\n\tvalidateConcurrency(concurrency);\n\n\tif (typeof rejectOnClear !== 'boolean') {\n\t\tthrow new TypeError('Expected `rejectOnClear` to be a boolean');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst resumeNext = () => {\n\t\t// Process the next queued function if we're under the concurrency limit\n\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\tactiveCount++;\n\t\t\tqueue.dequeue().run();\n\t\t}\n\t};\n\n\tconst next = () => {\n\t\tactiveCount--;\n\t\tresumeNext();\n\t};\n\n\tconst run = async (function_, resolve, arguments_) => {\n\t\t// Execute the function and capture the result promise\n\t\tconst result = (async () => function_(...arguments_))();\n\n\t\t// Resolve immediately with the promise (don't wait for completion)\n\t\tresolve(result);\n\n\t\t// Wait for the function to complete (success or failure)\n\t\t// We catch errors here to prevent unhandled rejections,\n\t\t// but the original promise rejection is preserved for the caller\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\t// Decrement active count and process next queued function\n\t\tnext();\n\t};\n\n\tconst enqueue = (function_, resolve, reject, arguments_) => {\n\t\tconst queueItem = {reject};\n\n\t\t// Queue the internal resolve function instead of the run function\n\t\t// to preserve the asynchronous execution context.\n\t\tnew Promise(internalResolve => { // eslint-disable-line promise/param-names\n\t\t\tqueueItem.run = internalResolve;\n\t\t\tqueue.enqueue(queueItem);\n\t\t}).then(run.bind(undefined, function_, resolve, arguments_)); // eslint-disable-line promise/prefer-await-to-then\n\n\t\t// Start processing immediately if we haven't reached the concurrency limit\n\t\tif (activeCount < concurrency) {\n\t\t\tresumeNext();\n\t\t}\n\t};\n\n\tconst generator = (function_, ...arguments_) => new Promise((resolve, reject) => {\n\t\tenqueue(function_, resolve, reject, arguments_);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue() {\n\t\t\t\tif (!rejectOnClear) {\n\t\t\t\t\tqueue.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst abortError = AbortSignal.abort().reason;\n\n\t\t\t\twhile (queue.size > 0) {\n\t\t\t\t\tqueue.dequeue().reject(abortError);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tconcurrency: {\n\t\t\tget: () => concurrency,\n\n\t\t\tset(newConcurrency) {\n\t\t\t\tvalidateConcurrency(newConcurrency);\n\t\t\t\tconcurrency = newConcurrency;\n\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t// eslint-disable-next-line no-unmodified-loop-condition\n\t\t\t\t\twhile (activeCount < concurrency && queue.size > 0) {\n\t\t\t\t\t\tresumeNext();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmap: {\n\t\t\tasync value(iterable, function_) {\n\t\t\t\tconst promises = Array.from(iterable, (value, index) => this(function_, value, index));\n\t\t\t\treturn Promise.all(promises);\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n\nexport function limitFunction(function_, options) {\n\tconst limit = pLimit(options);\n\n\treturn (...arguments_) => limit(() => function_(...arguments_));\n}\n\nfunction validateConcurrency(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n}\n","import pLimit from 'p-limit'\n\ntype PromiseFunc<T = unknown, T2 = never> = (state?: T) => T2 extends never ? Promise<T> : Promise<T> | T2\n\ntype ValueOfPromiseFuncArray<TInput extends Array<unknown>> = TInput extends Array<PromiseFunc<infer X, infer Y>> ? X | Y : never\n\ntype SeqOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = Promise<Array<Awaited<ValueOfPromiseFuncArray<TInput>>>>\n\n/**\n * Runs promise functions in sequence, threading each result into the next call.\n *\n * - Each function receives the accumulated state from the previous call.\n * - Skips functions that return a falsy value (acts as a no-op for that step).\n * - Returns an array of all individual results.\n * @deprecated\n */\nexport function hookSeq<TInput extends Array<PromiseFunc<TValue, null>>, TValue, TOutput = SeqOutput<TInput, TValue>>(promises: TInput): TOutput {\n return promises.filter(Boolean).reduce(\n (promise, func) => {\n if (typeof func !== 'function') {\n throw new Error('HookSeq needs a function that returns a promise `() => Promise<unknown>`')\n }\n\n return promise.then((state) => {\n const calledFunc = func(state as TValue)\n\n if (calledFunc) {\n return calledFunc.then(Array.prototype.concat.bind(state) as (result: TValue) => TValue[])\n }\n\n return state\n })\n },\n Promise.resolve([] as Array<TValue>),\n ) as TOutput\n}\n\ntype HookFirstOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown> = ValueOfPromiseFuncArray<TInput>\n\n/**\n * Runs promise functions in sequence and returns the first non-null result.\n *\n * - Stops as soon as `nullCheck` passes for a result (default: `!== null`).\n * - Subsequent functions are skipped once a match is found.\n * @deprecated\n */\nexport function hookFirst<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown, TOutput = HookFirstOutput<TInput, TValue>>(\n promises: TInput,\n nullCheck: (state: unknown) => boolean = (state) => state !== null,\n): TOutput {\n let promise: Promise<unknown> = Promise.resolve(null) as Promise<unknown>\n\n for (const func of promises.filter(Boolean)) {\n promise = promise.then((state) => {\n if (nullCheck(state)) {\n return state\n }\n\n return func(state as TValue)\n })\n }\n\n return promise as TOutput\n}\n\ntype HookParallelOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = Promise<PromiseSettledResult<Awaited<ValueOfPromiseFuncArray<TInput>>>[]>\n\n/**\n * Runs promise functions concurrently and returns all settled results.\n *\n * - Limits simultaneous executions to `concurrency` (default: unlimited).\n * - Uses `Promise.allSettled` so individual failures do not cancel other tasks.\n * @deprecated\n */\nexport function hookParallel<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown, TOutput = HookParallelOutput<TInput, TValue>>(\n promises: TInput,\n concurrency: number = Number.POSITIVE_INFINITY,\n): TOutput {\n const limit = pLimit(concurrency)\n\n const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()))\n\n return Promise.allSettled(tasks) as TOutput\n}\n\n/**\n * Execution strategy used when dispatching plugin hook calls.\n * @deprecated\n */\nexport type Strategy = 'seq' | 'first' | 'parallel'\n\ntype StrategyOutputMap<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = {\n first: HookFirstOutput<TInput, TValue>\n seq: SeqOutput<TInput, TValue>\n parallel: HookParallelOutput<TInput, TValue>\n}\n/**\n * @deprecated\n */\nexport type StrategySwitch<TStrategy extends Strategy, TInput extends Array<PromiseFunc<TValue, null>>, TValue> = StrategyOutputMap<TInput, TValue>[TStrategy]\n","import { basename, extname, resolve } from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport type { AsyncEventEmitter } from '@internals/utils'\nimport { isPromiseRejectedResult, transformReservedWord } from '@internals/utils'\nimport type { RootNode } from '@kubb/ast/types'\nimport type { FabricFile, Fabric as FabricType } from '@kubb/fabric-core/types'\nimport { DEFAULT_STUDIO_URL } from './constants.ts'\nimport { openInStudio as openInStudioFn } from './devtools.ts'\n\nimport type {\n Adapter,\n Config,\n DevtoolsOptions,\n KubbEvents,\n Plugin,\n PluginContext,\n PluginFactoryOptions,\n PluginLifecycle,\n PluginLifecycleHooks,\n PluginParameter,\n PluginWithLifeCycle,\n ResolveNameParams,\n ResolvePathParams,\n} from './types.ts'\nimport { hookFirst, hookParallel, hookSeq } from './utils/executeStrategies.ts'\n\ntype RequiredPluginLifecycle = Required<PluginLifecycle>\n\n/**\n * Hook dispatch strategy used by the `PluginDriver`.\n *\n * - `hookFirst` — stops at the first non-null result.\n * - `hookForPlugin` — calls only the matching plugin.\n * - `hookParallel` — calls all plugins concurrently.\n * - `hookSeq` — calls all plugins in order, threading the result.\n */\nexport type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq'\n\ntype ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H]\n\ntype SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {\n result: Result\n plugin: Plugin\n}\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\ntype Options = {\n fabric: FabricType\n events: AsyncEventEmitter<KubbEvents>\n /**\n * @default Number.POSITIVE_INFINITY\n */\n concurrency?: number\n}\n\n/**\n * Parameters accepted by `PluginDriver.getFile` to resolve a generated file descriptor.\n */\nexport type GetFileOptions<TOptions = object> = {\n name: string\n mode?: FabricFile.Mode\n extname: FabricFile.Extname\n pluginName: string\n options?: TOptions\n}\n\n/**\n * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.\n *\n * @example\n * ```ts\n * getMode('src/gen/types.ts') // 'single'\n * getMode('src/gen/types') // 'split'\n * ```\n */\nexport function getMode(fileOrFolder: string | undefined | null): FabricFile.Mode {\n if (!fileOrFolder) {\n return 'split'\n }\n return extname(fileOrFolder) ? 'single' : 'split'\n}\n\nconst hookFirstNullCheck = (state: unknown) => !!(state as SafeParseResult<'resolveName'> | null)?.result\n\nexport class PluginDriver {\n readonly config: Config\n readonly options: Options\n\n /**\n * The universal `@kubb/ast` `RootNode` produced by the adapter, set by\n * the build pipeline after the adapter's `parse()` resolves.\n */\n rootNode: RootNode | undefined = undefined\n adapter: Adapter | undefined = undefined\n #studioIsOpen = false\n\n readonly plugins = new Map<string, Plugin>()\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n config.plugins\n .map((plugin) => Object.assign({ buildStart() {}, buildEnd() {} }, plugin) as unknown as Plugin)\n .filter((plugin) => {\n if (typeof plugin.apply === 'function') {\n return plugin.apply(config)\n }\n return true\n })\n .sort((a, b) => {\n if (b.pre?.includes(a.name)) return 1\n if (b.post?.includes(a.name)) return -1\n return 0\n })\n .forEach((plugin) => {\n this.plugins.set(plugin.name, plugin)\n })\n }\n\n get events() {\n return this.options.events\n }\n\n getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown> {\n const driver = this\n\n const baseContext = {\n fabric: driver.options.fabric,\n config: driver.config,\n get root(): string {\n return resolve(driver.config.root, driver.config.output.path)\n },\n getMode(output: { path: string }): FabricFile.Mode {\n return getMode(resolve(driver.config.root, driver.config.output.path, output.path))\n },\n events: driver.options.events,\n plugin,\n getPlugin: driver.getPlugin.bind(driver),\n requirePlugin: driver.requirePlugin.bind(driver),\n driver: driver,\n addFile: async (...files: Array<FabricFile.File>) => {\n await this.options.fabric.addFile(...files)\n },\n upsertFile: async (...files: Array<FabricFile.File>) => {\n await this.options.fabric.upsertFile(...files)\n },\n get rootNode(): RootNode | undefined {\n return driver.rootNode\n },\n get adapter(): Adapter | undefined {\n return driver.adapter\n },\n get resolver() {\n return plugin.resolver\n },\n get transformer() {\n return plugin.transformer\n },\n warn(message: string) {\n driver.events.emit('warn', message)\n },\n error(error: string | Error) {\n driver.events.emit('error', typeof error === 'string' ? new Error(error) : error)\n },\n info(message: string) {\n driver.events.emit('info', message)\n },\n openInStudio(options?: DevtoolsOptions) {\n if (!driver.config.devtools || driver.#studioIsOpen) {\n return\n }\n\n if (typeof driver.config.devtools !== 'object') {\n throw new Error('Devtools must be an object')\n }\n\n if (!driver.rootNode || !driver.adapter) {\n throw new Error('adapter is not defined, make sure you have set the parser in kubb.config.ts')\n }\n\n driver.#studioIsOpen = true\n\n const studioUrl = driver.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL\n\n return openInStudioFn(driver.rootNode, studioUrl, options)\n },\n } as unknown as PluginContext<TOptions>\n\n const mergedExtras: Record<string, unknown> = {}\n\n for (const p of this.plugins.values()) {\n if (typeof p.inject === 'function') {\n const result = (p.inject as (this: PluginContext) => unknown).call(baseContext as unknown as PluginContext)\n if (result !== null && typeof result === 'object') {\n Object.assign(mergedExtras, result)\n }\n }\n }\n\n return {\n ...baseContext,\n ...mergedExtras,\n }\n }\n /**\n * @deprecated use resolvers context instead\n */\n getFile<TOptions = object>({ name, mode, extname, pluginName, options }: GetFileOptions<TOptions>): FabricFile.File<{ pluginName: string }> {\n const resolvedName = mode ? (mode === 'single' ? '' : this.resolveName({ name, pluginName, type: 'file' })) : name\n\n const path = this.resolvePath({\n baseName: `${resolvedName}${extname}` as const,\n mode,\n pluginName,\n options,\n })\n\n if (!path) {\n throw new Error(`Filepath should be defined for resolvedName \"${resolvedName}\" and pluginName \"${pluginName}\"`)\n }\n\n return {\n path,\n baseName: basename(path) as FabricFile.File['baseName'],\n meta: {\n pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n }\n }\n\n /**\n * @deprecated use resolvers context instead\n */\n resolvePath = <TOptions = object>(params: ResolvePathParams<TOptions>): FabricFile.Path => {\n const root = resolve(this.config.root, this.config.output.path)\n const defaultPath = resolve(root, params.baseName)\n\n if (params.pluginName) {\n const paths = this.hookForPluginSync({\n pluginName: params.pluginName,\n hookName: 'resolvePath',\n parameters: [params.baseName, params.mode, params.options as object],\n })\n\n return paths?.at(0) || defaultPath\n }\n\n const firstResult = this.hookFirstSync({\n hookName: 'resolvePath',\n parameters: [params.baseName, params.mode, params.options as object],\n })\n\n return firstResult?.result || defaultPath\n }\n /**\n * @deprecated use resolvers context instead\n */\n resolveName = (params: ResolveNameParams): string => {\n if (params.pluginName) {\n const names = this.hookForPluginSync({\n pluginName: params.pluginName,\n hookName: 'resolveName',\n parameters: [params.name.trim(), params.type],\n })\n\n return transformReservedWord(names?.at(0) ?? params.name)\n }\n\n const name = this.hookFirstSync({\n hookName: 'resolveName',\n parameters: [params.name.trim(), params.type],\n })?.result\n\n return transformReservedWord(name ?? params.name)\n }\n\n /**\n * Run a specific hookName for plugin x.\n */\n async hookForPlugin<H extends PluginLifecycleHooks>({\n pluginName,\n hookName,\n parameters,\n }: {\n pluginName: string\n hookName: H\n parameters: PluginParameter<H>\n }): Promise<Array<ReturnType<ParseResult<H>> | null>> {\n const plugin = this.plugins.get(pluginName)\n\n if (!plugin) {\n return [null]\n }\n\n this.events.emit('plugins:hook:progress:start', {\n hookName,\n plugins: [plugin],\n })\n\n const result = await this.#execute<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return [result]\n }\n\n /**\n * Run a specific hookName for plugin x.\n */\n hookForPluginSync<H extends PluginLifecycleHooks>({\n pluginName,\n hookName,\n parameters,\n }: {\n pluginName: string\n hookName: H\n parameters: PluginParameter<H>\n }): Array<ReturnType<ParseResult<H>>> | null {\n const plugin = this.plugins.get(pluginName)\n\n if (!plugin) {\n return null\n }\n\n const result = this.#executeSync<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n return result !== null ? [result] : []\n }\n\n /**\n * Returns the first non-null result.\n */\n async hookFirst<H extends PluginLifecycleHooks>({\n hookName,\n parameters,\n skipped,\n }: {\n hookName: H\n parameters: PluginParameter<H>\n skipped?: ReadonlySet<Plugin> | null\n }): Promise<SafeParseResult<H>> {\n const plugins: Array<Plugin> = []\n for (const plugin of this.plugins.values()) {\n if (hookName in plugin && (skipped ? !skipped.has(plugin) : true)) plugins.push(plugin)\n }\n\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const promises = plugins.map((plugin) => {\n return async () => {\n const value = await this.#execute<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n return Promise.resolve({\n plugin,\n result: value,\n } as SafeParseResult<H>)\n }\n })\n\n const result = await hookFirst(promises, hookFirstNullCheck)\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return result\n }\n\n /**\n * Returns the first non-null result.\n */\n hookFirstSync<H extends PluginLifecycleHooks>({\n hookName,\n parameters,\n skipped,\n }: {\n hookName: H\n parameters: PluginParameter<H>\n skipped?: ReadonlySet<Plugin> | null\n }): SafeParseResult<H> | null {\n let parseResult: SafeParseResult<H> | null = null\n\n for (const plugin of this.plugins.values()) {\n if (!(hookName in plugin)) continue\n if (skipped?.has(plugin)) continue\n\n parseResult = {\n result: this.#executeSync<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n }),\n plugin,\n } as SafeParseResult<H>\n\n if (parseResult.result != null) break\n }\n\n return parseResult\n }\n\n /**\n * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.\n */\n async hookParallel<H extends PluginLifecycleHooks, TOutput = void>({\n hookName,\n parameters,\n }: {\n hookName: H\n parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined\n }): Promise<Awaited<TOutput>[]> {\n const plugins: Array<Plugin> = []\n for (const plugin of this.plugins.values()) {\n if (hookName in plugin) plugins.push(plugin)\n }\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const pluginStartTimes = new Map<Plugin, number>()\n\n const promises = plugins.map((plugin) => {\n return () => {\n pluginStartTimes.set(plugin, performance.now())\n return this.#execute({\n strategy: 'hookParallel',\n hookName,\n parameters,\n plugin,\n }) as Promise<TOutput>\n }\n })\n\n const results = await hookParallel(promises, this.options.concurrency)\n\n results.forEach((result, index) => {\n if (isPromiseRejectedResult<Error>(result)) {\n const plugin = plugins[index]\n\n if (plugin) {\n const startTime = pluginStartTimes.get(plugin) ?? performance.now()\n this.events.emit('error', result.reason, {\n plugin,\n hookName,\n strategy: 'hookParallel',\n duration: Math.round(performance.now() - startTime),\n parameters,\n })\n }\n }\n })\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return results.reduce((acc, result) => {\n if (result.status === 'fulfilled') {\n acc.push(result.value)\n }\n return acc\n }, [] as Awaited<TOutput>[])\n }\n\n /**\n * Chains plugins\n */\n async hookSeq<H extends PluginLifecycleHooks>({ hookName, parameters }: { hookName: H; parameters?: PluginParameter<H> }): Promise<void> {\n const plugins: Array<Plugin> = []\n for (const plugin of this.plugins.values()) {\n if (hookName in plugin) plugins.push(plugin)\n }\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const promises = plugins.map((plugin) => {\n return () =>\n this.#execute({\n strategy: 'hookSeq',\n hookName,\n parameters,\n plugin,\n })\n })\n\n await hookSeq(promises)\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n }\n\n getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined\n getPlugin(pluginName: string): Plugin | undefined {\n return this.plugins.get(pluginName) as Plugin | undefined\n }\n\n /**\n * Like `getPlugin` but throws a descriptive error when the plugin is not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>\n requirePlugin(pluginName: string): Plugin {\n const plugin = this.plugins.get(pluginName)\n if (!plugin) {\n throw new Error(`[kubb] Plugin \"${pluginName}\" is required but not found. Make sure it is included in your Kubb config.`)\n }\n return plugin\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n #emitProcessingEnd<H extends PluginLifecycleHooks>({\n startTime,\n output,\n strategy,\n hookName,\n plugin,\n parameters,\n }: {\n startTime: number\n output: unknown\n strategy: Strategy\n hookName: H\n plugin: PluginWithLifeCycle\n parameters: unknown[] | undefined\n }): void {\n this.events.emit('plugins:hook:processing:end', {\n duration: Math.round(performance.now() - startTime),\n parameters,\n output,\n strategy,\n hookName,\n plugin,\n })\n }\n\n // Implementation signature\n #execute<H extends PluginLifecycleHooks>({\n strategy,\n hookName,\n parameters,\n plugin,\n }: {\n strategy: Strategy\n hookName: H\n parameters: unknown[] | undefined\n plugin: PluginWithLifeCycle\n }): Promise<ReturnType<ParseResult<H>> | null> | null {\n const hook = plugin[hookName]\n\n if (!hook) {\n return null\n }\n\n this.events.emit('plugins:hook:processing:start', {\n strategy,\n hookName,\n parameters,\n plugin,\n })\n\n const startTime = performance.now()\n\n const task = (async () => {\n try {\n const output =\n typeof hook === 'function' ? await Promise.resolve((hook as (...args: unknown[]) => unknown).apply(this.getContext(plugin), parameters ?? [])) : hook\n\n this.#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters })\n\n return output as ReturnType<ParseResult<H>>\n } catch (error) {\n this.events.emit('error', error as Error, {\n plugin,\n hookName,\n strategy,\n duration: Math.round(performance.now() - startTime),\n })\n\n return null\n }\n })()\n\n return task\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual plugin\n */\n #executeSync<H extends PluginLifecycleHooks>({\n strategy,\n hookName,\n parameters,\n plugin,\n }: {\n strategy: Strategy\n hookName: H\n parameters: PluginParameter<H>\n plugin: PluginWithLifeCycle\n }): ReturnType<ParseResult<H>> | null {\n const hook = plugin[hookName]\n\n if (!hook) {\n return null\n }\n\n this.events.emit('plugins:hook:processing:start', {\n strategy,\n hookName,\n parameters,\n plugin,\n })\n\n const startTime = performance.now()\n\n try {\n const output =\n typeof hook === 'function'\n ? ((hook as (...args: unknown[]) => unknown).apply(this.getContext(plugin), parameters) as ReturnType<ParseResult<H>>)\n : (hook as ReturnType<ParseResult<H>>)\n\n this.#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters })\n\n return output\n } catch (error) {\n this.events.emit('error', error as Error, {\n plugin,\n hookName,\n strategy,\n duration: Math.round(performance.now() - startTime),\n })\n\n return null\n }\n }\n}\n","import type { FabricFile } from '@kubb/fabric-core/types'\nimport { createReactFabric, Fabric } from '@kubb/react-fabric'\nimport type { FabricReactNode, Fabric as FabricType } from '@kubb/react-fabric/types'\n\n/**\n * Handles the return value of a plugin AST hook or generator method.\n *\n * - React element → rendered via an isolated react-fabric context, files merged into `fabric`\n * - `Array<FabricFile.File>` → upserted directly into `fabric`\n * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)\n */\nexport async function applyHookResult(result: FabricReactNode | Array<FabricFile.File> | void, fabric: FabricType): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n await fabric.upsertFile(...(result as Array<FabricFile.File>))\n return\n }\n\n // Non-array truthy result is treated as a React element (FabricReactNode)\n const fabricChild = createReactFabric()\n await fabricChild.render(<Fabric>{result as FabricReactNode}</Fabric>)\n fabric.context.fileManager.upsert(...fabricChild.files)\n fabricChild.unmount()\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 { FabricFile } from '@kubb/fabric-core/types'\nimport { getMode } from '../PluginDriver.ts'\n\ntype BarrelData = {\n file?: FabricFile.File\n /**\n * @deprecated use file instead\n */\n type: FabricFile.Mode\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 FabricFile.File} 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: FabricFile.File[], 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?: FabricFile.File\n children: Array<DirectoryTree>\n}\n\nconst normalizePath = (p: string): string => p.replaceAll('\\\\', '/')\n\nfunction buildDirectoryTree(files: Array<FabricFile.File>, 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 { FabricFile } from '@kubb/fabric-core/types'\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 * Root based on root and output.path specified in the config\n */\n root: string\n /**\n * Output for 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<FabricFile.ResolvedFile>): Array<FabricFile.File> {\n const cachedFiles = new Map<FabricFile.Path, FabricFile.File>()\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') as FabricFile.Path\n const barrelFile: FabricFile.File = {\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 name: [source.name],\n path: getRelativePath(treeNode.parent?.data.path, item.data.path),\n isTypeOnly: source.isTypeOnly,\n })\n\n barrelFile.sources.push({\n name: source.name,\n isTypeOnly: source.isTypeOnly,\n //TODO use parser to generate import\n value: '',\n isExportable: false,\n isIndexable: false,\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(\n files: Array<FabricFile.ResolvedFile>,\n { type, meta = {}, root, output }: AddIndexesProps,\n): Promise<Array<FabricFile.File>> {\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 }\n })\n }\n\n return barrelFiles.map((indexFile) => {\n return {\n ...indexFile,\n meta,\n }\n })\n}\n","import { dirname, relative, resolve } from 'node:path'\nimport { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, getRelativePath, URLPath } from '@internals/utils'\nimport { transform, walk } from '@kubb/ast'\nimport type { OperationNode } from '@kubb/ast/types'\nimport type { FabricFile, Fabric as FabricType } from '@kubb/fabric-core/types'\nimport { createFabric } from '@kubb/react-fabric'\nimport { typescriptParser } from '@kubb/react-fabric/parsers'\nimport { fsPlugin } from '@kubb/react-fabric/plugins'\nimport { isInputPath } from './config.ts'\nimport { BARREL_FILENAME, DEFAULT_BANNER, DEFAULT_CONCURRENCY, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport { PluginDriver } from './PluginDriver.ts'\nimport { applyHookResult } from './renderNode.tsx'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, KubbEvents, Plugin, PluginContext, Storage, UserConfig } from './types.ts'\nimport { getDiagnosticInfo } from './utils/diagnostics.ts'\nimport type { FileMetaBase } from './utils/getBarrelFiles.ts'\nimport { getBarrelFiles } from './utils/getBarrelFiles.ts'\n\ntype BuildOptions = {\n config: UserConfig\n events?: AsyncEventEmitter<KubbEvents>\n}\n\n/**\n * Full output produced by a successful or failed build.\n */\ntype BuildOutput = {\n /**\n * Plugins that threw during installation, paired with the caught error.\n */\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n fabric: FabricType\n files: Array<FabricFile.ResolvedFile>\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<FabricFile.Path, string>\n}\n\n/**\n * Intermediate result returned by {@link setup} and accepted by {@link safeBuild}.\n */\ntype SetupResult = {\n events: AsyncEventEmitter<KubbEvents>\n fabric: FabricType\n driver: PluginDriver\n sources: Map<FabricFile.Path, string>\n}\n\n/**\n * Initializes all Kubb infrastructure for a build without executing any plugins.\n *\n * - Validates the input path (when applicable).\n * - Applies config defaults (`root`, `output.*`, `devtools`).\n * - Creates the Fabric instance and wires storage, format, and lint hooks.\n * - Runs the adapter (if configured) to produce the universal `RootNode`.\n *\n * Pass the returned {@link SetupResult} directly to {@link safeBuild} or {@link build}\n * via the `overrides` argument to reuse the same infrastructure across multiple runs.\n */\nexport async function setup(options: BuildOptions): Promise<SetupResult> {\n const { config: userConfig, events = new AsyncEventEmitter<KubbEvents>() } = options\n\n const sources: Map<FabricFile.Path, string> = new Map<FabricFile.Path, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n if (Array.isArray(userConfig.input)) {\n await events.emit('warn', 'This feature is still under development — use with caution')\n }\n\n await events.emit('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 events.emit('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 const definedConfig: Config = {\n root: userConfig.root || process.cwd(),\n ...userConfig,\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 Config['plugins'],\n }\n\n // write: false is the explicit dry-run opt-out; otherwise use the provided\n // storage or fall back to fsStorage (backwards-compatible default).\n // Keys are root-relative (e.g. `src/gen/api/getPets.ts`) so fsStorage()\n // needs no configuration — it resolves them against process.cwd().\n const storage: Storage | null = definedConfig.output.write === false ? null : (definedConfig.output.storage ?? fsStorage())\n\n if (definedConfig.output.clean) {\n await events.emit('debug', {\n date: new Date(),\n logs: ['Cleaning output directories', ` • Output: ${definedConfig.output.path}`],\n })\n await storage?.clear(resolve(definedConfig.root, definedConfig.output.path))\n }\n\n const fabric = createFabric()\n fabric.use(fsPlugin)\n fabric.use(typescriptParser)\n\n fabric.context.on('files:processing:start', (files) => {\n events.emit('files:processing:start', files)\n events.emit('debug', {\n date: new Date(),\n logs: [`Writing ${files.length} files...`],\n })\n })\n\n fabric.context.on('file:processing:update', async (params) => {\n const { file, source } = params\n await events.emit('file:processing:update', {\n ...params,\n config: definedConfig,\n source,\n })\n\n if (source) {\n // Key is root-relative so it's meaningful for any backend (fs, S3, Redis…)\n const key = relative(resolve(definedConfig.root), file.path)\n await storage?.setItem(key, source)\n sources.set(file.path, source)\n }\n })\n\n fabric.context.on('files:processing:end', async (files) => {\n await events.emit('files:processing:end', files)\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${files.length} files`],\n })\n })\n\n await events.emit('debug', {\n date: new Date(),\n logs: [\n '✓ Fabric initialized',\n ` • Storage: ${storage ? storage.name : 'disabled (dry-run)'}`,\n ` • Barrel type: ${definedConfig.output.barrelType || 'none'}`,\n ],\n })\n\n const pluginDriver = new PluginDriver(definedConfig, {\n fabric,\n events,\n concurrency: DEFAULT_CONCURRENCY,\n })\n\n // Run the adapter (if provided) to produce the universal RootNode\n if (definedConfig.adapter) {\n const source = inputToAdapterSource(definedConfig)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`Running adapter: ${definedConfig.adapter.name}`],\n })\n\n pluginDriver.adapter = definedConfig.adapter\n pluginDriver.rootNode = await definedConfig.adapter.parse(source)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [\n `✓ Adapter '${definedConfig.adapter.name}' resolved RootNode`,\n ` • Schemas: ${pluginDriver.rootNode.schemas.length}`,\n ` • Operations: ${pluginDriver.rootNode.operations.length}`,\n ],\n })\n }\n\n return {\n events,\n fabric,\n driver: pluginDriver,\n sources,\n }\n}\n\n/**\n * Runs a full Kubb build and throws on any error or plugin failure.\n *\n * Internally delegates to {@link safeBuild} and rethrows collected errors.\n * Pass an existing {@link SetupResult} via `overrides` to skip the setup phase.\n */\nexport async function build(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { fabric, files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(options, overrides)\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 fabric,\n files,\n driver,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\n/**\n * Walks the AST and dispatches nodes to a plugin's direct AST hooks\n * (`schema`, `operation`, `operations`).\n *\n * - Each hook accepts a single handler **or an array** — all entries are called in sequence.\n * - Nodes that are excluded by `exclude`/`include` plugin options are skipped automatically.\n * - Return values are handled via `applyHookResult`: React elements are rendered,\n * `FabricFile.File[]` are written via upsert, and `void` is a no-op (manual handling).\n * - Barrel files are generated automatically when `output.barrelType` is set.\n */\nasync function runPluginAstHooks(plugin: Plugin, context: PluginContext): Promise<void> {\n const { adapter, rootNode, resolver, fabric } = context\n const { exclude, include, override } = plugin.options\n\n if (!adapter || !rootNode) {\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 const collectedOperations: Array<OperationNode> = []\n\n await walk(rootNode, {\n depth: 'shallow',\n async schema(node) {\n if (!plugin.schema) return\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 const result = await plugin.schema.call(context, transformedNode, options)\n\n await applyHookResult(result, fabric)\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 if (plugin.operation) {\n const result = await plugin.operation.call(context, transformedNode, options)\n await applyHookResult(result, fabric)\n }\n }\n },\n })\n\n if (plugin.operations && collectedOperations.length > 0) {\n const result = await plugin.operations.call(context, collectedOperations, plugin.options)\n\n await applyHookResult(result, fabric)\n }\n}\n\n/**\n * Runs a full Kubb build and captures errors instead of throwing.\n *\n * - Installs each plugin in order, recording failures in `failedPlugins`.\n * - Generates the root barrel file when `output.barrelType` is set.\n * - Writes all files through Fabric.\n *\n * Returns a {@link BuildOutput} even on failure — inspect `error` and\n * `failedPlugins` to determine whether the build succeeded.\n */\nexport async function safeBuild(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { fabric, driver, events, sources } = overrides ? overrides : await setup(options)\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n // in ms\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\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 events.emit('plugin:start', plugin)\n\n await events.emit('debug', {\n date: timestamp,\n logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n // Call buildStart() for any custom plugin logic\n await plugin.buildStart.call(context)\n\n // Dispatch schema/operation/operations hooks (direct hooks or composed via composeGenerators)\n if (plugin.schema || plugin.operation || plugin.operations) {\n await runPluginAstHooks(plugin, context)\n }\n\n if (output) {\n const barrelFiles = await getBarrelFiles(fabric.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 events.emit('plugin:end', plugin, { duration, success: true })\n\n await events.emit('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 events.emit('plugin:end', plugin, {\n duration,\n success: false,\n error,\n })\n\n await events.emit('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 events.emit('debug', {\n date: new Date(),\n logs: ['Generating barrel file', ` • Type: ${config.output.barrelType}`, ` • Path: ${rootPath}`],\n })\n\n const barrelFiles = fabric.files.filter((file) => {\n return file.sources.some((source) => source.isIndexable)\n })\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`Found ${barrelFiles.length} indexable files for barrel export`],\n })\n\n const existingBarrel = fabric.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: FabricFile.File = {\n path: rootPath,\n baseName: BARREL_FILENAME,\n exports: buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }),\n sources: [],\n imports: [],\n meta: {},\n }\n\n await fabric.upsertFile(rootFile)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ Generated barrel file (${rootFile.exports?.length || 0} exports)`],\n })\n }\n\n const files = [...fabric.files]\n\n await fabric.write({ extension: config.output.extension })\n\n // Call buildEnd() on each plugin after all files are written\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 return {\n failedPlugins,\n fabric,\n files,\n driver,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n fabric,\n files: [],\n driver,\n pluginTimings,\n error: error as Error,\n sources,\n }\n }\n}\n\ntype BuildBarrelExportsParams = {\n barrelFiles: FabricFile.ResolvedFile[]\n rootDir: string\n existingExports: Set<string>\n config: Config\n driver: PluginDriver\n}\n\nfunction buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }: BuildBarrelExportsParams): FabricFile.Export[] {\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 {\n name: exportName,\n path: getRelativePath(rootDir, file.path),\n isTypeOnly: config.output.barrelType === 'all' ? containsOnlyTypes : source.isTypeOnly,\n } satisfies FabricFile.Export,\n ]\n })\n })\n}\n\n/**\n * Maps the resolved `Config['input']` shape into an `AdapterSource` that\n * the adapter's `parse()` can consume.\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","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 { 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 */\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 { PossiblePromise } from '@internals/utils'\nimport type { OperationNode, SchemaNode } from '@kubb/ast/types'\nimport type { FabricFile } from '@kubb/fabric-core/types'\nimport type { FabricReactNode } from '@kubb/react-fabric/types'\nimport { applyHookResult } from './renderNode.tsx'\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 is called with `this = PluginContext` of the parent plugin,\n * giving full access to `this.config`, `this.resolver`, `this.adapter`, `this.fabric`,\n * `this.driver`, etc.\n *\n * Return a React element, an array of `FabricFile.File`, or `void` to handle file\n * writing manually via `this.upsertFile`. Both React and core (non-React) generators\n * use the same method signatures — the return type determines how output is handled.\n *\n * @example\n * ```ts\n * export const typeGenerator = defineGenerator<PluginTs>({\n * name: 'typescript',\n * schema(node, options) {\n * const { adapter, resolver, root } = this\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * operation(node, options) {\n * return <File ...><OperationType node={node} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {\n /** Used in diagnostic messages and debug output. */\n name: string\n /**\n * Called for each schema node in the AST walk.\n * `this` is the parent plugin's context with `adapter` and `rootNode` guaranteed present.\n * `options` contains the per-node resolved options (after exclude/include/override).\n */\n schema?: (\n this: GeneratorContext<TOptions>,\n node: SchemaNode,\n options: TOptions['resolvedOptions'],\n ) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>\n /**\n * Called for each operation node in the AST walk.\n * `this` is the parent plugin's context with `adapter` and `rootNode` guaranteed present.\n */\n operation?: (\n this: GeneratorContext<TOptions>,\n node: OperationNode,\n options: TOptions['resolvedOptions'],\n ) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>\n /**\n * Called once after all operations have been walked.\n * `this` is the parent plugin's context with `adapter` and `rootNode` guaranteed present.\n */\n operations?: (\n this: GeneratorContext<TOptions>,\n nodes: Array<OperationNode>,\n options: TOptions['resolvedOptions'],\n ) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>\n}\n\n/**\n * Defines a generator. Returns the object as-is with correct `this` typings.\n * No type discrimination (`type: 'react' | 'core'`) needed — `applyHookResult`\n * handles React elements and `File[]` uniformly.\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generator: Generator<TOptions>): Generator<TOptions> {\n return generator\n}\n\n/**\n * Merges an array of generators into a single generator.\n *\n * The merged generator's `schema`, `operation`, and `operations` methods run\n * the corresponding method from each input generator in sequence, applying each\n * result via `applyHookResult`. This eliminates the need to write the loop\n * manually in each plugin.\n *\n * @param generators - Array of generators to merge into a single generator.\n *\n * @example\n * ```ts\n * const merged = mergeGenerators(generators)\n *\n * return {\n * name: pluginName,\n * schema: merged.schema,\n * operation: merged.operation,\n * operations: merged.operations,\n * }\n * ```\n */\nexport function mergeGenerators<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generators: Array<Generator<TOptions>>): Generator<TOptions> {\n return {\n name: generators.length > 0 ? generators.map((g) => g.name).join('+') : 'merged',\n async schema(node, options) {\n for (const gen of generators) {\n if (!gen.schema) continue\n const result = await gen.schema.call(this, node, options)\n\n await applyHookResult(result, this.fabric)\n }\n },\n async operation(node, options) {\n for (const gen of generators) {\n if (!gen.operation) continue\n const result = await gen.operation.call(this, node, options)\n\n await applyHookResult(result, this.fabric)\n }\n },\n async operations(nodes, options) {\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations.call(this, nodes, options)\n\n await applyHookResult(result, this.fabric)\n }\n },\n }\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('info', (message) => console.log('ℹ', message))\n * context.on('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 { Preset, Presets, Resolver } from './types.ts'\n\n/**\n * Creates a typed presets registry object — a named collection of {@link Preset} entries.\n *\n * @example\n * import { definePreset, definePresets } from '@kubb/core'\n * import { resolverTsLegacy } from '@kubb/plugin-ts'\n *\n * export const myPresets = definePresets({\n * kubbV4: definePreset('kubbV4', { resolvers: [resolverTsLegacy] }),\n * })\n */\nexport function definePresets<TResolver extends Resolver = Resolver>(presets: Presets<TResolver>): Presets<TResolver> {\n return presets\n}\n","import path from 'node:path'\nimport { camelCase, pascalCase } from '@internals/utils'\nimport { isOperationNode, isSchemaNode } from '@kubb/ast'\nimport type { Node, OperationNode, RootNode, SchemaNode } from '@kubb/ast/types'\nimport type { FabricFile } from '@kubb/fabric-core/types'\nimport { getMode } from './PluginDriver.ts'\nimport type {\n Config,\n PluginFactoryOptions,\n ResolveBannerContext,\n ResolveNameParams,\n ResolveOptionsContext,\n Resolver,\n ResolverContext,\n ResolverFileParams,\n ResolverPathParams,\n} from './types.ts'\n\n/**\n * Builder type for the plugin-specific resolver fields.\n *\n * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`\n * are optional — built-in fallbacks are injected when omitted.\n */\ntype ResolverBuilder<T extends PluginFactoryOptions> = () => Omit<\n T['resolver'],\n 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter' | 'name' | 'pluginName'\n> &\n Partial<Pick<T['resolver'], 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter'>> & {\n name: string\n pluginName: T['name']\n } & ThisType<T['resolver']>\n\n/**\n * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).\n */\nfunction matchesOperationPattern(node: OperationNode, type: string, pattern: string | RegExp): boolean {\n switch (type) {\n case 'tag':\n return node.tags.some((tag) => !!tag.match(pattern))\n case 'operationId':\n return !!node.operationId.match(pattern)\n case 'path':\n return !!node.path.match(pattern)\n case 'method':\n return !!(node.method.toLowerCase() as string).match(pattern)\n case 'contentType':\n return !!node.requestBody?.contentType?.match(pattern)\n default:\n return false\n }\n}\n\n/**\n * Checks if a schema matches a pattern for a given filter type (`schemaName`).\n *\n * Returns `null` when the filter type doesn't apply to schemas.\n */\nfunction matchesSchemaPattern(node: SchemaNode, type: string, pattern: string | RegExp): boolean | null {\n switch (type) {\n case 'schemaName':\n return node.name ? !!node.name.match(pattern) : false\n default:\n return null\n }\n}\n\n/**\n * Default name resolver used by `defineResolver`.\n *\n * - `camelCase` for `function` and `file` types.\n * - `PascalCase` for `type`.\n * - `camelCase` for everything else.\n */\nfunction defaultResolver(name: ResolveNameParams['name'], type: ResolveNameParams['type']): string {\n let resolvedName = camelCase(name)\n\n if (type === 'file' || type === 'function') {\n resolvedName = camelCase(name, {\n isFile: type === 'file',\n })\n }\n\n if (type === 'type') {\n resolvedName = pascalCase(name)\n }\n\n return resolvedName\n}\n\n/**\n * Default option resolver — applies include/exclude filters and merges matching override options.\n *\n * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.\n *\n * @example Include/exclude filtering\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { output: 'types' },\n * exclude: [{ type: 'tag', pattern: 'internal' }],\n * })\n * // → null when node has tag 'internal'\n * ```\n *\n * @example Override merging\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { enumType: 'asConst' },\n * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],\n * })\n * // → { enumType: 'enum' } when operationId matches\n * ```\n */\nexport function defaultResolveOptions<TOptions>(\n node: Node,\n { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>,\n): TOptions | null {\n if (isOperationNode(node)) {\n const isExcluded = exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))\n if (isExcluded) {\n return null\n }\n\n if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) {\n return null\n }\n\n const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options\n\n return { ...options, ...overrideOptions }\n }\n\n if (isSchemaNode(node)) {\n if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) {\n return null\n }\n\n if (include) {\n const results = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern))\n const applicable = results.filter((r) => r !== null)\n if (applicable.length > 0 && !applicable.includes(true)) {\n return null\n }\n }\n\n const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options\n\n return { ...options, ...overrideOptions }\n }\n\n return options\n}\n\n/**\n * Default path resolver used by `defineResolver`.\n *\n * - Returns the output directory in `single` mode.\n * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.\n * - Falls back to a flat `output/baseName` path otherwise.\n *\n * A custom `group.name` function overrides the default subdirectory naming.\n * For `tag` groups the default is `${camelCase(tag)}Controller`.\n * For `path` groups the default is the first path segment after `/`.\n *\n * @example Flat output\n * ```ts\n * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })\n * // → '/src/types/petTypes.ts'\n * ```\n *\n * @example Tag-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → '/src/types/petsController/petTypes.ts'\n * ```\n *\n * @example Path-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', path: '/pets/list' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\n *\n * @example Single-file mode\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', pathMode: 'single' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → '/src/types'\n * ```\n */\nexport function defaultResolvePath(\n { baseName, pathMode, tag, path: groupPath }: ResolverPathParams,\n { root, output, group }: ResolverContext,\n): FabricFile.Path {\n const mode = pathMode ?? getMode(path.resolve(root, output.path))\n\n if (mode === 'single') {\n return path.resolve(root, output.path) as FabricFile.Path\n }\n\n if (group && (groupPath || tag)) {\n return path.resolve(root, output.path, group.name({ group: group.type === 'path' ? groupPath! : tag! }), baseName) as FabricFile.Path\n }\n\n return path.resolve(root, output.path, baseName) as FabricFile.Path\n}\n\n/**\n * Default file resolver used by `defineResolver`.\n *\n * Resolves a `FabricFile.File` by combining name resolution (`resolver.default`) with\n * path resolution (`resolver.resolvePath`). The resolved file always has empty\n * `sources`, `imports`, and `exports` arrays — consumers populate those separately.\n *\n * In `single` mode the name is omitted and the file sits directly in the output directory.\n *\n * @example Resolve a schema file\n * ```ts\n * const file = defaultResolveFile.call(resolver,\n * { name: 'pet', extname: '.ts' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }\n * ```\n *\n * @example Resolve an operation file with tag grouping\n * ```ts\n * const file = defaultResolveFile.call(resolver,\n * { name: 'listPets', extname: '.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }\n * ```\n */\nexport function defaultResolveFile(this: Resolver, { name, extname, tag, path: groupPath }: ResolverFileParams, context: ResolverContext): FabricFile.File {\n const pathMode = getMode(path.resolve(context.root, context.output.path))\n const resolvedName = pathMode === 'single' ? '' : this.default(name, 'file')\n const baseName = `${resolvedName}${extname}` as FabricFile.BaseName\n const filePath = this.resolvePath({ baseName, pathMode, tag, path: groupPath }, context)\n\n return {\n path: filePath,\n baseName: path.basename(filePath) as FabricFile.BaseName,\n meta: {\n pluginName: this.pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n }\n}\n\n/**\n * Generates the default \"Generated by Kubb\" banner from config and optional node metadata.\n */\nexport function buildDefaultBanner({\n title,\n description,\n version,\n config,\n}: {\n title?: string\n description?: string\n version?: string\n config: Config\n}): string {\n try {\n let source = ''\n if (Array.isArray(config.input)) {\n const first = config.input[0]\n if (first && 'path' in first) {\n source = path.basename(first.path)\n }\n } else if ('path' in config.input) {\n source = path.basename(config.input.path)\n } else if ('data' in config.input) {\n source = 'text content'\n }\n\n let banner = '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n'\n\n if (config.output.defaultBanner === 'simple') {\n banner += '*/\\n'\n return banner\n }\n\n if (source) {\n banner += `* Source: ${source}\\n`\n }\n\n if (title) {\n banner += `* Title: ${title}\\n`\n }\n\n if (description) {\n const formattedDescription = description.replace(/\\n/gm, '\\n* ')\n banner += `* Description: ${formattedDescription}\\n`\n }\n\n if (version) {\n banner += `* OpenAPI spec version: ${version}\\n`\n }\n\n banner += '*/\\n'\n return banner\n } catch (_error) {\n return '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n*/'\n }\n}\n\n/**\n * Default banner resolver — returns the banner string for a generated file.\n *\n * A user-supplied `output.banner` overrides the default Kubb \"Generated by Kubb\" notice.\n * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`\n * from the OAS spec when a `node` is provided).\n *\n * - When `output.banner` is a function and `node` is provided, returns `output.banner(node)`.\n * - When `output.banner` is a function and `node` is absent, falls back to the Kubb notice.\n * - When `output.banner` is a string, returns it directly.\n * - When `config.output.defaultBanner` is `false`, returns `undefined`.\n * - Otherwise returns the Kubb \"Generated by Kubb\" notice.\n *\n * @example String banner overrides default\n * ```ts\n * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })\n * // → '// my banner'\n * ```\n *\n * @example Function banner with node\n * ```ts\n * defaultResolveBanner(rootNode, { output: { banner: (node) => `// v${node.version}` }, config })\n * // → '// v3.0.0'\n * ```\n *\n * @example No user banner — Kubb notice with OAS metadata\n * ```ts\n * defaultResolveBanner(rootNode, { config })\n * // → '/** Generated by Kubb ... Title: Pet Store ... *\\/'\n * ```\n *\n * @example Disabled default banner\n * ```ts\n * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })\n * // → undefined\n * ```\n */\nexport function defaultResolveBanner(node: RootNode | undefined, { output, config }: ResolveBannerContext): string | undefined {\n if (typeof output?.banner === 'function') {\n return output.banner(node)\n }\n\n if (typeof output?.banner === 'string') {\n return output.banner\n }\n\n if (config.output.defaultBanner === false) {\n return undefined\n }\n\n return buildDefaultBanner({ title: node?.meta?.title, version: node?.meta?.version, config })\n}\n\n/**\n * Default footer resolver — returns the footer string for a generated file.\n *\n * - When `output.footer` is a function and `node` is provided, calls it with the node.\n * - When `output.footer` is a function and `node` is absent, returns `undefined`.\n * - When `output.footer` is a string, returns it directly.\n * - Otherwise returns `undefined`.\n *\n * @example String footer\n * ```ts\n * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })\n * // → '// end of file'\n * ```\n *\n * @example Function footer with node\n * ```ts\n * defaultResolveFooter(rootNode, { output: { footer: (node) => `// ${node.title}` }, config })\n * // → '// Pet Store'\n * ```\n */\nexport function defaultResolveFooter(node: RootNode | undefined, { output }: ResolveBannerContext): string | undefined {\n if (typeof output?.footer === 'function') {\n return node ? output.footer(node) : undefined\n }\n if (typeof output?.footer === 'string') {\n return output.footer\n }\n return undefined\n}\n\n/**\n * Defines a resolver for a plugin, injecting built-in defaults for name casing,\n * include/exclude/override filtering, path resolution, and file construction.\n *\n * All four defaults can be overridden by providing them in the builder function:\n * - `default` — name casing strategy (camelCase / PascalCase)\n * - `resolveOptions` — include/exclude/override filtering\n * - `resolvePath` — output path computation\n * - `resolveFile` — full `FabricFile.File` construction\n *\n * Methods in the builder have access to `this` (the full resolver object), so they\n * can call other resolver methods without circular imports.\n *\n * @example Basic resolver with naming helpers\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveName(node) {\n * return this.default(node.name, 'function')\n * },\n * resolveTypedName(node) {\n * return this.default(node.name, 'type')\n * },\n * }))\n * ```\n *\n * @example Override resolvePath for a custom output structure\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'custom',\n * resolvePath({ baseName }, { root, output }) {\n * return path.resolve(root, output.path, 'generated', baseName)\n * },\n * }))\n * ```\n *\n * @example Use this.default inside a helper\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveParamName(node, param) {\n * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')\n * },\n * }))\n * ```\n */\nexport function defineResolver<T extends PluginFactoryOptions>(build: ResolverBuilder<T>): T['resolver'] {\n return {\n default: defaultResolver,\n resolveOptions: defaultResolveOptions,\n resolvePath: defaultResolvePath,\n resolveFile: defaultResolveFile,\n resolveBanner: defaultResolveBanner,\n resolveFooter: defaultResolveFooter,\n ...build(),\n } as T['resolver']\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 { camelCase } from '@internals/utils'\n// TODO replace with @internals/utils\nimport { sortBy } from 'remeda'\n\ntype FunctionParamsASTWithoutType = {\n name?: string\n type?: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n\ntype FunctionParamsASTWithType = {\n name?: never\n type: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n/**\n * @deprecated use ast package instead\n */\nexport type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType\n\n/**\n * @deprecated use ast package instead\n */\nexport class FunctionParams {\n #items: Array<FunctionParamsAST | FunctionParamsAST[]> = []\n\n get items(): FunctionParamsAST[] {\n return this.#items.flat()\n }\n\n add(item: FunctionParamsAST | Array<FunctionParamsAST | FunctionParamsAST[] | undefined> | undefined): FunctionParams {\n if (!item) {\n return this\n }\n\n if (Array.isArray(item)) {\n item\n .filter((x): x is FunctionParamsAST | FunctionParamsAST[] => x !== undefined)\n .forEach((it) => {\n this.#items.push(it)\n })\n return this\n }\n this.#items.push(item)\n\n return this\n }\n static #orderItems(items: Array<FunctionParamsAST | FunctionParamsAST[]>) {\n return sortBy(\n items.filter(Boolean),\n [(item) => Array.isArray(item), 'desc'], // arrays (rest params) first\n [(item) => !Array.isArray(item) && (item as FunctionParamsAST).default !== undefined, 'asc'], // no-default before has-default\n [(item) => Array.isArray(item) || ((item as FunctionParamsAST).required ?? true), 'desc'], // required before optional\n )\n }\n\n static #addParams(acc: string[], item: FunctionParamsAST) {\n const { enabled = true, name, type, required = true, ...rest } = item\n\n if (!enabled) {\n return acc\n }\n\n if (!name) {\n // when name is not se we uses TypeScript generics\n acc.push(`${type}${rest.default ? ` = ${rest.default}` : ''}`)\n\n return acc\n }\n // TODO check why we still need the camelcase here\n const parameterName = name.startsWith('{') ? name : camelCase(name)\n\n if (type) {\n if (required) {\n acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ''}`)\n } else {\n acc.push(`${parameterName}?: ${type}`)\n }\n } else {\n acc.push(`${parameterName}`)\n }\n\n return acc\n }\n\n static toObject(items: FunctionParamsAST[]): FunctionParamsAST {\n let type: string[] = []\n let name: string[] = []\n\n const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true\n const required = items.every((item) => item.required) ?? true\n\n items.forEach((item) => {\n name = FunctionParams.#addParams(name, { ...item, type: undefined })\n if (items.some((item) => item.type)) {\n type = FunctionParams.#addParams(type, item)\n }\n })\n\n return {\n name: `{ ${name.join(', ')} }`,\n type: type.length ? `{ ${type.join('; ')} }` : undefined,\n enabled,\n required,\n }\n }\n\n toObject(): FunctionParamsAST {\n const items = FunctionParams.#orderItems(this.#items).flat()\n\n return FunctionParams.toObject(items)\n }\n\n static toString(items: (FunctionParamsAST | FunctionParamsAST[])[]): string {\n const sortedData = FunctionParams.#orderItems(items)\n\n return sortedData\n .reduce((acc, item) => {\n if (Array.isArray(item)) {\n if (item.length <= 0) {\n return acc\n }\n const subItems = FunctionParams.#orderItems(item) as FunctionParamsAST[]\n const objectItem = FunctionParams.toObject(subItems)\n\n return FunctionParams.#addParams(acc, objectItem)\n }\n\n return FunctionParams.#addParams(acc, item)\n }, [] as string[])\n .join(', ')\n }\n\n toString(): string {\n const items = FunctionParams.#orderItems(this.#items)\n\n return FunctionParams.toString(items)\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 type { CLIOptions, ConfigInput } from '../config.ts'\nimport type { Config, UserConfig } from '../types.ts'\n\n/**\n * Resolves a {@link ConfigInput} into a normalized array of {@link Config} objects.\n *\n * - Awaits the config when it is a `Promise`.\n * - Calls the factory function with `args` when the config is a function.\n * - Wraps a single config object in an array for uniform downstream handling.\n */\nexport async function getConfigs(config: ConfigInput | UserConfig, args: CLIOptions): Promise<Array<Config>> {\n const resolved = await (typeof config === 'function' ? config(args as CLIOptions) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return userConfigs.map((item) => ({ plugins: [], ...item }) as Config)\n}\n","import { composeTransformers } from '@kubb/ast'\nimport type { Visitor } from '@kubb/ast/types'\nimport type { CompatibilityPreset, Generator, Preset, Presets, Resolver } from '../types.ts'\n\n/**\n * Returns a copy of `defaults` where each function in `userOverrides` is wrapped\n * so a `null`/`undefined` return falls back to the original. Non-function values\n * are assigned directly. All calls use the merged object as `this`.\n */\nfunction withFallback<T extends object>(defaults: T, userOverrides: Partial<T>): T {\n const merged = { ...defaults } as T\n\n for (const key of Object.keys(userOverrides) as Array<keyof T>) {\n const userVal = userOverrides[key]\n const defaultVal = defaults[key]\n\n if (typeof userVal === 'function' && typeof defaultVal === 'function') {\n ;(merged as any)[key] = (...args: any[]) => (userVal as Function).apply(merged, args) ?? (defaultVal as Function).apply(merged, args)\n } else if (userVal !== undefined) {\n merged[key] = userVal as T[typeof key]\n }\n }\n\n return merged\n}\n\ntype GetPresetParams<TResolver extends Resolver> = {\n preset: CompatibilityPreset\n presets: Presets<TResolver>\n /**\n * Optional single resolver whose methods override the preset resolver.\n * When a method returns `null` or `undefined` the preset resolver's method is used instead.\n */\n resolver?: Partial<TResolver> & ThisType<TResolver>\n /**\n * User-supplied generators to append after the preset's generators.\n */\n generators?: Array<Generator<any>>\n /**\n * Optional single transformer visitor whose methods override the preset transformer.\n * When a method returns `null` or `undefined` the preset transformer's method is used instead.\n */\n transformer?: Visitor\n}\n\ntype GetPresetResult<TResolver extends Resolver> = {\n resolver: TResolver\n transformer: Visitor | undefined\n generators: Array<Generator<any>>\n preset: Preset<TResolver> | undefined\n}\n\n/**\n * Resolves a named preset into a resolver, transformer, and generators.\n *\n * - Selects the preset resolver; wraps it with user overrides using null/undefined fallback.\n * - Composes the preset's transformers into a single visitor; wraps it with the user transformer using null/undefined fallback.\n * - Combines preset generators with user-supplied generators; falls back to the `default` preset's generators when neither provides any.\n */\nexport function getPreset<TResolver extends Resolver = Resolver>(params: GetPresetParams<TResolver>): GetPresetResult<TResolver> {\n const { preset: presetName, presets, resolver: userResolver, transformer: userTransformer, generators: userGenerators = [] } = params\n const preset = presets[presetName]\n\n const presetResolver = preset?.resolver ?? presets['default']!.resolver\n const resolver = userResolver ? withFallback(presetResolver, userResolver) : presetResolver\n\n const presetTransformers = preset?.transformers ?? []\n const presetTransformer = presetTransformers.length > 0 ? composeTransformers(...presetTransformers) : undefined\n const transformer = presetTransformer && userTransformer ? withFallback(presetTransformer, userTransformer) : (userTransformer ?? presetTransformer)\n\n const presetGenerators = preset?.generators ?? []\n const defaultGenerators = presets['default']?.generators ?? []\n const generators = (presetGenerators.length > 0 || userGenerators.length > 0 ? [...presetGenerators, ...userGenerators] : defaultGenerators) as Array<\n Generator<any>\n >\n\n return { resolver, transformer, generators, preset }\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 { readSync } from '@internals/utils'\nimport * as pkg from 'empathic/package'\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 = pkg.up({ 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"],"x_google_ignoreList":[11,12],"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,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AAE,EAAE,aAAa,EAAE,OAAO,UAAU,EAAE,CAAC;AACpE,SAAO;SACD;AACN,SAAO;;;;;;;;;;;;;;;;;AAkBX,eAAsB,eAAuC;CAC3D,MAAM,cAAc,IAAI,IAAI;EAAC;EAAS;EAAU;EAAS,CAAU;AAEnE,MAAK,MAAM,UAAU,YACnB,KAAI,MAAM,kBAAkB,OAAO,CACjC,QAAO;AAIX,QAAO;;;;AC/BT,SAAS,mBAAmB,KAAkC;CAC5D,MAAM,UAAU,IAAI,GAAG,EAAE,KAAK,CAAC;AAC/B,KAAI,CAAC,QACH,QAAO;AAGT,QAAO,KAAK,MAAM,SAAS,QAAQ,CAAC;;AAGtC,SAAS,MAAM,aAA0B,YAAoD;CAC3F,MAAM,eAAe;EACnB,GAAI,YAAY,gBAAgB,EAAE;EAClC,GAAI,YAAY,mBAAmB,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,SAAS,OAAO,eAAe;AAErC,KAAI,CAAC,OACH,QAAO;AAGT,QAAO,UAAU,QAAQ,QAAQ"}
1
+ {"version":3,"file":"index.js","names":["#emitter","NodeEventEmitter","trimExtName","#options","#transformParam","#eachParam","#head","#tail","#size","#limit","#cache","#filesCache","trimExtName","#studioIsOpen","openInStudioFn","#execute","#executeSync","#emitProcessingEnd","#cachedLeaves","#items","#orderItems","#addParams","composeTransformers"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/string.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/constants.ts","../../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js","../../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js","../src/FileProcessor.ts","../src/devtools.ts","../src/FileManager.ts","../src/utils/executeStrategies.ts","../src/PluginDriver.ts","../src/renderNode.tsx","../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/build.ts","../src/createAdapter.ts","../src/createPlugin.ts","../src/defineConfig.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineParser.ts","../src/definePresets.ts","../src/defineResolver.ts","../src/storages/memoryStorage.ts","../src/utils/FunctionParams.ts","../src/utils/formatters.ts","../src/utils/getConfigs.ts","../src/utils/getPreset.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 * 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","type Options = {\n /**\n * When `true`, dot-separated segments are split on `.` and joined with `/` after casing.\n */\n isFile?: boolean\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Splits `text` on `.` and applies `transformPart` to each segment.\n * The last segment receives `isLast = true`, all earlier segments receive `false`.\n * Segments are joined with `/` to form a file path.\n *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\n\n/**\n * Converts `text` to camelCase.\n * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n *\n * @example\n * camelCase('hello-world') // 'helloWorld'\n * camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n *\n * @example\n * pascalCase('hello-world') // 'HelloWorld'\n * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\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 { readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, posix, resolve } from 'node:path'\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","/**\n * Strips a single matching pair of `\"...\"`, `'...'`, or `` `...` `` from both ends of `text`.\n * Returns the string unchanged when no balanced quote pair is found.\n *\n * @example\n * trimQuotes('\"hello\"') // 'hello'\n * trimQuotes('hello') // 'hello'\n */\nexport function trimQuotes(text: string): string {\n if (text.length >= 2) {\n const first = text[0]\n const last = text[text.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\") || (first === '`' && last === '`')) {\n return text.slice(1, -1)\n }\n }\n return text\n}\n\n/**\n * Escapes characters that are not allowed inside JS string literals.\n * Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).\n *\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4\n *\n * @example\n * ```ts\n * jsStringEscape('say \"hi\"\\nbye') // 'say \\\\\"hi\\\\\"\\\\nbye'\n * ```\n */\nexport function jsStringEscape(input: unknown): string {\n return `${input}`.replace(/[\"'\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n switch (character) {\n case '\"':\n case \"'\":\n case '\\\\':\n return `\\\\${character}`\n case '\\n':\n return '\\\\n'\n case '\\r':\n return '\\\\r'\n case '\\u2028':\n return '\\\\u2028'\n case '\\u2029':\n return '\\\\u2029'\n default:\n return ''\n }\n })\n}\n\n/**\n * Returns a masked version of a string, showing only the first and last few characters.\n * Useful for logging sensitive values (tokens, keys) without exposing the full value.\n *\n * @example\n * maskString('KUBB_STUDIO-abc123-xyz789') // 'KUBB_STUDIO-…789'\n */\nexport function maskString(value: string, start = 8, end = 4): string {\n if (value.length <= start + end) return value\n return `${value.slice(0, start)}…${value.slice(-end)}`\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\n/** Returns `true` when `result` is a fulfilled `Promise.allSettled` result.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseFulfilledResult).map((r) => r.value)\n * ```\n */\nexport function isPromiseFulfilledResult<T = unknown>(result: PromiseSettledResult<unknown>): result is PromiseFulfilledResult<T> {\n return result.status === 'fulfilled'\n}\n\n/** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)\n * ```\n */\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return 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 { FileNode } from '@kubb/ast/types'\n\n/**\n * Base URL for the Kubb Studio web app.\n */\nexport const DEFAULT_STUDIO_URL = 'https://studio.kubb.dev' as const\n\n/**\n * Default number of plugins that may run concurrently during a build.\n */\nexport const DEFAULT_CONCURRENCY = 15\n\n/**\n * Maximum number of files processed in parallel by FileProcessor.\n */\nexport const PARALLEL_CONCURRENCY_LIMIT = 100\n\n/**\n * File name used for generated barrel (index) files.\n */\nexport const BARREL_FILENAME = 'index.ts' as const\n\n/**\n * Default banner style written at the top of every generated file.\n */\nexport const DEFAULT_BANNER = 'simple' as const\n\n/**\n * Default file-extension mapping used when no explicit mapping is configured.\n */\nexport const DEFAULT_EXTENSION: Record<FileNode['extname'], FileNode['extname'] | ''> = { '.ts': '.ts' }\n\n/**\n * Characters recognized as path separators on both POSIX and Windows.\n */\nexport const PATH_SEPARATORS = new Set(['/', '\\\\'] as const)\n\n/**\n * Numeric log-level thresholds used internally to compare verbosity.\n *\n * Higher numbers are more verbose.\n */\nexport const logLevel = {\n silent: Number.NEGATIVE_INFINITY,\n error: 0,\n warn: 1,\n info: 3,\n verbose: 4,\n debug: 5,\n} as const\n\n/**\n * CLI command descriptors for each supported linter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the linter is not found.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n args: (outputPath: string) => ['--fix', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const\n\n/**\n * CLI command descriptors for each supported code formatter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the formatter is not found.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const\n","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tlet rejectOnClear = false;\n\n\tif (typeof concurrency === 'object') {\n\t\t({concurrency, rejectOnClear = false} = concurrency);\n\t}\n\n\tvalidateConcurrency(concurrency);\n\n\tif (typeof rejectOnClear !== 'boolean') {\n\t\tthrow new TypeError('Expected `rejectOnClear` to be a boolean');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst resumeNext = () => {\n\t\t// Process the next queued function if we're under the concurrency limit\n\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\tactiveCount++;\n\t\t\tqueue.dequeue().run();\n\t\t}\n\t};\n\n\tconst next = () => {\n\t\tactiveCount--;\n\t\tresumeNext();\n\t};\n\n\tconst run = async (function_, resolve, arguments_) => {\n\t\t// Execute the function and capture the result promise\n\t\tconst result = (async () => function_(...arguments_))();\n\n\t\t// Resolve immediately with the promise (don't wait for completion)\n\t\tresolve(result);\n\n\t\t// Wait for the function to complete (success or failure)\n\t\t// We catch errors here to prevent unhandled rejections,\n\t\t// but the original promise rejection is preserved for the caller\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\t// Decrement active count and process next queued function\n\t\tnext();\n\t};\n\n\tconst enqueue = (function_, resolve, reject, arguments_) => {\n\t\tconst queueItem = {reject};\n\n\t\t// Queue the internal resolve function instead of the run function\n\t\t// to preserve the asynchronous execution context.\n\t\tnew Promise(internalResolve => { // eslint-disable-line promise/param-names\n\t\t\tqueueItem.run = internalResolve;\n\t\t\tqueue.enqueue(queueItem);\n\t\t}).then(run.bind(undefined, function_, resolve, arguments_)); // eslint-disable-line promise/prefer-await-to-then\n\n\t\t// Start processing immediately if we haven't reached the concurrency limit\n\t\tif (activeCount < concurrency) {\n\t\t\tresumeNext();\n\t\t}\n\t};\n\n\tconst generator = (function_, ...arguments_) => new Promise((resolve, reject) => {\n\t\tenqueue(function_, resolve, reject, arguments_);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue() {\n\t\t\t\tif (!rejectOnClear) {\n\t\t\t\t\tqueue.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst abortError = AbortSignal.abort().reason;\n\n\t\t\t\twhile (queue.size > 0) {\n\t\t\t\t\tqueue.dequeue().reject(abortError);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tconcurrency: {\n\t\t\tget: () => concurrency,\n\n\t\t\tset(newConcurrency) {\n\t\t\t\tvalidateConcurrency(newConcurrency);\n\t\t\t\tconcurrency = newConcurrency;\n\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t// eslint-disable-next-line no-unmodified-loop-condition\n\t\t\t\t\twhile (activeCount < concurrency && queue.size > 0) {\n\t\t\t\t\t\tresumeNext();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmap: {\n\t\t\tasync value(iterable, function_) {\n\t\t\t\tconst promises = Array.from(iterable, (value, index) => this(function_, value, index));\n\t\t\t\treturn Promise.all(promises);\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n\nexport function limitFunction(function_, options) {\n\tconst limit = pLimit(options);\n\n\treturn (...arguments_) => limit(() => function_(...arguments_));\n}\n\nfunction validateConcurrency(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n}\n","import type { FileNode } from '@kubb/ast/types'\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) => item.value)\n .filter((value): value is string => value != null)\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","import type { InputNode } from '@kubb/ast/types'\nimport { deflateSync, inflateSync } from 'fflate'\nimport { x } from 'tinyexec'\nimport type { DevtoolsOptions } from './types.ts'\n\n/**\n * Encodes an `InputNode` as a compressed, URL-safe string.\n *\n * The JSON representation is deflate-compressed with {@link deflateSync} before\n * base64url encoding, which typically reduces payload size by 70–80 % and\n * keeps URLs well within browser and server path-length limits.\n *\n * Use {@link decodeAst} to reverse.\n */\nexport function encodeAst(input: InputNode): string {\n const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(input)))\n return Buffer.from(compressed).toString('base64url')\n}\n\n/**\n * Decodes an `InputNode` from a string produced by {@link encodeAst}.\n *\n * Works in both Node.js and the browser — no streaming APIs required.\n */\nexport function decodeAst(encoded: string): InputNode {\n const bytes = Buffer.from(encoded, 'base64url')\n return JSON.parse(new TextDecoder().decode(inflateSync(bytes))) as InputNode\n}\n\n/**\n * Constructs the Kubb Studio URL for the given `InputNode`.\n * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).\n * The `input` is encoded and attached as the `?root=` query parameter so Studio\n * can decode and render it without a round-trip to any server.\n */\nexport function getStudioUrl(input: InputNode, studioUrl: string, options: DevtoolsOptions = {}): string {\n const baseUrl = studioUrl.replace(/\\/$/, '')\n const path = options.ast ? '/ast' : ''\n\n return `${baseUrl}${path}?root=${encodeAst(input)}`\n}\n\n/**\n * Opens the Kubb Studio URL for the given `InputNode` in the default browser —\n *\n * Falls back to printing the URL if the browser cannot be launched.\n */\nexport async function openInStudio(input: InputNode, studioUrl: string, options: DevtoolsOptions = {}): Promise<void> {\n const url = getStudioUrl(input, studioUrl, options)\n\n const cmd = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open'\n const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]\n\n try {\n await x(cmd, args)\n } catch {\n console.log(`\\n ${url}\\n`)\n }\n}\n","import { trimExtName } from '@internals/utils'\nimport { createFile } from '@kubb/ast'\nimport type { FileNode } from '@kubb/ast/types'\n\nfunction mergeFile<TMeta extends object = object>(a: FileNode<TMeta>, b: FileNode<TMeta>): FileNode<TMeta> {\n return {\n ...a,\n sources: [...(a.sources || []), ...(b.sources || [])],\n imports: [...(a.imports || []), ...(b.imports || [])],\n exports: [...(a.exports || []), ...(b.exports || [])],\n }\n}\n\n/**\n * In-memory file store for generated files.\n *\n * Files with the same `path` are merged — sources, imports, and exports are concatenated.\n * The `files` getter returns all stored files sorted by path length (shortest first).\n *\n * @example\n * ```ts\n * import { FileManager } from '@kubb/core'\n *\n * const manager = new FileManager()\n * manager.upsert(myFile)\n * console.log(manager.files) // all stored files\n * ```\n */\nexport class FileManager {\n readonly #cache = new Map<string, FileNode>()\n #filesCache: Array<FileNode> | null = null\n\n /**\n * Adds one or more files. Files with the same path are merged — sources, imports,\n * and exports from all calls with the same path are concatenated together.\n */\n add(...files: Array<FileNode>): Array<FileNode> {\n const resolvedFiles: Array<FileNode> = []\n const mergedFiles = new Map<string, FileNode>()\n\n files.forEach((file) => {\n const existing = mergedFiles.get(file.path)\n if (existing) {\n mergedFiles.set(file.path, mergeFile(existing, file))\n } else {\n mergedFiles.set(file.path, file)\n }\n })\n\n for (const file of mergedFiles.values()) {\n const resolvedFile = createFile(file)\n this.#cache.set(resolvedFile.path, resolvedFile)\n this.#filesCache = null\n resolvedFiles.push(resolvedFile)\n }\n\n return resolvedFiles\n }\n\n /**\n * Adds or merges one or more files.\n * If a file with the same path already exists, its sources/imports/exports are merged together.\n */\n upsert(...files: Array<FileNode>): Array<FileNode> {\n const resolvedFiles: Array<FileNode> = []\n const mergedFiles = new Map<string, FileNode>()\n\n files.forEach((file) => {\n const existing = mergedFiles.get(file.path)\n if (existing) {\n mergedFiles.set(file.path, mergeFile(existing, file))\n } else {\n mergedFiles.set(file.path, file)\n }\n })\n\n for (const file of mergedFiles.values()) {\n const existing = this.#cache.get(file.path)\n const merged = existing ? mergeFile(existing, file) : file\n const resolvedFile = createFile(merged)\n this.#cache.set(resolvedFile.path, resolvedFile)\n this.#filesCache = null\n resolvedFiles.push(resolvedFile)\n }\n\n return resolvedFiles\n }\n\n getByPath(path: string): FileNode | null {\n return this.#cache.get(path) ?? null\n }\n\n deleteByPath(path: string): void {\n this.#cache.delete(path)\n this.#filesCache = null\n }\n\n clear(): void {\n this.#cache.clear()\n this.#filesCache = null\n }\n\n /**\n * All stored files, sorted by path length (shorter paths first).\n * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.\n */\n get files(): Array<FileNode> {\n if (this.#filesCache) {\n return this.#filesCache\n }\n\n const keys = [...this.#cache.keys()].sort((a, b) => {\n if (a.length !== b.length) return a.length - b.length\n const aIsIndex = trimExtName(a).endsWith('index')\n const bIsIndex = trimExtName(b).endsWith('index')\n if (aIsIndex !== bIsIndex) return aIsIndex ? 1 : -1\n return 0\n })\n\n const files: Array<FileNode> = []\n for (const key of keys) {\n const file = this.#cache.get(key)\n if (file) {\n files.push(file)\n }\n }\n\n this.#filesCache = files\n return files\n }\n}\n","import pLimit from 'p-limit'\n\ntype PromiseFunc<T = unknown, T2 = never> = (state?: T) => T2 extends never ? Promise<T> : Promise<T> | T2\n\ntype ValueOfPromiseFuncArray<TInput extends Array<unknown>> = TInput extends Array<PromiseFunc<infer X, infer Y>> ? X | Y : never\n\ntype SeqOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = Promise<Array<Awaited<ValueOfPromiseFuncArray<TInput>>>>\n\n/**\n * Runs promise functions in sequence, threading each result into the next call.\n *\n * - Each function receives the accumulated state from the previous call.\n * - Skips functions that return a falsy value (acts as a no-op for that step).\n * - Returns an array of all individual results.\n * @deprecated\n */\nexport function hookSeq<TInput extends Array<PromiseFunc<TValue, null>>, TValue, TOutput = SeqOutput<TInput, TValue>>(promises: TInput): TOutput {\n return promises.filter(Boolean).reduce(\n (promise, func) => {\n if (typeof func !== 'function') {\n throw new Error('HookSeq needs a function that returns a promise `() => Promise<unknown>`')\n }\n\n return promise.then((state) => {\n const calledFunc = func(state as TValue)\n\n if (calledFunc) {\n return calledFunc.then(Array.prototype.concat.bind(state) as (result: TValue) => TValue[])\n }\n\n return state\n })\n },\n Promise.resolve([] as Array<TValue>),\n ) as TOutput\n}\n\ntype HookFirstOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown> = ValueOfPromiseFuncArray<TInput>\n\n/**\n * Runs promise functions in sequence and returns the first non-null result.\n *\n * - Stops as soon as `nullCheck` passes for a result (default: `!== null`).\n * - Subsequent functions are skipped once a match is found.\n * @deprecated\n */\nexport function hookFirst<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown, TOutput = HookFirstOutput<TInput, TValue>>(\n promises: TInput,\n nullCheck: (state: unknown) => boolean = (state) => state !== null,\n): TOutput {\n let promise: Promise<unknown> = Promise.resolve(null) as Promise<unknown>\n\n for (const func of promises.filter(Boolean)) {\n promise = promise.then((state) => {\n if (nullCheck(state)) {\n return state\n }\n\n return func(state as TValue)\n })\n }\n\n return promise as TOutput\n}\n\ntype HookParallelOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = Promise<PromiseSettledResult<Awaited<ValueOfPromiseFuncArray<TInput>>>[]>\n\n/**\n * Runs promise functions concurrently and returns all settled results.\n *\n * - Limits simultaneous executions to `concurrency` (default: unlimited).\n * - Uses `Promise.allSettled` so individual failures do not cancel other tasks.\n * @deprecated\n */\nexport function hookParallel<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown, TOutput = HookParallelOutput<TInput, TValue>>(\n promises: TInput,\n concurrency: number = Number.POSITIVE_INFINITY,\n): TOutput {\n const limit = pLimit(concurrency)\n\n const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()))\n\n return Promise.allSettled(tasks) as TOutput\n}\n\n/**\n * Execution strategy used when dispatching plugin hook calls.\n * @deprecated\n */\nexport type Strategy = 'seq' | 'first' | 'parallel'\n\ntype StrategyOutputMap<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = {\n first: HookFirstOutput<TInput, TValue>\n seq: SeqOutput<TInput, TValue>\n parallel: HookParallelOutput<TInput, TValue>\n}\n/**\n * @deprecated\n */\nexport type StrategySwitch<TStrategy extends Strategy, TInput extends Array<PromiseFunc<TValue, null>>, TValue> = StrategyOutputMap<TInput, TValue>[TStrategy]\n","import { basename, extname, resolve } from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport type { AsyncEventEmitter } from '@internals/utils'\nimport { isPromiseRejectedResult, transformReservedWord } from '@internals/utils'\nimport { createFile } from '@kubb/ast'\nimport type { FileNode, InputNode } from '@kubb/ast/types'\nimport { DEFAULT_STUDIO_URL } from './constants.ts'\nimport { openInStudio as openInStudioFn } from './devtools.ts'\nimport { FileManager } from './FileManager.ts'\n\nimport type {\n Adapter,\n Config,\n DevtoolsOptions,\n KubbEvents,\n Plugin,\n PluginContext,\n PluginFactoryOptions,\n PluginLifecycle,\n PluginLifecycleHooks,\n PluginParameter,\n PluginWithLifeCycle,\n ResolveNameParams,\n ResolvePathParams,\n} from './types.ts'\nimport { hookFirst, hookParallel, hookSeq } from './utils/executeStrategies.ts'\n\ntype RequiredPluginLifecycle = Required<PluginLifecycle>\n\n/**\n * Hook dispatch strategy used by the `PluginDriver`.\n *\n * - `hookFirst` — stops at the first non-null result.\n * - `hookForPlugin` — calls only the matching plugin.\n * - `hookParallel` — calls all plugins concurrently.\n * - `hookSeq` — calls all plugins in order, threading the result.\n */\nexport type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq'\n\ntype ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H]\n\ntype SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {\n result: Result\n plugin: Plugin\n}\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\ntype Options = {\n events: AsyncEventEmitter<KubbEvents>\n /**\n * @default Number.POSITIVE_INFINITY\n */\n concurrency?: number\n}\n\n/**\n * Parameters accepted by `PluginDriver.getFile` to resolve a generated file descriptor.\n */\nexport type GetFileOptions<TOptions = object> = {\n name: string\n mode?: 'single' | 'split'\n extname: FileNode['extname']\n pluginName: string\n options?: TOptions\n}\n\n/**\n * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.\n *\n * @example\n * ```ts\n * getMode('src/gen/types.ts') // 'single'\n * getMode('src/gen/types') // 'split'\n * ```\n */\nexport function getMode(fileOrFolder: string | undefined | null): 'single' | 'split' {\n if (!fileOrFolder) {\n return 'split'\n }\n return extname(fileOrFolder) ? 'single' : 'split'\n}\n\nconst hookFirstNullCheck = (state: unknown) => !!(state as SafeParseResult<'resolveName'> | null)?.result\n\nexport class PluginDriver {\n readonly config: Config\n readonly options: Options\n\n /**\n * The universal `@kubb/ast` `InputNode` produced by the adapter, set by\n * the build pipeline after the adapter's `parse()` resolves.\n */\n inputNode: InputNode | undefined = undefined\n adapter: Adapter | undefined = undefined\n #studioIsOpen = false\n\n /**\n * Central file store for all generated files.\n * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to\n * add files; this property gives direct read/write access when needed.\n */\n readonly fileManager = new FileManager()\n\n readonly plugins = new Map<string, Plugin>()\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n config.plugins\n .map((plugin) => Object.assign({ buildStart() {}, buildEnd() {} }, plugin) as unknown as Plugin)\n .filter((plugin) => {\n if (typeof plugin.apply === 'function') {\n return plugin.apply(config)\n }\n return true\n })\n .sort((a, b) => {\n if (b.pre?.includes(a.name)) return 1\n if (b.post?.includes(a.name)) return -1\n return 0\n })\n .forEach((plugin) => {\n this.plugins.set(plugin.name, plugin)\n })\n }\n\n get events() {\n return this.options.events\n }\n\n getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown> {\n const driver = this\n\n const baseContext = {\n config: driver.config,\n get root(): string {\n return resolve(driver.config.root, driver.config.output.path)\n },\n getMode(output: { path: string }): 'single' | 'split' {\n return getMode(resolve(driver.config.root, driver.config.output.path, output.path))\n },\n events: driver.options.events,\n plugin,\n getPlugin: driver.getPlugin.bind(driver),\n requirePlugin: driver.requirePlugin.bind(driver),\n driver: driver,\n addFile: async (...files: Array<FileNode>) => {\n driver.fileManager.add(...files)\n },\n upsertFile: async (...files: Array<FileNode>) => {\n driver.fileManager.upsert(...files)\n },\n get inputNode(): InputNode | undefined {\n return driver.inputNode\n },\n get adapter(): Adapter | undefined {\n return driver.adapter\n },\n get resolver() {\n return plugin.resolver\n },\n get transformer() {\n return plugin.transformer\n },\n warn(message: string) {\n driver.events.emit('warn', message)\n },\n error(error: string | Error) {\n driver.events.emit('error', typeof error === 'string' ? new Error(error) : error)\n },\n info(message: string) {\n driver.events.emit('info', message)\n },\n openInStudio(options?: DevtoolsOptions) {\n if (!driver.config.devtools || driver.#studioIsOpen) {\n return\n }\n\n if (typeof driver.config.devtools !== 'object') {\n throw new Error('Devtools must be an object')\n }\n\n if (!driver.inputNode || !driver.adapter) {\n throw new Error('adapter is not defined, make sure you have set the parser in kubb.config.ts')\n }\n\n driver.#studioIsOpen = true\n\n const studioUrl = driver.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL\n\n return openInStudioFn(driver.inputNode, studioUrl, options)\n },\n } as unknown as PluginContext<TOptions>\n\n const mergedExtras: Record<string, unknown> = {}\n\n for (const p of this.plugins.values()) {\n if (typeof p.inject === 'function') {\n const result = (p.inject as (this: PluginContext) => unknown).call(baseContext as unknown as PluginContext)\n if (result !== null && typeof result === 'object') {\n Object.assign(mergedExtras, result)\n }\n }\n }\n\n return {\n ...baseContext,\n ...mergedExtras,\n }\n }\n /**\n * @deprecated use resolvers context instead\n */\n getFile<TOptions = object>({ name, mode, extname, pluginName, options }: GetFileOptions<TOptions>): FileNode<{ pluginName: string }> {\n const resolvedName = mode ? (mode === 'single' ? '' : this.resolveName({ name, pluginName, type: 'file' })) : name\n\n const path = this.resolvePath({\n baseName: `${resolvedName}${extname}` as const,\n mode,\n pluginName,\n options,\n })\n\n if (!path) {\n throw new Error(`Filepath should be defined for resolvedName \"${resolvedName}\" and pluginName \"${pluginName}\"`)\n }\n\n return createFile<{ pluginName: string }>({\n path,\n baseName: basename(path) as `${string}.${string}`,\n meta: {\n pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n })\n }\n\n /**\n * @deprecated use resolvers context instead\n */\n resolvePath = <TOptions = object>(params: ResolvePathParams<TOptions>): string => {\n const root = resolve(this.config.root, this.config.output.path)\n const defaultPath = resolve(root, params.baseName)\n\n if (params.pluginName) {\n const paths = this.hookForPluginSync({\n pluginName: params.pluginName,\n hookName: 'resolvePath',\n parameters: [params.baseName, params.mode, params.options as object],\n })\n\n return paths?.at(0) || defaultPath\n }\n\n const firstResult = this.hookFirstSync({\n hookName: 'resolvePath',\n parameters: [params.baseName, params.mode, params.options as object],\n })\n\n return firstResult?.result || defaultPath\n }\n /**\n * @deprecated use resolvers context instead\n */\n resolveName = (params: ResolveNameParams): string => {\n if (params.pluginName) {\n const names = this.hookForPluginSync({\n pluginName: params.pluginName,\n hookName: 'resolveName',\n parameters: [params.name.trim(), params.type],\n })\n\n return transformReservedWord(names?.at(0) ?? params.name)\n }\n\n const name = this.hookFirstSync({\n hookName: 'resolveName',\n parameters: [params.name.trim(), params.type],\n })?.result\n\n return transformReservedWord(name ?? params.name)\n }\n\n /**\n * Run a specific hookName for plugin x.\n */\n async hookForPlugin<H extends PluginLifecycleHooks>({\n pluginName,\n hookName,\n parameters,\n }: {\n pluginName: string\n hookName: H\n parameters: PluginParameter<H>\n }): Promise<Array<ReturnType<ParseResult<H>> | null>> {\n const plugin = this.plugins.get(pluginName)\n\n if (!plugin) {\n return [null]\n }\n\n this.events.emit('plugins:hook:progress:start', {\n hookName,\n plugins: [plugin],\n })\n\n const result = await this.#execute<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return [result]\n }\n\n /**\n * Run a specific hookName for plugin x.\n */\n hookForPluginSync<H extends PluginLifecycleHooks>({\n pluginName,\n hookName,\n parameters,\n }: {\n pluginName: string\n hookName: H\n parameters: PluginParameter<H>\n }): Array<ReturnType<ParseResult<H>>> | null {\n const plugin = this.plugins.get(pluginName)\n\n if (!plugin) {\n return null\n }\n\n const result = this.#executeSync<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n return result !== null ? [result] : []\n }\n\n /**\n * Returns the first non-null result.\n */\n async hookFirst<H extends PluginLifecycleHooks>({\n hookName,\n parameters,\n skipped,\n }: {\n hookName: H\n parameters: PluginParameter<H>\n skipped?: ReadonlySet<Plugin> | null\n }): Promise<SafeParseResult<H>> {\n const plugins: Array<Plugin> = []\n for (const plugin of this.plugins.values()) {\n if (hookName in plugin && (skipped ? !skipped.has(plugin) : true)) plugins.push(plugin)\n }\n\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const promises = plugins.map((plugin) => {\n return async () => {\n const value = await this.#execute<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n return Promise.resolve({\n plugin,\n result: value,\n } as SafeParseResult<H>)\n }\n })\n\n const result = await hookFirst(promises, hookFirstNullCheck)\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return result\n }\n\n /**\n * Returns the first non-null result.\n */\n hookFirstSync<H extends PluginLifecycleHooks>({\n hookName,\n parameters,\n skipped,\n }: {\n hookName: H\n parameters: PluginParameter<H>\n skipped?: ReadonlySet<Plugin> | null\n }): SafeParseResult<H> | null {\n let parseResult: SafeParseResult<H> | null = null\n\n for (const plugin of this.plugins.values()) {\n if (!(hookName in plugin)) continue\n if (skipped?.has(plugin)) continue\n\n parseResult = {\n result: this.#executeSync<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n }),\n plugin,\n } as SafeParseResult<H>\n\n if (parseResult.result != null) break\n }\n\n return parseResult\n }\n\n /**\n * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.\n */\n async hookParallel<H extends PluginLifecycleHooks, TOutput = void>({\n hookName,\n parameters,\n }: {\n hookName: H\n parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined\n }): Promise<Awaited<TOutput>[]> {\n const plugins: Array<Plugin> = []\n for (const plugin of this.plugins.values()) {\n if (hookName in plugin) plugins.push(plugin)\n }\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const pluginStartTimes = new Map<Plugin, number>()\n\n const promises = plugins.map((plugin) => {\n return () => {\n pluginStartTimes.set(plugin, performance.now())\n return this.#execute({\n strategy: 'hookParallel',\n hookName,\n parameters,\n plugin,\n }) as Promise<TOutput>\n }\n })\n\n const results = await hookParallel(promises, this.options.concurrency)\n\n results.forEach((result, index) => {\n if (isPromiseRejectedResult<Error>(result)) {\n const plugin = plugins[index]\n\n if (plugin) {\n const startTime = pluginStartTimes.get(plugin) ?? performance.now()\n this.events.emit('error', result.reason, {\n plugin,\n hookName,\n strategy: 'hookParallel',\n duration: Math.round(performance.now() - startTime),\n parameters,\n })\n }\n }\n })\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return results.reduce((acc, result) => {\n if (result.status === 'fulfilled') {\n acc.push(result.value)\n }\n return acc\n }, [] as Awaited<TOutput>[])\n }\n\n /**\n * Chains plugins\n */\n async hookSeq<H extends PluginLifecycleHooks>({ hookName, parameters }: { hookName: H; parameters?: PluginParameter<H> }): Promise<void> {\n const plugins: Array<Plugin> = []\n for (const plugin of this.plugins.values()) {\n if (hookName in plugin) plugins.push(plugin)\n }\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const promises = plugins.map((plugin) => {\n return () =>\n this.#execute({\n strategy: 'hookSeq',\n hookName,\n parameters,\n plugin,\n })\n })\n\n await hookSeq(promises)\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n }\n\n getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined\n getPlugin(pluginName: string): Plugin | undefined {\n return this.plugins.get(pluginName) as Plugin | undefined\n }\n\n /**\n * Like `getPlugin` but throws a descriptive error when the plugin is not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>\n requirePlugin(pluginName: string): Plugin {\n const plugin = this.plugins.get(pluginName)\n if (!plugin) {\n throw new Error(`[kubb] Plugin \"${pluginName}\" is required but not found. Make sure it is included in your Kubb config.`)\n }\n return plugin\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n #emitProcessingEnd<H extends PluginLifecycleHooks>({\n startTime,\n output,\n strategy,\n hookName,\n plugin,\n parameters,\n }: {\n startTime: number\n output: unknown\n strategy: Strategy\n hookName: H\n plugin: PluginWithLifeCycle\n parameters: unknown[] | undefined\n }): void {\n this.events.emit('plugins:hook:processing:end', {\n duration: Math.round(performance.now() - startTime),\n parameters,\n output,\n strategy,\n hookName,\n plugin,\n })\n }\n\n // Implementation signature\n #execute<H extends PluginLifecycleHooks>({\n strategy,\n hookName,\n parameters,\n plugin,\n }: {\n strategy: Strategy\n hookName: H\n parameters: unknown[] | undefined\n plugin: PluginWithLifeCycle\n }): Promise<ReturnType<ParseResult<H>> | null> | null {\n const hook = plugin[hookName]\n\n if (!hook) {\n return null\n }\n\n this.events.emit('plugins:hook:processing:start', {\n strategy,\n hookName,\n parameters,\n plugin,\n })\n\n const startTime = performance.now()\n\n const task = (async () => {\n try {\n const output =\n typeof hook === 'function' ? await Promise.resolve((hook as (...args: unknown[]) => unknown).apply(this.getContext(plugin), parameters ?? [])) : hook\n\n this.#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters })\n\n return output as ReturnType<ParseResult<H>>\n } catch (error) {\n this.events.emit('error', error as Error, {\n plugin,\n hookName,\n strategy,\n duration: Math.round(performance.now() - startTime),\n })\n\n return null\n }\n })()\n\n return task\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual plugin\n */\n #executeSync<H extends PluginLifecycleHooks>({\n strategy,\n hookName,\n parameters,\n plugin,\n }: {\n strategy: Strategy\n hookName: H\n parameters: PluginParameter<H>\n plugin: PluginWithLifeCycle\n }): ReturnType<ParseResult<H>> | null {\n const hook = plugin[hookName]\n\n if (!hook) {\n return null\n }\n\n this.events.emit('plugins:hook:processing:start', {\n strategy,\n hookName,\n parameters,\n plugin,\n })\n\n const startTime = performance.now()\n\n try {\n const output =\n typeof hook === 'function'\n ? ((hook as (...args: unknown[]) => unknown).apply(this.getContext(plugin), parameters) as ReturnType<ParseResult<H>>)\n : (hook as ReturnType<ParseResult<H>>)\n\n this.#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters })\n\n return output\n } catch (error) {\n this.events.emit('error', error as Error, {\n plugin,\n hookName,\n strategy,\n duration: Math.round(performance.now() - startTime),\n })\n\n return null\n }\n }\n}\n","import type { FileNode } from '@kubb/ast/types'\nimport { createReactFabric, Fabric } from '@kubb/react-fabric'\nimport type { FabricReactNode } from '@kubb/react-fabric/types'\nimport type { PluginDriver } from './PluginDriver.ts'\n\n/**\n * Handles the return value of a plugin AST hook or generator method.\n *\n * - React element → rendered via an isolated react-fabric context, files stored in `driver.fileManager`\n * - `Array<FileNode>` → upserted directly into `driver.fileManager`\n * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)\n */\nexport async function applyHookResult(result: FabricReactNode | Array<FileNode> | void, driver: PluginDriver): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n driver.fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n // Non-array truthy result is treated as a React element (FabricReactNode)\n const fabricChild = createReactFabric()\n await fabricChild.render(<Fabric>{result as FabricReactNode}</Fabric>)\n driver.fileManager.upsert(...(fabricChild.files as unknown as Array<FileNode>))\n fabricChild.unmount()\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/types'\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 { createExport, createFile, createSource } from '@kubb/ast'\nimport type { FileNode } from '@kubb/ast/types'\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 * Root based on root and output.path specified in the config\n */\n root: string\n /**\n * Output for 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 //TODO use parser to generate import\n value: '',\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 { InputPath, UserConfig } from '../types'\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: UserConfig | undefined): config is UserConfig<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 { createExport, createFile, transform, walk } from '@kubb/ast'\nimport type { ExportNode, FileNode, OperationNode } from '@kubb/ast/types'\nimport { BARREL_FILENAME, DEFAULT_BANNER, DEFAULT_CONCURRENCY, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport type { Parser } from './defineParser.ts'\nimport { FileProcessor } from './FileProcessor.ts'\nimport { PluginDriver } from './PluginDriver.ts'\nimport { applyHookResult } from './renderNode.tsx'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, KubbEvents, Plugin, PluginContext, Storage, UserConfig } 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: UserConfig\n events?: AsyncEventEmitter<KubbEvents>\n}\n\n/**\n * Full output produced by a successful or failed build.\n */\ntype 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\n/**\n * Intermediate result returned by {@link setup} and accepted by {@link safeBuild}.\n */\ntype SetupResult = {\n events: AsyncEventEmitter<KubbEvents>\n driver: PluginDriver\n sources: Map<string, string>\n config: Config\n storage: Storage | null\n}\n\n/**\n * Initializes all Kubb infrastructure for a build without executing any plugins.\n *\n * - Validates the input path (when applicable).\n * - Applies config defaults (`root`, `output.*`, `devtools`).\n * - Creates the Fabric instance and wires storage, format, and lint hooks.\n * - Runs the adapter (if configured) to produce the universal `InputNode`.\n * When no adapter is supplied and `@kubb/adapter-oas` is installed as an\n *\n * Pass the returned {@link SetupResult} directly to {@link safeBuild} or {@link build}\n * via the `overrides` argument to reuse the same infrastructure across multiple runs.\n */\nexport async function setup(options: BuildOptions): Promise<SetupResult> {\n const { config: userConfig, events = new AsyncEventEmitter<KubbEvents>() } = options\n\n const sources: Map<string, string> = new Map<string, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n if (Array.isArray(userConfig.input)) {\n await events.emit('warn', 'This feature is still under development — use with caution')\n }\n\n await events.emit('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 events.emit('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 root: userConfig.root || process.cwd(),\n ...userConfig,\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 Config['plugins'],\n }\n\n // write: false is the explicit dry-run opt-out; otherwise use the provided\n // storage or fall back to fsStorage (backwards-compatible default).\n // Storage keys are the absolute file.path values so fsStorage() resolves\n // them correctly regardless of the current working directory.\n const storage: Storage | null = config.output.write === false ? null : (config.output.storage ?? fsStorage())\n\n if (config.output.clean) {\n await events.emit('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 events,\n concurrency: DEFAULT_CONCURRENCY,\n })\n\n // Run the adapter to produce the universal InputNode.\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 events.emit('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 events.emit('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 events,\n driver,\n sources,\n storage,\n }\n}\n\n/**\n * Runs a full Kubb build and throws on any error or plugin failure.\n *\n * Internally delegates to {@link safeBuild} and rethrows collected errors.\n * Pass an existing {@link SetupResult} via `overrides` to skip the setup phase.\n */\nexport async function build(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(options, overrides)\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\n/**\n * Walks the AST and dispatches nodes to a plugin's direct AST hooks\n * (`schema`, `operation`, `operations`).\n *\n * - Each hook accepts a single handler **or an array** — all entries are called in sequence.\n * - Nodes that are excluded by `exclude`/`include` plugin options are skipped automatically.\n * - Return values are handled via `applyHookResult`: React elements are rendered,\n * `FileNode[]` are written via upsert, and `void` is a no-op (manual handling).\n * - Barrel files are generated automatically when `output.barrelType` is set.\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 const collectedOperations: Array<OperationNode> = []\n\n await walk(inputNode, {\n depth: 'shallow',\n async schema(node) {\n if (!plugin.schema) return\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 const result = await plugin.schema.call(context, transformedNode, options)\n\n await applyHookResult(result, driver)\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 if (plugin.operation) {\n const result = await plugin.operation.call(context, transformedNode, options)\n await applyHookResult(result, driver)\n }\n }\n },\n })\n\n if (plugin.operations && collectedOperations.length > 0) {\n const result = await plugin.operations.call(context, collectedOperations, plugin.options)\n\n await applyHookResult(result, driver)\n }\n}\n\n/**\n * Runs a full Kubb build and captures errors instead of throwing.\n *\n * - Installs each plugin in order, recording failures in `failedPlugins`.\n * - Generates the root barrel file when `output.barrelType` is set.\n * - Writes all files through the driver's FileManager and FileProcessor.\n *\n * Returns a {@link BuildOutput} even on failure — inspect `error` and\n * `failedPlugins` to determine whether the build succeeded.\n */\nexport async function safeBuild(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const setupResult = overrides ? overrides : await setup(options)\n const { driver, events, sources, storage } = setupResult\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n // in ms\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\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 events.emit('plugin:start', plugin)\n\n await events.emit('debug', {\n date: timestamp,\n logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n // Call buildStart() for any custom plugin logic\n await plugin.buildStart.call(context)\n\n // Dispatch schema/operation/operations hooks (direct hooks or composed via composeGenerators)\n if (plugin.schema || plugin.operation || plugin.operations) {\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 events.emit('plugin:end', plugin, { duration, success: true })\n\n await events.emit('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 events.emit('plugin:end', plugin, {\n duration,\n success: false,\n error,\n })\n\n await events.emit('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 events.emit('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 events.emit('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 events.emit('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 // Build a parsers map from config.parsers\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 events.emit('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 events.emit('files:processing:start', processingFiles)\n },\n onUpdate: async ({ file, source, processed, total, percentage }) => {\n await events.emit('file:processing:update', {\n file,\n source,\n processed,\n total,\n percentage,\n config,\n })\n if (source) {\n // Use the absolute file.path as the storage key so fsStorage resolves\n // it correctly regardless of the current working directory.\n await storage?.setItem(file.path, source)\n sources.set(file.path, source)\n }\n },\n onEnd: async (processedFiles) => {\n await events.emit('files:processing:end', processedFiles)\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${processedFiles.length} files`],\n })\n },\n })\n\n // Call buildEnd() on each plugin after all files are written\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 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 }\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\n/**\n * Maps the resolved `Config['input']` shape into an `AdapterSource` that\n * the adapter's `parse()` can consume.\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","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 { 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 */\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 { PossiblePromise } from '@internals/utils'\nimport type { UserConfig } from './types.ts'\n\n/**\n * CLI options derived from command-line flags.\n */\nexport type CLIOptions = {\n /**\n * Path to `kubb.config.js`.\n */\n config?: string\n /**\n * Enable watch mode for input files.\n */\n watch?: boolean\n /**\n * Logging verbosity for CLI usage.\n *\n * - `silent`: hide non-essential logs\n * - `info`: show general logs (non-plugin-related)\n * - `debug`: include detailed plugin lifecycle logs\n * @default 'silent'\n */\n logLevel?: 'silent' | 'info' | 'debug'\n}\n\n/**\n * All accepted forms of a Kubb configuration.\n */\nexport type ConfigInput = PossiblePromise<UserConfig | UserConfig[]> | ((cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>)\n\n/**\n * Helper for defining a Kubb configuration.\n *\n * Accepts either:\n * - A config object or array of configs\n * - A function returning the config(s), optionally async,\n * receiving the CLI options as argument\n *\n * @example\n * export default defineConfig(({ logLevel }) => ({\n * root: 'src',\n * plugins: [myPlugin()],\n * }))\n * @deprecated as of Kubb v5, @kubb/core will not expose `defineConfig` anymore. use the `kubb` package instead\n */\nexport function defineConfig(config: (cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>): typeof config\nexport function defineConfig(config: PossiblePromise<UserConfig | UserConfig[]>): typeof config\nexport function defineConfig(config: ConfigInput): ConfigInput {\n return config\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { FileNode, OperationNode, SchemaNode } from '@kubb/ast/types'\nimport type { FabricReactNode } from '@kubb/react-fabric/types'\nimport { applyHookResult } from './renderNode.tsx'\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 is called with `this = PluginContext` of the parent plugin,\n * giving full access to `this.config`, `this.resolver`, `this.adapter`,\n * `this.driver`, etc.\n *\n * Return a React element, an array of `FileNode`, or `void` to handle file\n * writing manually via `this.upsertFile`. Both React and core (non-React) generators\n * use the same method signatures — the return type determines how output is handled.\n *\n * @example\n * ```ts\n * export const typeGenerator = defineGenerator<PluginTs>({\n * name: 'typescript',\n * schema(node, options) {\n * const { adapter, resolver, root } = this\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * operation(node, options) {\n * return <File ...><OperationType node={node} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {\n /** Used in diagnostic messages and debug output. */\n name: string\n /**\n * Called for each schema node in the AST walk.\n * `this` is the parent plugin's context with `adapter` and `inputNode` guaranteed present.\n * `options` contains the per-node resolved options (after exclude/include/override).\n */\n schema?: (\n this: GeneratorContext<TOptions>,\n node: SchemaNode,\n options: TOptions['resolvedOptions'],\n ) => PossiblePromise<FabricReactNode | Array<FileNode> | void>\n /**\n * Called for each operation node in the AST walk.\n * `this` is the parent plugin's context with `adapter` and `inputNode` guaranteed present.\n */\n operation?: (\n this: GeneratorContext<TOptions>,\n node: OperationNode,\n options: TOptions['resolvedOptions'],\n ) => PossiblePromise<FabricReactNode | Array<FileNode> | void>\n /**\n * Called once after all operations have been walked.\n * `this` is the parent plugin's context with `adapter` and `inputNode` guaranteed present.\n */\n operations?: (\n this: GeneratorContext<TOptions>,\n nodes: Array<OperationNode>,\n options: TOptions['resolvedOptions'],\n ) => PossiblePromise<FabricReactNode | Array<FileNode> | void>\n}\n\n/**\n * Defines a generator. Returns the object as-is with correct `this` typings.\n * No type discrimination (`type: 'react' | 'core'`) needed — `applyHookResult`\n * handles React elements and `File[]` uniformly.\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generator: Generator<TOptions>): Generator<TOptions> {\n return generator\n}\n\n/**\n * Merges an array of generators into a single generator.\n *\n * The merged generator's `schema`, `operation`, and `operations` methods run\n * the corresponding method from each input generator in sequence, applying each\n * result via `applyHookResult`. This eliminates the need to write the loop\n * manually in each plugin.\n *\n * @param generators - Array of generators to merge into a single generator.\n *\n * @example\n * ```ts\n * const merged = mergeGenerators(generators)\n *\n * return {\n * name: pluginName,\n * schema: merged.schema,\n * operation: merged.operation,\n * operations: merged.operations,\n * }\n * ```\n */\nexport function mergeGenerators<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generators: Array<Generator<TOptions>>): Generator<TOptions> {\n return {\n name: generators.length > 0 ? generators.map((g) => g.name).join('+') : 'merged',\n async schema(node, options) {\n for (const gen of generators) {\n if (!gen.schema) continue\n const result = await gen.schema.call(this, node, options)\n\n await applyHookResult(result, this.driver)\n }\n },\n async operation(node, options) {\n for (const gen of generators) {\n if (!gen.operation) continue\n const result = await gen.operation.call(this, node, options)\n\n await applyHookResult(result, this.driver)\n }\n },\n async operations(nodes, options) {\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations.call(this, nodes, options)\n\n await applyHookResult(result, this.driver)\n }\n },\n }\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('info', (message) => console.log('ℹ', message))\n * context.on('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/types'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\nexport type Parser<TMeta extends object = any> = {\n name: string\n type: 'parser'\n /**\n * File extensions this parser handles.\n * Use `undefined` to create a catch-all fallback parser.\n *\n * @example ['.ts', '.js']\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * @deprecated Will be removed once Fabric no longer requires it.\n * @default () => {}\n */\n install(...args: unknown[]): void | Promise<void>\n /**\n * Convert a resolved file to a string.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string\n}\n\nexport type UserParser<TMeta extends object = any> = Omit<Parser<TMeta>, 'type' | 'install'> & {\n install?(...args: unknown[]): void | Promise<void>\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 * return file.sources.map((s) => s.value).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<TMeta extends object = any>(parser: UserParser<TMeta>): Parser<TMeta> {\n return {\n install() {},\n type: 'parser',\n ...parser,\n }\n}\n","import type { Preset, Presets, Resolver } from './types.ts'\n\n/**\n * Creates a typed presets registry object — a named collection of {@link Preset} entries.\n *\n * @example\n * import { definePreset, definePresets } from '@kubb/core'\n * import { resolverTsLegacy } from '@kubb/plugin-ts'\n *\n * export const myPresets = definePresets({\n * kubbV4: definePreset('kubbV4', { resolvers: [resolverTsLegacy] }),\n * })\n */\nexport function definePresets<TResolver extends Resolver = Resolver>(presets: Presets<TResolver>): Presets<TResolver> {\n return presets\n}\n","import path from 'node:path'\nimport { camelCase, pascalCase } from '@internals/utils'\nimport { createFile, isOperationNode, isSchemaNode } from '@kubb/ast'\nimport type { FileNode, InputNode, Node, OperationNode, SchemaNode } from '@kubb/ast/types'\nimport { getMode } from './PluginDriver.ts'\nimport type {\n Config,\n PluginFactoryOptions,\n ResolveBannerContext,\n ResolveNameParams,\n ResolveOptionsContext,\n Resolver,\n ResolverContext,\n ResolverFileParams,\n ResolverPathParams,\n} from './types.ts'\n\n/**\n * Builder type for the plugin-specific resolver fields.\n *\n * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`\n * are optional — built-in fallbacks are injected when omitted.\n */\ntype ResolverBuilder<T extends PluginFactoryOptions> = () => Omit<\n T['resolver'],\n 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter' | 'name' | 'pluginName'\n> &\n Partial<Pick<T['resolver'], 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter'>> & {\n name: string\n pluginName: T['name']\n } & ThisType<T['resolver']>\n\n/**\n * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).\n */\nfunction matchesOperationPattern(node: OperationNode, type: string, pattern: string | RegExp): boolean {\n switch (type) {\n case 'tag':\n return node.tags.some((tag) => !!tag.match(pattern))\n case 'operationId':\n return !!node.operationId.match(pattern)\n case 'path':\n return !!node.path.match(pattern)\n case 'method':\n return !!(node.method.toLowerCase() as string).match(pattern)\n case 'contentType':\n return !!node.requestBody?.contentType?.match(pattern)\n default:\n return false\n }\n}\n\n/**\n * Checks if a schema matches a pattern for a given filter type (`schemaName`).\n *\n * Returns `null` when the filter type doesn't apply to schemas.\n */\nfunction matchesSchemaPattern(node: SchemaNode, type: string, pattern: string | RegExp): boolean | null {\n switch (type) {\n case 'schemaName':\n return node.name ? !!node.name.match(pattern) : false\n default:\n return null\n }\n}\n\n/**\n * Default name resolver used by `defineResolver`.\n *\n * - `camelCase` for `function` and `file` types.\n * - `PascalCase` for `type`.\n * - `camelCase` for everything else.\n */\nfunction defaultResolver(name: ResolveNameParams['name'], type: ResolveNameParams['type']): string {\n let resolvedName = camelCase(name)\n\n if (type === 'file' || type === 'function') {\n resolvedName = camelCase(name, {\n isFile: type === 'file',\n })\n }\n\n if (type === 'type') {\n resolvedName = pascalCase(name)\n }\n\n return resolvedName\n}\n\n/**\n * Default option resolver — applies include/exclude filters and merges matching override options.\n *\n * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.\n *\n * @example Include/exclude filtering\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { output: 'types' },\n * exclude: [{ type: 'tag', pattern: 'internal' }],\n * })\n * // → null when node has tag 'internal'\n * ```\n *\n * @example Override merging\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { enumType: 'asConst' },\n * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],\n * })\n * // → { enumType: 'enum' } when operationId matches\n * ```\n */\nexport function defaultResolveOptions<TOptions>(\n node: Node,\n { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>,\n): TOptions | null {\n if (isOperationNode(node)) {\n const isExcluded = exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))\n if (isExcluded) {\n return null\n }\n\n if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) {\n return null\n }\n\n const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options\n\n return { ...options, ...overrideOptions }\n }\n\n if (isSchemaNode(node)) {\n if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) {\n return null\n }\n\n if (include) {\n const results = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern))\n const applicable = results.filter((r) => r !== null)\n if (applicable.length > 0 && !applicable.includes(true)) {\n return null\n }\n }\n\n const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options\n\n return { ...options, ...overrideOptions }\n }\n\n return options\n}\n\n/**\n * Default path resolver used by `defineResolver`.\n *\n * - Returns the output directory in `single` mode.\n * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.\n * - Falls back to a flat `output/baseName` path otherwise.\n *\n * A custom `group.name` function overrides the default subdirectory naming.\n * For `tag` groups the default is `${camelCase(tag)}Controller`.\n * For `path` groups the default is the first path segment after `/`.\n *\n * @example Flat output\n * ```ts\n * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })\n * // → '/src/types/petTypes.ts'\n * ```\n *\n * @example Tag-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → '/src/types/petsController/petTypes.ts'\n * ```\n *\n * @example Path-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', path: '/pets/list' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\n *\n * @example Single-file mode\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', pathMode: 'single' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → '/src/types'\n * ```\n */\nexport function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }: ResolverPathParams, { root, output, group }: ResolverContext): string {\n const mode = pathMode ?? getMode(path.resolve(root, output.path))\n\n if (mode === 'single') {\n return path.resolve(root, output.path)\n }\n\n if (group && (groupPath || tag)) {\n return path.resolve(root, output.path, group.name({ group: group.type === 'path' ? groupPath! : tag! }), baseName)\n }\n\n return path.resolve(root, output.path, baseName)\n}\n\n/**\n * Default file resolver used by `defineResolver`.\n *\n * Resolves a `FileNode` by combining name resolution (`resolver.default`) with\n * path resolution (`resolver.resolvePath`). The resolved file always has empty\n * `sources`, `imports`, and `exports` arrays — consumers populate those separately.\n *\n * In `single` mode the name is omitted and the file sits directly in the output directory.\n *\n * @example Resolve a schema file\n * ```ts\n * const file = defaultResolveFile.call(resolver,\n * { name: 'pet', extname: '.ts' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }\n * ```\n *\n * @example Resolve an operation file with tag grouping\n * ```ts\n * const file = defaultResolveFile.call(resolver,\n * { name: 'listPets', extname: '.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }\n * ```\n */\nexport function defaultResolveFile(this: Resolver, { name, extname, tag, path: groupPath }: ResolverFileParams, context: ResolverContext): FileNode {\n const pathMode = getMode(path.resolve(context.root, context.output.path))\n const resolvedName = pathMode === 'single' ? '' : this.default(name, 'file')\n const baseName = `${resolvedName}${extname}` as FileNode['baseName']\n const filePath = this.resolvePath({ baseName, pathMode, tag, path: groupPath }, context)\n\n return createFile({\n path: filePath,\n baseName: path.basename(filePath) as `${string}.${string}`,\n meta: {\n pluginName: this.pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n })\n}\n\n/**\n * Generates the default \"Generated by Kubb\" banner from config and optional node metadata.\n */\nexport function buildDefaultBanner({\n title,\n description,\n version,\n config,\n}: {\n title?: string\n description?: string\n version?: string\n config: Config\n}): string {\n try {\n let source = ''\n if (Array.isArray(config.input)) {\n const first = config.input[0]\n if (first && 'path' in first) {\n source = path.basename(first.path)\n }\n } else if ('path' in config.input) {\n source = path.basename(config.input.path)\n } else if ('data' in config.input) {\n source = 'text content'\n }\n\n let banner = '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n'\n\n if (config.output.defaultBanner === 'simple') {\n banner += '*/\\n'\n return banner\n }\n\n if (source) {\n banner += `* Source: ${source}\\n`\n }\n\n if (title) {\n banner += `* Title: ${title}\\n`\n }\n\n if (description) {\n const formattedDescription = description.replace(/\\n/gm, '\\n* ')\n banner += `* Description: ${formattedDescription}\\n`\n }\n\n if (version) {\n banner += `* OpenAPI spec version: ${version}\\n`\n }\n\n banner += '*/\\n'\n return banner\n } catch (_error) {\n return '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n*/'\n }\n}\n\n/**\n * Default banner resolver — returns the banner string for a generated file.\n *\n * A user-supplied `output.banner` overrides the default Kubb \"Generated by Kubb\" notice.\n * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`\n * from the OAS spec when a `node` is provided).\n *\n * - When `output.banner` is a function and `node` is provided, returns `output.banner(node)`.\n * - When `output.banner` is a function and `node` is absent, falls back to the Kubb notice.\n * - When `output.banner` is a string, returns it directly.\n * - When `config.output.defaultBanner` is `false`, returns `undefined`.\n * - Otherwise returns the Kubb \"Generated by Kubb\" notice.\n *\n * @example String banner overrides default\n * ```ts\n * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })\n * // → '// my banner'\n * ```\n *\n * @example Function banner with node\n * ```ts\n * defaultResolveBanner(inputNode, { output: { banner: (node) => `// v${node.version}` }, config })\n * // → '// v3.0.0'\n * ```\n *\n * @example No user banner — Kubb notice with OAS metadata\n * ```ts\n * defaultResolveBanner(inputNode, { config })\n * // → '/** Generated by Kubb ... Title: Pet Store ... *\\/'\n * ```\n *\n * @example Disabled default banner\n * ```ts\n * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })\n * // → undefined\n * ```\n */\nexport function defaultResolveBanner(node: InputNode | undefined, { output, config }: ResolveBannerContext): string | undefined {\n if (typeof output?.banner === 'function') {\n return output.banner(node)\n }\n\n if (typeof output?.banner === 'string') {\n return output.banner\n }\n\n if (config.output.defaultBanner === false) {\n return undefined\n }\n\n return buildDefaultBanner({ title: node?.meta?.title, version: node?.meta?.version, config })\n}\n\n/**\n * Default footer resolver — returns the footer string for a generated file.\n *\n * - When `output.footer` is a function and `node` is provided, calls it with the node.\n * - When `output.footer` is a function and `node` is absent, returns `undefined`.\n * - When `output.footer` is a string, returns it directly.\n * - Otherwise returns `undefined`.\n *\n * @example String footer\n * ```ts\n * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })\n * // → '// end of file'\n * ```\n *\n * @example Function footer with node\n * ```ts\n * defaultResolveFooter(inputNode, { output: { footer: (node) => `// ${node.title}` }, config })\n * // → '// Pet Store'\n * ```\n */\nexport function defaultResolveFooter(node: InputNode | undefined, { output }: ResolveBannerContext): string | undefined {\n if (typeof output?.footer === 'function') {\n return node ? output.footer(node) : undefined\n }\n if (typeof output?.footer === 'string') {\n return output.footer\n }\n return undefined\n}\n\n/**\n * Defines a resolver for a plugin, injecting built-in defaults for name casing,\n * include/exclude/override filtering, path resolution, and file construction.\n *\n * All four defaults can be overridden by providing them in the builder function:\n * - `default` — name casing strategy (camelCase / PascalCase)\n * - `resolveOptions` — include/exclude/override filtering\n * - `resolvePath` — output path computation\n * - `resolveFile` — full `FileNode` construction\n *\n * Methods in the builder have access to `this` (the full resolver object), so they\n * can call other resolver methods without circular imports.\n *\n * @example Basic resolver with naming helpers\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveName(node) {\n * return this.default(node.name, 'function')\n * },\n * resolveTypedName(node) {\n * return this.default(node.name, 'type')\n * },\n * }))\n * ```\n *\n * @example Override resolvePath for a custom output structure\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'custom',\n * resolvePath({ baseName }, { root, output }) {\n * return path.resolve(root, output.path, 'generated', baseName)\n * },\n * }))\n * ```\n *\n * @example Use this.default inside a helper\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveParamName(node, param) {\n * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')\n * },\n * }))\n * ```\n */\nexport function defineResolver<T extends PluginFactoryOptions>(build: ResolverBuilder<T>): T['resolver'] {\n return {\n default: defaultResolver,\n resolveOptions: defaultResolveOptions,\n resolvePath: defaultResolvePath,\n resolveFile: defaultResolveFile,\n resolveBanner: defaultResolveBanner,\n resolveFooter: defaultResolveFooter,\n ...build(),\n } as T['resolver']\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 { camelCase } from '@internals/utils'\n// TODO replace with @internals/utils\nimport { sortBy } from 'remeda'\n\ntype FunctionParamsASTWithoutType = {\n name?: string\n type?: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n\ntype FunctionParamsASTWithType = {\n name?: never\n type: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n/**\n * @deprecated use ast package instead\n */\nexport type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType\n\n/**\n * @deprecated use ast package instead\n */\nexport class FunctionParams {\n #items: Array<FunctionParamsAST | FunctionParamsAST[]> = []\n\n get items(): FunctionParamsAST[] {\n return this.#items.flat()\n }\n\n add(item: FunctionParamsAST | Array<FunctionParamsAST | FunctionParamsAST[] | undefined> | undefined): FunctionParams {\n if (!item) {\n return this\n }\n\n if (Array.isArray(item)) {\n item\n .filter((x): x is FunctionParamsAST | FunctionParamsAST[] => x !== undefined)\n .forEach((it) => {\n this.#items.push(it)\n })\n return this\n }\n this.#items.push(item)\n\n return this\n }\n static #orderItems(items: Array<FunctionParamsAST | FunctionParamsAST[]>) {\n return sortBy(\n items.filter(Boolean),\n [(item) => Array.isArray(item), 'desc'], // arrays (rest params) first\n [(item) => !Array.isArray(item) && (item as FunctionParamsAST).default !== undefined, 'asc'], // no-default before has-default\n [(item) => Array.isArray(item) || ((item as FunctionParamsAST).required ?? true), 'desc'], // required before optional\n )\n }\n\n static #addParams(acc: string[], item: FunctionParamsAST) {\n const { enabled = true, name, type, required = true, ...rest } = item\n\n if (!enabled) {\n return acc\n }\n\n if (!name) {\n // when name is not se we uses TypeScript generics\n acc.push(`${type}${rest.default ? ` = ${rest.default}` : ''}`)\n\n return acc\n }\n // TODO check why we still need the camelcase here\n const parameterName = name.startsWith('{') ? name : camelCase(name)\n\n if (type) {\n if (required) {\n acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ''}`)\n } else {\n acc.push(`${parameterName}?: ${type}`)\n }\n } else {\n acc.push(`${parameterName}`)\n }\n\n return acc\n }\n\n static toObject(items: FunctionParamsAST[]): FunctionParamsAST {\n let type: string[] = []\n let name: string[] = []\n\n const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true\n const required = items.every((item) => item.required) ?? true\n\n items.forEach((item) => {\n name = FunctionParams.#addParams(name, { ...item, type: undefined })\n if (items.some((item) => item.type)) {\n type = FunctionParams.#addParams(type, item)\n }\n })\n\n return {\n name: `{ ${name.join(', ')} }`,\n type: type.length ? `{ ${type.join('; ')} }` : undefined,\n enabled,\n required,\n }\n }\n\n toObject(): FunctionParamsAST {\n const items = FunctionParams.#orderItems(this.#items).flat()\n\n return FunctionParams.toObject(items)\n }\n\n static toString(items: (FunctionParamsAST | FunctionParamsAST[])[]): string {\n const sortedData = FunctionParams.#orderItems(items)\n\n return sortedData\n .reduce((acc, item) => {\n if (Array.isArray(item)) {\n if (item.length <= 0) {\n return acc\n }\n const subItems = FunctionParams.#orderItems(item) as FunctionParamsAST[]\n const objectItem = FunctionParams.toObject(subItems)\n\n return FunctionParams.#addParams(acc, objectItem)\n }\n\n return FunctionParams.#addParams(acc, item)\n }, [] as string[])\n .join(', ')\n }\n\n toString(): string {\n const items = FunctionParams.#orderItems(this.#items)\n\n return FunctionParams.toString(items)\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 type { CLIOptions, ConfigInput } from '../defineConfig.ts'\nimport type { Config, UserConfig } from '../types.ts'\n\n/**\n * Resolves a {@link ConfigInput} into a normalized array of {@link Config} objects.\n *\n * - Awaits the config when it is a `Promise`.\n * - Calls the factory function with `args` when the config is a function.\n * - Wraps a single config object in an array for uniform downstream handling.\n */\nexport async function getConfigs(config: ConfigInput | UserConfig, args: CLIOptions): Promise<Array<Config>> {\n const resolved = await (typeof config === 'function' ? config(args as CLIOptions) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return userConfigs.map((item) => ({ plugins: [], ...item }) as Config)\n}\n","import { composeTransformers } from '@kubb/ast'\nimport type { Visitor } from '@kubb/ast/types'\nimport type { CompatibilityPreset, Generator, Preset, Presets, Resolver } from '../types.ts'\n\n/**\n * Returns a copy of `defaults` where each function in `userOverrides` is wrapped\n * so a `null`/`undefined` return falls back to the original. Non-function values\n * are assigned directly. All calls use the merged object as `this`.\n */\nfunction withFallback<T extends object>(defaults: T, userOverrides: Partial<T>): T {\n const merged = { ...defaults } as T\n\n for (const key of Object.keys(userOverrides) as Array<keyof T>) {\n const userVal = userOverrides[key]\n const defaultVal = defaults[key]\n\n if (typeof userVal === 'function' && typeof defaultVal === 'function') {\n ;(merged as any)[key] = (...args: any[]) => (userVal as Function).apply(merged, args) ?? (defaultVal as Function).apply(merged, args)\n } else if (userVal !== undefined) {\n merged[key] = userVal as T[typeof key]\n }\n }\n\n return merged\n}\n\ntype GetPresetParams<TResolver extends Resolver> = {\n preset: CompatibilityPreset\n presets: Presets<TResolver>\n /**\n * Optional single resolver whose methods override the preset resolver.\n * When a method returns `null` or `undefined` the preset resolver's method is used instead.\n */\n resolver?: Partial<TResolver> & ThisType<TResolver>\n /**\n * User-supplied generators to append after the preset's generators.\n */\n generators?: Array<Generator<any>>\n /**\n * Optional single transformer visitor whose methods override the preset transformer.\n * When a method returns `null` or `undefined` the preset transformer's method is used instead.\n */\n transformer?: Visitor\n}\n\ntype GetPresetResult<TResolver extends Resolver> = {\n resolver: TResolver\n transformer: Visitor | undefined\n generators: Array<Generator<any>>\n preset: Preset<TResolver> | undefined\n}\n\n/**\n * Resolves a named preset into a resolver, transformer, and generators.\n *\n * - Selects the preset resolver; wraps it with user overrides using null/undefined fallback.\n * - Composes the preset's transformers into a single visitor; wraps it with the user transformer using null/undefined fallback.\n * - Combines preset generators with user-supplied generators; falls back to the `default` preset's generators when neither provides any.\n */\nexport function getPreset<TResolver extends Resolver = Resolver>(params: GetPresetParams<TResolver>): GetPresetResult<TResolver> {\n const { preset: presetName, presets, resolver: userResolver, transformer: userTransformer, generators: userGenerators = [] } = params\n const preset = presets[presetName]\n\n const presetResolver = preset?.resolver ?? presets['default']!.resolver\n const resolver = userResolver ? withFallback(presetResolver, userResolver) : presetResolver\n\n const presetTransformers = preset?.transformers ?? []\n const presetTransformer = presetTransformers.length > 0 ? composeTransformers(...presetTransformers) : undefined\n const transformer = presetTransformer && userTransformer ? withFallback(presetTransformer, userTransformer) : (userTransformer ?? presetTransformer)\n\n const presetGenerators = preset?.generators ?? []\n const defaultGenerators = presets['default']?.generators ?? []\n const generators = (presetGenerators.length > 0 || userGenerators.length > 0 ? [...presetGenerators, ...userGenerators] : defaultGenerators) as Array<\n Generator<any>\n >\n\n return { resolver, transformer, generators, preset }\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 { readSync } from '@internals/utils'\nimport * as pkg from 'empathic/package'\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 = pkg.up({ 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"],"x_google_ignoreList":[10,11],"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,QA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