@kubb/core 5.0.0-beta.37 → 5.0.0-beta.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{KubbDriver-CXoKVRxI.cjs → KubbDriver-BYBUfOZ8.cjs} +2 -11
- package/dist/KubbDriver-BYBUfOZ8.cjs.map +1 -0
- package/dist/{KubbDriver-CckeYpMG.js → KubbDriver-CyNF-NIb.js} +2 -11
- package/dist/KubbDriver-CyNF-NIb.js.map +1 -0
- package/dist/{diagnostics-B0ONXReg.d.ts → diagnostics-CYfKPtbU.d.ts} +28 -11
- package/dist/index.cjs +25 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +25 -7
- package/dist/index.js.map +1 -1
- package/dist/mocks.cjs +25 -2
- package/dist/mocks.cjs.map +1 -1
- package/dist/mocks.d.ts +1 -1
- package/dist/mocks.js +25 -2
- package/dist/mocks.js.map +1 -1
- package/package.json +4 -4
- package/src/KubbDriver.ts +3 -9
- package/src/createReporter.ts +44 -11
- package/src/mocks.ts +23 -2
- package/dist/KubbDriver-CXoKVRxI.cjs.map +0 -1
- package/dist/KubbDriver-CckeYpMG.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#userConfig","#storage","#driver","#config"],"sources":["../../../internals/utils/src/fs.ts","../src/createAdapter.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../src/createKubb.ts","../src/createReporter.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineMiddleware.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\n\n/**\n * Walks up the directory tree from `cwd` (defaults to `process.cwd()`) and\n * returns the absolute path of the nearest `package.json`, or `null` when none\n * is found before reaching the filesystem root.\n *\n * @example\n * ```ts\n * const pkgPath = findPackageJSON('/home/user/project/src') // '/home/user/project/package.json'\n * ```\n */\nexport function findPackageJSON(cwd?: string): string | null {\n let dir = cwd ? resolve(cwd) : process.cwd()\n while (true) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) return pkgPath\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Converts all backslashes to forward slashes.\n * Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n */\nfunction toSlash(p: string): string {\n if (p.startsWith('\\\\\\\\?\\\\')) return p\n return p.replaceAll('\\\\', '/')\n}\n\n/**\n * Returns the relative path from `rootDir` to `filePath`, always using forward slashes\n * and prefixed with `./` when not already traversing upward.\n *\n * @example\n * ```ts\n * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'\n * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'\n * ```\n */\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath))\n\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\n/**\n * Synchronous counterpart of `read`.\n *\n * @example\n * ```ts\n * const source = readSync('./src/Pet.ts')\n * ```\n */\nexport function readSync(path: string): string {\n return readFileSync(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (typeof Bun !== 'undefined') {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { ImportNode, InputNode, InputStreamNode, SchemaNode } from '@kubb/ast'\n\n/**\n * Source data handed to an adapter's `parse` function. Mirrors the config\n * input shape with paths resolved to absolute.\n *\n * - `{ type: 'path' }`: single file on disk.\n * - `{ type: 'paths' }`: multiple files (e.g. split spec).\n * - `{ type: 'data' }`: raw string or parsed object provided inline.\n */\nexport type AdapterSource = { type: 'path'; path: string } | { type: 'data'; data: string | unknown } | { type: 'paths'; paths: Array<string> }\n\n/**\n * Generic parameters used by `createAdapter` and the resulting `Adapter` type.\n *\n * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).\n * - `TOptions`: user-facing options accepted by the adapter factory.\n * - `TResolvedOptions`: options after defaults are applied.\n * - `TDocument`: type of the parsed source document.\n */\nexport type AdapterFactoryOptions<\n TName extends string = string,\n TOptions extends object = object,\n TResolvedOptions extends object = TOptions,\n TDocument = unknown,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n document: TDocument\n}\n\n/**\n * Converts input files or inline data into Kubb's universal AST `InputNode`.\n *\n * Adapters live between the spec format and the plugins. The built-in\n * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1; custom adapters can\n * support GraphQL, gRPC, AsyncAPI, or any domain-specific schema language.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n /**\n * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).\n */\n name: TOptions['name']\n /**\n * Resolved adapter options after defaults have been applied.\n */\n options: TOptions['resolvedOptions']\n /**\n * Parsed source document after the first `parse()` call. `null` before parsing.\n */\n document: TOptions['document'] | null\n /**\n * Parse the source into a universal `InputNode`.\n */\n parse: (source: AdapterSource) => PossiblePromise<InputNode>\n /**\n * Extract `ImportNode` entries for a schema tree.\n * Returns an empty array before the first `parse()` call.\n *\n * The `resolve` callback receives the collision-corrected schema name and must\n * return `{ name, path }` for the import, or `undefined` to skip it.\n */\n getImports: (node: SchemaNode, resolve: (schemaName: string) => { name: string; path: string }) => Array<ImportNode>\n /**\n * Validate the document at the given path or URL.\n */\n validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>\n /**\n * Memory-efficient streaming variant of `parse()`.\n *\n * Returns an `InputStreamNode` whose `schemas` and `operations` are `AsyncIterable`.\n * Each `for await` loop creates a fresh parse pass over the cached in-memory document.\n * No pre-built arrays are held in memory.\n */\n stream?: (source: AdapterSource) => Promise<InputStreamNode>\n}\n\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Defines a custom adapter that translates a spec format into Kubb's universal\n * AST. Use this when you need to consume GraphQL, gRPC, AsyncAPI, or another\n * domain-specific schema. Built-in adapters: `@kubb/adapter-oas` for\n * OpenAPI/Swagger documents.\n *\n * Adapters must return an `InputNode` from `parse`. That node is what every\n * plugin in the build consumes.\n *\n * @example\n * ```ts\n * import { createAdapter, ast, type AdapterFactoryOptions } from '@kubb/core'\n *\n * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>\n *\n * export const myAdapter = createAdapter<MyAdapter>((options) => ({\n * name: 'my-adapter',\n * options,\n * document: null,\n * async parse(_source) {\n * // Convert `source` (path or inline data) into an InputNode.\n * return ast.createInput()\n * },\n * getImports: () => [],\n * async validate() {\n * // Throw or call ctx.error here when the spec is invalid.\n * },\n * }))\n * ```\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","/**\n * Backend that persists generated files. Kubb ships with `fsStorage` (writes\n * to disk) and `memoryStorage` (keeps everything in RAM). Implement this\n * interface to write to S3, a database, or any other target.\n */\nexport type Storage = {\n /**\n * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Reads the stored string. Returns `null` when the key is missing.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Stores `value` under `key`, creating any required structure (directories,\n * buckets, ...).\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Deletes the entry for `key`. No-op when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns every key. Pass `base` to filter to keys starting with that prefix.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes every entry. Pass `base` to scope the wipe to a key prefix.\n */\n clear(base?: string): Promise<void>\n /**\n * Optional teardown hook called after the build completes. Use to flush\n * buffers, close connections, or release file locks.\n */\n dispose?(): Promise<void>\n}\n\n/**\n * Defines a custom storage backend. The builder receives user options and\n * returns a `Storage` implementation. Kubb ships with filesystem and\n * in-memory storages, reach for this when you need to write generated files\n * elsewhere (cloud storage, a database, a remote API).\n *\n * @example In-memory storage (the built-in implementation)\n * ```ts\n * import { createStorage } from '@kubb/core'\n *\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n *\n * return {\n * name: 'memory',\n * async hasItem(key) {\n * return store.has(key)\n * },\n * async getItem(key) {\n * return store.get(key) ?? null\n * },\n * async setItem(key, value) {\n * store.set(key, value)\n * },\n * async removeItem(key) {\n * store.delete(key)\n * },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) {\n * if (!base) store.clear()\n * },\n * }\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 the root config.\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 { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch (_error) {\n return false\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch (_error) {\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 resolvedBase = resolve(base ?? process.cwd())\n\n async function* walk(dir: string, prefix: string): AsyncGenerator<string, void, undefined> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, {\n withFileTypes: true,\n })) as Array<Dirent>\n } catch (_error) {\n return\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n yield* walk(join(dir, entry.name), rel)\n } else {\n yield rel\n }\n }\n }\n\n const keys: Array<string> = []\n for await (const key of walk(resolvedBase, '')) {\n keys.push(key)\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 { resolve } from 'node:path'\nimport type { PossiblePromise } from '@internals/utils'\nimport { AsyncEventEmitter, BuildError } from '@internals/utils'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode } from '@kubb/ast'\nimport { DEFAULT_STUDIO_URL, HOOK_LISTENERS_PER_PLUGIN } from './constants.ts'\nimport type { Adapter } from './createAdapter.ts'\nimport { type Diagnostic, DiagnosticError, Diagnostics, isProblemDiagnostic, type ProblemDiagnostic, type UpdateDiagnostic } from './diagnostics.ts'\nimport { createStorage, type Storage } from './createStorage.ts'\nimport type { GeneratorContext } from './defineGenerator.ts'\nimport type { Middleware } from './defineMiddleware.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { KubbPluginEndContext, KubbPluginSetupContext, KubbPluginStartContext, Plugin } from './definePlugin.ts'\nimport type { ReporterName } from './createReporter.ts'\n\nimport { KubbDriver } from './KubbDriver.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\n\n/**\n * Safely extracts a type from a registry, returning `{}` if the key doesn't exist.\n * Enables optional interface augmentation for `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`\n * without requiring changes to core.\n *\n * @internal\n */\ntype ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}\n\n/**\n * Path to an input file to generate from, absolute or relative to the config file. The adapter\n * parses it (e.g. an OpenAPI YAML or JSON spec) into the universal AST.\n */\nexport type InputPath = {\n /**\n * Path to your Swagger/OpenAPI file, absolute or relative to the config file location.\n *\n * @example\n * ```ts\n * { path: './petstore.yaml' }\n * { path: '/absolute/path/to/openapi.json' }\n * ```\n */\n path: string\n}\n\n/**\n * Inline spec to generate from, passed directly instead of read from a file. A string\n * (YAML/JSON) or a parsed object.\n */\nexport type InputData = {\n /**\n * Swagger/OpenAPI data as a string (YAML/JSON) or a parsed object.\n *\n * @example\n * ```ts\n * { data: fs.readFileSync('./openapi.yaml', 'utf8') }\n * { data: { openapi: '3.1.0', info: { ... } } }\n * ```\n */\n data: string | unknown\n}\n\ntype Input = InputPath | InputData\n\n/**\n * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to\n * write it (output), how (plugins, middleware), and the runtime pieces (parsers, storage). See\n * `UserConfig` for the relaxed form with defaults applied.\n *\n * @private\n */\nexport type Config<TInput = Input> = {\n /**\n * Display name for this configuration in CLI output and logs.\n * Useful when running multiple builds with `defineConfig` arrays.\n *\n * @example\n * ```ts\n * name: 'api-client'\n * ```\n */\n name?: string\n /**\n * Project root directory, absolute or relative to the config file. Already\n * resolved on the `Config` instance (see `UserConfig` for the optional\n * form that defaults to `process.cwd()`).\n */\n root: string\n /**\n * Parsers that convert generated files into strings. Each parser handles a\n * set of file extensions, and a fallback parser handles anything else.\n *\n * Already resolved on the `Config` instance (see `UserConfig` for the\n * optional form that defaults to `[parserTs, parserTsx, parserMd]`).\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { parserTs, parserTsx } from '@kubb/parser-ts'\n *\n * export default defineConfig({\n * parsers: [parserTs, parserTsx],\n * })\n * ```\n */\n parsers: Array<Parser>\n /**\n * Adapter that parses input files into the universal AST representation.\n * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.\n *\n * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files\n * injected via `injectFile` are written, but no AST walk occurs and generator hooks\n * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.\n *\n * @example\n * ```ts\n * import { adapterOas } from '@kubb/adapter-oas'\n * export default defineConfig({\n * adapter: adapterOas(),\n * input: { path: './petstore.yaml' },\n * })\n * ```\n */\n adapter?: Adapter\n /**\n * Source file or data to generate code from.\n * Use `input.path` for a file path or `input.data` for inline data.\n * Required when an adapter is configured. Omit it when running in plugin-only mode.\n */\n input?: TInput\n output: {\n /**\n * Output directory for generated files, absolute or relative to `root`. Plugins can nest\n * subdirectories under it by grouping strategy (tag, path).\n *\n * @example\n * ```ts\n * output: {\n * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.\n * }\n * ```\n */\n path: string\n /**\n * Remove every file in the output directory before the build, so stale output isn't mixed\n * with new files. Leave `false` to preserve manual edits in the output directory.\n *\n * @default false\n * @example\n * ```ts\n * clean: true // wipes ./src/gen/* before generating\n * ```\n */\n clean?: boolean\n /**\n * Format the generated files after generation. `'auto'` runs the first formatter it finds\n * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.\n *\n * @default false\n * @example\n * ```ts\n * format: 'auto' // auto-detect prettier, biome, or oxfmt\n * format: 'prettier' // force prettier\n * format: false // skip formatting\n * ```\n */\n format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false\n /**\n * Lint the generated files after generation. `'auto'` runs the first linter it finds\n * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.\n *\n * @default false\n * @example\n * ```ts\n * lint: 'auto' // auto-detect oxlint, biome, or eslint\n * lint: 'eslint' // force eslint\n * lint: false // skip linting\n * ```\n */\n lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false\n /**\n * Rewrite import extensions in generated files, e.g. emit `.js` imports from `.ts` sources for\n * ESM dual packages. Keys are the source extension, values the output, and `''` drops it.\n *\n * @default { '.ts': '.ts' }\n * @example\n * ```ts\n * extension: { '.ts': '.js' } // generates import './api.js' instead of './api.ts'\n * extension: { '.ts': '', '.tsx': '.jsx' }\n * ```\n */\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n /**\n * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds\n * source, title, description, and API version, and `false` omits it.\n *\n * @default 'simple'\n * @example\n * ```ts\n * defaultBanner: 'simple' // \"This file was autogenerated by Kubb\"\n * defaultBanner: 'full' // adds source, title, description, API version\n * defaultBanner: false // no banner\n * ```\n */\n defaultBanner?: 'simple' | 'full' | false\n /**\n * Overwrite existing files when `true`, skip files that already exist when `false`. Individual\n * plugins can override it. Keep `false` to avoid clobbering local edits in the output folder.\n *\n * @default false\n * @example\n * ```ts\n * override: true // regenerate everything, even existing files\n * override: false // skip files that already exist\n * ```\n */\n override?: boolean\n } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>\n /**\n * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`\n * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.\n *\n * @default fsStorage()\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n *\n * // Keep generated files in memory (useful for testing, CI pipelines)\n * storage: memoryStorage()\n *\n * // Use custom S3 storage\n * storage: myS3Storage()\n * ```\n *\n * @see {@link Storage} interface for implementing custom backends.\n */\n storage: Storage\n /**\n * Plugins that run during the build to generate code and transform the AST. Each one processes\n * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin\n * that depends on another throws when that plugin isn't registered.\n *\n * @example\n * ```ts\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * plugins: [\n * pluginTs({ output: { path: './src/gen' } }),\n * pluginZod({ output: { path: './src/gen' } }),\n * ]\n * ```\n */\n plugins: Array<Plugin>\n /**\n * Middleware instances that observe build events and post-process generated code.\n *\n * Middleware fires AFTER all plugins for each event. Perfect for tasks like:\n * - Auditing what was generated\n * - Adding barrel/index files\n * - Validating output\n * - Running custom transformations\n *\n * @example\n * ```ts\n * import { middlewareBarrel } from '@kubb/middleware-barrel'\n *\n * middleware: [middlewareBarrel()]\n * ```\n *\n * @see {@link defineMiddleware} to create custom middleware.\n */\n middleware?: Array<Middleware>\n /**\n * Kubb Studio cloud integration settings.\n *\n * Kubb Studio (https://kubb.studio) is a web-based IDE for managing API specs and generated code.\n * Set to `true` to enable with default settings, or pass an object to customize the Studio URL.\n *\n * @default false // disabled by default\n * @example\n * ```ts\n * devtools: true // use default Kubb Studio\n * devtools: { studioUrl: 'https://my-studio.dev' } // custom Studio instance\n * ```\n */\n devtools?:\n | true\n | {\n /**\n * Override the Kubb Studio base URL.\n * @default 'https://kubb.studio'\n */\n studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {})\n }\n /**\n * Lifecycle hooks that execute during or after the build process.\n *\n * Hooks allow you to run external tools (prettier, eslint, custom scripts) based on build events.\n * Currently supports the `done` hook which fires after all plugins and middleware complete.\n *\n * @example\n * ```ts\n * hooks: {\n * done: 'prettier --write \"./src/gen\"', // auto-format generated files\n * // or multiple commands:\n * done: ['prettier --write \"./src/gen\"', 'eslint --fix \"./src/gen\"']\n * }\n * ```\n */\n hooks?: {\n /**\n * Command(s) to run after all plugins and middleware complete generation.\n *\n * Useful for post-processing: formatting, linting, copying files, or custom validation.\n * Pass a single command string or array of command strings to run sequentially.\n * Commands are executed relative to the `root` directory.\n *\n * @example\n * ```ts\n * done: 'prettier --write \"./src/gen\"'\n * done: ['prettier --write \"./src/gen\"', 'eslint --fix \"./src/gen\"']\n * ```\n */\n done?: string | Array<string>\n }\n /**\n * Reporters that render the run's output, like Vitest. List one or more by name;\n * the CLI `--reporter` flag overrides this when set.\n *\n * - `cli` writes the end-of-run summary to the terminal.\n * - `json` writes a machine-readable report to stdout, for CI.\n * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.\n *\n * @default ['cli']\n *\n * @example\n * ```ts\n * reporters: ['cli', 'file']\n * ```\n */\n reporters?: Array<ReporterName>\n}\n\n/**\n * Partial `Config` for user-facing entry points with sensible defaults.\n *\n * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`\n * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,\n * `storage`, `middleware`, `devtools`, and `hooks`.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * input: { path: './petstore.yaml' },\n * output: { path: './src/gen' },\n * plugins: [pluginTs(), pluginZod()],\n * })\n * ```\n */\nexport type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage'> & {\n /**\n * Project root directory, absolute or relative to the config file location.\n * @default process.cwd()\n */\n root?: string\n /**\n * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).\n * @default [parserTs, parserTsx, parserMd] // applied by `defineConfig` from the `kubb` package\n */\n parsers?: Array<Parser>\n /**\n * Adapter that parses your API specification into Kubb's universal AST.\n * When omitted, Kubb runs in plugin-only mode.\n */\n adapter?: Adapter\n /**\n * Plugins that execute during the build to generate code and transform the AST.\n * @default []\n */\n plugins?: Array<Plugin>\n /**\n * Storage backend that controls where and how generated files are persisted.\n * @default fsStorage()\n */\n storage?: Storage\n}\n\ndeclare global {\n namespace Kubb {\n /**\n * Registry that maps plugin names to their `PluginFactoryOptions`.\n * Augment this interface in each plugin's `types.ts` to enable automatic\n * typing for `getPlugin` and `requirePlugin`.\n *\n * @example\n * ```ts\n * // packages/plugin-ts/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface PluginRegistry {\n * 'plugin-ts': PluginTs\n * }\n * }\n * }\n * ```\n */\n interface PluginRegistry {}\n\n /**\n * Extension point for root `Config['output']` options.\n * Augment the `output` key in middleware or plugin packages to add extra fields\n * to the global output configuration without touching core types.\n *\n * @example\n * ```ts\n * // packages/middleware-barrel/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface ConfigOptionsRegistry {\n * output: {\n * barrel?: import('./types.ts').BarrelConfig | false\n * }\n * }\n * }\n * }\n * ```\n */\n interface ConfigOptionsRegistry {}\n\n /**\n * Extension point for per-plugin `Output` options.\n * Augment the `output` key in middleware or plugin packages to add extra fields\n * to the per-plugin output configuration without touching core types.\n *\n * @example\n * ```ts\n * // packages/middleware-barrel/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface PluginOptionsRegistry {\n * output: {\n * barrel?: import('./types.ts').PluginBarrelConfig | false\n * }\n * }\n * }\n * }\n * ```\n */\n interface PluginOptionsRegistry {}\n }\n}\n\n/**\n * Lifecycle events emitted during Kubb code generation.\n * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.\n *\n * @example\n * ```ts\n * kubb.hooks.on('kubb:lifecycle:start', () => {\n * console.log('Starting Kubb generation')\n * })\n *\n * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {\n * console.log(`${plugin.name} completed in ${duration}ms`)\n * })\n * ```\n */\nexport interface KubbHooks {\n 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext]\n 'kubb:lifecycle:end': []\n 'kubb:config:start': []\n 'kubb:config:end': [ctx: KubbConfigEndContext]\n 'kubb:generation:start': [ctx: KubbGenerationStartContext]\n 'kubb:generation:end': [ctx: KubbGenerationEndContext]\n 'kubb:format:start': []\n 'kubb:format:end': []\n 'kubb:lint:start': []\n 'kubb:lint:end': []\n 'kubb:hooks:start': []\n 'kubb:hooks:end': []\n 'kubb:hook:start': [ctx: KubbHookStartContext]\n 'kubb:hook:end': [ctx: KubbHookEndContext]\n 'kubb:info': [ctx: KubbInfoContext]\n 'kubb:error': [ctx: KubbErrorContext]\n 'kubb:success': [ctx: KubbSuccessContext]\n 'kubb:warn': [ctx: KubbWarnContext]\n 'kubb:diagnostic': [ctx: KubbDiagnosticContext]\n 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext]\n 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext]\n 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext]\n 'kubb:plugin:start': [ctx: KubbPluginStartContext]\n 'kubb:plugin:end': [ctx: KubbPluginEndContext]\n 'kubb:plugin:setup': [ctx: KubbPluginSetupContext]\n 'kubb:build:start': [ctx: KubbBuildStartContext]\n 'kubb:plugins:end': [ctx: KubbPluginsEndContext]\n 'kubb:build:end': [ctx: KubbBuildEndContext]\n 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext]\n 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext]\n 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext]\n}\n\nexport type KubbBuildStartContext = {\n /**\n * Resolved configuration for this build.\n */\n config: Config\n /**\n * Adapter that parsed the input into the universal AST.\n */\n adapter: Adapter\n /**\n * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).\n * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.\n */\n meta: InputMeta | undefined\n /**\n * Looks up a registered plugin by name, typed by the plugin registry.\n */\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n /**\n * Snapshot of all files accumulated so far.\n */\n readonly files: ReadonlyArray<FileNode>\n /**\n * Adds or merges one or more files into the file manager.\n */\n upsertFile: (...files: Array<FileNode>) => void\n}\n\nexport type KubbPluginsEndContext = {\n /**\n * Resolved configuration for this build.\n */\n config: Config\n /**\n * Snapshot of all files accumulated across all plugins.\n */\n readonly files: ReadonlyArray<FileNode>\n /**\n * Adds or merges one or more files into the file manager.\n */\n upsertFile: (...files: Array<FileNode>) => void\n}\n\nexport type KubbBuildEndContext = {\n /**\n * All files generated during this build.\n */\n files: Array<FileNode>\n /**\n * Resolved configuration for this build.\n */\n config: Config\n /**\n * Absolute path to the output directory.\n */\n outputDir: string\n}\n\nexport type KubbLifecycleStartContext = {\n /**\n * Current Kubb version string.\n */\n version: string\n}\n\nexport type KubbConfigEndContext = {\n /**\n * All resolved configs after defaults are applied.\n */\n configs: Array<Config>\n}\n\nexport type KubbGenerationStartContext = {\n /**\n * Resolved configuration for this generation run.\n */\n config: Config\n}\n\nexport type KubbGenerationEndContext = {\n /**\n * Resolved configuration for this generation run.\n */\n config: Config\n /**\n * Read-only view of the files written during this build.\n * Reads go directly to `config.storage`, nothing extra is held in memory.\n *\n * @example Read a generated file\n * `const code = await storage.getItem('/src/gen/pet.ts')`\n *\n * @example Walk every generated file\n * ```ts\n * for (const path of await storage.getKeys()) {\n * const code = await storage.getItem(path)\n * }\n * ```\n */\n storage: Storage\n /**\n * Diagnostics collected during the build: error/warning/info problems plus a\n * `timing` diagnostic per plugin. The end-of-run summary derives its failure counts\n * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.\n */\n diagnostics?: Array<Diagnostic>\n /**\n * `'success'` when all plugins completed without errors, `'failed'` otherwise.\n */\n status?: 'success' | 'failed'\n /**\n * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.\n */\n hrStart?: [number, number]\n /**\n * Total number of files created during this run.\n */\n filesCreated?: number\n}\n\nexport type KubbInfoContext = {\n /**\n * Human-readable info message.\n */\n message: string\n /**\n * Optional supplementary detail.\n */\n info?: string\n}\n\nexport type KubbErrorContext = {\n /**\n * The caught error.\n */\n error: Error\n /**\n * Optional structured metadata for additional context.\n */\n meta?: Record<string, unknown>\n}\n\nexport type KubbSuccessContext = {\n /**\n * Human-readable success message.\n */\n message: string\n /**\n * Optional supplementary detail.\n */\n info?: string\n}\n\nexport type KubbWarnContext = {\n /**\n * Human-readable warning message.\n */\n message: string\n /**\n * Optional supplementary detail.\n */\n info?: string\n}\n\nexport type KubbDiagnosticContext = {\n /**\n * The structured diagnostic to render: a build problem or a version-update notice.\n */\n diagnostic: ProblemDiagnostic | UpdateDiagnostic\n}\n\nexport type KubbFilesProcessingStartContext = {\n /**\n * Files about to be serialised and written.\n */\n files: Array<FileNode>\n}\n\nexport type KubbFileProcessingUpdate = {\n /**\n * Number of files processed so far in this batch.\n */\n processed: number\n /**\n * Total number of files in this batch.\n */\n total: number\n /**\n * Completion percentage, `0` to `100`.\n */\n percentage: number\n /**\n * Serialised file content, or `undefined` when the file produced no output.\n */\n source?: string\n /**\n * The file that was just processed.\n */\n file: FileNode\n /**\n * Resolved configuration for this build.\n */\n config: Config\n}\n\nexport type KubbFilesProcessingUpdateContext = {\n /**\n * All files processed in this flush chunk.\n */\n files: Array<KubbFileProcessingUpdate>\n}\n\nexport type KubbFilesProcessingEndContext = {\n /**\n * All files that were serialised in this batch.\n */\n files: Array<FileNode>\n}\n\nexport type KubbHookStartContext = {\n /**\n * Optional identifier for correlating start/end events.\n */\n id?: string\n /**\n * The shell command that is about to run.\n */\n command: string\n /**\n * Parsed argument list, when available.\n */\n args?: ReadonlyArray<string>\n}\n\nexport type KubbHookEndContext = {\n /**\n * Optional identifier matching the corresponding `kubb:hook:start` event.\n */\n id?: string\n /**\n * The shell command that ran.\n */\n command: string\n /**\n * Parsed argument list, when available.\n */\n args?: ReadonlyArray<string>\n /**\n * `true` when the command exited with code `0`.\n */\n success: boolean\n /**\n * Error thrown by the command, or `null` on success.\n */\n error: Error | null\n}\n\n/**\n * CLI options derived from command-line flags.\n */\nexport type CLIOptions = {\n /**\n * Path to the Kubb config file.\n */\n config?: string\n /**\n * OpenAPI input path passed as the positional argument to `kubb generate`.\n * Overrides `config.input.path` when set.\n */\n input?: string\n /**\n * Re-run generation whenever input files change.\n */\n watch?: boolean\n /**\n * Controls how much output the CLI prints.\n *\n * @default 'info'\n */\n logLevel?: 'silent' | 'info' | 'verbose'\n /**\n * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.\n */\n reporters?: Array<ReporterName>\n}\n\n/**\n * All accepted forms of a Kubb configuration.\n * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`.\n */\nexport type PossibleConfig<TCliOptions = undefined> =\n | PossiblePromise<Config | Array<Config>>\n | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>)\n\n/**\n * Full output produced by a successful or failed build.\n */\nexport type BuildOutput = {\n /**\n * Structured diagnostics collected during the build: error/warning/info problems\n * (each with a code, severity, and where known a JSON-pointer location) plus a\n * `timing` diagnostic per plugin. Includes a top-level diagnostic when the build\n * threw before completing. Use {@link Diagnostics.hasError} to test for failure.\n */\n diagnostics: Array<Diagnostic>\n /**\n * All files generated during this build.\n */\n files: Array<FileNode>\n /**\n * The plugin driver that orchestrated this build.\n */\n driver: KubbDriver\n /**\n * Read-only view of every file written during this build.\n * Reads go straight to `config.storage`, nothing extra is held in memory.\n *\n * @example Read a generated file\n * `const code = await buildOutput.storage.getItem('/src/gen/pet.ts')`\n *\n * @example List all generated file paths\n * `const paths = await buildOutput.storage.getKeys()`\n */\n storage: Storage\n}\n\n/**\n * Builds a `Storage` view scoped to the file paths produced by the current build.\n * Reads delegate to the underlying `storage` so source bytes stay where they were\n * written. Writes register the key so subsequent reads and `getKeys` are scoped\n * to this build's output.\n */\nfunction createSourcesView(storage: Storage): Storage {\n const paths = new Set<string>()\n\n return createStorage(() => ({\n name: `${storage.name}:sources`,\n async hasItem(key: string) {\n return paths.has(key) && (await storage.hasItem(key))\n },\n async getItem(key: string) {\n return paths.has(key) ? storage.getItem(key) : null\n },\n async setItem(key: string, value: string) {\n paths.add(key)\n await storage.setItem(key, value)\n },\n async removeItem(key: string) {\n paths.delete(key)\n await storage.removeItem(key)\n },\n async getKeys(base?: string) {\n if (!base) return [...paths]\n const result: Array<string> = []\n for (const key of paths) {\n if (key.startsWith(base)) result.push(key)\n }\n return result\n },\n async clear() {\n paths.clear()\n await storage.clear()\n },\n }))()\n}\n\nfunction resolveConfig(userConfig: UserConfig): Config {\n return {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n output: {\n format: false,\n lint: false,\n extension: { '.ts': '.ts' },\n defaultBanner: 'simple',\n ...userConfig.output,\n },\n storage: userConfig.storage ?? fsStorage(),\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: userConfig.plugins ?? [],\n }\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> & { input: InputPath }\nexport function isInputPath(config: Config | undefined): config is Config<InputPath> & { input: InputPath }\nexport function isInputPath(config: Config | UserConfig | undefined): config is (Config<InputPath> | UserConfig<InputPath>) & { input: InputPath } {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n\ntype CreateKubbOptions = {\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Kubb code-generation instance bound to a single config entry. Resolves the user\n * config during `setup()` and shares `hooks`, `storage`, `driver`, and `config` across\n * the `setup → build` lifecycle.\n *\n * Attach event listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))\n * const { files, diagnostics } = await kubb.safeBuild()\n * ```\n */\nexport class Kubb {\n readonly hooks: AsyncEventEmitter<KubbHooks>\n readonly #userConfig: UserConfig\n #config: Config | null = null\n #driver: KubbDriver | null = null\n #storage: Storage | null = null\n\n constructor(userConfig: UserConfig, options: CreateKubbOptions = {}) {\n this.#userConfig = userConfig\n this.hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n }\n\n get storage(): Storage {\n if (!this.#storage) throw new Error('[kubb] setup() must be called before accessing storage')\n return this.#storage\n }\n\n get driver(): KubbDriver {\n if (!this.#driver) throw new Error('[kubb] setup() must be called before accessing driver')\n return this.#driver\n }\n\n get config(): Config {\n if (!this.#config) throw new Error('[kubb] setup() must be called before accessing config')\n return this.#config\n }\n\n /**\n * Resolves config and initializes the driver. `build()` calls this automatically.\n */\n async setup(): Promise<void> {\n const config = resolveConfig(this.#userConfig)\n const driver = new KubbDriver(config, { hooks: this.hooks })\n const storage = createSourcesView(config.storage)\n\n // Each generator a plugin registers adds a listener to the shared hooks emitter, so size the\n // ceiling to the plugin count. Without this, a multi-generator plugin set trips Node's\n // EventEmitter leak warning at the default 10.\n this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN))\n\n if (config.output.clean) {\n await config.storage.clear(resolve(config.root, config.output.path))\n }\n\n await driver.setup()\n\n this.#config = config\n this.#driver = driver\n this.#storage = storage\n }\n\n /**\n * Runs the full pipeline and throws on any plugin error.\n * Automatically calls `setup()` if needed.\n */\n async build(): Promise<BuildOutput> {\n const out = await this.safeBuild()\n if (Diagnostics.hasError(out.diagnostics)) {\n const errors = out.diagnostics\n .filter(isProblemDiagnostic)\n .filter((diagnostic) => diagnostic.severity === 'error')\n .map((diagnostic) => diagnostic.cause ?? new DiagnosticError(diagnostic))\n throw new BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? 'error' : 'errors'}`, { errors })\n }\n return out\n }\n\n /**\n * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.\n * Automatically calls `setup()` if needed.\n */\n async safeBuild(): Promise<BuildOutput> {\n if (!this.#driver) await this.setup()\n using cleanup = this\n const driver = cleanup.driver\n const storage = cleanup.storage\n const { diagnostics } = await driver.run({ storage })\n\n return { diagnostics, files: driver.fileManager.files, driver, storage }\n }\n\n dispose(): void {\n this.#driver?.dispose()\n }\n\n [Symbol.dispose](): void {\n this.dispose()\n }\n}\n\n/**\n * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent\n * to `new Kubb(userConfig, options)` and the canonical public entry point.\n *\n * @example\n * ```ts\n * import { createKubb } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * const kubb = createKubb({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n *\n * await kubb.build()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n return new Kubb(userConfig, options)\n}\n","import type { logLevel } from './constants.ts'\nimport type { Config } from './createKubb.ts'\nimport type { Diagnostic } from './diagnostics.ts'\n\n/**\n * A built-in reporter that renders a run's output, independent of the live logger view.\n *\n * - `cli` renders the per-config summary to the terminal (the default).\n * - `json` writes a machine-readable report to stdout, for CI.\n * - `file` writes a config's diagnostics to `.kubb/kubb-<name>-<timestamp>.log`.\n */\nexport type ReporterName = 'cli' | 'json' | 'file'\n\n/**\n * One config's outcome within a run, as handed to a {@link Reporter}.\n */\nexport type GenerationResult = {\n config: Config\n /**\n * Diagnostics collected while generating this config.\n */\n diagnostics: Array<Diagnostic>\n /**\n * Number of files written for this config.\n */\n filesCreated: number\n status: 'success' | 'failed'\n /**\n * `process.hrtime()` snapshot taken when this config started generating.\n */\n hrStart: [number, number]\n}\n\n/**\n * Render context passed alongside the {@link GenerationResult}, carrying knobs a reporter needs\n * but that are not part of the run data (e.g. verbosity).\n */\nexport type ReporterContext = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`, `debug`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Reporter contract. Unlike a Logger (the live TUI view), a reporter never sees the event\n * emitter. `report` is called once per config with its {@link GenerationResult} and produces\n * output (a terminal summary, a JSON report, a log file).\n */\nexport type Reporter = {\n /**\n * Display name, matching a {@link ReporterName} for the built-ins.\n */\n name: string\n /**\n * Called once per config with that config's result and the render context.\n */\n report: (result: GenerationResult, context: ReporterContext) => void | Promise<void>\n}\n\nexport type UserReporter = Reporter\n\n/**\n * Defines a reporter. Returns the reporter unchanged at runtime. It exists for type inference and\n * to mark the value as a reporter, mirroring {@link defineLogger}. Wiring the reporter onto the\n * run's events is the host's job, so the reporter only ever deals with a {@link GenerationResult}.\n *\n * @example\n * ```ts\n * import { createReporter, Diagnostics } from '@kubb/core'\n *\n * export const jsonReporter = createReporter({\n * name: 'json',\n * report(result) {\n * const status = Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success'\n * process.stdout.write(`${JSON.stringify({ status, diagnostics: result.diagnostics }, null, 2)}\\n`)\n * },\n * })\n * ```\n */\nexport function createReporter(reporter: UserReporter): Reporter {\n return reporter\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * `TElement` is the type the renderer accepts, for example `KubbReactElement`\n * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to\n * `unknown` so generators that don't care about the element type work without\n * specifying it.\n */\nexport type Renderer<TElement = unknown> = {\n /**\n * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.\n * Called once per render cycle. Must resolve before {@link files} is read.\n */\n render(element: TElement): Promise<void>\n /**\n * Tears down the renderer and releases any held resources.\n * Pass an `Error` to signal a failure, a number for an exit code, or omit for a clean shutdown.\n */\n unmount(error?: Error | number | null): void\n /**\n * Releases any held resources. `[Symbol.dispose]` delegates here.\n */\n dispose(): void\n /**\n * Accumulated {@link FileNode} results produced by the last {@link render} call.\n * Not populated when {@link stream} is implemented.\n */\n readonly files: Array<FileNode>\n /**\n * When present, core calls this instead of {@link render} and {@link files},\n * forwarding each file to `FileManager` as soon as it is ready.\n */\n stream?(element: TElement): Iterable<FileNode>\n /**\n * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`\n * guarantees {@link dispose} runs on every exit path, including thrown errors.\n */\n [Symbol.dispose](): void\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render cycle.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Defines a renderer factory. Renderers turn the generator's return value\n * (JSX, a template string, a tree of any shape) into `FileNode`s that get\n * written to disk.\n *\n * Use this to support output formats beyond JSX, for instance, a Handlebars\n * renderer, a string-template renderer, or a renderer that writes binary\n * files. Plugins and generators pick the renderer to use via the `renderer`\n * field on `defineGenerator`.\n *\n * @example A minimal renderer that wraps a custom runtime\n * ```ts\n * import { createRenderer } from '@kubb/core'\n *\n * export const myRenderer = createRenderer(() => {\n * const runtime = new MyRuntime()\n * return {\n * async render(element) {\n * await runtime.render(element)\n * },\n * get files() {\n * return runtime.files\n * },\n * dispose() {\n * runtime.dispose()\n * },\n * unmount(error) {\n * runtime.dispose(error)\n * },\n * [Symbol.dispose]() {\n * this.dispose()\n * },\n * }\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { AsyncEventEmitter, PossiblePromise } from '@internals/utils'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport type { Adapter } from './createAdapter.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { Plugin, PluginFactoryOptions } from './definePlugin.ts'\nimport type { Resolver } from './defineResolver.ts'\nimport type { Config, DevtoolsOptions } from './types.ts'\n\n/**\n * Context object passed to generator `schema`, `operation`, and `operations` methods.\n *\n * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks\n * are needed. `ctx.options` carries resolved per-node options after exclude/include/override\n * filtering for individual schema/operation calls, or plugin-level options for operations.\n */\nexport type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n /**\n * Absolute path to the current plugin's output directory.\n */\n root: string\n /**\n * Determine output mode based on the output config.\n * Returns `'single'` when `output.path` is a file, `'split'` for a directory.\n */\n getMode: (output: { path: string }) => 'single' | 'split'\n driver: KubbDriver\n /**\n * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.\n */\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n /**\n * Get a plugin by name, throws an error if not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin(name: string): Plugin\n /**\n * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.\n */\n getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']\n getResolver(name: string): Resolver\n /**\n * Add files only if they don't exist.\n */\n addFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * Merge sources into the same output file.\n */\n upsertFile: (...file: Array<FileNode>) => Promise<void>\n hooks: AsyncEventEmitter<KubbHooks>\n /**\n * The current plugin instance.\n */\n plugin: Plugin<TOptions>\n /**\n * The current plugin's resolver.\n */\n resolver: TOptions['resolver']\n /**\n * The current plugin's transformer.\n */\n transformer: Visitor | undefined\n /**\n * Report a warning. Collected as a `warning` diagnostic attributed to the current\n * plugin. It surfaces in the run summary but does not fail the build. For a structured\n * diagnostic with a code and source location, use `Diagnostics.report` or throw a\n * `DiagnosticError` directly.\n */\n warn: (message: string) => void\n /**\n * Report an error. Collected as an `error` diagnostic attributed to the current\n * plugin, which fails the build.\n */\n error: (error: string | Error) => void\n /**\n * Report an informational message. Collected as an `info` diagnostic attributed to\n * the current plugin.\n */\n info: (message: string) => void\n /**\n * Open the current input node in Kubb Studio.\n */\n openInStudio: (options?: DevtoolsOptions) => Promise<void>\n /**\n * The configured adapter instance.\n */\n adapter: Adapter\n /**\n * Document metadata from the adapter: title, version, base URL, and pre-computed\n * schema index fields (`circularNames`, `enumNames`).\n */\n meta: InputMeta\n /**\n * Resolved options after exclude/include/override filtering.\n */\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Declares a named generator unit that walks the AST and emits files.\n *\n * Each method (`schema`, `operation`, `operations`) is called for the matching node type.\n * Each method returns `TElement | Array<FileNode> | undefined | null`. JSX-based generators require a `renderer` factory.\n * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `undefined` or `null` to bypass rendering.\n *\n * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.\n *\n * @example\n * ```ts\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Leave it unset or set `renderer: null` to opt out of rendering.\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n}\n\n/**\n * Defines a generator: a unit of work that runs during the plugin's AST walk\n * and produces files. Plugins register generators via `ctx.addGenerator()`\n * inside `kubb:plugin:setup`.\n *\n * The returned object is the input as-is, but with `this` types preserved so\n * `schema`/`operation`/`operations` methods are correctly typed against the\n * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns\n * are both handled by the runtime, so pick whichever style fits.\n *\n * @example JSX-based schema generator\n * ```tsx\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * return (\n * <File path={`${ctx.root}/${node.name}.ts`}>\n * <Type node={node} resolver={ctx.resolver} />\n * </File>\n * )\n * },\n * })\n * ```\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { AsyncEventEmitter } from '@internals/utils'\nimport type { logLevel } from './constants.ts'\nimport type { KubbHooks } from './types.ts'\n\n/**\n * Options accepted by a logger's `install` callback.\n */\nexport type LoggerOptions = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`, `debug`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Event emitter handed to `Logger.install`. Use `.on('kubb:info', ...)` and\n * friends to subscribe to build events.\n */\nexport type LoggerContext = AsyncEventEmitter<KubbHooks>\n\n/**\n * Logger contract. A logger receives the build's event emitter and subscribes\n * to whichever lifecycle events it wants to forward to its destination\n * (console, file, remote sink).\n */\nexport type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {\n /**\n * Display name used in diagnostics.\n */\n name: string\n /**\n * Called once per build with the shared event emitter. Subscribe to events\n * here. The return value (if any) is forwarded to whoever installed the\n * logger, which is handy for sink factories.\n */\n install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>\n}\n\nexport type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>\n\n/**\n * Defines a typed logger. Use the second type parameter to declare a return\n * value from `install`, which is handy when the logger exposes a sink factory\n * or cleanup callback to the caller.\n *\n * @example Basic logger\n * ```ts\n * import { defineLogger } from '@kubb/core'\n *\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context) {\n * context.on('kubb:info', ({ message }) => console.log('ℹ', message))\n * context.on('kubb:error', ({ error }) => console.error('✗', error.message))\n * },\n * })\n * ```\n *\n * @example Logger that returns a hook sink factory\n * ```ts\n * import { defineLogger, type LoggerOptions } from '@kubb/core'\n * import type { HookSinkFactory } from './sinks'\n *\n * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({\n * name: 'my-logger',\n * install(context) {\n * // … register event handlers …\n * return () => ({ onStdout: console.log })\n * },\n * })\n * ```\n */\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions, TInstallReturn = void>(\n logger: UserLogger<Options, TInstallReturn>,\n): Logger<Options, TInstallReturn> {\n return logger\n}\n","import type { KubbHooks } from './types.ts'\n\n/**\n * A middleware instance. Subscribes to lifecycle events via `hooks`. Middleware\n * handlers always fire after every plugin handler for the same event, so they\n * see the full set of generated files.\n */\nexport type Middleware = {\n /**\n * Unique name. Use a `middleware-<feature>` convention (e.g.\n * `middleware-barrel`).\n */\n name: string\n /**\n * Lifecycle event handlers. Any event from the global `KubbHooks` map can be\n * subscribed to here. Handlers run after all plugin handlers for that event.\n */\n hooks: {\n [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void>\n }\n}\n\n/**\n * Creates a middleware factory. Middleware fires after every plugin handler\n * for the same event, which makes it the natural place for post-processing\n * (barrel files, lint runs, audit logs).\n *\n * Per-build state belongs inside the factory closure so each `createKubb`\n * invocation gets its own isolated instance.\n *\n * @example Stateless middleware\n * ```ts\n * import { defineMiddleware } from '@kubb/core'\n *\n * export const logMiddleware = defineMiddleware(() => ({\n * name: 'log-middleware',\n * hooks: {\n * 'kubb:build:end'({ files }) {\n * console.log(`Build complete with ${files.length} files`)\n * },\n * },\n * }))\n * ```\n *\n * @example Middleware with options and per-build state\n * ```ts\n * import { defineMiddleware } from '@kubb/core'\n *\n * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {\n * const seen = new Set<string>()\n * return {\n * name: 'prefix-middleware',\n * hooks: {\n * 'kubb:plugin:end'({ plugin }) {\n * seen.add(`${options.prefix}${plugin.name}`)\n * },\n * },\n * }\n * })\n * ```\n */\nexport function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware {\n return (options) => factory(options ?? ({} as TOptions))\n}\n","import type { FileNode } from '@kubb/ast'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\n/**\n * Converts a resolved {@link FileNode} into the final source string that gets\n * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own\n * for new file types (JSON, Markdown, ...).\n */\nexport type Parser<TMeta extends object = object, TNode = unknown> = {\n /**\n * Display name used in diagnostics and the parser registry.\n */\n name: string\n /**\n * File extensions this parser handles. Set to `undefined` to define a\n * catch-all fallback used when no other parser claims the extension.\n *\n * @example\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Serialise the file's AST into source code.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): string\n /**\n * Render compiler AST nodes for this parser's language into source text.\n * Plugins call this to format the nodes they assemble before handing them\n * back to the parser as `FileNode.sources`.\n */\n print(...nodes: Array<TNode>): string\n}\n\n/**\n * Defines a parser with type-safe `this`. Used to register handlers for new\n * file extensions or to plug a non-TypeScript output into the build.\n *\n * @example\n * ```ts\n * import { defineParser, ast } from '@kubb/core'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * return file.sources\n * .map((source) => ast.extractStringsFromNodes(source.nodes ?? []))\n * .join('\\n')\n * },\n * print(...nodes) {\n * return nodes.map(String).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<T extends Parser>(parser: T): T {\n return parser\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4HA,eAAsB,MAAM,MAAc,MAAc,UAAwB,CAAC,GAA2B;CAC1G,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,YAAY,IAAI,OAAO;CAE3B,MAAM,WAAW,QAAQ,IAAI;CAE7B,IAAI,OAAO,QAAQ,aAAa;EAC9B,MAAM,OAAO,IAAI,KAAK,QAAQ;EAE9B,KADoB,MAAM,KAAK,OAAO,IAAK,MAAM,KAAK,KAAK,IAAI,UAC5C,SAAS,OAAO;EACnC,MAAM,IAAI,MAAM,UAAU,OAAO;EACjC,OAAO;CACT;CAEA,IAAI;EAEF,IAAI,MADqB,SAAS,UAAU,EAAE,UAAU,QAAQ,CAAC,MAC9C,SAAS,OAAO;CACrC,QAAQ,CAER;CAEA,MAAM,MAAM,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CAClD,MAAM,UAAU,UAAU,SAAS,EAAE,UAAU,QAAQ,CAAC;CAExD,IAAI,QAAQ,QAAQ;EAClB,MAAM,YAAY,MAAM,SAAS,UAAU,EAAE,UAAU,QAAQ,CAAC;EAChE,IAAI,cAAc,SAChB,MAAM,IAAI,MAAM,2BAA2B,KAAK,WAAW,KAAK,OAAO,MAAM,KAAK,YAAY,UAAU,OAAO,MAAM,UAAU,GAAG;EAEpI,OAAO;CACT;CAEA,OAAO;AACT;;;;;;;;;AAUA,eAAsB,MAAM,MAA6B;CACvD,OAAO,GAAG,MAAM;EAAE,WAAW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,QAAQ,YAAY,QAAQ,WAAY,CAAC,CAAc;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;ACLA,SAAgB,aAA+B,QAAc;CAC3D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;ACvCA,MAAa,gBAAgB,oBAAoB;CAC/C,MAAM,wBAAQ,IAAI,IAAoB;CAEtC,OAAO;EACL,MAAM;EACN,MAAM,QAAQ,KAAa;GACzB,OAAO,MAAM,IAAI,GAAG;EACtB;EACA,MAAM,QAAQ,KAAa;GACzB,OAAO,MAAM,IAAI,GAAG,KAAK;EAC3B;EACA,MAAM,QAAQ,KAAa,OAAe;GACxC,MAAM,IAAI,KAAK,KAAK;EACtB;EACA,MAAM,WAAW,KAAa;GAC5B,MAAM,OAAO,GAAG;EAClB;EACA,MAAM,QAAQ,MAAe;GAC3B,MAAM,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC;GAC7B,OAAO,OAAO,KAAK,QAAQ,MAAM,EAAE,WAAW,IAAI,CAAC,IAAI;EACzD;EACA,MAAM,MAAM,MAAe;GACzB,IAAI,CAAC,MAAM;IACT,MAAM,MAAM;IACZ;GACF;GACA,KAAK,MAAM,OAAO,MAAM,KAAK,GAC3B,IAAI,IAAI,WAAW,IAAI,GACrB,MAAM,OAAO,GAAG;EAGtB;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#userConfig","#storage","#driver","#config"],"sources":["../../../internals/utils/src/fs.ts","../src/createAdapter.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../src/createKubb.ts","../src/createReporter.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineMiddleware.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\n\n/**\n * Walks up the directory tree from `cwd` (defaults to `process.cwd()`) and\n * returns the absolute path of the nearest `package.json`, or `null` when none\n * is found before reaching the filesystem root.\n *\n * @example\n * ```ts\n * const pkgPath = findPackageJSON('/home/user/project/src') // '/home/user/project/package.json'\n * ```\n */\nexport function findPackageJSON(cwd?: string): string | null {\n let dir = cwd ? resolve(cwd) : process.cwd()\n while (true) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) return pkgPath\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Converts all backslashes to forward slashes.\n * Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n */\nfunction toSlash(p: string): string {\n if (p.startsWith('\\\\\\\\?\\\\')) return p\n return p.replaceAll('\\\\', '/')\n}\n\n/**\n * Returns the relative path from `rootDir` to `filePath`, always using forward slashes\n * and prefixed with `./` when not already traversing upward.\n *\n * @example\n * ```ts\n * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'\n * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'\n * ```\n */\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath))\n\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\n/**\n * Synchronous counterpart of `read`.\n *\n * @example\n * ```ts\n * const source = readSync('./src/Pet.ts')\n * ```\n */\nexport function readSync(path: string): string {\n return readFileSync(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (typeof Bun !== 'undefined') {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { ImportNode, InputNode, InputStreamNode, SchemaNode } from '@kubb/ast'\n\n/**\n * Source data handed to an adapter's `parse` function. Mirrors the config\n * input shape with paths resolved to absolute.\n *\n * - `{ type: 'path' }`: single file on disk.\n * - `{ type: 'paths' }`: multiple files (e.g. split spec).\n * - `{ type: 'data' }`: raw string or parsed object provided inline.\n */\nexport type AdapterSource = { type: 'path'; path: string } | { type: 'data'; data: string | unknown } | { type: 'paths'; paths: Array<string> }\n\n/**\n * Generic parameters used by `createAdapter` and the resulting `Adapter` type.\n *\n * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).\n * - `TOptions`: user-facing options accepted by the adapter factory.\n * - `TResolvedOptions`: options after defaults are applied.\n * - `TDocument`: type of the parsed source document.\n */\nexport type AdapterFactoryOptions<\n TName extends string = string,\n TOptions extends object = object,\n TResolvedOptions extends object = TOptions,\n TDocument = unknown,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n document: TDocument\n}\n\n/**\n * Converts input files or inline data into Kubb's universal AST `InputNode`.\n *\n * Adapters live between the spec format and the plugins. The built-in\n * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1; custom adapters can\n * support GraphQL, gRPC, AsyncAPI, or any domain-specific schema language.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n /**\n * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).\n */\n name: TOptions['name']\n /**\n * Resolved adapter options after defaults have been applied.\n */\n options: TOptions['resolvedOptions']\n /**\n * Parsed source document after the first `parse()` call. `null` before parsing.\n */\n document: TOptions['document'] | null\n /**\n * Parse the source into a universal `InputNode`.\n */\n parse: (source: AdapterSource) => PossiblePromise<InputNode>\n /**\n * Extract `ImportNode` entries for a schema tree.\n * Returns an empty array before the first `parse()` call.\n *\n * The `resolve` callback receives the collision-corrected schema name and must\n * return `{ name, path }` for the import, or `undefined` to skip it.\n */\n getImports: (node: SchemaNode, resolve: (schemaName: string) => { name: string; path: string }) => Array<ImportNode>\n /**\n * Validate the document at the given path or URL.\n */\n validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>\n /**\n * Memory-efficient streaming variant of `parse()`.\n *\n * Returns an `InputStreamNode` whose `schemas` and `operations` are `AsyncIterable`.\n * Each `for await` loop creates a fresh parse pass over the cached in-memory document.\n * No pre-built arrays are held in memory.\n */\n stream?: (source: AdapterSource) => Promise<InputStreamNode>\n}\n\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Defines a custom adapter that translates a spec format into Kubb's universal\n * AST. Use this when you need to consume GraphQL, gRPC, AsyncAPI, or another\n * domain-specific schema. Built-in adapters: `@kubb/adapter-oas` for\n * OpenAPI/Swagger documents.\n *\n * Adapters must return an `InputNode` from `parse`. That node is what every\n * plugin in the build consumes.\n *\n * @example\n * ```ts\n * import { createAdapter, ast, type AdapterFactoryOptions } from '@kubb/core'\n *\n * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>\n *\n * export const myAdapter = createAdapter<MyAdapter>((options) => ({\n * name: 'my-adapter',\n * options,\n * document: null,\n * async parse(_source) {\n * // Convert `source` (path or inline data) into an InputNode.\n * return ast.createInput()\n * },\n * getImports: () => [],\n * async validate() {\n * // Throw or call ctx.error here when the spec is invalid.\n * },\n * }))\n * ```\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","/**\n * Backend that persists generated files. Kubb ships with `fsStorage` (writes\n * to disk) and `memoryStorage` (keeps everything in RAM). Implement this\n * interface to write to S3, a database, or any other target.\n */\nexport type Storage = {\n /**\n * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Reads the stored string. Returns `null` when the key is missing.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Stores `value` under `key`, creating any required structure (directories,\n * buckets, ...).\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Deletes the entry for `key`. No-op when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns every key. Pass `base` to filter to keys starting with that prefix.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes every entry. Pass `base` to scope the wipe to a key prefix.\n */\n clear(base?: string): Promise<void>\n /**\n * Optional teardown hook called after the build completes. Use to flush\n * buffers, close connections, or release file locks.\n */\n dispose?(): Promise<void>\n}\n\n/**\n * Defines a custom storage backend. The builder receives user options and\n * returns a `Storage` implementation. Kubb ships with filesystem and\n * in-memory storages, reach for this when you need to write generated files\n * elsewhere (cloud storage, a database, a remote API).\n *\n * @example In-memory storage (the built-in implementation)\n * ```ts\n * import { createStorage } from '@kubb/core'\n *\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n *\n * return {\n * name: 'memory',\n * async hasItem(key) {\n * return store.has(key)\n * },\n * async getItem(key) {\n * return store.get(key) ?? null\n * },\n * async setItem(key, value) {\n * store.set(key, value)\n * },\n * async removeItem(key) {\n * store.delete(key)\n * },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) {\n * if (!base) store.clear()\n * },\n * }\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 the root config.\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 { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch (_error) {\n return false\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch (_error) {\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 resolvedBase = resolve(base ?? process.cwd())\n\n async function* walk(dir: string, prefix: string): AsyncGenerator<string, void, undefined> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, {\n withFileTypes: true,\n })) as Array<Dirent>\n } catch (_error) {\n return\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n yield* walk(join(dir, entry.name), rel)\n } else {\n yield rel\n }\n }\n }\n\n const keys: Array<string> = []\n for await (const key of walk(resolvedBase, '')) {\n keys.push(key)\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 { resolve } from 'node:path'\nimport type { PossiblePromise } from '@internals/utils'\nimport { AsyncEventEmitter, BuildError } from '@internals/utils'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode } from '@kubb/ast'\nimport { DEFAULT_STUDIO_URL, HOOK_LISTENERS_PER_PLUGIN } from './constants.ts'\nimport type { Adapter } from './createAdapter.ts'\nimport { type Diagnostic, DiagnosticError, Diagnostics, isProblemDiagnostic, type ProblemDiagnostic, type UpdateDiagnostic } from './diagnostics.ts'\nimport { createStorage, type Storage } from './createStorage.ts'\nimport type { GeneratorContext } from './defineGenerator.ts'\nimport type { Middleware } from './defineMiddleware.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { KubbPluginEndContext, KubbPluginSetupContext, KubbPluginStartContext, Plugin } from './definePlugin.ts'\nimport type { ReporterName } from './createReporter.ts'\n\nimport { KubbDriver } from './KubbDriver.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\n\n/**\n * Safely extracts a type from a registry, returning `{}` if the key doesn't exist.\n * Enables optional interface augmentation for `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`\n * without requiring changes to core.\n *\n * @internal\n */\ntype ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}\n\n/**\n * Path to an input file to generate from, absolute or relative to the config file. The adapter\n * parses it (e.g. an OpenAPI YAML or JSON spec) into the universal AST.\n */\nexport type InputPath = {\n /**\n * Path to your Swagger/OpenAPI file, absolute or relative to the config file location.\n *\n * @example\n * ```ts\n * { path: './petstore.yaml' }\n * { path: '/absolute/path/to/openapi.json' }\n * ```\n */\n path: string\n}\n\n/**\n * Inline spec to generate from, passed directly instead of read from a file. A string\n * (YAML/JSON) or a parsed object.\n */\nexport type InputData = {\n /**\n * Swagger/OpenAPI data as a string (YAML/JSON) or a parsed object.\n *\n * @example\n * ```ts\n * { data: fs.readFileSync('./openapi.yaml', 'utf8') }\n * { data: { openapi: '3.1.0', info: { ... } } }\n * ```\n */\n data: string | unknown\n}\n\ntype Input = InputPath | InputData\n\n/**\n * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to\n * write it (output), how (plugins, middleware), and the runtime pieces (parsers, storage). See\n * `UserConfig` for the relaxed form with defaults applied.\n *\n * @private\n */\nexport type Config<TInput = Input> = {\n /**\n * Display name for this configuration in CLI output and logs.\n * Useful when running multiple builds with `defineConfig` arrays.\n *\n * @example\n * ```ts\n * name: 'api-client'\n * ```\n */\n name?: string\n /**\n * Project root directory, absolute or relative to the config file. Already\n * resolved on the `Config` instance (see `UserConfig` for the optional\n * form that defaults to `process.cwd()`).\n */\n root: string\n /**\n * Parsers that convert generated files into strings. Each parser handles a\n * set of file extensions, and a fallback parser handles anything else.\n *\n * Already resolved on the `Config` instance (see `UserConfig` for the\n * optional form that defaults to `[parserTs, parserTsx, parserMd]`).\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { parserTs, parserTsx } from '@kubb/parser-ts'\n *\n * export default defineConfig({\n * parsers: [parserTs, parserTsx],\n * })\n * ```\n */\n parsers: Array<Parser>\n /**\n * Adapter that parses input files into the universal AST representation.\n * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.\n *\n * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files\n * injected via `injectFile` are written, but no AST walk occurs and generator hooks\n * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.\n *\n * @example\n * ```ts\n * import { adapterOas } from '@kubb/adapter-oas'\n * export default defineConfig({\n * adapter: adapterOas(),\n * input: { path: './petstore.yaml' },\n * })\n * ```\n */\n adapter?: Adapter\n /**\n * Source file or data to generate code from.\n * Use `input.path` for a file path or `input.data` for inline data.\n * Required when an adapter is configured. Omit it when running in plugin-only mode.\n */\n input?: TInput\n output: {\n /**\n * Output directory for generated files, absolute or relative to `root`. Plugins can nest\n * subdirectories under it by grouping strategy (tag, path).\n *\n * @example\n * ```ts\n * output: {\n * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.\n * }\n * ```\n */\n path: string\n /**\n * Remove every file in the output directory before the build, so stale output isn't mixed\n * with new files. Leave `false` to preserve manual edits in the output directory.\n *\n * @default false\n * @example\n * ```ts\n * clean: true // wipes ./src/gen/* before generating\n * ```\n */\n clean?: boolean\n /**\n * Format the generated files after generation. `'auto'` runs the first formatter it finds\n * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.\n *\n * @default false\n * @example\n * ```ts\n * format: 'auto' // auto-detect prettier, biome, or oxfmt\n * format: 'prettier' // force prettier\n * format: false // skip formatting\n * ```\n */\n format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false\n /**\n * Lint the generated files after generation. `'auto'` runs the first linter it finds\n * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.\n *\n * @default false\n * @example\n * ```ts\n * lint: 'auto' // auto-detect oxlint, biome, or eslint\n * lint: 'eslint' // force eslint\n * lint: false // skip linting\n * ```\n */\n lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false\n /**\n * Rewrite import extensions in generated files, e.g. emit `.js` imports from `.ts` sources for\n * ESM dual packages. Keys are the source extension, values the output, and `''` drops it.\n *\n * @default { '.ts': '.ts' }\n * @example\n * ```ts\n * extension: { '.ts': '.js' } // generates import './api.js' instead of './api.ts'\n * extension: { '.ts': '', '.tsx': '.jsx' }\n * ```\n */\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n /**\n * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds\n * source, title, description, and API version, and `false` omits it.\n *\n * @default 'simple'\n * @example\n * ```ts\n * defaultBanner: 'simple' // \"This file was autogenerated by Kubb\"\n * defaultBanner: 'full' // adds source, title, description, API version\n * defaultBanner: false // no banner\n * ```\n */\n defaultBanner?: 'simple' | 'full' | false\n /**\n * Overwrite existing files when `true`, skip files that already exist when `false`. Individual\n * plugins can override it. Keep `false` to avoid clobbering local edits in the output folder.\n *\n * @default false\n * @example\n * ```ts\n * override: true // regenerate everything, even existing files\n * override: false // skip files that already exist\n * ```\n */\n override?: boolean\n } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>\n /**\n * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`\n * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.\n *\n * @default fsStorage()\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n *\n * // Keep generated files in memory (useful for testing, CI pipelines)\n * storage: memoryStorage()\n *\n * // Use custom S3 storage\n * storage: myS3Storage()\n * ```\n *\n * @see {@link Storage} interface for implementing custom backends.\n */\n storage: Storage\n /**\n * Plugins that run during the build to generate code and transform the AST. Each one processes\n * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin\n * that depends on another throws when that plugin isn't registered.\n *\n * @example\n * ```ts\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * plugins: [\n * pluginTs({ output: { path: './src/gen' } }),\n * pluginZod({ output: { path: './src/gen' } }),\n * ]\n * ```\n */\n plugins: Array<Plugin>\n /**\n * Middleware instances that observe build events and post-process generated code.\n *\n * Middleware fires AFTER all plugins for each event. Perfect for tasks like:\n * - Auditing what was generated\n * - Adding barrel/index files\n * - Validating output\n * - Running custom transformations\n *\n * @example\n * ```ts\n * import { middlewareBarrel } from '@kubb/middleware-barrel'\n *\n * middleware: [middlewareBarrel()]\n * ```\n *\n * @see {@link defineMiddleware} to create custom middleware.\n */\n middleware?: Array<Middleware>\n /**\n * Kubb Studio cloud integration settings.\n *\n * Kubb Studio (https://kubb.studio) is a web-based IDE for managing API specs and generated code.\n * Set to `true` to enable with default settings, or pass an object to customize the Studio URL.\n *\n * @default false // disabled by default\n * @example\n * ```ts\n * devtools: true // use default Kubb Studio\n * devtools: { studioUrl: 'https://my-studio.dev' } // custom Studio instance\n * ```\n */\n devtools?:\n | true\n | {\n /**\n * Override the Kubb Studio base URL.\n * @default 'https://kubb.studio'\n */\n studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {})\n }\n /**\n * Lifecycle hooks that execute during or after the build process.\n *\n * Hooks allow you to run external tools (prettier, eslint, custom scripts) based on build events.\n * Currently supports the `done` hook which fires after all plugins and middleware complete.\n *\n * @example\n * ```ts\n * hooks: {\n * done: 'prettier --write \"./src/gen\"', // auto-format generated files\n * // or multiple commands:\n * done: ['prettier --write \"./src/gen\"', 'eslint --fix \"./src/gen\"']\n * }\n * ```\n */\n hooks?: {\n /**\n * Command(s) to run after all plugins and middleware complete generation.\n *\n * Useful for post-processing: formatting, linting, copying files, or custom validation.\n * Pass a single command string or array of command strings to run sequentially.\n * Commands are executed relative to the `root` directory.\n *\n * @example\n * ```ts\n * done: 'prettier --write \"./src/gen\"'\n * done: ['prettier --write \"./src/gen\"', 'eslint --fix \"./src/gen\"']\n * ```\n */\n done?: string | Array<string>\n }\n /**\n * Reporters that render the run's output, like Vitest. List one or more by name;\n * the CLI `--reporter` flag overrides this when set.\n *\n * - `cli` writes the end-of-run summary to the terminal.\n * - `json` writes a machine-readable report to stdout, for CI.\n * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.\n *\n * @default ['cli']\n *\n * @example\n * ```ts\n * reporters: ['cli', 'file']\n * ```\n */\n reporters?: Array<ReporterName>\n}\n\n/**\n * Partial `Config` for user-facing entry points with sensible defaults.\n *\n * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`\n * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,\n * `storage`, `middleware`, `devtools`, and `hooks`.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * input: { path: './petstore.yaml' },\n * output: { path: './src/gen' },\n * plugins: [pluginTs(), pluginZod()],\n * })\n * ```\n */\nexport type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage'> & {\n /**\n * Project root directory, absolute or relative to the config file location.\n * @default process.cwd()\n */\n root?: string\n /**\n * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).\n * @default [parserTs, parserTsx, parserMd] // applied by `defineConfig` from the `kubb` package\n */\n parsers?: Array<Parser>\n /**\n * Adapter that parses your API specification into Kubb's universal AST.\n * When omitted, Kubb runs in plugin-only mode.\n */\n adapter?: Adapter\n /**\n * Plugins that execute during the build to generate code and transform the AST.\n * @default []\n */\n plugins?: Array<Plugin>\n /**\n * Storage backend that controls where and how generated files are persisted.\n * @default fsStorage()\n */\n storage?: Storage\n}\n\ndeclare global {\n namespace Kubb {\n /**\n * Registry that maps plugin names to their `PluginFactoryOptions`.\n * Augment this interface in each plugin's `types.ts` to enable automatic\n * typing for `getPlugin` and `requirePlugin`.\n *\n * @example\n * ```ts\n * // packages/plugin-ts/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface PluginRegistry {\n * 'plugin-ts': PluginTs\n * }\n * }\n * }\n * ```\n */\n interface PluginRegistry {}\n\n /**\n * Extension point for root `Config['output']` options.\n * Augment the `output` key in middleware or plugin packages to add extra fields\n * to the global output configuration without touching core types.\n *\n * @example\n * ```ts\n * // packages/middleware-barrel/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface ConfigOptionsRegistry {\n * output: {\n * barrel?: import('./types.ts').BarrelConfig | false\n * }\n * }\n * }\n * }\n * ```\n */\n interface ConfigOptionsRegistry {}\n\n /**\n * Extension point for per-plugin `Output` options.\n * Augment the `output` key in middleware or plugin packages to add extra fields\n * to the per-plugin output configuration without touching core types.\n *\n * @example\n * ```ts\n * // packages/middleware-barrel/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface PluginOptionsRegistry {\n * output: {\n * barrel?: import('./types.ts').PluginBarrelConfig | false\n * }\n * }\n * }\n * }\n * ```\n */\n interface PluginOptionsRegistry {}\n }\n}\n\n/**\n * Lifecycle events emitted during Kubb code generation.\n * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.\n *\n * @example\n * ```ts\n * kubb.hooks.on('kubb:lifecycle:start', () => {\n * console.log('Starting Kubb generation')\n * })\n *\n * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {\n * console.log(`${plugin.name} completed in ${duration}ms`)\n * })\n * ```\n */\nexport interface KubbHooks {\n 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext]\n 'kubb:lifecycle:end': []\n 'kubb:config:start': []\n 'kubb:config:end': [ctx: KubbConfigEndContext]\n 'kubb:generation:start': [ctx: KubbGenerationStartContext]\n 'kubb:generation:end': [ctx: KubbGenerationEndContext]\n 'kubb:format:start': []\n 'kubb:format:end': []\n 'kubb:lint:start': []\n 'kubb:lint:end': []\n 'kubb:hooks:start': []\n 'kubb:hooks:end': []\n 'kubb:hook:start': [ctx: KubbHookStartContext]\n 'kubb:hook:end': [ctx: KubbHookEndContext]\n 'kubb:info': [ctx: KubbInfoContext]\n 'kubb:error': [ctx: KubbErrorContext]\n 'kubb:success': [ctx: KubbSuccessContext]\n 'kubb:warn': [ctx: KubbWarnContext]\n 'kubb:diagnostic': [ctx: KubbDiagnosticContext]\n 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext]\n 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext]\n 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext]\n 'kubb:plugin:start': [ctx: KubbPluginStartContext]\n 'kubb:plugin:end': [ctx: KubbPluginEndContext]\n 'kubb:plugin:setup': [ctx: KubbPluginSetupContext]\n 'kubb:build:start': [ctx: KubbBuildStartContext]\n 'kubb:plugins:end': [ctx: KubbPluginsEndContext]\n 'kubb:build:end': [ctx: KubbBuildEndContext]\n 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext]\n 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext]\n 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext]\n}\n\nexport type KubbBuildStartContext = {\n /**\n * Resolved configuration for this build.\n */\n config: Config\n /**\n * Adapter that parsed the input into the universal AST.\n */\n adapter: Adapter\n /**\n * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).\n * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.\n */\n meta: InputMeta | undefined\n /**\n * Looks up a registered plugin by name, typed by the plugin registry.\n */\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n /**\n * Snapshot of all files accumulated so far.\n */\n readonly files: ReadonlyArray<FileNode>\n /**\n * Adds or merges one or more files into the file manager.\n */\n upsertFile: (...files: Array<FileNode>) => void\n}\n\nexport type KubbPluginsEndContext = {\n /**\n * Resolved configuration for this build.\n */\n config: Config\n /**\n * Snapshot of all files accumulated across all plugins.\n */\n readonly files: ReadonlyArray<FileNode>\n /**\n * Adds or merges one or more files into the file manager.\n */\n upsertFile: (...files: Array<FileNode>) => void\n}\n\nexport type KubbBuildEndContext = {\n /**\n * All files generated during this build.\n */\n files: Array<FileNode>\n /**\n * Resolved configuration for this build.\n */\n config: Config\n /**\n * Absolute path to the output directory.\n */\n outputDir: string\n}\n\nexport type KubbLifecycleStartContext = {\n /**\n * Current Kubb version string.\n */\n version: string\n}\n\nexport type KubbConfigEndContext = {\n /**\n * All resolved configs after defaults are applied.\n */\n configs: Array<Config>\n}\n\nexport type KubbGenerationStartContext = {\n /**\n * Resolved configuration for this generation run.\n */\n config: Config\n}\n\nexport type KubbGenerationEndContext = {\n /**\n * Resolved configuration for this generation run.\n */\n config: Config\n /**\n * Read-only view of the files written during this build.\n * Reads go directly to `config.storage`, nothing extra is held in memory.\n *\n * @example Read a generated file\n * `const code = await storage.getItem('/src/gen/pet.ts')`\n *\n * @example Walk every generated file\n * ```ts\n * for (const path of await storage.getKeys()) {\n * const code = await storage.getItem(path)\n * }\n * ```\n */\n storage: Storage\n /**\n * Diagnostics collected during the build: error/warning/info problems plus a\n * `timing` diagnostic per plugin. The end-of-run summary derives its failure counts\n * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.\n */\n diagnostics?: Array<Diagnostic>\n /**\n * `'success'` when all plugins completed without errors, `'failed'` otherwise.\n */\n status?: 'success' | 'failed'\n /**\n * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.\n */\n hrStart?: [number, number]\n /**\n * Total number of files created during this run.\n */\n filesCreated?: number\n}\n\nexport type KubbInfoContext = {\n /**\n * Human-readable info message.\n */\n message: string\n /**\n * Optional supplementary detail.\n */\n info?: string\n}\n\nexport type KubbErrorContext = {\n /**\n * The caught error.\n */\n error: Error\n /**\n * Optional structured metadata for additional context.\n */\n meta?: Record<string, unknown>\n}\n\nexport type KubbSuccessContext = {\n /**\n * Human-readable success message.\n */\n message: string\n /**\n * Optional supplementary detail.\n */\n info?: string\n}\n\nexport type KubbWarnContext = {\n /**\n * Human-readable warning message.\n */\n message: string\n /**\n * Optional supplementary detail.\n */\n info?: string\n}\n\nexport type KubbDiagnosticContext = {\n /**\n * The structured diagnostic to render: a build problem or a version-update notice.\n */\n diagnostic: ProblemDiagnostic | UpdateDiagnostic\n}\n\nexport type KubbFilesProcessingStartContext = {\n /**\n * Files about to be serialised and written.\n */\n files: Array<FileNode>\n}\n\nexport type KubbFileProcessingUpdate = {\n /**\n * Number of files processed so far in this batch.\n */\n processed: number\n /**\n * Total number of files in this batch.\n */\n total: number\n /**\n * Completion percentage, `0` to `100`.\n */\n percentage: number\n /**\n * Serialised file content, or `undefined` when the file produced no output.\n */\n source?: string\n /**\n * The file that was just processed.\n */\n file: FileNode\n /**\n * Resolved configuration for this build.\n */\n config: Config\n}\n\nexport type KubbFilesProcessingUpdateContext = {\n /**\n * All files processed in this flush chunk.\n */\n files: Array<KubbFileProcessingUpdate>\n}\n\nexport type KubbFilesProcessingEndContext = {\n /**\n * All files that were serialised in this batch.\n */\n files: Array<FileNode>\n}\n\nexport type KubbHookStartContext = {\n /**\n * Optional identifier for correlating start/end events.\n */\n id?: string\n /**\n * The shell command that is about to run.\n */\n command: string\n /**\n * Parsed argument list, when available.\n */\n args?: ReadonlyArray<string>\n}\n\nexport type KubbHookEndContext = {\n /**\n * Optional identifier matching the corresponding `kubb:hook:start` event.\n */\n id?: string\n /**\n * The shell command that ran.\n */\n command: string\n /**\n * Parsed argument list, when available.\n */\n args?: ReadonlyArray<string>\n /**\n * `true` when the command exited with code `0`.\n */\n success: boolean\n /**\n * Error thrown by the command, or `null` on success.\n */\n error: Error | null\n}\n\n/**\n * CLI options derived from command-line flags.\n */\nexport type CLIOptions = {\n /**\n * Path to the Kubb config file.\n */\n config?: string\n /**\n * OpenAPI input path passed as the positional argument to `kubb generate`.\n * Overrides `config.input.path` when set.\n */\n input?: string\n /**\n * Re-run generation whenever input files change.\n */\n watch?: boolean\n /**\n * Controls how much output the CLI prints.\n *\n * @default 'info'\n */\n logLevel?: 'silent' | 'info' | 'verbose'\n /**\n * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.\n */\n reporters?: Array<ReporterName>\n}\n\n/**\n * All accepted forms of a Kubb configuration.\n * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`.\n */\nexport type PossibleConfig<TCliOptions = undefined> =\n | PossiblePromise<Config | Array<Config>>\n | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>)\n\n/**\n * Full output produced by a successful or failed build.\n */\nexport type BuildOutput = {\n /**\n * Structured diagnostics collected during the build: error/warning/info problems\n * (each with a code, severity, and where known a JSON-pointer location) plus a\n * `timing` diagnostic per plugin. Includes a top-level diagnostic when the build\n * threw before completing. Use {@link Diagnostics.hasError} to test for failure.\n */\n diagnostics: Array<Diagnostic>\n /**\n * All files generated during this build.\n */\n files: Array<FileNode>\n /**\n * The plugin driver that orchestrated this build.\n */\n driver: KubbDriver\n /**\n * Read-only view of every file written during this build.\n * Reads go straight to `config.storage`, nothing extra is held in memory.\n *\n * @example Read a generated file\n * `const code = await buildOutput.storage.getItem('/src/gen/pet.ts')`\n *\n * @example List all generated file paths\n * `const paths = await buildOutput.storage.getKeys()`\n */\n storage: Storage\n}\n\n/**\n * Builds a `Storage` view scoped to the file paths produced by the current build.\n * Reads delegate to the underlying `storage` so source bytes stay where they were\n * written. Writes register the key so subsequent reads and `getKeys` are scoped\n * to this build's output.\n */\nfunction createSourcesView(storage: Storage): Storage {\n const paths = new Set<string>()\n\n return createStorage(() => ({\n name: `${storage.name}:sources`,\n async hasItem(key: string) {\n return paths.has(key) && (await storage.hasItem(key))\n },\n async getItem(key: string) {\n return paths.has(key) ? storage.getItem(key) : null\n },\n async setItem(key: string, value: string) {\n paths.add(key)\n await storage.setItem(key, value)\n },\n async removeItem(key: string) {\n paths.delete(key)\n await storage.removeItem(key)\n },\n async getKeys(base?: string) {\n if (!base) return [...paths]\n const result: Array<string> = []\n for (const key of paths) {\n if (key.startsWith(base)) result.push(key)\n }\n return result\n },\n async clear() {\n paths.clear()\n await storage.clear()\n },\n }))()\n}\n\nfunction resolveConfig(userConfig: UserConfig): Config {\n return {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n output: {\n format: false,\n lint: false,\n extension: { '.ts': '.ts' },\n defaultBanner: 'simple',\n ...userConfig.output,\n },\n storage: userConfig.storage ?? fsStorage(),\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: userConfig.plugins ?? [],\n }\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> & { input: InputPath }\nexport function isInputPath(config: Config | undefined): config is Config<InputPath> & { input: InputPath }\nexport function isInputPath(config: Config | UserConfig | undefined): config is (Config<InputPath> | UserConfig<InputPath>) & { input: InputPath } {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n\ntype CreateKubbOptions = {\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Kubb code-generation instance bound to a single config entry. Resolves the user\n * config during `setup()` and shares `hooks`, `storage`, `driver`, and `config` across\n * the `setup → build` lifecycle.\n *\n * Attach event listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))\n * const { files, diagnostics } = await kubb.safeBuild()\n * ```\n */\nexport class Kubb {\n readonly hooks: AsyncEventEmitter<KubbHooks>\n readonly #userConfig: UserConfig\n #config: Config | null = null\n #driver: KubbDriver | null = null\n #storage: Storage | null = null\n\n constructor(userConfig: UserConfig, options: CreateKubbOptions = {}) {\n this.#userConfig = userConfig\n this.hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n }\n\n get storage(): Storage {\n if (!this.#storage) throw new Error('[kubb] setup() must be called before accessing storage')\n return this.#storage\n }\n\n get driver(): KubbDriver {\n if (!this.#driver) throw new Error('[kubb] setup() must be called before accessing driver')\n return this.#driver\n }\n\n get config(): Config {\n if (!this.#config) throw new Error('[kubb] setup() must be called before accessing config')\n return this.#config\n }\n\n /**\n * Resolves config and initializes the driver. `build()` calls this automatically.\n */\n async setup(): Promise<void> {\n const config = resolveConfig(this.#userConfig)\n const driver = new KubbDriver(config, { hooks: this.hooks })\n const storage = createSourcesView(config.storage)\n\n // Each generator a plugin registers adds a listener to the shared hooks emitter, so size the\n // ceiling to the plugin count. Without this, a multi-generator plugin set trips Node's\n // EventEmitter leak warning at the default 10.\n this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN))\n\n if (config.output.clean) {\n await config.storage.clear(resolve(config.root, config.output.path))\n }\n\n await driver.setup()\n\n this.#config = config\n this.#driver = driver\n this.#storage = storage\n }\n\n /**\n * Runs the full pipeline and throws on any plugin error.\n * Automatically calls `setup()` if needed.\n */\n async build(): Promise<BuildOutput> {\n const out = await this.safeBuild()\n if (Diagnostics.hasError(out.diagnostics)) {\n const errors = out.diagnostics\n .filter(isProblemDiagnostic)\n .filter((diagnostic) => diagnostic.severity === 'error')\n .map((diagnostic) => diagnostic.cause ?? new DiagnosticError(diagnostic))\n throw new BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? 'error' : 'errors'}`, { errors })\n }\n return out\n }\n\n /**\n * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.\n * Automatically calls `setup()` if needed.\n */\n async safeBuild(): Promise<BuildOutput> {\n if (!this.#driver) await this.setup()\n using cleanup = this\n const driver = cleanup.driver\n const storage = cleanup.storage\n const { diagnostics } = await driver.run({ storage })\n\n return { diagnostics, files: driver.fileManager.files, driver, storage }\n }\n\n dispose(): void {\n this.#driver?.dispose()\n }\n\n [Symbol.dispose](): void {\n this.dispose()\n }\n}\n\n/**\n * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent\n * to `new Kubb(userConfig, options)` and the canonical public entry point.\n *\n * @example\n * ```ts\n * import { createKubb } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * const kubb = createKubb({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n *\n * await kubb.build()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n return new Kubb(userConfig, options)\n}\n","import type { logLevel } from './constants.ts'\nimport type { Config } from './createKubb.ts'\nimport type { Diagnostic } from './diagnostics.ts'\n\n/**\n * A built-in reporter that renders a run's output, independent of the live logger view.\n *\n * - `cli` renders the per-config summary to the terminal (the default).\n * - `json` writes a machine-readable report to stdout, for CI.\n * - `file` writes a config's diagnostics to `.kubb/kubb-<name>-<timestamp>.log`.\n */\nexport type ReporterName = 'cli' | 'json' | 'file'\n\n/**\n * One config's outcome within a run, as handed to a {@link Reporter}.\n */\nexport type GenerationResult = {\n config: Config\n /**\n * Diagnostics collected while generating this config.\n */\n diagnostics: Array<Diagnostic>\n /**\n * Number of files written for this config.\n */\n filesCreated: number\n status: 'success' | 'failed'\n /**\n * `process.hrtime()` snapshot taken when this config started generating.\n */\n hrStart: [number, number]\n}\n\n/**\n * Render context passed alongside the {@link GenerationResult}, carrying knobs a reporter needs\n * but that are not part of the run data (e.g. verbosity).\n */\nexport type ReporterContext = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`, `debug`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter\n * never sees the event emitter. `report` runs once per config; `flush`, when present, runs once\n * after the last config.\n */\nexport type Reporter = {\n /**\n * Display name, matching a {@link ReporterName} for the built-ins.\n */\n name: string\n /**\n * Called once per config with that config's result and the render context.\n */\n report: (result: GenerationResult, context: ReporterContext) => void | Promise<void>\n /**\n * Optional finalizer called once after the run's last config. The host wires it to\n * `kubb:lifecycle:end`. {@link createReporter} closes it over the reports `report` returned.\n */\n flush?: (context: ReporterContext) => void | Promise<void>\n}\n\n/**\n * Reporter definition passed to {@link createReporter}. `report` returns the value to collect for\n * this config (e.g. a built report), and the optional `flush` receives the collected reports to\n * emit as one document. `T` is inferred from `report`'s return type.\n */\nexport type UserReporter<T = void> = {\n name: string\n report: (result: GenerationResult, context: ReporterContext) => T | Promise<T>\n flush?: (context: ReporterContext, reports: Array<T>) => void | Promise<void>\n}\n\n/**\n * Defines a reporter. When the definition has a `flush`, the returned reporter buffers each value\n * `report` returns and hands the array to `flush` once, then clears it. Without a `flush`, nothing\n * is buffered. Wiring the reporter onto the run's events is the host's job, so the reporter only\n * ever deals with a {@link GenerationResult}.\n *\n * @example\n * ```ts\n * import { createReporter, Diagnostics } from '@kubb/core'\n *\n * export const jsonReporter = createReporter({\n * name: 'json',\n * report(result) {\n * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }\n * },\n * flush(context, reports) {\n * process.stdout.write(`${JSON.stringify(reports, null, 2)}\\n`)\n * },\n * })\n * ```\n */\nexport function createReporter<T = void>(reporter: UserReporter<T>): Reporter {\n const flush = reporter.flush\n if (!flush) {\n return { name: reporter.name, report: reporter.report }\n }\n\n const reports: Array<T> = []\n\n return {\n name: reporter.name,\n async report(result, context) {\n reports.push(await reporter.report(result, context))\n },\n async flush(context) {\n await flush(context, reports)\n reports.length = 0\n },\n }\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * `TElement` is the type the renderer accepts, for example `KubbReactElement`\n * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to\n * `unknown` so generators that don't care about the element type work without\n * specifying it.\n */\nexport type Renderer<TElement = unknown> = {\n /**\n * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.\n * Called once per render cycle. Must resolve before {@link files} is read.\n */\n render(element: TElement): Promise<void>\n /**\n * Tears down the renderer and releases any held resources.\n * Pass an `Error` to signal a failure, a number for an exit code, or omit for a clean shutdown.\n */\n unmount(error?: Error | number | null): void\n /**\n * Releases any held resources. `[Symbol.dispose]` delegates here.\n */\n dispose(): void\n /**\n * Accumulated {@link FileNode} results produced by the last {@link render} call.\n * Not populated when {@link stream} is implemented.\n */\n readonly files: Array<FileNode>\n /**\n * When present, core calls this instead of {@link render} and {@link files},\n * forwarding each file to `FileManager` as soon as it is ready.\n */\n stream?(element: TElement): Iterable<FileNode>\n /**\n * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`\n * guarantees {@link dispose} runs on every exit path, including thrown errors.\n */\n [Symbol.dispose](): void\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render cycle.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Defines a renderer factory. Renderers turn the generator's return value\n * (JSX, a template string, a tree of any shape) into `FileNode`s that get\n * written to disk.\n *\n * Use this to support output formats beyond JSX, for instance, a Handlebars\n * renderer, a string-template renderer, or a renderer that writes binary\n * files. Plugins and generators pick the renderer to use via the `renderer`\n * field on `defineGenerator`.\n *\n * @example A minimal renderer that wraps a custom runtime\n * ```ts\n * import { createRenderer } from '@kubb/core'\n *\n * export const myRenderer = createRenderer(() => {\n * const runtime = new MyRuntime()\n * return {\n * async render(element) {\n * await runtime.render(element)\n * },\n * get files() {\n * return runtime.files\n * },\n * dispose() {\n * runtime.dispose()\n * },\n * unmount(error) {\n * runtime.dispose(error)\n * },\n * [Symbol.dispose]() {\n * this.dispose()\n * },\n * }\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { AsyncEventEmitter, PossiblePromise } from '@internals/utils'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport type { Adapter } from './createAdapter.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { Plugin, PluginFactoryOptions } from './definePlugin.ts'\nimport type { Resolver } from './defineResolver.ts'\nimport type { Config, DevtoolsOptions } from './types.ts'\n\n/**\n * Context object passed to generator `schema`, `operation`, and `operations` methods.\n *\n * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks\n * are needed. `ctx.options` carries resolved per-node options after exclude/include/override\n * filtering for individual schema/operation calls, or plugin-level options for operations.\n */\nexport type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n /**\n * Absolute path to the current plugin's output directory.\n */\n root: string\n /**\n * Determine output mode based on the output config.\n * Returns `'single'` when `output.path` is a file, `'split'` for a directory.\n */\n getMode: (output: { path: string }) => 'single' | 'split'\n driver: KubbDriver\n /**\n * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.\n */\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n /**\n * Get a plugin by name, throws an error if not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin(name: string): Plugin\n /**\n * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.\n */\n getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']\n getResolver(name: string): Resolver\n /**\n * Add files only if they don't exist.\n */\n addFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * Merge sources into the same output file.\n */\n upsertFile: (...file: Array<FileNode>) => Promise<void>\n hooks: AsyncEventEmitter<KubbHooks>\n /**\n * The current plugin instance.\n */\n plugin: Plugin<TOptions>\n /**\n * The current plugin's resolver.\n */\n resolver: TOptions['resolver']\n /**\n * The current plugin's transformer.\n */\n transformer: Visitor | undefined\n /**\n * Report a warning. Collected as a `warning` diagnostic attributed to the current\n * plugin. It surfaces in the run summary but does not fail the build. For a structured\n * diagnostic with a code and source location, use `Diagnostics.report` or throw a\n * `DiagnosticError` directly.\n */\n warn: (message: string) => void\n /**\n * Report an error. Collected as an `error` diagnostic attributed to the current\n * plugin, which fails the build.\n */\n error: (error: string | Error) => void\n /**\n * Report an informational message. Collected as an `info` diagnostic attributed to\n * the current plugin.\n */\n info: (message: string) => void\n /**\n * Open the current input node in Kubb Studio.\n */\n openInStudio: (options?: DevtoolsOptions) => Promise<void>\n /**\n * The configured adapter instance.\n */\n adapter: Adapter\n /**\n * Document metadata from the adapter: title, version, base URL, and pre-computed\n * schema index fields (`circularNames`, `enumNames`).\n */\n meta: InputMeta\n /**\n * Resolved options after exclude/include/override filtering.\n */\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Declares a named generator unit that walks the AST and emits files.\n *\n * Each method (`schema`, `operation`, `operations`) is called for the matching node type.\n * Each method returns `TElement | Array<FileNode> | undefined | null`. JSX-based generators require a `renderer` factory.\n * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `undefined` or `null` to bypass rendering.\n *\n * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.\n *\n * @example\n * ```ts\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Leave it unset or set `renderer: null` to opt out of rendering.\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n}\n\n/**\n * Defines a generator: a unit of work that runs during the plugin's AST walk\n * and produces files. Plugins register generators via `ctx.addGenerator()`\n * inside `kubb:plugin:setup`.\n *\n * The returned object is the input as-is, but with `this` types preserved so\n * `schema`/`operation`/`operations` methods are correctly typed against the\n * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns\n * are both handled by the runtime, so pick whichever style fits.\n *\n * @example JSX-based schema generator\n * ```tsx\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * return (\n * <File path={`${ctx.root}/${node.name}.ts`}>\n * <Type node={node} resolver={ctx.resolver} />\n * </File>\n * )\n * },\n * })\n * ```\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { AsyncEventEmitter } from '@internals/utils'\nimport type { logLevel } from './constants.ts'\nimport type { KubbHooks } from './types.ts'\n\n/**\n * Options accepted by a logger's `install` callback.\n */\nexport type LoggerOptions = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`, `debug`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Event emitter handed to `Logger.install`. Use `.on('kubb:info', ...)` and\n * friends to subscribe to build events.\n */\nexport type LoggerContext = AsyncEventEmitter<KubbHooks>\n\n/**\n * Logger contract. A logger receives the build's event emitter and subscribes\n * to whichever lifecycle events it wants to forward to its destination\n * (console, file, remote sink).\n */\nexport type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {\n /**\n * Display name used in diagnostics.\n */\n name: string\n /**\n * Called once per build with the shared event emitter. Subscribe to events\n * here. The return value (if any) is forwarded to whoever installed the\n * logger, which is handy for sink factories.\n */\n install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>\n}\n\nexport type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>\n\n/**\n * Defines a typed logger. Use the second type parameter to declare a return\n * value from `install`, which is handy when the logger exposes a sink factory\n * or cleanup callback to the caller.\n *\n * @example Basic logger\n * ```ts\n * import { defineLogger } from '@kubb/core'\n *\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context) {\n * context.on('kubb:info', ({ message }) => console.log('ℹ', message))\n * context.on('kubb:error', ({ error }) => console.error('✗', error.message))\n * },\n * })\n * ```\n *\n * @example Logger that returns a hook sink factory\n * ```ts\n * import { defineLogger, type LoggerOptions } from '@kubb/core'\n * import type { HookSinkFactory } from './sinks'\n *\n * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({\n * name: 'my-logger',\n * install(context) {\n * // … register event handlers …\n * return () => ({ onStdout: console.log })\n * },\n * })\n * ```\n */\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions, TInstallReturn = void>(\n logger: UserLogger<Options, TInstallReturn>,\n): Logger<Options, TInstallReturn> {\n return logger\n}\n","import type { KubbHooks } from './types.ts'\n\n/**\n * A middleware instance. Subscribes to lifecycle events via `hooks`. Middleware\n * handlers always fire after every plugin handler for the same event, so they\n * see the full set of generated files.\n */\nexport type Middleware = {\n /**\n * Unique name. Use a `middleware-<feature>` convention (e.g.\n * `middleware-barrel`).\n */\n name: string\n /**\n * Lifecycle event handlers. Any event from the global `KubbHooks` map can be\n * subscribed to here. Handlers run after all plugin handlers for that event.\n */\n hooks: {\n [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void>\n }\n}\n\n/**\n * Creates a middleware factory. Middleware fires after every plugin handler\n * for the same event, which makes it the natural place for post-processing\n * (barrel files, lint runs, audit logs).\n *\n * Per-build state belongs inside the factory closure so each `createKubb`\n * invocation gets its own isolated instance.\n *\n * @example Stateless middleware\n * ```ts\n * import { defineMiddleware } from '@kubb/core'\n *\n * export const logMiddleware = defineMiddleware(() => ({\n * name: 'log-middleware',\n * hooks: {\n * 'kubb:build:end'({ files }) {\n * console.log(`Build complete with ${files.length} files`)\n * },\n * },\n * }))\n * ```\n *\n * @example Middleware with options and per-build state\n * ```ts\n * import { defineMiddleware } from '@kubb/core'\n *\n * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {\n * const seen = new Set<string>()\n * return {\n * name: 'prefix-middleware',\n * hooks: {\n * 'kubb:plugin:end'({ plugin }) {\n * seen.add(`${options.prefix}${plugin.name}`)\n * },\n * },\n * }\n * })\n * ```\n */\nexport function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware {\n return (options) => factory(options ?? ({} as TOptions))\n}\n","import type { FileNode } from '@kubb/ast'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\n/**\n * Converts a resolved {@link FileNode} into the final source string that gets\n * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own\n * for new file types (JSON, Markdown, ...).\n */\nexport type Parser<TMeta extends object = object, TNode = unknown> = {\n /**\n * Display name used in diagnostics and the parser registry.\n */\n name: string\n /**\n * File extensions this parser handles. Set to `undefined` to define a\n * catch-all fallback used when no other parser claims the extension.\n *\n * @example\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Serialise the file's AST into source code.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): string\n /**\n * Render compiler AST nodes for this parser's language into source text.\n * Plugins call this to format the nodes they assemble before handing them\n * back to the parser as `FileNode.sources`.\n */\n print(...nodes: Array<TNode>): string\n}\n\n/**\n * Defines a parser with type-safe `this`. Used to register handlers for new\n * file extensions or to plug a non-TypeScript output into the build.\n *\n * @example\n * ```ts\n * import { defineParser, ast } from '@kubb/core'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * return file.sources\n * .map((source) => ast.extractStringsFromNodes(source.nodes ?? []))\n * .join('\\n')\n * },\n * print(...nodes) {\n * return nodes.map(String).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<T extends Parser>(parser: T): T {\n return parser\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4HA,eAAsB,MAAM,MAAc,MAAc,UAAwB,CAAC,GAA2B;CAC1G,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,YAAY,IAAI,OAAO;CAE3B,MAAM,WAAW,QAAQ,IAAI;CAE7B,IAAI,OAAO,QAAQ,aAAa;EAC9B,MAAM,OAAO,IAAI,KAAK,QAAQ;EAE9B,KADoB,MAAM,KAAK,OAAO,IAAK,MAAM,KAAK,KAAK,IAAI,UAC5C,SAAS,OAAO;EACnC,MAAM,IAAI,MAAM,UAAU,OAAO;EACjC,OAAO;CACT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,MAAM,QAAQ,KAAa,OAAe;GACxC,MAAM,IAAI,KAAK,KAAK;EACtB;EACA,MAAM,WAAW,KAAa;GAC5B,MAAM,OAAO,GAAG;EAClB;EACA,MAAM,QAAQ,MAAe;GAC3B,MAAM,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC;GAC7B,OAAO,OAAO,KAAK,QAAQ,MAAM,EAAE,WAAW,IAAI,CAAC,IAAI;EACzD;EACA,MAAM,MAAM,MAAe;GACzB,IAAI,CAAC,MAAM;IACT,MAAM,MAAM;IACZ;GACF;GACA,KAAK,MAAM,OAAO,MAAM,KAAK,GAC3B,IAAI,IAAI,WAAW,IAAI,GACrB,MAAM,OAAO,GAAG;EAGtB;CACF;AACF,CAAC"}
|
package/dist/mocks.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_KubbDriver = require("./KubbDriver-
|
|
2
|
+
const require_KubbDriver = require("./KubbDriver-BYBUfOZ8.cjs");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
4
|
let _kubb_ast = require("@kubb/ast");
|
|
5
5
|
//#region src/mocks.ts
|
|
@@ -8,6 +8,7 @@ let _kubb_ast = require("@kubb/ast");
|
|
|
8
8
|
* Creates a minimal `PluginDriver` mock for unit tests.
|
|
9
9
|
*/
|
|
10
10
|
function createMockedPluginDriver(options = {}) {
|
|
11
|
+
const fileManager = new require_KubbDriver.FileManager();
|
|
11
12
|
return {
|
|
12
13
|
config: options?.config ?? {
|
|
13
14
|
root: ".",
|
|
@@ -17,7 +18,29 @@ function createMockedPluginDriver(options = {}) {
|
|
|
17
18
|
return options?.plugin;
|
|
18
19
|
},
|
|
19
20
|
getResolver: (_pluginName) => options?.plugin?.resolver,
|
|
20
|
-
fileManager
|
|
21
|
+
fileManager,
|
|
22
|
+
async dispatch({ result, renderer }) {
|
|
23
|
+
try {
|
|
24
|
+
var _usingCtx$1 = require_KubbDriver._usingCtx();
|
|
25
|
+
if (!result) return;
|
|
26
|
+
if (Array.isArray(result)) {
|
|
27
|
+
fileManager.upsert(...result);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (!renderer) return;
|
|
31
|
+
const instance = _usingCtx$1.u(renderer());
|
|
32
|
+
if (instance.stream) {
|
|
33
|
+
for (const file of instance.stream(result)) fileManager.upsert(file);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
await instance.render(result);
|
|
37
|
+
fileManager.upsert(...instance.files);
|
|
38
|
+
} catch (_) {
|
|
39
|
+
_usingCtx$1.e = _;
|
|
40
|
+
} finally {
|
|
41
|
+
_usingCtx$1.d();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
21
44
|
};
|
|
22
45
|
}
|
|
23
46
|
/**
|
package/dist/mocks.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mocks.cjs","names":["FileManager","KubbDriver"],"sources":["../src/mocks.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport { transform } from '@kubb/ast'\nimport { FileManager } from './FileManager.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport type { Adapter, AdapterFactoryOptions, Config, Generator, GeneratorContext, NormalizedPlugin, PluginFactoryOptions } from './types.ts'\n\n/**\n\n * Creates a minimal `PluginDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager:
|
|
1
|
+
{"version":3,"file":"mocks.cjs","names":["FileManager","KubbDriver"],"sources":["../src/mocks.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport { transform } from '@kubb/ast'\nimport { FileManager } from './FileManager.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport type { Adapter, AdapterFactoryOptions, Config, Generator, GeneratorContext, NormalizedPlugin, PluginFactoryOptions, RendererFactory } from './types.ts'\n\n/**\n\n * Creates a minimal `PluginDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n const fileManager = new FileManager()\n\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager,\n async dispatch({ result, renderer }: { result: unknown; renderer?: RendererFactory | null }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n if (instance.stream) {\n for (const file of instance.stream(result)) fileManager.upsert(file)\n return\n }\n\n await instance.render(result)\n fileManager.upsert(...instance.files)\n },\n } as unknown as KubbDriver\n}\n\n/**\n * Creates a minimal `Adapter` mock for unit tests.\n * `parse` returns an empty `InputNode` by default. Override via `options.parse`.\n * `getImports` returns `[]` by default.\n */\nexport function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(\n options: {\n name?: TOptions['name']\n resolvedOptions?: TOptions['resolvedOptions']\n parse?: Adapter<TOptions>['parse']\n getImports?: Adapter<TOptions>['getImports']\n } = {},\n): Adapter<TOptions> {\n return {\n name: (options.name ?? 'oas') as TOptions['name'],\n options: (options.resolvedOptions ?? {}) as TOptions['resolvedOptions'],\n parse: options.parse ?? (async () => ({ kind: 'Input' as const, schemas: [], operations: [] })),\n getImports: options.getImports ?? ((_node: SchemaNode, _resolve: (schemaName: string) => { name: string; path: string }) => []),\n } as Adapter<TOptions>\n}\n\n/**\n * Creates a minimal plugin mock for unit tests.\n *\n * @example\n * `const plugin = createMockedPlugin<PluginTs>({ name: '@kubb/plugin-ts', options })`\n */\nexport function createMockedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(params: {\n name: TOptions['name']\n options: TOptions['resolvedOptions']\n resolver?: TOptions['resolver']\n transformer?: Visitor\n dependencies?: Array<string>\n}): NormalizedPlugin<TOptions> {\n return {\n name: params.name,\n options: params.options,\n resolver: params.resolver,\n transformer: params.transformer,\n dependencies: params.dependencies,\n hooks: {},\n } as unknown as NormalizedPlugin<TOptions>\n}\n\ntype RenderGeneratorOptions<TOptions extends PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n meta?: InputMeta\n driver: KubbDriver\n plugin: NormalizedPlugin<TOptions>\n options: TOptions['resolvedOptions']\n resolver: TOptions['resolver']\n}\n\nfunction createMockedPluginContext<TOptions extends PluginFactoryOptions>(opts: RenderGeneratorOptions<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const root = resolve(opts.config.root, opts.config.output.path)\n\n return {\n config: opts.config,\n root,\n getMode: (output: { path: string }) => KubbDriver.getMode(resolve(root, output.path)),\n adapter: opts.adapter,\n resolver: opts.resolver,\n plugin: opts.plugin,\n driver: opts.driver,\n getResolver: (name: string) => opts.driver.getResolver(name),\n meta: opts.meta ?? { circularNames: [], enumNames: [] },\n addFile: async (...files: Array<FileNode>) => opts.driver.fileManager.add(...files),\n upsertFile: async (...files: Array<FileNode>) => opts.driver.fileManager.upsert(...files),\n hooks: opts.driver.hooks ?? ({} as never),\n warn: (msg: string) => console.warn(msg),\n error: (msg: string) => console.error(msg),\n info: (msg: string) => console.info(msg),\n openInStudio: async () => {},\n } as unknown as Omit<GeneratorContext<TOptions>, 'options'>\n}\n\n/**\n * Renders a generator's `schema` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorSchema<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: SchemaNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.schema) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.transformer ? transform(node, opts.plugin.transformer) : node\n const result = await generator.schema(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operation` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperation(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperation<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: OperationNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operation) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.transformer ? transform(node, opts.plugin.transformer) : node\n const result = await generator.operation(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operations` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperations(classClientGenerator, nodes, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperations<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n nodes: Array<OperationNode>,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operations) return\n const context = createMockedPluginContext(opts)\n const transformedNodes = opts.plugin.transformer ? nodes.map((n) => transform(n, opts.plugin.transformer!)) : nodes\n const result = await generator.operations(transformedNodes, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,yBAAyB,UAAyE,CAAC,GAAe;CAChI,MAAM,cAAc,IAAIA,mBAAAA,YAAY;CAEpC,OAAO;EACL,QA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;CACf,IAAI,CAAC,UAAU,YAAY;CAC3B,MAAM,UAAU,0BAA0B,IAAI;CAC9C,MAAM,mBAAmB,KAAK,OAAO,cAAc,MAAM,KAAK,OAAA,GAAA,UAAA,WAAgB,GAAG,KAAK,OAAO,WAAY,CAAC,IAAI;CAC9G,MAAM,SAAS,MAAM,UAAU,WAAW,kBAAkB;EAC1D,GAAG;EACH,SAAS,KAAK;CAChB,CAAC;CACD,MAAM,KAAK,OAAO,SAAS;EAAE;EAAQ,UAAU,UAAU;CAAS,CAAC;AACrE"}
|
package/dist/mocks.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __name } from "./chunk-C0LytTxp.js";
|
|
2
|
-
import { Gt as AdapterFactoryOptions, J as Generator, Wt as Adapter, Z as KubbDriver, at as NormalizedPlugin, lt as PluginFactoryOptions, x as Config } from "./diagnostics-
|
|
2
|
+
import { Gt as AdapterFactoryOptions, J as Generator, Wt as Adapter, Z as KubbDriver, at as NormalizedPlugin, lt as PluginFactoryOptions, x as Config } from "./diagnostics-CYfKPtbU.js";
|
|
3
3
|
import { InputMeta, OperationNode, SchemaNode, Visitor } from "@kubb/ast";
|
|
4
4
|
|
|
5
5
|
//#region src/mocks.d.ts
|
package/dist/mocks.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./chunk-C0LytTxp.js";
|
|
2
|
-
import { i as FileManager, t as KubbDriver } from "./KubbDriver-
|
|
2
|
+
import { i as FileManager, n as _usingCtx, t as KubbDriver } from "./KubbDriver-CyNF-NIb.js";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
import { transform } from "@kubb/ast";
|
|
5
5
|
//#region src/mocks.ts
|
|
@@ -8,6 +8,7 @@ import { transform } from "@kubb/ast";
|
|
|
8
8
|
* Creates a minimal `PluginDriver` mock for unit tests.
|
|
9
9
|
*/
|
|
10
10
|
function createMockedPluginDriver(options = {}) {
|
|
11
|
+
const fileManager = new FileManager();
|
|
11
12
|
return {
|
|
12
13
|
config: options?.config ?? {
|
|
13
14
|
root: ".",
|
|
@@ -17,7 +18,29 @@ function createMockedPluginDriver(options = {}) {
|
|
|
17
18
|
return options?.plugin;
|
|
18
19
|
},
|
|
19
20
|
getResolver: (_pluginName) => options?.plugin?.resolver,
|
|
20
|
-
fileManager
|
|
21
|
+
fileManager,
|
|
22
|
+
async dispatch({ result, renderer }) {
|
|
23
|
+
try {
|
|
24
|
+
var _usingCtx$1 = _usingCtx();
|
|
25
|
+
if (!result) return;
|
|
26
|
+
if (Array.isArray(result)) {
|
|
27
|
+
fileManager.upsert(...result);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (!renderer) return;
|
|
31
|
+
const instance = _usingCtx$1.u(renderer());
|
|
32
|
+
if (instance.stream) {
|
|
33
|
+
for (const file of instance.stream(result)) fileManager.upsert(file);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
await instance.render(result);
|
|
37
|
+
fileManager.upsert(...instance.files);
|
|
38
|
+
} catch (_) {
|
|
39
|
+
_usingCtx$1.e = _;
|
|
40
|
+
} finally {
|
|
41
|
+
_usingCtx$1.d();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
21
44
|
};
|
|
22
45
|
}
|
|
23
46
|
/**
|
package/dist/mocks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mocks.js","names":[],"sources":["../src/mocks.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport { transform } from '@kubb/ast'\nimport { FileManager } from './FileManager.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport type { Adapter, AdapterFactoryOptions, Config, Generator, GeneratorContext, NormalizedPlugin, PluginFactoryOptions } from './types.ts'\n\n/**\n\n * Creates a minimal `PluginDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager:
|
|
1
|
+
{"version":3,"file":"mocks.js","names":[],"sources":["../src/mocks.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport { transform } from '@kubb/ast'\nimport { FileManager } from './FileManager.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport type { Adapter, AdapterFactoryOptions, Config, Generator, GeneratorContext, NormalizedPlugin, PluginFactoryOptions, RendererFactory } from './types.ts'\n\n/**\n\n * Creates a minimal `PluginDriver` mock for unit tests.\n */\nexport function createMockedPluginDriver(options: { name?: string; plugin?: NormalizedPlugin; config?: Config } = {}): KubbDriver {\n const fileManager = new FileManager()\n\n return {\n config: options?.config ?? {\n root: '.',\n output: {\n path: './path',\n },\n },\n getPlugin(_pluginName: string): NormalizedPlugin | undefined {\n return options?.plugin\n },\n getResolver: (_pluginName: string) => options?.plugin?.resolver,\n fileManager,\n async dispatch({ result, renderer }: { result: unknown; renderer?: RendererFactory | null }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n if (instance.stream) {\n for (const file of instance.stream(result)) fileManager.upsert(file)\n return\n }\n\n await instance.render(result)\n fileManager.upsert(...instance.files)\n },\n } as unknown as KubbDriver\n}\n\n/**\n * Creates a minimal `Adapter` mock for unit tests.\n * `parse` returns an empty `InputNode` by default. Override via `options.parse`.\n * `getImports` returns `[]` by default.\n */\nexport function createMockedAdapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions>(\n options: {\n name?: TOptions['name']\n resolvedOptions?: TOptions['resolvedOptions']\n parse?: Adapter<TOptions>['parse']\n getImports?: Adapter<TOptions>['getImports']\n } = {},\n): Adapter<TOptions> {\n return {\n name: (options.name ?? 'oas') as TOptions['name'],\n options: (options.resolvedOptions ?? {}) as TOptions['resolvedOptions'],\n parse: options.parse ?? (async () => ({ kind: 'Input' as const, schemas: [], operations: [] })),\n getImports: options.getImports ?? ((_node: SchemaNode, _resolve: (schemaName: string) => { name: string; path: string }) => []),\n } as Adapter<TOptions>\n}\n\n/**\n * Creates a minimal plugin mock for unit tests.\n *\n * @example\n * `const plugin = createMockedPlugin<PluginTs>({ name: '@kubb/plugin-ts', options })`\n */\nexport function createMockedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(params: {\n name: TOptions['name']\n options: TOptions['resolvedOptions']\n resolver?: TOptions['resolver']\n transformer?: Visitor\n dependencies?: Array<string>\n}): NormalizedPlugin<TOptions> {\n return {\n name: params.name,\n options: params.options,\n resolver: params.resolver,\n transformer: params.transformer,\n dependencies: params.dependencies,\n hooks: {},\n } as unknown as NormalizedPlugin<TOptions>\n}\n\ntype RenderGeneratorOptions<TOptions extends PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n meta?: InputMeta\n driver: KubbDriver\n plugin: NormalizedPlugin<TOptions>\n options: TOptions['resolvedOptions']\n resolver: TOptions['resolver']\n}\n\nfunction createMockedPluginContext<TOptions extends PluginFactoryOptions>(opts: RenderGeneratorOptions<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const root = resolve(opts.config.root, opts.config.output.path)\n\n return {\n config: opts.config,\n root,\n getMode: (output: { path: string }) => KubbDriver.getMode(resolve(root, output.path)),\n adapter: opts.adapter,\n resolver: opts.resolver,\n plugin: opts.plugin,\n driver: opts.driver,\n getResolver: (name: string) => opts.driver.getResolver(name),\n meta: opts.meta ?? { circularNames: [], enumNames: [] },\n addFile: async (...files: Array<FileNode>) => opts.driver.fileManager.add(...files),\n upsertFile: async (...files: Array<FileNode>) => opts.driver.fileManager.upsert(...files),\n hooks: opts.driver.hooks ?? ({} as never),\n warn: (msg: string) => console.warn(msg),\n error: (msg: string) => console.error(msg),\n info: (msg: string) => console.info(msg),\n openInStudio: async () => {},\n } as unknown as Omit<GeneratorContext<TOptions>, 'options'>\n}\n\n/**\n * Renders a generator's `schema` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorSchema(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorSchema<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: SchemaNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.schema) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.transformer ? transform(node, opts.plugin.transformer) : node\n const result = await generator.schema(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operation` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperation(typeGenerator, node, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperation<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n node: OperationNode,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operation) return\n const context = createMockedPluginContext(opts)\n const transformedNode = opts.plugin.transformer ? transform(node, opts.plugin.transformer) : node\n const result = await generator.operation(transformedNode, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n\n/**\n * Renders a generator's `operations` method in a test context.\n *\n * @example\n * ```ts\n * await renderGeneratorOperations(classClientGenerator, nodes, { config, adapter, driver, plugin, options, resolver })\n * await matchFiles(driver.fileManager.files)\n * ```\n */\nexport async function renderGeneratorOperations<TOptions extends PluginFactoryOptions>(\n generator: Generator<TOptions>,\n nodes: Array<OperationNode>,\n opts: RenderGeneratorOptions<TOptions>,\n): Promise<void> {\n if (!generator.operations) return\n const context = createMockedPluginContext(opts)\n const transformedNodes = opts.plugin.transformer ? nodes.map((n) => transform(n, opts.plugin.transformer!)) : nodes\n const result = await generator.operations(transformedNodes, {\n ...context,\n options: opts.options,\n })\n await opts.driver.dispatch({ result, renderer: generator.renderer })\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,yBAAyB,UAAyE,CAAC,GAAe;CAChI,MAAM,cAAc,IAAI,YAAY;CAEpC,OAAO;EACL,QAAQ,SAAS,UAAU;GACzB,MAAM;GACN,QAAQ,EACN,MAAM,SACR;EACF;EACA,UAAU,aAAmD;GAC3D,OAAO,SAAS;EAClB;EACA,cAAc,gBAAwB,SAAS,QAAQ;EACvD;EACA,MAAM,SAAS,EAAE,QAAQ,YAAmF;;;IAC1G,IAAI,CAAC,QAAQ;IAEb,IAAI,MAAM,QAAQ,MAAM,GAAG;KACzB,YAAY,OAAO,GAAI,MAA0B;KACjD;IACF;IAEA,IAAI,CAAC,UAAU;IAEf,MAAM,WAAA,YAAA,EAAW,SAAS,CAAA;IAC1B,IAAI,SAAS,QAAQ;KACnB,KAAK,MAAM,QAAQ,SAAS,OAAO,MAAM,GAAG,YAAY,OAAO,IAAI;KACnE;IACF;IAEA,MAAM,SAAS,OAAO,MAAM;IAC5B,YAAY,OAAO,GAAG,SAAS,KAAK;;;;;;EACtC;CACF;AACF;;;;;;AAOA,SAAgB,oBACd,UAKI,CAAC,GACc;CACnB,OAAO;EACL,MAAO,QAAQ,QAAQ;EACvB,SAAU,QAAQ,mBAAmB,CAAC;EACtC,OAAO,QAAQ,UAAU,aAAa;GAAE,MAAM;GAAkB,SAAS,CAAC;GAAG,YAAY,CAAC;EAAE;EAC5F,YAAY,QAAQ,gBAAgB,OAAmB,aAAqE,CAAC;CAC/H;AACF;;;;;;;AAQA,SAAgB,mBAAiF,QAMlE;CAC7B,OAAO;EACL,MAAM,OAAO;EACb,SAAS,OAAO;EAChB,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,cAAc,OAAO;EACrB,OAAO,CAAC;CACV;AACF;AAYA,SAAS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