@kubb/adapter-oas 5.0.0-beta.55 → 5.0.0-beta.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["ast","Diagnostics","path","Diagnostics","ast","Diagnostics","ast","ast","Diagnostics","ast","ast"],"sources":["../src/constants.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/object.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/url.ts","../src/bundler.ts","../src/guards.ts","../src/factory.ts","../src/refs.ts","../src/dialect.ts","../src/mime.ts","../src/operation.ts","../src/resolvers.ts","../src/parser.ts","../src/discriminator.ts","../src/schemaDiagnostics.ts","../src/stream.ts","../src/adapter.ts"],"sourcesContent":["import { ast } from '@kubb/core'\n\n/**\n * Default parser options applied when no explicit options are provided.\n *\n * @example\n * ```ts\n * import { DEFAULT_PARSER_OPTIONS } from '@kubb/adapter-oas'\n *\n * const parser = createOasParser(oas)\n * const root = parser.parse({ ...DEFAULT_PARSER_OPTIONS, dateType: 'date' })\n * ```\n */\nexport const DEFAULT_PARSER_OPTIONS = {\n dateType: 'string',\n integerType: 'bigint',\n unknownType: 'any',\n emptySchemaType: 'any',\n enumSuffix: 'enum',\n} as const satisfies ast.ParserOptions\n\n/**\n * JSON-Pointer prefix for schemas declared under `components.schemas` in an OpenAPI document.\n *\n * Used when building or parsing `$ref` strings.\n *\n * @example\n * ```ts\n * `${SCHEMA_REF_PREFIX}Pet` // '#/components/schemas/Pet'\n * ```\n */\nexport const SCHEMA_REF_PREFIX = '#/components/schemas/' as const\n\n/**\n * HTTP methods that count as operations on an OpenAPI path item. Other keys\n * (`parameters`, `summary`, `$ref`, vendor extensions) are skipped when iterating operations.\n */\nexport const SUPPORTED_METHODS: ReadonlySet<string> = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'])\n\n/**\n * OpenAPI version string written into the stub document created during multi-spec merges.\n */\nexport const MERGE_OPENAPI_VERSION = '3.0.0' as const\n\n/**\n * Fallback `info.title` placed in the stub document when merging multiple API files.\n */\nexport const MERGE_DEFAULT_TITLE = 'Merged API' as const\n\n/**\n * Fallback `info.version` placed in the stub document when merging multiple API files.\n */\nexport const MERGE_DEFAULT_VERSION = '1.0.0' as const\n\n/**\n * Set of JSON Schema keywords that prevent a schema fragment from being inlined during `allOf` flattening.\n *\n * A fragment that contains any of these keys carries structural meaning of its own and must stay as a separate\n * intersection member rather than being merged into the parent.\n *\n * @example\n * ```ts\n * import { structuralKeys } from '@kubb/adapter-oas'\n *\n * const isStructural = Object.keys(fragment).some((key) => structuralKeys.has(key))\n * // true when fragment has e.g. 'properties' or 'oneOf'\n * ```\n */\nexport const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)\n\n/**\n * Static map from OAS `format` strings to Kubb `SchemaType` values.\n *\n * Only formats whose AST type differs from the OAS `type` field appear here.\n * Formats that depend on runtime options (`int64`, `date-time`, `date`, `time`) are handled separately\n * in the parser. `ipv4` and `ipv6` map to their own dedicated schema types; `hostname` and\n * `idn-hostname` map to `'url'` as the closest generic string-format type.\n *\n * @example\n * ```ts\n * import { formatMap } from '@kubb/adapter-oas'\n *\n * formatMap['uuid'] // 'uuid'\n * formatMap['binary'] // 'blob'\n * formatMap['float'] // 'number'\n * ```\n */\n/**\n * Formats `convertFormat` maps to a dedicated type without going through `formatMap`:\n * `int64` and the date/time family. Keep this in sync with the `convertFormat`\n * special-cases in `parser.ts`. `isHandledFormat` reads it so the\n * `KUBB_UNSUPPORTED_FORMAT` diagnostic and the parser agree on what is handled.\n */\nexport const specialCasedFormats: ReadonlySet<string> = new Set(['int64', 'date-time', 'date', 'time'])\n\nexport const formatMap = {\n uuid: 'uuid',\n email: 'email',\n 'idn-email': 'email',\n uri: 'url',\n 'uri-reference': 'url',\n url: 'url',\n ipv4: 'ipv4',\n ipv6: 'ipv6',\n hostname: 'url',\n 'idn-hostname': 'url',\n binary: 'blob',\n byte: 'blob',\n // Numeric formats override the OAS `type` because format is more specific.\n // See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7\n int32: 'integer',\n float: 'number',\n double: 'number',\n} as const satisfies Record<string, ast.SchemaType>\n\n/**\n * Vendor extension keys that attach human-readable labels to enum values, checked in priority order.\n *\n * @example\n * ```ts\n * import { enumExtensionKeys } from '@kubb/adapter-oas'\n *\n * const key = enumExtensionKeys.find((k) => k in schema) // 'x-enumNames' | 'x-enum-varnames' | undefined\n * ```\n */\nexport const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const\n\n/**\n * Maps `'any' | 'unknown' | 'void'` option strings to their `ScalarSchemaType` constant.\n * Replaces a plain object lookup with a `Map` for explicit key membership testing via `.has()`.\n */\nexport const typeOptionMap = new Map<'any' | 'unknown' | 'void', ast.ScalarSchemaType>([\n ['any', ast.schemaTypes.any],\n ['unknown', ast.schemaTypes.unknown],\n ['void', ast.schemaTypes.void],\n])\n","type Options = {\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n return text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","import { existsSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\nimport { camelCase } from './casing.ts'\nimport { runtime } from './runtime.ts'\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\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 (runtime.isBun) {\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 (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(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 (runtime.isBun) {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Builds a nested file path from a dotted name. Splits on dots that precede a letter\n * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases\n * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.\n *\n * Empty segments are dropped before joining. They arise when the name starts with a dot\n * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to\n * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an\n * absolute path, letting generated files escape the configured output directory.\n *\n * @example Nested path from a dotted name\n * `toFilePath('pet.petId') // 'pet/petId'`\n *\n * @example PascalCase the final segment\n * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`\n *\n * @example Suffix applied to the final segment only\n * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`\n */\nexport function toFilePath(name: string, caseLast: (part: string) => string = camelCase): string {\n const parts = name.split(/\\.(?=[a-zA-Z])/)\n return parts\n .map((part, i) => (i === parts.length - 1 ? caseLast(part) : camelCase(part)))\n .filter(Boolean)\n .join('/')\n}\n","/**\n * Returns `true` when `value` is a plain (non-null, non-array) object.\n *\n * @example\n * ```ts\n * isPlainObject({}) // true\n * isPlainObject([]) // false\n * isPlainObject(null) // false\n * ```\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n}\n\n/**\n * Recursively merges `source` into `target`, combining nested plain objects.\n * Arrays and non-object values from `source` override the corresponding values in `target`.\n *\n * @example\n * ```ts\n * mergeDeep({ a: { x: 1 } }, { a: { y: 2 } })\n * // { a: { x: 1, y: 2 } }\n * ```\n */\nexport function mergeDeep(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = { ...target }\n for (const key of Object.keys(source)) {\n const sv = source[key]\n const tv = result[key]\n result[key] =\n sv !== null && typeof sv === 'object' && !Array.isArray(sv) && tv !== null && typeof tv === 'object' && !Array.isArray(tv)\n ? mergeDeep(tv as Record<string, unknown>, sv as Record<string, unknown>)\n : sv\n }\n return result\n}\n\n/**\n * Strips functions, symbols, and `undefined` values from plugin options for safe JSON transport.\n *\n * @example\n * ```ts\n * serializePluginOptions({ output: './src', onWrite: () => {} })\n * // { output: './src' } (function stripped)\n * ```\n */\nexport function serializePluginOptions<TOptions extends object>(options: TOptions): TOptions {\n if (options === null || options === undefined) return {} as TOptions\n if (typeof options !== 'object') return options\n if (Array.isArray(options)) return options.map(serializePluginOptions) as unknown as TOptions\n\n const serialized: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(options)) {\n if (typeof value === 'function' || typeof value === 'symbol' || value === undefined) continue\n serialized[key] = value !== null && typeof value === 'object' ? serializePluginOptions(value as object) : value\n }\n return serialized as TOptions\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return isIdentifier(name)\n}\n\n/**\n * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.\n *\n * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys\n * even though they are not valid variable names, so use this (not {@link isValidVarName}) when\n * deciding whether an object key needs quoting.\n *\n * @example\n * ```ts\n * isIdentifier('name') // true\n * isIdentifier('x-total')// false\n * ```\n */\nexport function isIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `null` when the path has none.\n */\n params: Record<string, string> | null\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\nexport type PathCasing = 'camelcase'\n\ntype TemplateOptions = {\n /**\n * Literal text prepended inside the template literal, e.g. a base URL.\n */\n prefix?: string | null\n /**\n * Transform applied to each extracted parameter name before interpolation.\n */\n replacer?: (pathParam: string) => string\n /**\n * Casing strategy applied to path parameter names.\n */\n casing?: PathCasing\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n /**\n * Casing strategy applied to path parameter names.\n */\n casing?: PathCasing\n}\n\nfunction transformParam(raw: string, casing?: PathCasing): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return casing === 'camelcase' ? camelCase(param) : param\n}\n\nfunction toParamsObject(\n path: string,\n { replacer, casing }: { replacer?: (pathParam: string) => string; casing?: PathCasing } = {},\n): Record<string, string> | null {\n const params: Record<string, string> = {}\n\n for (const match of path.matchAll(/\\{([^}]+)\\}/g)) {\n const param = transformParam(match[1]!, casing)\n const key = replacer ? replacer(param) : param\n params[key] = key\n }\n\n return Object.keys(params).length > 0 ? params : null\n}\n\n/**\n * Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.\n */\nexport class Url {\n /**\n * Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.\n *\n * @example\n * Url.canParse('https://petstore.swagger.io/v2') // true\n * Url.canParse('/pet/{petId}') // false\n */\n static canParse(url: string, base?: string | URL): boolean {\n return URL.canParse(url, base)\n }\n\n /**\n * Converts an OpenAPI/Swagger path to Express-style colon syntax.\n *\n * @example\n * Url.toPath('/pet/{petId}') // '/pet/:petId'\n */\n static toPath(path: string): string {\n return path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n\n /**\n * Converts an OpenAPI/Swagger path to a TypeScript template literal string.\n * `prefix` is prepended inside the literal, `replacer` transforms each parameter name,\n * and `casing` controls parameter identifier casing.\n *\n * @example\n * Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'\n *\n * @example\n * Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'\n */\n static toTemplateString(path: string, { prefix, replacer, casing }: TemplateOptions = {}): string {\n const parts = path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = transformParam(part, casing)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix ?? ''}${result}\\``\n }\n\n /**\n * Returns the path and its extracted params as a structured `URLObject`, or as a stringified\n * expression when `stringify` is set.\n *\n * @example\n * Url.toObject('/pet/{petId}')\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n */\n static toObject(path: string, { type = 'path', replacer, stringify, casing }: ObjectOptions = {}): URLObject | string {\n const object: URLObject = {\n url: type === 'path' ? Url.toPath(path) : Url.toTemplateString(path, { replacer, casing }),\n params: toParamsObject(path, { replacer, casing }),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n}\n","import { read } from '@internals/utils'\nimport { bundle } from 'api-ref-bundler'\nimport { parse } from 'yaml'\nimport type { Document } from './types.ts'\n\nconst urlRegExp = /^https?:\\/+/i\n\nasync function readSource(sourcePath: string): Promise<string> {\n if (urlRegExp.test(sourcePath)) {\n // api-ref-bundler joins relative refs with posix normalization, collapsing `https://` to\n // `https:/`. The WHATWG URL parser restores the double slash.\n const url = new URL(sourcePath)\n const response = await fetch(url)\n\n if (!response.ok) {\n throw new Error(`Cannot fetch the OAS document at ${url.href} (HTTP ${response.status})`)\n }\n\n return response.text()\n }\n\n return read(sourcePath)\n}\n\nasync function resolveSource(sourcePath: string): Promise<object | string> {\n const data = await readSource(sourcePath)\n\n if (sourcePath.toLowerCase().endsWith('.md')) {\n return data\n }\n\n return parse(data) as object\n}\n\n/**\n * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.\n *\n * External file schemas are hoisted into named `components.schemas` entries, so a property\n * pointing at `./schemas/User.yaml` ends up referencing `#/components/schemas/User`. Generators\n * can then emit a named type with an import instead of inlining the shape. Sources are read with\n * the Bun-aware `read` util for local YAML and JSON files, and with `fetch` for HTTP(S) URLs.\n *\n * @example Local file\n * `const document = await bundleDocument('./openapi.yaml')`\n *\n * @example Remote URL\n * `const document = await bundleDocument('https://example.com/openapi.yaml')`\n */\nexport async function bundleDocument(pathOrUrl: string): Promise<Document> {\n const cache = new Map<string, Promise<object | string>>()\n\n const resolver = (sourcePath: string) => {\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, so cache on the canonical href to fetch each source once.\n const key = urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath\n const cached = cache.get(key)\n if (cached) {\n return cached\n }\n\n const result = resolveSource(sourcePath)\n cache.set(key, result)\n return result\n }\n\n // api-ref-bundler swallows resolver errors and leaves refs unresolved, so surface an\n // unreadable input document as a hard error before bundling.\n await resolver(pathOrUrl)\n\n return (await bundle(pathOrUrl, resolver)) as Document\n}\n","import { isPlainObject } from '@internals/utils'\nimport type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\nimport type { DiscriminatorObject, SchemaObject } from './types.ts'\n\n/**\n * Returns `true` when `doc` is a Swagger 2.0 document (no `openapi` key).\n *\n * @example\n * ```ts\n * if (isOpenApiV2Document(doc)) {\n * // doc is OpenAPIV2.Document\n * }\n * ```\n */\nexport function isOpenApiV2Document(doc: unknown): doc is OpenAPIV2.Document {\n return !!doc && isPlainObject(doc) && !('openapi' in doc)\n}\n\n/**\n * Returns `true` when a schema should be treated as nullable.\n *\n * Recognizes all nullable signals across OAS versions: `nullable: true` (OAS 3.0),\n * `x-nullable: true` (vendor extension), `type: 'null'`, and `type: ['null', ...]` (OAS 3.1).\n *\n * @example\n * ```ts\n * isNullable({ type: 'string', nullable: true }) // true\n * isNullable({ type: ['string', 'null'] }) // true\n * isNullable({ type: 'string' }) // false\n * ```\n */\nexport function isNullable(schema?: SchemaObject & { 'x-nullable'?: boolean }): boolean {\n const explicitNullable = schema?.nullable ?? schema?.['x-nullable']\n if (explicitNullable === true) return true\n\n const schemaType = schema?.type\n if (schemaType === 'null') return true\n if (Array.isArray(schemaType)) return schemaType.includes('null')\n\n return false\n}\n\n/**\n * Returns `true` when `obj` is an OpenAPI `$ref` pointer object.\n *\n * @example\n * ```ts\n * isReference({ $ref: '#/components/schemas/Pet' }) // true\n * isReference({ type: 'string' }) // false\n * ```\n */\nexport function isReference(obj?: unknown): obj is OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject {\n return !!obj && typeof obj === 'object' && '$ref' in obj\n}\n\n/**\n * Returns `true` when `obj` is a schema with a structured OAS 3.x `discriminator` object.\n *\n * @example\n * ```ts\n * isDiscriminator({ discriminator: { propertyName: 'type', mapping: {} } }) // true\n * isDiscriminator({ discriminator: 'type' }) // false (Swagger 2 string form)\n * ```\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: DiscriminatorObject } {\n const record = obj as Record<string, unknown>\n return !!obj && !!record['discriminator'] && typeof record['discriminator'] !== 'string'\n}\n","import path from 'node:path'\nimport { exists, mergeDeep, Url } from '@internals/utils'\nimport { Diagnostics } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { compileErrors, validate } from '@readme/openapi-parser'\nimport { parse } from 'yaml'\nimport { bundleDocument } from './bundler.ts'\nimport { MERGE_DEFAULT_TITLE, MERGE_DEFAULT_VERSION, MERGE_OPENAPI_VERSION } from './constants.ts'\nimport { isOpenApiV2Document } from './guards.ts'\nimport type { Document } from './types.ts'\n\nexport type ParseOptions = {\n canBundle?: boolean\n}\n\nexport type ValidateDocumentOptions = {\n throwOnError?: boolean\n}\n\n/**\n * Loads and dereferences an OpenAPI document, returning the raw `Document`.\n *\n * Accepts a file path string or an already-parsed document object. File paths and URLs are\n * bundled via `api-ref-bundler`, hoisting external file schemas into named `components.schemas`\n * entries so generators can emit named types and imports. Swagger 2.0 documents are\n * automatically up-converted to OpenAPI 3.0 via `swagger2openapi`.\n *\n * @example\n * ```ts\n * const document = await parseDocument('./openapi.yaml')\n * const document = await parse(rawDocumentObject, { canBundle: false })\n * ```\n */\nexport async function parseDocument(pathOrApi: string | Document, { canBundle = true }: ParseOptions = {}): Promise<Document> {\n if (typeof pathOrApi === 'string' && canBundle) {\n const bundled = await bundleDocument(pathOrApi)\n\n return parseDocument(bundled, { canBundle: false })\n }\n\n // A string here is always inline YAML/JSON content: file paths and URLs are read and parsed by\n // `bundleDocument` first. `yaml.parse` also parses JSON, since JSON is a subset of YAML.\n const document = (typeof pathOrApi === 'string' ? parse(pathOrApi) : pathOrApi) as Document\n\n if (isOpenApiV2Document(document)) {\n const { default: swagger2openapi } = await import('swagger2openapi')\n const { openapi } = await swagger2openapi.convertObj(document, {\n anchors: true,\n })\n\n return openapi as Document\n }\n\n return document\n}\n\n/**\n * Deep-merges multiple OpenAPI documents into a single `Document`.\n *\n * Each document is parsed independently, then deep-merged into one in array order.\n * Throws when the input array is empty.\n *\n * @example\n * ```ts\n * const document = await mergeDocuments(['./pets.yaml', './orders.yaml'])\n * ```\n */\nexport async function mergeDocuments(pathOrApi: Array<string | Document>): Promise<Document> {\n const documents = await Promise.all(pathOrApi.map((p) => parseDocument(p, { canBundle: false })))\n\n if (documents.length === 0) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: 'No OAS documents were provided for merging.',\n help: 'Pass at least one path or document to `input.path`.',\n location: { kind: 'config' },\n })\n }\n\n const seed: Document = {\n openapi: MERGE_OPENAPI_VERSION,\n info: { title: MERGE_DEFAULT_TITLE, version: MERGE_DEFAULT_VERSION },\n paths: {},\n components: { schemas: {} },\n } as Document\n\n const merged = documents.reduce(\n (acc, current) => mergeDeep(acc as Record<string, unknown>, current as Record<string, unknown>),\n seed as Record<string, unknown>,\n )\n\n return parseDocument(merged as Document)\n}\n\n/**\n * Creates a `Document` from an `AdapterSource`.\n *\n * Handles all three source types:\n * - `{ type: 'path' }` resolves and bundles a local file path or remote URL.\n * - `{ type: 'paths' }` merges multiple file paths into a single document.\n * - `{ type: 'data' }` parses an inline string (YAML/JSON) or raw object.\n *\n * @example\n * ```ts\n * const document = await parseFromConfig({ type: 'path', path: './openapi.yaml' })\n * const document = await parseFromConfig({ type: 'data', data: '{\"openapi\":\"3.0.0\",...}' })\n * ```\n */\nexport async function parseFromConfig(source: AdapterSource): Promise<Document> {\n if (source.type === 'data') {\n if (typeof source.data === 'object') {\n return parseDocument(structuredClone(source.data) as Document)\n }\n\n return parseDocument(source.data as string, { canBundle: false })\n }\n\n if (source.type === 'paths') {\n return mergeDocuments(source.paths)\n }\n\n // type === 'path'\n if (Url.canParse(source.path)) {\n return parseDocument(source.path)\n }\n\n const resolved = path.resolve(path.dirname(source.path), source.path)\n await assertInputExists(resolved)\n return parseDocument(resolved)\n}\n\n/**\n * Throws a coded `KUBB_INPUT_NOT_FOUND` diagnostic when a local input path does not exist.\n * URLs are skipped, and a malformed but readable file is left for `parseDocument` to surface\n * its parse error instead.\n */\nexport async function assertInputExists(input: string): Promise<void> {\n if (Url.canParse(input)) {\n return\n }\n if (!(await exists(input))) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputNotFound,\n severity: 'error',\n message: `Cannot read the file set in \\`input.path\\` (or via \\`kubb generate PATH\\`): ${input}`,\n help: 'Check that the path exists and is readable, then set it in `input.path` or pass it as `kubb generate PATH`.',\n location: { kind: 'config' },\n })\n }\n}\n\n/**\n * Validates an OpenAPI document using `@readme/openapi-parser` with colorized error output.\n *\n * @example\n * ```ts\n * await validateDocument(document)\n * ```\n */\nexport async function validateDocument(document: Document, { throwOnError = false }: ValidateDocumentOptions = {}): Promise<void> {\n try {\n // `validate` dereferences its input in place, so clone to keep the cached document intact.\n const result = await validate(structuredClone(document), {\n validate: {\n errors: { colorize: true },\n },\n })\n\n if (!result.valid) {\n throw new Error(compileErrors(result))\n }\n } catch (error) {\n if (throwOnError) {\n throw error\n }\n\n // Validation failures are non-fatal, mirror plugin-oas behavior\n }\n}\n","import { type Diagnostic, Diagnostics } from '@kubb/core'\nimport { isReference } from './guards.ts'\nimport type { Document } from './types.ts'\n\nconst _refCache = new WeakMap<Document, Map<string, unknown>>()\n\n/**\n * Resolves a local JSON pointer reference from a document.\n *\n * Accepts `#/...` refs. Returns `null` for empty or non-local refs.\n * Throws when the pointer cannot be resolved.\n *\n * @example\n * ```ts\n * resolveRef<SchemaObject>(document, '#/components/schemas/Pet') // SchemaObject | null\n * ```\n */\nexport function resolveRef<T = unknown>(document: Document, $ref: string): T | null {\n const origRef = $ref\n $ref = $ref.trim()\n if ($ref === '') {\n return null\n }\n if (!$ref.startsWith('#')) return null\n $ref = globalThis.decodeURIComponent($ref.substring(1))\n\n let docCache = _refCache.get(document)\n if (!docCache) {\n docCache = new Map()\n _refCache.set(document, docCache)\n }\n\n if (docCache.has($ref)) {\n return docCache.get($ref) as T\n }\n\n const current = $ref\n .split('/')\n .filter(Boolean)\n .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)\n\n if (!current) {\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: 'error',\n message: `Could not find a definition for ${origRef}.`,\n help: 'Add the schema under `components.schemas`, or fix the `$ref`. Run `kubb validate` to check the spec.',\n location: { kind: 'schema', pointer: origRef, ref: origRef },\n }\n // Report the unresolved ref into the active build and resolve to null, like any\n // other unresolvable ref. The build collects it and keeps going. Outside a build there is no\n // sink, so throw rather than silently returning null.\n if (!Diagnostics.report(diagnostic)) {\n throw new Diagnostics.Error(diagnostic)\n }\n return null\n }\n\n docCache.set($ref, current)\n return current as T\n}\n\n/**\n * Resolves a `$ref` object while preserving the original `$ref` field on the result.\n *\n * Useful for parser flows that need both dereferenced fields and pointer\n * identity (for naming/import purposes). Non-reference values are returned as-is.\n *\n * @example\n * ```ts\n * dereferenceWithRef(document, { $ref: '#/components/schemas/Pet' })\n * // { $ref: '#/components/schemas/Pet', type: 'object', properties: { ... } }\n * ```\n */\nexport function dereferenceWithRef<T = unknown>(document: Document, schema?: T): T {\n if (isReference(schema)) {\n return {\n ...schema,\n ...resolveRef(document, schema.$ref),\n $ref: schema.$ref,\n }\n }\n\n return schema as T\n}\n","import { ast } from '@kubb/core'\nimport { isDiscriminator, isNullable, isReference } from './guards.ts'\nimport { resolveRef } from './refs.ts'\nimport type { SchemaObject } from './types.ts'\n\n/**\n * The OpenAPI / Swagger dialect, the default used by `@kubb/adapter-oas`.\n *\n * Implements the spec-agnostic {@link ast.SchemaDialect} contract: it isolates the\n * decisions that differ between specs (nullability, `$ref`, discriminator, binary,\n * ref resolution) so the converter pipeline and dispatch rules stay shared. A\n * future adapter (e.g. AsyncAPI) ships its own dialect, `type: ['null', …]`\n * nullability, no discriminator object, binary via `contentEncoding` and reuses\n * the rest unchanged.\n *\n * Formats (`uuid`, `email`, dates, …) are intentionally NOT here: they are shared\n * JSON Schema vocabulary, so the converters keep that common case.\n *\n * @example\n * ```ts\n * const parser = createSchemaParser(context) // uses oasDialect\n * const parser = createSchemaParser(context, oasDialect) // explicit\n * ```\n */\nexport const oasDialect = ast.defineSchemaDialect({\n name: 'oas',\n isNullable,\n isReference,\n isDiscriminator,\n isBinary: (schema: SchemaObject) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n resolveRef,\n})\n\n/**\n * The concrete dialect type for `@kubb/adapter-oas`. Keeps the OAS guard predicates\n * (`isReference`, `isDiscriminator`) intact so converters narrow schemas after a check.\n */\nexport type OasDialect = typeof oasDialect\n","/**\n * MIME type fragments that mark a media type as JSON-like.\n *\n * Matches the substrings used by the `oas` library's `matchesMimeType.json`, so a content type is\n * JSON when it contains any of these. The `+json` entry catches structured-syntax suffixes such as\n * `application/vnd.api+json`.\n */\nconst jsonMimeFragments = ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'] as const\n\n/**\n * Returns `true` when a media type string is JSON-like.\n *\n * @example\n * ```ts\n * isJsonMimeType('application/json') // true\n * isJsonMimeType('application/vnd.api+json') // true\n * isJsonMimeType('multipart/form-data') // false\n * ```\n */\nexport function isJsonMimeType(mimeType: string): boolean {\n return jsonMimeFragments.some((fragment) => mimeType.includes(fragment))\n}\n","import { SUPPORTED_METHODS } from './constants.ts'\nimport { isReference } from './guards.ts'\nimport { isJsonMimeType } from './mime.ts'\nimport { resolveRef } from './refs.ts'\nimport type { Document, MediaTypeObject, OperationObject, PathItemObject, ReferenceObject, RequestBodyObject, ResponseObject } from './types.ts'\n\n/**\n * A single OpenAPI operation: its URL path, HTTP method, and the raw operation object.\n *\n * `schema` is a live reference into the document, so any in-place `$ref` resolution the resolvers\n * perform is visible here too.\n */\nexport type Operation = {\n path: string\n method: string\n schema: OperationObject\n}\n\n/**\n * The document plus the operation being read. Shared by the request/response accessors so they can\n * resolve `$ref`s against the document.\n */\ntype OperationContext = {\n document: Document\n operation: Operation\n}\n\n/**\n * Slugifies a path for the `operationId` fallback: non-alphanumerics collapse to single dashes,\n * with no leading or trailing dash.\n */\nfunction slugify(value: string): string {\n return value\n .replace(/[^a-zA-Z0-9]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-|-$/g, '')\n}\n\n/**\n * Returns the operation's `operationId`, falling back to `<method>_<slugified-path>` when absent.\n */\nexport function getOperationId({ path, method, schema }: Operation): string {\n const { operationId } = schema\n if (typeof operationId === 'string' && operationId.length > 0) {\n return operationId\n }\n return `${method}_${slugify(path).toLowerCase()}`\n}\n\n/**\n * Returns the declared response status codes, skipping `x-` extensions and non-object entries.\n */\nexport function getResponseStatusCodes({ schema }: Operation): Array<string> {\n const responses = schema.responses as Record<string, unknown> | undefined\n if (!responses || isReference(responses)) {\n return []\n }\n return Object.keys(responses).filter((key) => !key.startsWith('x-') && !!responses[key] && typeof responses[key] === 'object')\n}\n\n/**\n * Returns the response object for a status code, resolving a `$ref` in place. `false` when absent.\n */\nexport function getResponseByStatusCode({ document, operation, statusCode }: OperationContext & { statusCode: string | number }): ResponseObject | false {\n const responses = operation.schema.responses as Record<string, ResponseObject | ReferenceObject> | undefined\n if (!responses || isReference(responses)) {\n return false\n }\n const response = responses[statusCode]\n if (!response) {\n return false\n }\n if (isReference(response)) {\n const resolved = resolveRef<ResponseObject>(document, response.$ref)\n responses[statusCode] = resolved as ResponseObject\n if (!resolved || isReference(resolved)) {\n return false\n }\n return resolved\n }\n return response\n}\n\n/**\n * Resolves the request body (dereferencing a `$ref` in place) and returns its content map, or\n * `undefined` when the operation has no request body.\n */\nfunction getRequestBodyContent({ document, operation }: OperationContext): Record<string, MediaTypeObject> | undefined {\n const { schema } = operation\n let requestBody = schema.requestBody as RequestBodyObject | ReferenceObject | undefined\n if (!requestBody) {\n return undefined\n }\n if (isReference(requestBody)) {\n const resolved = resolveRef<RequestBodyObject>(document, requestBody.$ref)\n ;(schema as { requestBody?: unknown }).requestBody = resolved\n if (!resolved || isReference(resolved)) {\n return undefined\n }\n requestBody = resolved\n }\n return requestBody.content\n}\n\n/**\n * Returns the request body media type. With `mediaType` set, returns that entry or `false`.\n * Otherwise picks the first JSON-like media type, then the first declared one, as a\n * `[mediaType, object]` tuple.\n */\nexport function getRequestContent({\n document,\n operation,\n mediaType,\n}: OperationContext & { mediaType?: string }): MediaTypeObject | false | [string, MediaTypeObject] {\n const content = getRequestBodyContent({ document, operation })\n if (!content) {\n return false\n }\n if (mediaType) {\n return mediaType in content ? content[mediaType]! : false\n }\n const mediaTypes = Object.keys(content)\n const available = mediaTypes.find((mt) => isJsonMimeType(mt)) ?? mediaTypes[0]\n return available ? [available, content[available]!] : false\n}\n\n/**\n * Returns the primary request content type. Prefers a JSON-like media type (the last one wins,\n * matching the previous behavior), then the first declared one, defaulting to `'application/json'`.\n */\nexport function getRequestContentType({ document, operation }: OperationContext): string {\n const content = getRequestBodyContent({ document, operation })\n const mediaTypes = content ? Object.keys(content) : []\n\n let result = mediaTypes[0] ?? 'application/json'\n for (const mt of mediaTypes) {\n if (isJsonMimeType(mt)) {\n result = mt\n }\n }\n return result\n}\n\n/**\n * Builds an `Operation` for every supported HTTP method on every path, in document order.\n * `x-` path keys and unresolvable path-item `$ref`s are skipped.\n *\n * @example\n * ```ts\n * for (const operation of getOperations(document)) {\n * parseOperation(options, operation)\n * }\n * ```\n */\nexport function getOperations(document: Document): Array<Operation> {\n const operations: Array<Operation> = []\n const paths = document.paths\n if (!paths) {\n return operations\n }\n\n for (const path of Object.keys(paths)) {\n if (path.startsWith('x-')) {\n continue\n }\n\n let pathItem = paths[path] as PathItemObject | ReferenceObject | undefined\n if (!pathItem) {\n continue\n }\n if (isReference(pathItem)) {\n const resolved = resolveRef<PathItemObject>(document, pathItem.$ref)\n ;(paths as Record<string, unknown>)[path] = resolved\n if (!resolved || isReference(resolved)) {\n continue\n }\n pathItem = resolved\n }\n\n const item = pathItem as Record<string, unknown>\n for (const method of Object.keys(item)) {\n if (!SUPPORTED_METHODS.has(method)) {\n continue\n }\n const schema = item[method]\n if (!schema || typeof schema !== 'object') {\n continue\n }\n operations.push({ path, method, schema: schema as OperationObject })\n }\n }\n\n return operations\n}\n","import { pascalCase } from '@internals/utils'\nimport { Diagnostics } from '@kubb/core'\nimport type { ast } from '@kubb/core'\nimport { formatMap, SCHEMA_REF_PREFIX, specialCasedFormats, structuralKeys } from './constants.ts'\nimport { isReference } from './guards.ts'\nimport { isJsonMimeType } from './mime.ts'\nimport { getRequestContent, getResponseByStatusCode } from './operation.ts'\nimport { dereferenceWithRef, resolveRef } from './refs.ts'\nimport type { ContentType, Document, MediaTypeObject, Operation, ParameterObject, ResponseObject, SchemaObject, ServerObject } from './types.ts'\n\n/**\n * Replaces `{variable}` placeholders in an OpenAPI server URL with provided values.\n * Resolution order: `overrides[key]` → `variable.default` → left unreplaced.\n * Throws if an override value is not in the variable's `enum` list.\n *\n * @example\n * ```ts\n * resolveServerUrl(\n * { url: 'https://{env}.api.example.com', variables: { env: { default: 'dev', enum: ['dev', 'prod'] } } },\n * { env: 'prod' },\n * )\n * // 'https://prod.api.example.com'\n * ```\n */\nexport function resolveServerUrl(server: ServerObject, overrides?: Record<string, string>): string {\n if (!server.variables) {\n return server.url\n }\n\n let url = server.url\n for (const [key, variable] of Object.entries(server.variables)) {\n const value = overrides?.[key] ?? (variable.default != null ? String(variable.default) : undefined)\n if (value === undefined) {\n continue\n }\n\n if (variable.enum?.length && !variable.enum.some((e) => String(e) === value)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidServerVariable,\n severity: 'error',\n message: `Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`,\n help: `Use one of the allowed enum values, or drop the enum on the '${key}' server variable.`,\n location: { kind: 'document', pointer: '#/servers' },\n })\n }\n\n url = url.replaceAll(`{${key}}`, value)\n }\n\n return url\n}\n\n/**\n * Returns the Kubb `SchemaType` for a given OAS `format` string, or `null` if not found.\n * Formats not in `formatMap` (e.g., `int64`, `date-time`) are handled separately by parser options.\n */\nexport function getSchemaType(format: string): ast.SchemaType | null {\n return formatMap[format as keyof typeof formatMap] ?? null\n}\n\n/**\n * Whether the parser maps `format` to a dedicated type. True for any `formatMap` entry and the\n * `specialCasedFormats` `convertFormat` handles directly. False means the format falls back to the\n * base type, which is what `KUBB_UNSUPPORTED_FORMAT` flags. Reading both sources keeps the\n * diagnostic in step with the parser as `formatMap` grows.\n */\nexport function isHandledFormat(format: string): boolean {\n return getSchemaType(format) !== null || specialCasedFormats.has(format)\n}\n\n/**\n * Converts an OAS primitive type string to its `PrimitiveSchemaType` equivalent.\n * Numeric types (`number`, `integer`, `bigint`) pass through unchanged. `boolean` maps to `'boolean'`. Everything else becomes `'string'`.\n */\nexport function getPrimitiveType(type: string | undefined): ast.PrimitiveSchemaType {\n if (type === 'number' || type === 'integer' || type === 'bigint') return type\n if (type === 'boolean') return 'boolean'\n\n return 'string'\n}\n\nexport type OperationsOptions = {\n contentType?: ContentType\n}\n\n/**\n * Returns all parameters for an operation, merging path-level and operation-level entries.\n * Operation-level parameters override path-level ones with the same `in:name` key.\n * `$ref` parameters resolve via `dereferenceWithRef` for backward compatibility.\n *\n * @example\n * ```ts\n * getParameters(document, operation)\n * // [{ name: 'petId', in: 'path', required: true, schema: { type: 'integer' } }]\n * ```\n */\nexport function getParameters(document: Document, operation: Operation): Array<ParameterObject> {\n const resolveParams = (params: Array<unknown>): Array<ParameterObject> =>\n params.map((p) => dereferenceWithRef(document, p)).filter((p): p is ParameterObject => !!p && typeof p === 'object' && 'in' in p && 'name' in p)\n\n const operationParams = resolveParams(operation.schema?.parameters || [])\n const pathItem = document.paths?.[operation.path]\n const pathLevelParams = resolveParams(pathItem && !isReference(pathItem) && pathItem.parameters ? pathItem.parameters : [])\n\n const paramMap = new Map<string, ParameterObject>()\n for (const p of pathLevelParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n for (const p of operationParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n\n return Array.from(paramMap.values())\n}\n\nfunction getResponseBody(responseBody: boolean | ResponseObject, contentType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...Array<string>] {\n if (!responseBody) return false\n if (isReference(responseBody)) return false\n\n const body = responseBody as ResponseObject\n if (!body.content) return false\n\n if (contentType) {\n if (!(contentType in body.content)) return false\n return body.content[contentType]!\n }\n\n let availableContentType: string | undefined\n const contentTypes = Object.keys(body.content)\n for (const mt of contentTypes) {\n if (isJsonMimeType(mt)) {\n availableContentType = mt\n break\n }\n }\n\n if (!availableContentType) {\n availableContentType = contentTypes[0]\n }\n\n if (availableContentType) {\n return [availableContentType, body.content[availableContentType]!, ...(body.description ? [body.description] : [])]\n }\n\n return false\n}\n\n/**\n * Returns the response schema for a given operation and HTTP status code.\n *\n * Returns an empty object `{}` when no response body schema is available.\n *\n * @example\n * ```ts\n * getResponseSchema(document, operation, 200) // SchemaObject\n * getResponseSchema(document, operation, '4XX') // {}\n * ```\n */\nexport function getResponseSchema(document: Document, operation: Operation, statusCode: string | number, options: OperationsOptions = {}): SchemaObject {\n if (operation.schema.responses) {\n const responses = operation.schema.responses\n for (const key in responses) {\n const schema = responses[key]\n if (schema && isReference(schema)) {\n responses[key] = resolveRef<any>(document, schema.$ref)\n }\n }\n }\n\n const responseBody = getResponseBody(getResponseByStatusCode({ document, operation, statusCode }), options.contentType)\n\n if (responseBody === false) {\n return {}\n }\n\n const schema = Array.isArray(responseBody) ? responseBody[1].schema : responseBody.schema\n\n if (!schema) {\n return {}\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * Returns the request body schema for an operation, or `null` when absent.\n *\n * @example\n * ```ts\n * getRequestSchema(document, operation) // SchemaObject | null\n * ```\n */\nexport function getRequestSchema(document: Document, operation: Operation, options: OperationsOptions = {}): SchemaObject | null {\n if (operation.schema.requestBody) {\n operation.schema.requestBody = dereferenceWithRef(document, operation.schema.requestBody)\n }\n\n const requestBody = getRequestContent({ document, operation, mediaType: options.contentType })\n\n if (requestBody === false) {\n return null\n }\n\n const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema\n\n if (!schema) {\n return null\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * The three component sections Kubb reads schemas from.\n */\ntype SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'\n\n/**\n * A schema annotated with its component section source and original name. Used by `resolveNameCollisions` for cross-source collision resolution.\n */\ntype SchemaWithMetadata = {\n schema: SchemaObject\n source: SchemaSourceMode\n originalName: string\n}\n\nexport type GetSchemasOptions = {\n contentType?: ContentType\n}\n\nexport type GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n nameMapping: Map<string, string>\n}\n\n/**\n * Flattens a keyword-only `allOf` into its parent schema.\n *\n * Only flattens when every member is a plain fragment, with no `$ref` and no structural keywords\n * (see `structuralKeys`). Outer schema values take precedence over fragment values.\n * Returns `null` for a `null` input, and the original schema unchanged when flattening is unsafe.\n *\n * @example\n * ```ts\n * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })\n * // { type: 'object', properties: {}, description: 'A pet' }\n *\n * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })\n * // returned unchanged, contains a $ref\n * ```\n */\n/**\n * Returns `true` when `fragment` carries any JSON Schema keyword that makes it\n * structurally significant on its own (see `structuralKeys`).\n *\n * A fragment with a structural keyword can't be safely merged into a parent schema.\n */\nfunction hasStructuralKeywords(fragment: SchemaObject): boolean {\n for (const key in fragment) {\n if (structuralKeys.has(key as 'properties')) return true\n }\n return false\n}\n\nexport function flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null\n\n const allOfFragments = schema.allOf as Array<SchemaObject>\n if (allOfFragments.some((item) => isReference(item))) return schema\n if (allOfFragments.some(hasStructuralKeywords)) return schema\n\n const merged: SchemaObject = { ...schema }\n delete merged.allOf\n\n for (const fragment of allOfFragments) {\n for (const [key, value] of Object.entries(fragment)) {\n if (merged[key as keyof typeof merged] === undefined) {\n merged[key as keyof typeof merged] = value\n }\n }\n }\n\n return merged\n}\n\n/**\n * Extracts the inline schema from a media-type `content` map.\n *\n * Prefers `preferredContentType` when given, otherwise uses the first key in the map.\n * Returns `null` when `content` is absent, the schema is missing, or the schema is a `$ref`.\n *\n * @example\n * ```ts\n * extractSchemaFromContent(operation.content, 'application/json')\n * // SchemaObject | null\n * ```\n */\nexport function extractSchemaFromContent(content: Record<string, unknown> | undefined, preferredContentType?: ContentType): SchemaObject | null {\n if (!content) return null\n\n const firstContentType = Object.keys(content)[0] ?? 'application/json'\n const targetContentType = preferredContentType ?? firstContentType\n const contentSchema = content[targetContentType] as { schema?: SchemaObject } | undefined\n const schema = contentSchema?.schema\n\n if (schema && '$ref' in schema) return null\n return schema ?? null\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.\n */\nfunction* collectRefs(schema: unknown): Generator<string, void, undefined> {\n if (Array.isArray(schema)) {\n for (const item of schema) yield* collectRefs(item)\n return\n }\n\n if (schema && typeof schema === 'object') {\n for (const key in schema) {\n const value = (schema as Record<string, unknown>)[key]\n if (!(key === '$ref' && typeof value === 'string')) {\n yield* collectRefs(value)\n continue\n }\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = value.slice(SCHEMA_REF_PREFIX.length)\n if (name) yield name\n }\n }\n }\n}\n\n/**\n * Returns a copy of `schemas` topologically sorted by `$ref` dependency.\n *\n * Referenced schemas appear before the schemas that depend on them, so code generators\n * can emit types in the correct order. Cycles are silently skipped.\n *\n * @example\n * ```ts\n * const sorted = sortSchemas({ Order: orderSchema, Pet: petSchema })\n * // Pet appears before Order when Order.$ref points at Pet\n * ```\n */\nexport function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {\n const deps = new Map<string, Array<string>>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n deps.set(name, [...new Set(collectRefs(schema))])\n }\n\n const sorted: Array<string> = []\n const visited = new Set<string>()\n\n function visit(name: string, stack: Set<string>) {\n if (visited.has(name) || stack.has(name)) return\n stack.add(name)\n for (const child of deps.get(name) ?? []) {\n if (deps.has(child)) visit(child, stack)\n }\n stack.delete(name)\n visited.add(name)\n sorted.push(name)\n }\n\n for (const name of Object.keys(schemas)) {\n visit(name, new Set())\n }\n\n const result: Record<string, SchemaObject> = {}\n for (const name of sorted) result[name] = schemas[name]!\n return result\n}\n\nconst semanticSuffixes: Record<SchemaSourceMode, string> = {\n schemas: 'Schema',\n responses: 'Response',\n requestBodies: 'Request',\n}\n\nfunction getSemanticSuffix(source: SchemaSourceMode): string {\n return semanticSuffixes[source]\n}\n\nfunction resolveSchemaRef(document: Document, schema: SchemaObject): SchemaObject {\n if (!isReference(schema)) return schema\n const resolved = resolveRef<SchemaObject>(document, schema.$ref)\n return resolved && !isReference(resolved) ? resolved : schema\n}\n\n/**\n * Collects component schemas from one or more sources and resolves name collisions.\n *\n * Sources default to `['schemas', 'requestBodies', 'responses']`. Returned schemas are\n * topologically sorted by `$ref` dependency so generators emit types in the correct order.\n *\n * When two or more schemas normalize to the same PascalCase name:\n * - Same source → numeric suffix (`2`, `3`, …).\n * - Different sources → semantic suffix (`Schema`, `Response`, `Request`).\n *\n * @example\n * ```ts\n * const { schemas, nameMapping } = getSchemas(document, { contentType: 'application/json' })\n * ```\n */\nexport function getSchemas(document: Document, { contentType }: GetSchemasOptions): GetSchemasResult {\n const components = document.components\n\n const candidates: Array<SchemaWithMetadata> = [\n ...Object.entries((components?.schemas as Record<string, SchemaObject>) ?? {}).map(([name, schema]) => ({\n schema: resolveSchemaRef(document, schema),\n source: 'schemas' as const,\n originalName: name,\n })),\n ...(['responses', 'requestBodies'] as const).flatMap((source) =>\n Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {\n const schema = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)\n return schema\n ? [\n {\n schema: resolveSchemaRef(document, schema),\n source,\n originalName: name,\n },\n ]\n : []\n }),\n ),\n ]\n\n const normalizedNames = new Map<string, Array<SchemaWithMetadata>>()\n for (const item of candidates) {\n const key = pascalCase(item.originalName)\n const bucket = normalizedNames.get(key) ?? []\n bucket.push(item)\n normalizedNames.set(key, bucket)\n }\n\n const schemas: Record<string, SchemaObject> = {}\n const nameMapping = new Map<string, string>()\n\n for (const [, items] of normalizedNames) {\n const isSingle = items.length === 1\n let hasMultipleSources = false\n if (!isSingle) {\n const firstSource = items[0]!.source\n for (let i = 1; i < items.length; i++) {\n if (items[i]!.source !== firstSource) {\n hasMultipleSources = true\n break\n }\n }\n }\n\n items.forEach((item, index) => {\n const suffix = isSingle ? '' : hasMultipleSources ? getSemanticSuffix(item.source) : index === 0 ? '' : String(index + 1)\n const uniqueName = item.originalName + suffix\n schemas[uniqueName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas), nameMapping }\n}\n\n/**\n * Resolves the AST type descriptor for a date/time format, honoring the `dateType` option.\n * Returns `null` when `dateType: false`, signalling the format should fall through to `string`.\n */\nexport function getDateType(\n options: ast.ParserOptions,\n format: 'date-time' | 'date' | 'time',\n): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | null {\n if (!options.dateType) {\n return null\n }\n\n if (format === 'date-time') {\n if (options.dateType === 'date') {\n return { type: 'date', representation: 'date' }\n }\n if (options.dateType === 'stringOffset') {\n return { type: 'datetime', offset: true }\n }\n if (options.dateType === 'stringLocal') {\n return { type: 'datetime', local: true }\n }\n return { type: 'datetime', offset: false }\n }\n\n if (format === 'date') {\n return {\n type: 'date',\n representation: options.dateType === 'date' ? 'date' : 'string',\n }\n }\n\n // time\n return {\n type: 'time',\n representation: options.dateType === 'date' ? 'date' : 'string',\n }\n}\n\n/**\n * Collects the shared metadata fields passed to every `createSchema` call.\n */\nexport function buildSchemaNode(schema: SchemaObject, name: string | null | undefined, nullable: true | undefined, defaultValue: unknown) {\n return {\n name,\n nullable,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n default: defaultValue,\n example: schema.example,\n format: schema.format,\n } as const\n}\n\n/**\n * Returns all request body content type keys for an operation.\n *\n * The requestBody is dereferenced in place when it is a `$ref` (the same mutation that\n * `getRequestSchema` already performs), so the returned list accurately reflects the\n * available content types even for referenced bodies.\n *\n * @example\n * ```ts\n * getRequestBodyContentTypes(document, operation)\n * // ['application/json', 'multipart/form-data']\n * ```\n */\nexport function getRequestBodyContentTypes(document: Document, operation: Operation): Array<string> {\n if (operation.schema.requestBody) {\n operation.schema.requestBody = dereferenceWithRef(document, operation.schema.requestBody)\n }\n\n const body = operation.schema.requestBody as { content?: Record<string, unknown> } | undefined\n if (!body) return []\n\n // dereferenceWithRef keeps $ref but spreads all resolved fields (including `content`).\n // Do not bail out on isReference, the content is already present on the merged object.\n return body.content ? Object.keys(body.content) : []\n}\n\n/**\n * Returns all response content type keys for an operation at a given status code.\n *\n * Response `$ref`s are resolved in place first (the same mutation `getResponseSchema` performs),\n * so the returned list reflects the available content types even for referenced responses.\n *\n * @example\n * ```ts\n * getResponseBodyContentTypes(document, operation, 200)\n * // ['application/json', 'application/xml']\n * ```\n */\nexport function getResponseBodyContentTypes(document: Document, operation: Operation, statusCode: string | number): Array<string> {\n if (operation.schema.responses) {\n const responses = operation.schema.responses\n for (const key in responses) {\n const schema = responses[key]\n if (schema && isReference(schema)) {\n responses[key] = resolveRef<any>(document, schema.$ref)\n }\n }\n }\n\n const responseObj = getResponseByStatusCode({ document, operation, statusCode })\n if (!responseObj || typeof responseObj !== 'object' || isReference(responseObj)) return []\n\n const body = responseObj as { content?: Record<string, unknown> }\n return body.content ? Object.keys(body.content) : []\n}\n","import { pascalCase } from '@internals/utils'\nimport { childName, enumPropName, extractRefName, findDiscriminator } from '@kubb/ast/utils'\nimport { ast } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS, enumExtensionKeys, SCHEMA_REF_PREFIX, typeOptionMap } from './constants.ts'\nimport { oasDialect, type OasDialect } from './dialect.ts'\nimport { getOperationId, getOperations, getRequestContentType, getResponseByStatusCode, getResponseStatusCodes } from './operation.ts'\nimport {\n buildSchemaNode,\n flattenSchema,\n getDateType,\n getParameters,\n getPrimitiveType,\n getRequestBodyContentTypes,\n getRequestSchema,\n getResponseBodyContentTypes,\n getResponseSchema,\n getSchemas,\n getSchemaType,\n} from './resolvers.ts'\nimport type { ContentType, Document, Operation, ReferenceObject, SchemaObject } from './types.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and optional content-type override.\n *\n * Passed to schema and operation converters to access the full specification\n * and handle content negotiation when multiple media types are available.\n */\nexport type OasParserContext = {\n document: Document\n contentType?: ContentType\n}\n\n/**\n * The object returned by {@link createSchemaParser}.\n * Contains parser functions bound to a specific document.\n */\nexport type SchemaParser = {\n parseSchema: (entry: { schema: SchemaObject; name?: string | null }, options?: Partial<ast.ParserOptions>) => ast.SchemaNode\n parseOperation: (options: ast.ParserOptions, operation: Operation) => ast.OperationNode\n parseParameter: (options: ast.ParserOptions, param: Record<string, unknown>) => ast.ParameterNode\n}\n\n/**\n * Pre-computed per-schema context passed to every schema converter.\n *\n * Centralizes schema derivations (type resolution, defaults, options) to avoid repeated\n * computation across all conversion branches. The `type` field is normalized from OAS 3.1\n * multi-type arrays to a single string.\n */\ntype SchemaContext = {\n schema: SchemaObject\n name: string | null | undefined\n nullable: true | undefined\n defaultValue: unknown\n /**\n * Normalized single type string (first element when OAS 3.1 multi-type array).\n */\n type: string | undefined\n rawOptions: Partial<ast.ParserOptions> | undefined\n options: ast.ParserOptions\n}\n\n/**\n * One entry in the ordered schema rule table: a predicate paired with a converter. A rule whose\n * `match` returns `true` may still `convert` to `null` to defer to the next rule (e.g. a `format`\n * that is not convertible falls through to plain `type` handling).\n */\ntype SchemaRule = {\n /** Identifies the rule when reading the table or debugging which branch ran. */\n name: string\n /** Returns `true` when this rule is responsible for the given context. */\n match: (context: SchemaContext) => boolean\n /** Produces a node for the context, or `null` to fall through to the next rule. */\n convert: (context: SchemaContext) => ast.SchemaNode | null\n}\n\n/**\n * Normalizes malformed `{ type: 'array', enum: [...] }` schemas by moving enum values into items.\n *\n * This pattern violates the OpenAPI spec but appears in real specs. The fix moves enum values\n * from the array to its items sub-schema, making them valid for downstream processing.\n *\n * @note This is a defensive measure for robustness with non-compliant specs.\n */\nfunction normalizeArrayEnum(schema: SchemaObject): SchemaObject {\n const isItemsObject = typeof schema.items === 'object' && !Array.isArray(schema.items)\n const normalizedItems: SchemaObject = {\n ...(isItemsObject ? (schema.items as SchemaObject) : {}),\n enum: schema.enum,\n }\n const { enum: _enum, ...schemaWithoutEnum } = schema\n\n return { ...schemaWithoutEnum, items: normalizedItems } as SchemaObject\n}\n\n/**\n * Factory function that creates schema and operation converters for a given OpenAPI context.\n *\n * Returns closures that share mutable state (`resolvingRefs` set for cycle detection).\n * Each converter branch (`convertRef`, `convertAllOf`, etc.) mutually recursively calls `parseSchema`,\n * made possible by hoisting of function declarations.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: OasParserContext, dialect: OasDialect = oasDialect) {\n const document = ctx.document\n\n // Branch handlers, each converts one OAS schema pattern to a SchemaNode.\n\n /**\n * Tracks `$ref` paths that are currently being resolved to prevent infinite\n * recursion when schemas contain circular references (e.g. `Pet → parent → Pet`).\n */\n const resolvingRefs = new Set<string>()\n\n /**\n * Cache of `$ref` schemas already resolved in this parser instance, keyed by ref path.\n *\n * Without it, a shared schema (e.g. `customer`) is re-expanded for every `$ref` that points at\n * it. In cross-referenced specs like Stripe (~1400 schemas) that becomes exponential blowup,\n * since one schema can be referenced from dozens of parents, each re-walking its whole subtree.\n * Memoizing by ref path drops the work from O(2^depth) to O(N) unique schema names.\n */\n const resolvedRefCache = new Map<string, ast.SchemaNode | null>()\n\n /**\n * Converts a `$ref` schema into a `RefSchemaNode`.\n *\n * The resolved schema is stored in `node.schema`. Usage-site sibling fields\n * (description, readOnly, nullable, etc.) are stored directly on the ref node.\n * Use `syncSchemaRef(node)` in printers to get a merged view of both.\n * Circular refs are detected via `resolvingRefs` and leave `schema` as `undefined`.\n */\n function convertRef({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n let resolvedSchema: ast.SchemaNode | null = null\n const refPath = schema.$ref\n if (refPath && !resolvingRefs.has(refPath)) {\n if (!resolvedRefCache.has(refPath)) {\n try {\n const referenced = dialect.resolveRef<SchemaObject>(document, refPath)\n if (referenced) {\n resolvingRefs.add(refPath)\n resolvedSchema = parseSchema({ schema: referenced }, rawOptions)\n resolvingRefs.delete(refPath)\n }\n } catch {\n // Ref cannot be resolved in this document (e.g. unit tests with minimal documents).\n }\n resolvedRefCache.set(refPath, resolvedSchema)\n }\n resolvedSchema = resolvedRefCache.get(refPath) ?? null\n }\n\n return ast.createSchema({\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n type: 'ref',\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n schema: resolvedSchema,\n })\n }\n\n /**\n * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.\n */\n function convertAllOf({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n if (\n schema.allOf!.length === 1 &&\n !schema.properties &&\n !(Array.isArray(schema.required) && schema.required.length) &&\n schema.additionalProperties === undefined\n ) {\n const [memberSchema] = schema.allOf as Array<SchemaObject | ReferenceObject>\n const memberNode = parseSchema({ schema: memberSchema! as SchemaObject, name }, rawOptions)\n const { kind: _kind, ...memberNodeProps } = memberNode\n const mergedNullable = nullable || memberNode.nullable || undefined\n const mergedDefault = schema.default === null && mergedNullable ? undefined : (schema.default ?? memberNode.default)\n\n return ast.createSchema({\n ...memberNodeProps,\n name,\n title: schema.title ?? memberNode.title,\n description: schema.description ?? memberNode.description,\n deprecated: schema.deprecated ?? memberNode.deprecated,\n nullable: mergedNullable,\n readOnly: schema.readOnly ?? memberNode.readOnly,\n writeOnly: schema.writeOnly ?? memberNode.writeOnly,\n default: mergedDefault,\n example: schema.example ?? memberNode.example,\n pattern: schema.pattern ?? ('pattern' in memberNode ? memberNode.pattern : undefined),\n format: schema.format ?? memberNode.format,\n } as ast.DistributiveOmit<ast.SchemaNode, 'kind'>)\n }\n\n const filteredDiscriminantValues: Array<{\n propertyName: string\n value: string\n }> = []\n const allOfMembers: Array<ast.SchemaNode> = (schema.allOf as Array<SchemaObject | ReferenceObject>)\n .filter((item) => {\n if (!dialect.isReference(item) || !name) return true\n const deref = dialect.resolveRef<SchemaObject>(document, item.$ref)\n if (!deref || !dialect.isDiscriminator(deref)) return true\n const parentUnion = deref.oneOf ?? deref.anyOf\n if (!parentUnion) return true\n const childRef = `${SCHEMA_REF_PREFIX}${name}`\n const inOneOf = parentUnion.some((oneOfItem) => dialect.isReference(oneOfItem) && oneOfItem.$ref === childRef)\n const inMapping = Object.values(deref.discriminator.mapping ?? {}).some((v) => v === childRef)\n if (inOneOf || inMapping) {\n const discriminatorValue = findDiscriminator(deref.discriminator.mapping, childRef)\n if (discriminatorValue) {\n filteredDiscriminantValues.push({\n propertyName: deref.discriminator.propertyName,\n value: discriminatorValue,\n })\n }\n return false\n }\n return true\n })\n .map((s) => parseSchema({ schema: s as SchemaObject, name }, rawOptions))\n\n const syntheticStart = allOfMembers.length\n\n if (Array.isArray(schema.required) && schema.required.length) {\n const outerKeys = schema.properties ? new Set(Object.keys(schema.properties)) : new Set<string>()\n const missingRequired = schema.required.filter((key) => !outerKeys.has(key))\n\n if (missingRequired.length) {\n const resolvedMembers = (schema.allOf as Array<SchemaObject | ReferenceObject>).flatMap((item) => {\n if (!dialect.isReference(item)) return [item as SchemaObject]\n const deref = dialect.resolveRef<SchemaObject>(document, item.$ref)\n return deref && !dialect.isReference(deref) ? [deref] : []\n })\n\n for (const key of missingRequired) {\n for (const resolved of resolvedMembers) {\n if (resolved.properties?.[key]) {\n allOfMembers.push(\n parseSchema(\n {\n schema: {\n properties: { [key]: resolved.properties[key] },\n required: [key],\n } as SchemaObject,\n name,\n },\n rawOptions,\n ),\n )\n break\n }\n }\n }\n }\n }\n\n if (schema.properties) {\n const { allOf: _allOf, ...schemaWithoutAllOf } = schema\n // Don't pass `name` here, the result must stay anonymous so it can be merged with the\n // adjacent synthetic object in `mergeAdjacentObjectsLazy`. Nested enum qualification\n // happens upstream via `convertObject`'s `setEnumName` propagation.\n allOfMembers.push(parseSchema({ schema: schemaWithoutAllOf }, rawOptions))\n }\n\n for (const { propertyName, value } of filteredDiscriminantValues) {\n allOfMembers.push(ast.createDiscriminantNode({ propertyName, value }))\n }\n\n return ast.createSchema({\n type: 'intersection',\n members: [...ast.mergeAdjacentObjectsLazy(allOfMembers.slice(0, syntheticStart)), ...ast.mergeAdjacentObjectsLazy(allOfMembers.slice(syntheticStart))],\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n */\n function convertUnion({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n function pickDiscriminatorPropertyNode(node: ast.SchemaNode, propertyName: string): ast.SchemaNode | null {\n const objectNode = ast.narrowSchema(node, 'object')\n const discriminatorProperty = objectNode?.properties?.find((property) => property.name === propertyName)\n\n if (!discriminatorProperty) {\n return null\n }\n\n return ast.createSchema({\n type: 'object',\n primitive: 'object',\n properties: [discriminatorProperty],\n })\n }\n\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const unionBase = {\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n discriminatorPropertyName: dialect.isDiscriminator(schema) ? schema.discriminator.propertyName : undefined,\n strategy,\n }\n const discriminator = dialect.isDiscriminator(schema) ? schema.discriminator : undefined\n const sharedPropertiesNode = schema.properties\n ? (() => {\n const { oneOf: _oneOf, anyOf: _anyOf, ...schemaWithoutUnion } = schema\n const memberBaseSchema: SchemaObject = discriminator\n ? (Object.fromEntries(Object.entries(schemaWithoutUnion).filter(([key]) => key !== 'discriminator')) as SchemaObject)\n : schemaWithoutUnion\n return parseSchema({ schema: memberBaseSchema, name }, rawOptions)\n })()\n : undefined\n\n if (sharedPropertiesNode || discriminator?.mapping) {\n const members = unionMembers.map((s) => {\n const ref = dialect.isReference(s) ? s.$ref : undefined\n const discriminatorValue = findDiscriminator(discriminator?.mapping, ref)\n const memberNode = parseSchema({ schema: s as SchemaObject, name }, rawOptions)\n\n if (!discriminatorValue || !discriminator) {\n return memberNode\n }\n\n const narrowedDiscriminatorNode = sharedPropertiesNode\n ? pickDiscriminatorPropertyNode(\n ast.setDiscriminatorEnum({\n node: sharedPropertiesNode,\n propertyName: discriminator.propertyName,\n values: [discriminatorValue],\n }),\n discriminator.propertyName,\n )\n : undefined\n\n return ast.createSchema({\n type: 'intersection',\n members: [\n memberNode,\n narrowedDiscriminatorNode ??\n ast.createDiscriminantNode({\n propertyName: discriminator.propertyName,\n value: discriminatorValue,\n }),\n ],\n })\n })\n\n const unionNode = ast.createSchema({\n type: 'union',\n ...unionBase,\n members,\n })\n\n if (!sharedPropertiesNode) {\n return unionNode\n }\n\n return ast.createSchema({\n type: 'intersection',\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n members: [unionNode, sharedPropertiesNode],\n })\n }\n\n return ast.createSchema({\n type: 'union',\n ...unionBase,\n members: ast.simplifyUnion(unionMembers.map((s) => parseSchema({ schema: s as SchemaObject, name }, rawOptions))),\n })\n }\n\n /**\n * Converts an OAS 3.1 `const` schema into a null scalar or a single-value `EnumSchemaNode`.\n */\n function convertConst({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n const constValue = schema.const\n\n if (constValue === null) {\n return ast.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n format: schema.format,\n })\n }\n\n const constPrimitive = getPrimitiveType(typeof constValue === 'number' ? 'number' : typeof constValue === 'boolean' ? 'boolean' : 'string')\n return ast.createSchema({\n type: 'enum',\n primitive: constPrimitive,\n enumValues: [constValue as string | number | boolean],\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a format-annotated schema into a special-type `SchemaNode`.\n * Returns `null` when the format should fall through to string handling (`dateType: false`).\n */\n function convertFormat({ schema, name, nullable, defaultValue, options }: SchemaContext): ast.SchemaNode | null {\n const base = buildSchemaNode(schema, name, nullable, defaultValue)\n\n if (schema.format === 'int64') {\n return ast.createSchema({\n type: options.integerType === 'bigint' ? 'bigint' : 'integer',\n primitive: 'integer',\n ...base,\n min: schema.minimum,\n max: schema.maximum,\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n })\n }\n\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const dateType = getDateType(options, schema.format)\n if (!dateType) return null\n\n if (dateType.type === 'datetime') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'datetime',\n offset: dateType.offset,\n local: dateType.local,\n })\n }\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: dateType.type,\n representation: dateType.representation,\n })\n }\n\n const specialType = getSchemaType(schema.format!)\n if (!specialType) return null\n\n const specialPrimitive: ast.PrimitiveSchemaType = specialType === 'number' || specialType === 'integer' || specialType === 'bigint' ? specialType : 'string'\n\n if (specialType === 'number' || specialType === 'integer' || specialType === 'bigint') {\n return ast.createSchema({\n ...base,\n primitive: specialPrimitive,\n type: specialType,\n })\n }\n if (specialType === 'url') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'url',\n min: schema.minLength,\n max: schema.maxLength,\n })\n }\n if (specialType === 'ipv4') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'ipv4',\n })\n }\n if (specialType === 'ipv6') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'ipv6',\n })\n }\n if (specialType === 'uuid' || specialType === 'email') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: specialType,\n min: schema.minLength,\n max: schema.maxLength,\n })\n }\n\n return ast.createSchema({\n ...base,\n primitive: specialPrimitive,\n type: specialType as ast.ScalarSchemaType,\n })\n }\n\n /**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n */\n function convertEnum({ schema, name, nullable, type, rawOptions }: SchemaContext): ast.SchemaNode {\n if (type === 'array') {\n return parseSchema({ schema: normalizeArrayEnum(schema), name }, rawOptions)\n }\n\n const nullInEnum = schema.enum!.includes(null)\n const filteredValues = (nullInEnum ? schema.enum!.filter((v) => v !== null) : schema.enum!) as Array<string | number | boolean>\n\n // drf-spectacular `NullEnum` ({ enum: [null] }) is just `null`. An empty enum node would\n // render as `never` (plugin-ts) / invalid `z.enum([])` (plugin-zod). Mirror the `const: null`\n // branch so it renders as a clean `null` (not `z.null().nullable()`).\n if (nullInEnum && filteredValues.length === 0) {\n return ast.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n format: schema.format,\n })\n }\n\n const enumNullable = nullable || nullInEnum || undefined\n const enumDefault = schema.default === null && enumNullable ? undefined : schema.default\n const enumPrimitive = getPrimitiveType(type)\n\n const enumBase = {\n type: 'enum' as const,\n primitive: enumPrimitive,\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable: enumNullable,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n default: enumDefault,\n example: schema.example,\n format: schema.format,\n }\n\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n if (extensionKey || enumPrimitive === 'number' || enumPrimitive === 'integer' || enumPrimitive === 'boolean') {\n const enumPrimitiveType = (enumPrimitive === 'number' || enumPrimitive === 'integer' ? 'number' : enumPrimitive === 'boolean' ? 'boolean' : 'string') as\n | 'number'\n | 'boolean'\n | 'string'\n const rawEnumNames = extensionKey ? ((schema as Record<string, unknown>)[extensionKey] as Array<string | number>) : undefined\n const uniqueValues = [...new Set(filteredValues)]\n const seenNames = new Set<string>()\n\n return ast.createSchema({\n ...enumBase,\n primitive: enumPrimitiveType,\n namedEnumValues: uniqueValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive: enumPrimitiveType,\n }))\n .filter((entry) => {\n if (seenNames.has(entry.name)) return false\n seenNames.add(entry.name)\n return true\n }),\n })\n }\n\n return ast.createSchema({\n ...enumBase,\n enumValues: [...new Set(filteredValues)],\n })\n }\n\n /**\n * Converts an object-like schema into an `ObjectSchemaNode`.\n */\n function convertObject({ schema, name, nullable, defaultValue, rawOptions, options }: SchemaContext): ast.SchemaNode {\n const properties: Array<ast.PropertyNode> = schema.properties\n ? Object.entries(schema.properties).map(([propName, propSchema]) => {\n const required = Array.isArray(schema.required) ? schema.required.includes(propName) : !!schema.required\n const resolvedPropSchema = propSchema as SchemaObject\n const propNullable = dialect.isNullable(resolvedPropSchema)\n\n const resolvedChildName = childName(name, propName)\n const propNode = parseSchema({ schema: resolvedPropSchema, name: resolvedChildName }, rawOptions)\n const schemaNode = (() => {\n const node = ast.setEnumName(propNode, name, propName, options.enumSuffix)\n const tupleNode = ast.narrowSchema(node, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => ast.setEnumName(item, name, propName, options.enumSuffix))\n if (namedItems.some((item, i) => item !== tupleNode.items![i])) {\n return { ...tupleNode, items: namedItems }\n }\n }\n return node\n })()\n\n return ast.createProperty({\n name: propName,\n schema: {\n ...schemaNode,\n nullable: schemaNode.type === 'null' ? undefined : propNullable || undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n const additionalPropertiesNode: ast.SchemaNode | boolean | undefined = (() => {\n if (additionalProperties === true) return true\n if (additionalProperties === false) return false\n if (additionalProperties && Object.keys(additionalProperties).length > 0) {\n return parseSchema({ schema: additionalProperties as SchemaObject }, rawOptions)\n }\n if (additionalProperties) return ast.createSchema({ type: typeOptionMap.get(options.unknownType)! })\n return undefined\n })()\n\n const rawPatternProperties = 'patternProperties' in schema ? schema.patternProperties : undefined\n\n const patternProperties = rawPatternProperties\n ? Object.fromEntries(\n Object.entries(rawPatternProperties).map(([pattern, patternSchema]) => [\n pattern,\n patternSchema === true || (typeof patternSchema === 'object' && Object.keys(patternSchema).length === 0)\n ? ast.createSchema({\n type: typeOptionMap.get(options.unknownType)!,\n })\n : parseSchema({ schema: patternSchema as SchemaObject }, rawOptions),\n ]),\n )\n : undefined\n\n const objectNode: ast.SchemaNode = ast.createSchema({\n type: 'object',\n primitive: 'object',\n properties,\n additionalProperties: additionalPropertiesNode,\n patternProperties,\n minProperties: schema.minProperties,\n maxProperties: schema.maxProperties,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n\n if (dialect.isDiscriminator(schema) && schema.discriminator.mapping) {\n const discPropName = schema.discriminator.propertyName\n const values = Object.keys(schema.discriminator.mapping)\n const enumName = name ? enumPropName(name, discPropName, options.enumSuffix) : undefined\n return ast.setDiscriminatorEnum({\n node: objectNode,\n propertyName: discPropName,\n values,\n enumName,\n })\n }\n\n return objectNode\n }\n\n /**\n * Converts an OAS 3.1 `prefixItems` tuple into a `TupleSchemaNode`.\n */\n function convertTuple({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => parseSchema({ schema: item as SchemaObject }, rawOptions))\n const rest = schema.items ? parseSchema({ schema: schema.items as SchemaObject }, rawOptions) : ast.createSchema({ type: 'any' })\n\n return ast.createSchema({\n type: 'tuple',\n primitive: 'array',\n items: tupleItems,\n rest,\n min: schema.minItems,\n max: schema.maxItems,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'array'` schema into an `ArraySchemaNode`.\n */\n function convertArray({ schema, name, nullable, defaultValue, rawOptions, options }: SchemaContext): ast.SchemaNode {\n const rawItems = schema.items as SchemaObject | undefined\n const itemName = rawItems?.enum?.length && name ? enumPropName(null, name, options.enumSuffix) : name\n const items = rawItems ? [parseSchema({ schema: rawItems, name: itemName }, rawOptions)] : []\n\n return ast.createSchema({\n type: 'array',\n primitive: 'array',\n items,\n min: schema.minItems,\n max: schema.maxItems,\n unique: schema.uniqueItems ?? undefined,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'string'` schema into a `StringSchemaNode`.\n */\n function convertString({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'number'` or `type: 'integer'` schema.\n */\n function convertNumeric({ schema, name, nullable, defaultValue }: SchemaContext, type: 'number' | 'integer'): ast.SchemaNode {\n return ast.createSchema({\n type,\n primitive: type,\n min: schema.minimum,\n max: schema.maximum,\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n multipleOf: schema.multipleOf,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'boolean'` schema.\n */\n function convertBoolean({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'boolean',\n primitive: 'boolean',\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts an explicit `type: 'null'` schema.\n */\n function convertNull({ schema, name, nullable }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable,\n format: schema.format,\n })\n }\n\n /**\n * Converts a binary string schema (`type: 'string'`, `contentMediaType: 'application/octet-stream'`)\n * into a `blob` node.\n */\n function convertBlob({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'blob',\n primitive: 'string',\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts an OAS 3.1 multi-type array (e.g. `type: ['string', 'number']`) into a `UnionSchemaNode`.\n *\n * Returns `null` when only one non-`null` type remains (e.g. `['string', 'null']`), so `parseSchema`\n * falls through and handles it as that single type with nullability already folded in.\n */\n function convertMultiType({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode | null {\n const types = schema.type as Array<string>\n const nonNullTypes = types.filter((t) => t !== 'null')\n if (nonNullTypes.length <= 1) return null\n\n const arrayNullable = types.includes('null') || nullable || undefined\n return ast.createSchema({\n type: 'union',\n members: nonNullTypes.map((t) => parseSchema({ schema: { ...schema, type: t } as SchemaObject, name }, rawOptions)),\n ...buildSchemaNode(schema, name, arrayNullable, defaultValue),\n })\n }\n\n /**\n * Ordered schema rule table. Order is significant: composition keywords (`$ref`, `allOf`,\n * `oneOf`/`anyOf`) take precedence over `const`/`format`, which take precedence over the plain\n * `type`. The first matching rule that produces a node wins. See {@link SchemaRule} for the\n * match/convert/fall-through contract.\n */\n const schemaRules: Array<SchemaRule> = [\n { name: 'ref', match: ({ schema }) => dialect.isReference(schema), convert: convertRef },\n { name: 'allOf', match: ({ schema }) => !!schema.allOf?.length, convert: convertAllOf },\n { name: 'union', match: ({ schema }) => !!(schema.oneOf?.length || schema.anyOf?.length), convert: convertUnion },\n { name: 'const', match: ({ schema }) => 'const' in schema && schema.const !== undefined, convert: convertConst },\n { name: 'format', match: ({ schema }) => !!schema.format, convert: convertFormat },\n {\n name: 'blob',\n match: ({ schema }) => dialect.isBinary(schema),\n convert: convertBlob,\n },\n { name: 'multi-type', match: ({ schema }) => Array.isArray(schema.type) && schema.type.length > 1, convert: convertMultiType },\n {\n name: 'constrained-string',\n match: ({ schema, type }) => !type && (schema.minLength !== undefined || schema.maxLength !== undefined || schema.pattern !== undefined),\n convert: convertString,\n },\n {\n name: 'constrained-number',\n match: ({ schema, type }) => !type && (schema.minimum !== undefined || schema.maximum !== undefined),\n convert: (ctx) => convertNumeric(ctx, 'number'),\n },\n { name: 'enum', match: ({ schema }) => !!schema.enum?.length, convert: convertEnum },\n {\n name: 'object',\n match: ({ schema, type }) => type === 'object' || !!schema.properties || !!schema.additionalProperties || 'patternProperties' in schema,\n convert: convertObject,\n },\n { name: 'tuple', match: ({ schema }) => 'prefixItems' in schema, convert: convertTuple },\n { name: 'array', match: ({ schema, type }) => type === 'array' || 'items' in schema, convert: convertArray },\n { name: 'string', match: ({ type }) => type === 'string', convert: convertString },\n { name: 'number', match: ({ type }) => type === 'number', convert: (ctx) => convertNumeric(ctx, 'number') },\n { name: 'integer', match: ({ type }) => type === 'integer', convert: (ctx) => convertNumeric(ctx, 'integer') },\n { name: 'boolean', match: ({ type }) => type === 'boolean', convert: convertBoolean },\n { name: 'null', match: ({ type }) => type === 'null', convert: convertNull },\n ]\n\n /**\n * Converts an OAS `SchemaObject` into a `SchemaNode`.\n *\n * Builds the per-schema context, then walks the ordered {@link schemaRules} table and returns\n * the first converter that produces a node. When none match, falls back to the configured\n * `emptySchemaType`.\n */\n function parseSchema({ schema, name }: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>): ast.SchemaNode {\n const options: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n ...rawOptions,\n }\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema && flattenedSchema !== schema) {\n return parseSchema({ schema: flattenedSchema, name }, rawOptions)\n }\n\n const nullable = dialect.isNullable(schema) || undefined\n const defaultValue = schema.default === null && nullable ? undefined : schema.default\n const type = Array.isArray(schema.type) ? schema.type[0] : schema.type\n\n const schemaCtx: SchemaContext = {\n schema,\n name,\n nullable,\n defaultValue,\n type,\n rawOptions,\n options,\n }\n\n for (const rule of schemaRules) {\n if (!rule.match(schemaCtx)) continue\n const node = rule.convert(schemaCtx)\n if (node) return node\n }\n\n const emptyType = typeOptionMap.get(options.emptySchemaType)!\n return ast.createSchema({\n type: emptyType as ast.ScalarSchemaType,\n name,\n title: schema.title,\n description: schema.description,\n format: schema.format,\n })\n }\n\n /**\n * Converts a dereferenced OAS parameter object into a `ParameterNode`.\n */\n function parseParameter(options: ast.ParserOptions, param: Record<string, unknown>, parentName?: string): ast.ParameterNode {\n const required = (param['required'] as boolean | undefined) ?? false\n const paramName = param['name'] as string\n const schemaName = parentName && paramName ? pascalCase(`${parentName} ${paramName}`) : undefined\n\n const schema: ast.SchemaNode = param['schema']\n ? parseSchema({ schema: param['schema'] as SchemaObject, name: schemaName }, options)\n : ast.createSchema({ type: typeOptionMap.get(options.unknownType)! })\n\n return ast.createParameter({\n name: paramName,\n in: param['in'] as ast.ParameterLocation,\n schema: {\n ...schema,\n description: (param['description'] as string | undefined) ?? schema.description,\n },\n required,\n })\n }\n\n /**\n * Reads the inline `requestBody` metadata (description / required) that OAS exposes\n * outside the schema itself. Returns an empty object when the request body is missing or a `$ref`.\n */\n function getRequestBodyMeta(operation: Operation): {\n description?: string\n required: boolean\n } {\n const body = operation.schema.requestBody as { description?: string; required?: boolean } | undefined\n if (!body) return { required: false }\n\n // After getRequestBodyContentTypes has run, body may still carry $ref but the\n // resolved fields (description, required, content) are already spread onto it.\n return {\n description: body.description,\n required: body.required === true,\n }\n }\n\n /**\n * Reads the inline response object (not a `$ref`) and returns its description plus its `content` map.\n */\n function getResponseMeta(responseObj: unknown): {\n description?: string\n content?: Record<string, unknown>\n } {\n if (typeof responseObj !== 'object' || responseObj === null || Array.isArray(responseObj)) return {}\n\n const inline = responseObj as {\n description?: string\n content?: Record<string, unknown>\n }\n return { description: inline.description, content: inline.content }\n }\n\n /**\n * Collects property names whose schema has a truthy boolean flag (`readOnly` or `writeOnly`).\n * `$ref` entries are skipped since their flags live on the dereferenced target.\n */\n function collectPropertyKeysByFlag(schema: SchemaObject | null, flag: 'readOnly' | 'writeOnly'): Array<string> | null {\n if (!schema?.properties) return null\n\n const keys: Array<string> = []\n for (const key in schema.properties) {\n const prop = schema.properties[key]\n if (prop && !dialect.isReference(prop) && (prop as Record<string, unknown>)[flag]) {\n keys.push(key)\n }\n }\n return keys.length ? keys : null\n }\n\n /**\n * Converts an OAS `Operation` into an `OperationNode`.\n */\n function parseOperation(options: ast.ParserOptions, operation: Operation): ast.OperationNode {\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const parameters: Array<ast.ParameterNode> = getParameters(document, operation).map((param) =>\n parseParameter(options, param as unknown as Record<string, unknown>, operationName),\n )\n\n // Determine which content types to include in requestBody.content.\n // When a global contentType is configured, restrict to that single type.\n // Otherwise include every content type declared in the spec.\n const allContentTypes = ctx.contentType ? [ctx.contentType] : getRequestBodyContentTypes(document, operation)\n\n const requestBodyMeta = getRequestBodyMeta(operation)\n const requestBodyName = operationName ? `${operationName}Request` : undefined\n\n const content = allContentTypes.flatMap((ct) => {\n const schema = getRequestSchema(document, operation, { contentType: ct })\n if (!schema) return []\n return [\n {\n contentType: ct,\n schema: ast.syncOptionality(parseSchema({ schema, name: requestBodyName }, options), requestBodyMeta.required),\n keysToOmit: collectPropertyKeysByFlag(schema, 'readOnly'),\n },\n ]\n })\n\n const requestBody =\n content.length > 0 || requestBodyMeta.description\n ? {\n description: requestBodyMeta.description,\n required: requestBodyMeta.required || undefined,\n content: content.length > 0 ? content : undefined,\n }\n : undefined\n\n const responses: Array<ast.ResponseNode> = getResponseStatusCodes(operation).map((statusCode) => {\n const responseObj = getResponseByStatusCode({ document, operation, statusCode })\n\n // Use `Status<code>` (matching plugin-ts's resolveResponseStatusName convention) so the\n // qualified names for nested enums don't collide with top-level component schemas that\n // happen to be named `<operation><statusCode>` (e.g. `GetMaintenance200`).\n const responseName = operationName ? `${operationName}Status${statusCode}` : undefined\n const { description } = getResponseMeta(responseObj)\n\n const parseEntrySchema = (contentType?: string) => {\n const raw = getResponseSchema(document, operation, statusCode, { contentType })\n const node =\n raw && Object.keys(raw).length > 0\n ? parseSchema({ schema: raw, name: responseName }, options)\n : ast.createSchema({ type: typeOptionMap.get(options.emptySchemaType)! })\n return { schema: node, keysToOmit: collectPropertyKeysByFlag(raw, 'writeOnly') }\n }\n\n // Build one entry per declared response content type so plugins can union the variants.\n // When a global contentType is configured, restrict to that single type (mirrors requestBody).\n const responseContentTypes = ctx.contentType ? [ctx.contentType] : getResponseBodyContentTypes(document, operation, statusCode)\n const content = responseContentTypes.map((contentType) => ({ contentType, ...parseEntrySchema(contentType) }))\n\n // Body-less responses keep a single fallback entry so the response still resolves to a\n // (void/any) schema, matching how `requestBody` only carries schemas inside `content`.\n if (content.length === 0) {\n content.push({ contentType: getRequestContentType({ document, operation }) || 'application/json', ...parseEntrySchema(ctx.contentType) })\n }\n\n return ast.createResponse({\n statusCode: statusCode as ast.StatusCode,\n description,\n content,\n })\n })\n\n const pathItem = document.paths?.[operation.path]\n const pathItemDoc = pathItem && !dialect.isReference(pathItem) ? (pathItem as { summary?: unknown; description?: unknown }) : undefined\n const pickDoc = (key: 'summary' | 'description'): string | undefined => {\n const own = operation.schema[key]\n if (typeof own === 'string') return own\n const fallback = pathItemDoc?.[key]\n return typeof fallback === 'string' ? fallback : undefined\n }\n\n return ast.createOperation({\n operationId,\n protocol: 'http',\n method: operation.method.toUpperCase() as ast.HttpMethod,\n path: operation.path,\n tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],\n summary: pickDoc('summary') || undefined,\n description: pickDoc('description') || undefined,\n deprecated: operation.schema.deprecated || undefined,\n parameters,\n requestBody,\n responses,\n })\n }\n\n return { parseSchema, parseOperation, parseParameter }\n}\n\n/**\n * Parses a single OpenAPI `SchemaObject` into a `SchemaNode`.\n *\n * Use this for targeted schema parsing when you don't need the full spec.\n * For complete spec parsing, use `parseOas()` instead which handles operations and all schemas together.\n *\n * @note Circular schema references are tracked via internal state and resolve appropriately.\n *\n * @example\n * ```ts\n * const document = yaml.parse(fs.readFileSync('openapi.yaml', 'utf8'))\n * const ctx = { document }\n * const schema = parseSchema(ctx, { schema: { type: 'string', format: 'uuid' } })\n * ```\n */\nexport function parseSchema(\n ctx: OasParserContext,\n { schema, name }: { schema: SchemaObject; name?: string },\n options?: Partial<ast.ParserOptions>,\n): ast.SchemaNode {\n return createSchemaParser(ctx).parseSchema({ schema, name }, options)\n}\n\n/**\n * Parses an OpenAPI specification into Kubb's universal `InputNode` AST.\n *\n * This is the main entry point for `@kubb/adapter-oas`. It converts OpenAPI/Swagger specs into a spec-agnostic tree\n * that downstream plugins (`plugin-ts`, `plugin-zod`, etc.) consume for code generation. No code is generated here, * the tree is a pure data structure representing all schemas and operations.\n *\n * Returns the AST root and a `nameMapping` for resolving schema references.\n *\n * @example\n * ```ts\n * import { parseOas } from '@kubb/adapter-oas'\n *\n * const document = await parseFromConfig(config)\n * const { root, nameMapping } = parseOas(document, { dateType: 'date', contentType: 'application/json' })\n * ```\n */\nexport function parseOas(\n document: Document,\n options: Partial<ast.ParserOptions> & { contentType?: ContentType } = {},\n): { root: ast.InputNode; nameMapping: Map<string, string> } {\n const { contentType, ...parserOptions } = options\n const mergedOptions: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n ...parserOptions,\n }\n\n const { schemas: schemaObjects, nameMapping } = getSchemas(document, {\n contentType,\n })\n const { parseSchema: _parseSchema, parseOperation: _parseOperation } = createSchemaParser({ document, contentType })\n\n const schemas: Array<ast.SchemaNode> = Object.entries(schemaObjects).map(([name, schema]) => _parseSchema({ schema, name }, mergedOptions))\n\n const operations: Array<ast.OperationNode> = getOperations(document)\n .map((operation) => _parseOperation(mergedOptions, operation))\n .filter((op): op is ast.OperationNode => op !== null)\n\n const root = ast.createInput({ schemas, operations })\n\n return { root, nameMapping }\n}\n","import { ast } from '@kubb/core'\nimport type { SchemaNodeByType } from '@kubb/ast'\n\nexport type DiscriminatorTarget = {\n propertyName: string\n enumValues: Array<string | number | boolean>\n}\n\n/**\n * Builds a map of child schema names → discriminator patch data by scanning the given\n * top-level AST schema nodes for union schemas that carry a `discriminatorPropertyName`.\n *\n * The streaming path calls this on a small pre-parsed subset of schemas (only the\n * discriminator parents) rather than on all schemas at once.\n */\nexport function buildDiscriminatorChildMap(schemas: Array<ast.SchemaNode>): Map<string, DiscriminatorTarget> {\n const childMap = new Map<string, DiscriminatorTarget>()\n\n for (const schema of schemas) {\n // Case 1: top-level schema is a union (oneOf/anyOf with discriminator)\n // Case 2: top-level schema is an intersection wrapping a union (oneOf/anyOf + shared properties)\n let unionNode = ast.narrowSchema(schema, 'union')\n\n if (!unionNode) {\n const intersectionMembers = ast.narrowSchema(schema, 'intersection')?.members\n if (intersectionMembers) {\n for (const m of intersectionMembers) {\n const u = ast.narrowSchema(m, 'union')\n if (u) {\n unionNode = u\n break\n }\n }\n }\n }\n\n if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue\n\n const { discriminatorPropertyName, members } = unionNode\n\n for (const member of members) {\n // Members with a discriminant value are intersections: [RefSchemaNode, ObjectSchemaNode]\n const intersectionNode = ast.narrowSchema(member, 'intersection')\n if (!intersectionNode?.members) continue\n\n let refNode: SchemaNodeByType['ref'] | null = null\n let objNode: SchemaNodeByType['object'] | null = null\n\n for (const m of intersectionNode.members) {\n refNode ??= ast.narrowSchema(m, 'ref')\n objNode ??= ast.narrowSchema(m, 'object')\n }\n\n if (!refNode?.name || !objNode) continue\n\n const prop = objNode.properties.find((p) => p.name === discriminatorPropertyName)\n const enumNode = prop ? ast.narrowSchema(prop.schema, 'enum') : null\n if (!enumNode?.enumValues?.length) continue\n\n const enumValues = enumNode.enumValues.filter((v): v is string | number | boolean => v !== null)\n if (!enumValues.length) continue\n\n const existing = childMap.get(refNode.name)\n if (!existing) {\n childMap.set(refNode.name, { propertyName: discriminatorPropertyName, enumValues: [...enumValues] })\n continue\n }\n existing.enumValues.push(...enumValues)\n }\n }\n\n return childMap\n}\n\n/**\n * Patches a single top-level `SchemaNode` with its discriminator entry (adds or replaces\n * the discriminant property). Used by the streaming path to apply patches inline per yield\n * without buffering all schemas.\n */\nexport function patchDiscriminatorNode(node: ast.SchemaNode, entry: { propertyName: string; enumValues: Array<string | number | boolean> }): ast.SchemaNode {\n const objectNode = ast.narrowSchema(node, 'object')\n if (!objectNode) return node\n\n const { propertyName, enumValues } = entry\n const enumSchema = ast.createSchema({ type: 'enum', enumValues })\n const newProp = ast.createProperty({ name: propertyName, required: true, schema: enumSchema })\n\n const existingIdx = objectNode.properties.findIndex((p) => p.name === propertyName)\n const newProperties = existingIdx >= 0 ? objectNode.properties.map((p, i) => (i === existingIdx ? newProp : p)) : [...objectNode.properties, newProp]\n\n return { ...objectNode, properties: newProperties }\n}\n","import { Diagnostics } from '@kubb/core'\nimport type { ast } from '@kubb/core'\nimport { isHandledFormat } from './resolvers.ts'\n\n/**\n * Reports the advisory diagnostics (`KUBB_UNSUPPORTED_FORMAT`, `KUBB_DEPRECATED`) for one\n * top-level schema. Walks the node the parser produced during `preScan`, threading the RFC 6901\n * pointer as it descends so a nested field reports against its full path\n * (`#/components/schemas/Pet/properties/owner/properties/name`). Refs are not followed, so the\n * resolved schema is reported under its own walk. Reports land in the active build run, are a\n * no-op outside one, and repeats are deduped by the build.\n */\nexport function reportSchemaDiagnostics({ node, name }: { node: ast.SchemaNode; name: string }): void {\n visit(node, `#/components/schemas/${escapePointerToken(name)}`)\n}\n\n/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * property name with those characters maps to a distinct pointer instead of colliding in the dedupe.\n */\nfunction escapePointerToken(token: string): string {\n return token.replace(/~/g, '~0').replace(/\\//g, '~1')\n}\n\nfunction visit(node: ast.SchemaNode, pointer: string): void {\n if (node.deprecated) {\n Diagnostics.report({\n code: Diagnostics.code.deprecated,\n severity: 'info',\n message: 'This schema is marked as deprecated.',\n location: { kind: 'schema', pointer },\n })\n }\n\n if (typeof node.format === 'string' && !isHandledFormat(node.format)) {\n Diagnostics.report({\n code: Diagnostics.code.unsupportedFormat,\n severity: 'warning',\n message: `Kubb does not map the format \"${node.format}\" to a specific type, so it falls back to the base type.`,\n help: `Use a format Kubb supports, or handle \"${node.format}\" with a custom parser or plugin.`,\n location: { kind: 'schema', pointer },\n })\n }\n\n if (node.type === 'object') {\n for (const property of node.properties) {\n visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`)\n }\n if (node.additionalProperties && typeof node.additionalProperties === 'object') {\n visit(node.additionalProperties, `${pointer}/additionalProperties`)\n }\n return\n }\n\n if (node.type === 'array') {\n for (const item of node.items ?? []) {\n visit(item, `${pointer}/items`)\n }\n return\n }\n\n if (node.type === 'tuple') {\n // Each tuple position has its own pointer, so index them. A shared `/items` would collapse\n // distinct diagnostics in the dedupe.\n for (const [index, item] of (node.items ?? []).entries()) {\n visit(item, `${pointer}/items/${index}`)\n }\n return\n }\n\n if (node.type === 'union' || node.type === 'intersection') {\n for (const [index, member] of (node.members ?? []).entries()) {\n visit(member, `${pointer}/members/${index}`)\n }\n }\n}\n","import { ast } from '@kubb/core'\nimport { SCHEMA_REF_PREFIX } from './constants.ts'\nimport { buildDiscriminatorChildMap, patchDiscriminatorNode } from './discriminator.ts'\nimport { getOperations } from './operation.ts'\nimport type { SchemaParser } from './parser.ts'\nimport { resolveServerUrl } from './resolvers.ts'\nimport { reportSchemaDiagnostics } from './schemaDiagnostics.ts'\nimport type { DiscriminatorTarget } from './discriminator.ts'\nimport type { AdapterOas, Document, SchemaObject } from './types.ts'\n\nexport type PreScanResult = {\n refAliasMap: Map<string, ast.SchemaNode>\n enumNames: Array<string>\n circularNames: Array<string>\n discriminatorChildMap: Map<string, DiscriminatorTarget> | null\n dedupePlan: ast.DedupePlan | null\n}\n\n/**\n * Builds the deduplication plan from the already-parsed top-level schema nodes plus a\n * single extra parse pass over operations (so duplicates in request/response bodies are seen).\n *\n * Only enums and objects are candidates, and object shapes that reference a circular schema are\n * rejected to avoid hoisting recursive structures. Inline shapes reuse their context-derived\n * name (collision-resolved against existing component names); shapes without a name stay inline.\n */\nfunction createDedupePlan({\n schemaNodes,\n operationNodes,\n schemaNames,\n circularNames,\n}: {\n schemaNodes: Array<ast.SchemaNode>\n operationNodes: Array<ast.OperationNode>\n schemaNames: Array<string>\n circularNames: Array<string>\n}): ast.DedupePlan {\n const circularSchemas = new Set(circularNames)\n const usedNames = new Set(schemaNames)\n\n return ast.buildDedupePlan([...schemaNodes, ...operationNodes], {\n isCandidate: (node) => {\n if (node.type === 'enum') return true\n if (node.type !== 'object') return false\n // Skip object shapes that are part of a circular chain, hoisting them would break the cycle.\n if (node.name && circularSchemas.has(node.name)) return false\n return !ast.containsCircularRef(node, { circularSchemas })\n },\n nameFor: (node) => {\n const base = node.name\n if (!base) return null\n\n let name = base\n let counter = 2\n while (usedNames.has(name)) {\n name = `${base}${counter++}`\n }\n usedNames.add(name)\n return name\n },\n refFor: (name) => `${SCHEMA_REF_PREFIX}${name}`,\n })\n}\n\n/**\n * Reads the server URL from the document's `servers` array at `serverIndex`,\n * interpolating any `serverVariables` into the URL template.\n *\n * Returns `null` when `serverIndex` is omitted or out of range.\n *\n * @example Resolve the first server\n * `resolveBaseUrl({ document, serverIndex: 0 })`\n *\n * @example Override a path variable\n * `resolveBaseUrl({ document, serverIndex: 0, serverVariables: { version: 'v2' } })`\n */\nexport function resolveBaseUrl({\n document,\n serverIndex,\n serverVariables,\n}: {\n document: Document\n serverIndex?: number\n serverVariables?: Record<string, string>\n}): string | null {\n const server = serverIndex !== undefined ? document.servers?.at(serverIndex) : undefined\n return server?.url ? resolveServerUrl(server, serverVariables) : null\n}\n\n/**\n * Parses every schema once to build the lookup structures that streaming needs upfront.\n *\n * Three things happen in this single pass:\n * - `refAliasMap` records schemas that are pure `$ref` aliases so the streaming pass can inline them.\n * - `enumNames` collects the names of every enum schema so plugins skip re-scanning the stream.\n * - `circularNames` runs cycle detection, which requires all nodes in memory simultaneously.\n * The `allNodes` array is local and drops out of scope as soon as this function returns.\n *\n * After this call, only `refAliasMap` and `discriminatorChildMap` stay alive in the adapter closure.\n * Both are proportional to the number of aliases or discriminator parents, not total schema count.\n *\n * Each schema is parsed again during the streaming pass. This is intentional.\n * Holding the parsed nodes in memory here would defeat the streaming memory benefit.\n *\n * @example\n * ```ts\n * const { refAliasMap, enumNames, circularNames } = preScan({\n * schemas,\n * parseSchema,\n * parserOptions,\n * discriminator: 'strict',\n * })\n * ```\n */\nexport function preScan({\n schemas,\n parseSchema,\n parseOperation,\n document,\n parserOptions,\n discriminator,\n dedupe,\n}: {\n schemas: Record<string, SchemaObject>\n parseSchema: (entry: { schema: SchemaObject; name: string }, options: ast.ParserOptions) => ast.SchemaNode\n parseOperation: SchemaParser['parseOperation']\n document: Document\n parserOptions: ast.ParserOptions\n discriminator: AdapterOas['options']['discriminator']\n dedupe: boolean\n}): PreScanResult {\n const allNodes: Array<ast.SchemaNode> = []\n const refAliasMap = new Map<string, ast.SchemaNode>()\n const enumNames: Array<string> = []\n const discriminatorParentNodes: Array<ast.SchemaNode> = []\n\n for (const [name, schema] of Object.entries(schemas)) {\n const node = parseSchema({ schema, name }, parserOptions)\n allNodes.push(node)\n reportSchemaDiagnostics({ node, name })\n if (node.type === 'ref' && node.name && node.name !== name) {\n refAliasMap.set(name, node)\n }\n if (ast.narrowSchema(node, ast.schemaTypes.enum) && node.name) {\n enumNames.push(node.name)\n }\n if (discriminator === 'inherit' && (schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const circularNames = [...ast.findCircularSchemas(allNodes)]\n const discriminatorChildMap = discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n let dedupePlan: ast.DedupePlan | null = null\n if (dedupe) {\n // One extra parse pass over operations so duplicates in request/response bodies are seen.\n // Reuses the already-parsed `allNodes` for schemas, no second schema parse.\n const operationNodes: Array<ast.OperationNode> = []\n for (const operation of getOperations(document)) {\n const operationNode = parseOperation(parserOptions, operation)\n if (operationNode) operationNodes.push(operationNode)\n }\n\n dedupePlan = createDedupePlan({ schemaNodes: allNodes, operationNodes, schemaNames: Object.keys(schemas), circularNames })\n\n for (const definition of dedupePlan.hoisted) {\n if (definition.type === 'enum' && definition.name) enumNames.push(definition.name)\n }\n }\n\n // Enum names that duplicate an earlier schema's content are never emitted, so they are not\n // advertised to plugins either.\n const aliasNames = dedupePlan?.aliasNames\n const emittedEnumNames = aliasNames && aliasNames.size > 0 ? enumNames.filter((name) => !aliasNames.has(name)) : enumNames\n\n return { refAliasMap, enumNames: emittedEnumNames, circularNames, discriminatorChildMap, dedupePlan }\n}\n\n/**\n * Creates a lazy `InputNode<true>` from already-resolved adapter state.\n *\n * The schema and operation iterables each start a fresh parse pass on every\n * `[Symbol.asyncIterator]()` call. This lets multiple plugins consume the same\n * stream object independently without sharing a cursor or holding all nodes in memory.\n *\n * Ref aliases in `refAliasMap` are inlined during iteration: an alias entry is replaced\n * with its target's parsed node (but keeps the alias name) so plugins never receive bare `ref` nodes.\n *\n * @example\n * ```ts\n * const streamNode = createInputStream({ schemas, parseSchema, parseOperation, document, parserOptions, refAliasMap, discriminatorChildMap, meta })\n * for await (const schema of streamNode.schemas) {\n * // each call to for-await restarts from the first schema\n * }\n * ```\n */\nexport function createInputStream({\n schemas,\n parseSchema,\n parseOperation,\n document,\n parserOptions,\n refAliasMap,\n discriminatorChildMap,\n dedupePlan,\n meta,\n}: {\n schemas: Record<string, SchemaObject>\n parseSchema: SchemaParser['parseSchema']\n parseOperation: SchemaParser['parseOperation']\n document: Document\n parserOptions: ast.ParserOptions\n refAliasMap: Map<string, ast.SchemaNode>\n discriminatorChildMap: Map<string, DiscriminatorTarget> | null\n dedupePlan: ast.DedupePlan | null\n meta: ast.InputMeta\n}): ast.InputNode<true> {\n // Rewrites a top-level schema against the dedupe plan: a structurally identical sibling\n // becomes a `ref` alias to the canonical one (keeping its own name); otherwise nested\n // duplicates are collapsed while the schema's own root is preserved.\n const rewriteTopLevelSchema = (node: ast.SchemaNode): ast.SchemaNode => {\n if (!dedupePlan) return node\n\n const canonical = dedupePlan.canonicalBySignature.get(ast.signatureOf(node))\n if (canonical && canonical.name !== node.name) {\n return ast.createSchema({\n type: 'ref',\n name: node.name ?? null,\n ref: canonical.ref,\n description: node.description,\n deprecated: node.deprecated,\n })\n }\n\n return ast.applyDedupe(node, dedupePlan, true)\n }\n\n const schemasIterable: AsyncIterable<ast.SchemaNode> = {\n [Symbol.asyncIterator]() {\n return (async function* () {\n // Hoisted canonical definitions are emitted first so the schema list owns the shared shapes.\n if (dedupePlan) {\n for (const definition of dedupePlan.hoisted) yield definition\n }\n\n for (const [name, schema] of Object.entries(schemas)) {\n // A top-level schema whose content duplicates an earlier one is not emitted: every\n // ref to it is repointed at the first schema with that content, so its model would\n // be dead code.\n if (dedupePlan?.aliasNames.has(name)) continue\n\n // Inline ref aliases: replace the alias entry with its target's parsed node\n // (keeping the alias name). Skip the first parse entirely for alias entries\n // since that result is never used.\n const alias = refAliasMap.get(name)\n if (alias?.name && schemas[alias.name]) {\n yield rewriteTopLevelSchema({ ...parseSchema({ schema: schemas[alias.name]!, name: alias.name }, parserOptions), name })\n continue\n }\n\n const parsed = parseSchema({ schema, name }, parserOptions)\n const node = discriminatorChildMap?.get(name) ? patchDiscriminatorNode(parsed, discriminatorChildMap.get(name)!) : parsed\n yield rewriteTopLevelSchema(node)\n }\n })()\n },\n }\n\n const operationsIterable: AsyncIterable<ast.OperationNode> = {\n [Symbol.asyncIterator]() {\n return (async function* () {\n for (const operation of getOperations(document)) {\n const node = parseOperation(parserOptions, operation)\n if (node) yield dedupePlan ? ast.applyDedupe(node, dedupePlan) : node\n }\n })()\n },\n }\n\n return ast.createStreamInput(schemasIterable, operationsIterable, meta)\n}\n","import { ast, createAdapter } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { assertInputExists, parseDocument, parseFromConfig, validateDocument } from './factory.ts'\nimport { createSchemaParser } from './parser.ts'\nimport { getSchemas } from './resolvers.ts'\nimport { createInputStream, preScan, resolveBaseUrl } from './stream.ts'\nimport type { AdapterOas, Document } from './types.ts'\nimport { collect, narrowSchema } from '@kubb/ast'\nimport { extractRefName } from '@kubb/ast/utils'\n\n/**\n * Canonical adapter name for `@kubb/adapter-oas`. Used for driver lookups.\n */\nexport const adapterOasName = 'oas' satisfies AdapterOas['name']\n\n/**\n * Default Kubb adapter for OpenAPI 2.0, 3.0, and 3.1 specifications. Reads the\n * file at `input.path`, validates it, resolves the base URL, and converts every\n * schema and operation into the universal AST that every downstream plugin\n * consumes.\n *\n * Configure once on `defineConfig`. The adapter's choices (date representation,\n * integer width, server URL) apply to every plugin in the build.\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 * serverIndex: 0,\n * discriminator: 'inherit',\n * dateType: 'date',\n * }),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport const adapterOas = createAdapter<AdapterOas>((options) => {\n const {\n validate = true,\n contentType,\n serverIndex,\n serverVariables,\n discriminator = 'strict',\n dedupe = true,\n dateType = DEFAULT_PARSER_OPTIONS.dateType,\n integerType = DEFAULT_PARSER_OPTIONS.integerType,\n unknownType = DEFAULT_PARSER_OPTIONS.unknownType,\n enumSuffix = DEFAULT_PARSER_OPTIONS.enumSuffix,\n emptySchemaType = unknownType || DEFAULT_PARSER_OPTIONS.emptySchemaType,\n } = options\n\n const parserOptions: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n }\n\n let nameMapping = new Map<string, string>()\n let parsedDocument: Document | null = null\n\n // Cache per source and per document so one adapter instance reused across a `defineConfig` array\n // parses each config's spec instead of replaying the first one. Keying the document by its source\n // object still collapses a config's concurrent `stream()` (build) and `parse()` (studio) calls,\n // which share one source object, onto a single parse. The document-derived caches key off the\n // resulting document, so distinct configs (distinct documents) stay isolated.\n const documentCache = new WeakMap<AdapterSource, Promise<Document>>()\n const schemasCache = new WeakMap<Document, Promise<ReturnType<typeof getSchemas>['schemas']>>()\n const schemaParserCache = new WeakMap<Document, ReturnType<typeof createSchemaParser>>()\n const preScanCache = new WeakMap<Document, ReturnType<typeof preScan>>()\n\n function ensureDocument(source: AdapterSource): Promise<Document> {\n const cached = documentCache.get(source)\n if (cached) return cached\n\n const promise = (async () => {\n const fresh = await parseFromConfig(source)\n if (validate) await validateDocument(fresh)\n parsedDocument = fresh\n return fresh\n })()\n documentCache.set(source, promise)\n return promise\n }\n\n function ensureSchemas(document: Document): Promise<ReturnType<typeof getSchemas>['schemas']> {\n const cached = schemasCache.get(document)\n if (cached) return cached\n\n const promise = Promise.resolve().then(() => {\n const result = getSchemas(document, { contentType })\n nameMapping = result.nameMapping\n return result.schemas\n })\n schemasCache.set(document, promise)\n return promise\n }\n\n function ensureSchemaParser(document: Document): ReturnType<typeof createSchemaParser> {\n const cached = schemaParserCache.get(document)\n if (cached) return cached\n\n const parser = createSchemaParser({ document, contentType })\n schemaParserCache.set(document, parser)\n return parser\n }\n\n function ensurePreScan(\n document: Document,\n schemas: ReturnType<typeof getSchemas>['schemas'],\n parseSchema: ReturnType<typeof ensureSchemaParser>['parseSchema'],\n parseOperation: ReturnType<typeof ensureSchemaParser>['parseOperation'],\n ): ReturnType<typeof preScan> {\n const cached = preScanCache.get(document)\n if (cached) return cached\n\n const result = preScan({ schemas, parseSchema, parseOperation, document, parserOptions, discriminator, dedupe })\n preScanCache.set(document, result)\n return result\n }\n\n async function createStream(source: AdapterSource): Promise<ast.InputNode<true>> {\n const document = await ensureDocument(source)\n const schemas = await ensureSchemas(document)\n const { parseSchema, parseOperation } = ensureSchemaParser(document)\n const { refAliasMap, enumNames, circularNames, discriminatorChildMap, dedupePlan } = ensurePreScan(document, schemas, parseSchema, parseOperation)\n\n return createInputStream({\n schemas,\n parseSchema,\n parseOperation,\n document,\n parserOptions,\n refAliasMap,\n discriminatorChildMap,\n dedupePlan,\n meta: {\n title: document.info?.title,\n description: document.info?.description,\n version: document.info?.version,\n baseURL: resolveBaseUrl({ document, serverIndex, serverVariables }),\n circularNames,\n enumNames,\n },\n })\n }\n\n return {\n name: adapterOasName,\n get options() {\n return {\n validate,\n contentType,\n serverIndex,\n serverVariables,\n discriminator,\n dedupe,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n nameMapping,\n }\n },\n get document() {\n return parsedDocument\n },\n async validate(input, options) {\n await assertInputExists(input)\n const document = await parseDocument(input)\n await validateDocument(document, options)\n },\n getImports(node, resolve) {\n return collect(node, {\n schema(schemaNode) {\n const schemaRef = narrowSchema(schemaNode, 'ref')\n if (!schemaRef?.ref) return null\n\n const rawName = extractRefName(schemaRef.ref)\n const schemaName = nameMapping.get(rawName) ?? rawName\n const result = resolve(schemaName)\n if (!result) return null\n\n return ast.createImport({ name: [result.name], path: result.path })\n },\n })\n },\n async parse(source) {\n const streamNode = await createStream(source)\n\n const [schemas, operations] = await Promise.all([Array.fromAsync(streamNode.schemas), Array.fromAsync(streamNode.operations)])\n\n return ast.createInput({ schemas, operations, meta: streamNode.meta })\n },\n stream: createStream,\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;CACb,aAAa;CACb,iBAAiB;CACjB,YAAY;AACd;;;;;;;;;;;AAYA,MAAa,oBAAoB;;;;;AAMjC,MAAa,oBAAyC,IAAI,IAAI;CAAC;CAAO;CAAO;CAAQ;CAAU;CAAW;CAAQ;CAAS;AAAO,CAAC;;;;AAKnI,MAAa,wBAAwB;;;;AAKrC,MAAa,sBAAsB;;;;AAKnC,MAAa,wBAAwB;;;;;;;;;;;;;;;AAgBrC,MAAa,iBAAiB,IAAI,IAAI;CAAC;CAAc;CAAS;CAAwB;CAAS;CAAS;CAAS;AAAK,CAAU;;;;;;;;;;;;;;;;;;;;;;;;AAyBhI,MAAa,sBAA2C,IAAI,IAAI;CAAC;CAAS;CAAa;CAAQ;AAAM,CAAC;AAEtG,MAAa,YAAY;CACvB,MAAM;CACN,OAAO;CACP,aAAa;CACb,KAAK;CACL,iBAAiB;CACjB,KAAK;CACL,MAAM;CACN,MAAM;CACN,UAAU;CACV,gBAAgB;CAChB,QAAQ;CACR,MAAM;CAGN,OAAO;CACP,OAAO;CACP,QAAQ;AACV;;;;;;;;;;;AAYA,MAAa,oBAAoB,CAAC,eAAe,iBAAiB;;;;;AAMlE,MAAa,gBAAgB,IAAI,IAAsD;CACrF,CAAC,OAAOA,WAAAA,IAAI,YAAY,GAAG;CAC3B,CAAC,WAAWA,WAAAA,IAAI,YAAY,OAAO;CACnC,CAAC,QAAQA,WAAAA,IAAI,YAAY,IAAI;AAC/B,CAAC;;;;;;;;;;ACrHD,SAAS,gBAAgB,MAAc,QAAyB;CAC9D,OAAO,KACJ,KAAK,CAAC,CACN,QAAQ,qBAAqB,OAA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AS;IAAY,MAAM,WAAW;GAAK,CAAC;EACvE;EACA,QAAQ;CACV;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["ast","Diagnostics","path","Diagnostics","ast","Diagnostics","ast","ast","Diagnostics","ast","ast"],"sources":["../src/constants.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/object.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/url.ts","../src/bundler.ts","../src/guards.ts","../src/factory.ts","../src/refs.ts","../src/dialect.ts","../src/mime.ts","../src/operation.ts","../src/resolvers.ts","../src/parser.ts","../src/discriminator.ts","../src/schemaDiagnostics.ts","../src/stream.ts","../src/adapter.ts"],"sourcesContent":["import { ast } from '@kubb/core'\n\n/**\n * Default parser options applied when no explicit options are provided.\n *\n * @example\n * ```ts\n * import { DEFAULT_PARSER_OPTIONS } from '@kubb/adapter-oas'\n *\n * const parser = createOasParser(oas)\n * const root = parser.parse({ ...DEFAULT_PARSER_OPTIONS, dateType: 'date' })\n * ```\n */\nexport const DEFAULT_PARSER_OPTIONS = {\n dateType: 'string',\n integerType: 'bigint',\n unknownType: 'any',\n emptySchemaType: 'any',\n enumSuffix: 'enum',\n} as const satisfies ast.ParserOptions\n\n/**\n * JSON-Pointer prefix for schemas declared under `components.schemas` in an OpenAPI document.\n *\n * Used when building or parsing `$ref` strings.\n *\n * @example\n * ```ts\n * `${SCHEMA_REF_PREFIX}Pet` // '#/components/schemas/Pet'\n * ```\n */\nexport const SCHEMA_REF_PREFIX = '#/components/schemas/' as const\n\n/**\n * HTTP methods that count as operations on an OpenAPI path item. Other keys\n * (`parameters`, `summary`, `$ref`, vendor extensions) are skipped when iterating operations.\n */\nexport const SUPPORTED_METHODS: ReadonlySet<string> = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'])\n\n/**\n * OpenAPI version string written into the stub document created during multi-spec merges.\n */\nexport const MERGE_OPENAPI_VERSION = '3.0.0' as const\n\n/**\n * Fallback `info.title` placed in the stub document when merging multiple API files.\n */\nexport const MERGE_DEFAULT_TITLE = 'Merged API' as const\n\n/**\n * Fallback `info.version` placed in the stub document when merging multiple API files.\n */\nexport const MERGE_DEFAULT_VERSION = '1.0.0' as const\n\n/**\n * Set of JSON Schema keywords that prevent a schema fragment from being inlined during `allOf` flattening.\n *\n * A fragment that contains any of these keys carries structural meaning of its own and must stay as a separate\n * intersection member rather than being merged into the parent.\n *\n * @example\n * ```ts\n * import { structuralKeys } from '@kubb/adapter-oas'\n *\n * const isStructural = Object.keys(fragment).some((key) => structuralKeys.has(key))\n * // true when fragment has e.g. 'properties' or 'oneOf'\n * ```\n */\nexport const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)\n\n/**\n * Static map from OAS `format` strings to Kubb `SchemaType` values.\n *\n * Only formats whose AST type differs from the OAS `type` field appear here.\n * Formats that depend on runtime options (`int64`, `date-time`, `date`, `time`) are handled separately\n * in the parser. `ipv4` and `ipv6` map to their own dedicated schema types; `hostname` and\n * `idn-hostname` map to `'url'` as the closest generic string-format type.\n *\n * @example\n * ```ts\n * import { formatMap } from '@kubb/adapter-oas'\n *\n * formatMap['uuid'] // 'uuid'\n * formatMap['binary'] // 'blob'\n * formatMap['float'] // 'number'\n * ```\n */\n/**\n * Formats `convertFormat` maps to a dedicated type without going through `formatMap`:\n * `int64` and the date/time family. Keep this in sync with the `convertFormat`\n * special-cases in `parser.ts`. `isHandledFormat` reads it so the\n * `KUBB_UNSUPPORTED_FORMAT` diagnostic and the parser agree on what is handled.\n */\nexport const specialCasedFormats: ReadonlySet<string> = new Set(['int64', 'date-time', 'date', 'time'])\n\nexport const formatMap = {\n uuid: 'uuid',\n email: 'email',\n 'idn-email': 'email',\n uri: 'url',\n 'uri-reference': 'url',\n url: 'url',\n ipv4: 'ipv4',\n ipv6: 'ipv6',\n hostname: 'url',\n 'idn-hostname': 'url',\n binary: 'blob',\n byte: 'blob',\n // Numeric formats override the OAS `type` because format is more specific.\n // See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7\n int32: 'integer',\n float: 'number',\n double: 'number',\n} as const satisfies Record<string, ast.SchemaType>\n\n/**\n * Vendor extension keys that attach human-readable labels to enum values, checked in priority order.\n *\n * @example\n * ```ts\n * import { enumExtensionKeys } from '@kubb/adapter-oas'\n *\n * const key = enumExtensionKeys.find((k) => k in schema) // 'x-enumNames' | 'x-enum-varnames' | undefined\n * ```\n */\nexport const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const\n\n/**\n * Maps `'any' | 'unknown' | 'void'` option strings to their `ScalarSchemaType` constant.\n * Replaces a plain object lookup with a `Map` for explicit key membership testing via `.has()`.\n */\nexport const typeOptionMap = new Map<'any' | 'unknown' | 'void', ast.ScalarSchemaType>([\n ['any', ast.schemaTypes.any],\n ['unknown', ast.schemaTypes.unknown],\n ['void', ast.schemaTypes.void],\n])\n","type Options = {\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n return text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","import { existsSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\nimport { camelCase } from './casing.ts'\nimport { runtime } from './runtime.ts'\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\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 (runtime.isBun) {\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 (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(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 (runtime.isBun) {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Builds a nested file path from a dotted name. Splits on dots that precede a letter\n * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases\n * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.\n *\n * Empty segments are dropped before joining. They arise when the name starts with a dot\n * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to\n * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an\n * absolute path, letting generated files escape the configured output directory.\n *\n * @example Nested path from a dotted name\n * `toFilePath('pet.petId') // 'pet/petId'`\n *\n * @example PascalCase the final segment\n * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`\n *\n * @example Suffix applied to the final segment only\n * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`\n */\nexport function toFilePath(name: string, caseLast: (part: string) => string = camelCase): string {\n const parts = name.split(/\\.(?=[a-zA-Z])/)\n return parts\n .map((part, i) => (i === parts.length - 1 ? caseLast(part) : camelCase(part)))\n .filter(Boolean)\n .join('/')\n}\n","/**\n * Returns `true` when `value` is a plain (non-null, non-array) object.\n *\n * @example\n * ```ts\n * isPlainObject({}) // true\n * isPlainObject([]) // false\n * isPlainObject(null) // false\n * ```\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n}\n\n/**\n * Recursively merges `source` into `target`, combining nested plain objects.\n * Arrays and non-object values from `source` override the corresponding values in `target`.\n *\n * @example\n * ```ts\n * mergeDeep({ a: { x: 1 } }, { a: { y: 2 } })\n * // { a: { x: 1, y: 2 } }\n * ```\n */\nexport function mergeDeep(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = { ...target }\n for (const key of Object.keys(source)) {\n const sv = source[key]\n const tv = result[key]\n result[key] =\n sv !== null && typeof sv === 'object' && !Array.isArray(sv) && tv !== null && typeof tv === 'object' && !Array.isArray(tv)\n ? mergeDeep(tv as Record<string, unknown>, sv as Record<string, unknown>)\n : sv\n }\n return result\n}\n\n/**\n * Strips functions, symbols, and `undefined` values from plugin options for safe JSON transport.\n *\n * @example\n * ```ts\n * serializePluginOptions({ output: './src', onWrite: () => {} })\n * // { output: './src' } (function stripped)\n * ```\n */\nexport function serializePluginOptions<TOptions extends object>(options: TOptions): TOptions {\n if (options === null || options === undefined) return {} as TOptions\n if (typeof options !== 'object') return options\n if (Array.isArray(options)) return options.map(serializePluginOptions) as unknown as TOptions\n\n const serialized: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(options)) {\n if (typeof value === 'function' || typeof value === 'symbol' || value === undefined) continue\n serialized[key] = value !== null && typeof value === 'object' ? serializePluginOptions(value as object) : value\n }\n return serialized as TOptions\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return isIdentifier(name)\n}\n\n/**\n * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.\n *\n * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys\n * even though they are not valid variable names, so use this (not {@link isValidVarName}) when\n * deciding whether an object key needs quoting.\n *\n * @example\n * ```ts\n * isIdentifier('name') // true\n * isIdentifier('x-total')// false\n * ```\n */\nexport function isIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\ntype URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `null` when the path has none.\n */\n params: Record<string, string> | null\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype TemplateOptions = {\n /**\n * Literal text prepended inside the template literal, e.g. a base URL.\n */\n prefix?: string | null\n /**\n * Transform applied to each extracted parameter name before interpolation.\n */\n replacer?: (pathParam: string) => string\n /**\n * Casing strategy applied to path parameter names.\n */\n casing?: PathCasing\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n /**\n * Casing strategy applied to path parameter names.\n */\n casing?: PathCasing\n}\n\nfunction transformParam(raw: string, casing?: PathCasing): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return casing === 'camelcase' ? camelCase(param) : param\n}\n\nfunction toParamsObject(\n path: string,\n { replacer, casing }: { replacer?: (pathParam: string) => string; casing?: PathCasing } = {},\n): Record<string, string> | null {\n const params: Record<string, string> = {}\n\n for (const match of path.matchAll(/\\{([^}]+)\\}/g)) {\n const param = transformParam(match[1]!, casing)\n const key = replacer ? replacer(param) : param\n params[key] = key\n }\n\n return Object.keys(params).length > 0 ? params : null\n}\n\n/**\n * Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.\n */\nexport class Url {\n /**\n * Reports whether `url` is a parseable absolute URL. Delegates to the native `URL.canParse`.\n *\n * @example\n * Url.canParse('https://petstore.swagger.io/v2') // true\n * Url.canParse('/pet/{petId}') // false\n */\n static canParse(url: string, base?: string | URL): boolean {\n return URL.canParse(url, base)\n }\n\n /**\n * Converts an OpenAPI/Swagger path to Express-style colon syntax.\n *\n * @example\n * Url.toPath('/pet/{petId}') // '/pet/:petId'\n */\n static toPath(path: string): string {\n return path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n\n /**\n * Converts an OpenAPI/Swagger path to a TypeScript template literal string.\n * `prefix` is prepended inside the literal, `replacer` transforms each parameter name,\n * and `casing` controls parameter identifier casing.\n *\n * @example\n * Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'\n *\n * @example\n * Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'\n */\n static toTemplateString(path: string, { prefix, replacer, casing }: TemplateOptions = {}): string {\n const parts = path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = transformParam(part, casing)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix ?? ''}${result}\\``\n }\n\n /**\n * Returns the path and its extracted params as a structured `URLObject`, or as a stringified\n * expression when `stringify` is set.\n *\n * @example\n * Url.toObject('/pet/{petId}')\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n */\n static toObject(path: string, { type = 'path', replacer, stringify, casing }: ObjectOptions = {}): URLObject | string {\n const object: URLObject = {\n url: type === 'path' ? Url.toPath(path) : Url.toTemplateString(path, { replacer, casing }),\n params: toParamsObject(path, { replacer, casing }),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n}\n","import { read } from '@internals/utils'\nimport { bundle } from 'api-ref-bundler'\nimport { parse } from 'yaml'\nimport type { Document } from './types.ts'\n\nconst urlRegExp = /^https?:\\/+/i\n\nasync function readSource(sourcePath: string): Promise<string> {\n if (urlRegExp.test(sourcePath)) {\n // api-ref-bundler joins relative refs with posix normalization, collapsing `https://` to\n // `https:/`. The WHATWG URL parser restores the double slash.\n const url = new URL(sourcePath)\n const response = await fetch(url)\n\n if (!response.ok) {\n throw new Error(`Cannot fetch the OAS document at ${url.href} (HTTP ${response.status})`)\n }\n\n return response.text()\n }\n\n return read(sourcePath)\n}\n\nasync function resolveSource(sourcePath: string): Promise<object | string> {\n const data = await readSource(sourcePath)\n\n if (sourcePath.toLowerCase().endsWith('.md')) {\n return data\n }\n\n return parse(data) as object\n}\n\n/**\n * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.\n *\n * External file schemas are hoisted into named `components.schemas` entries, so a property\n * pointing at `./schemas/User.yaml` ends up referencing `#/components/schemas/User`. Generators\n * can then emit a named type with an import instead of inlining the shape. Sources are read with\n * the Bun-aware `read` util for local YAML and JSON files, and with `fetch` for HTTP(S) URLs.\n *\n * @example Local file\n * `const document = await bundleDocument('./openapi.yaml')`\n *\n * @example Remote URL\n * `const document = await bundleDocument('https://example.com/openapi.yaml')`\n */\nexport async function bundleDocument(pathOrUrl: string): Promise<Document> {\n const cache = new Map<string, Promise<object | string>>()\n\n const resolver = (sourcePath: string) => {\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, so cache on the canonical href to fetch each source once.\n const key = urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath\n const cached = cache.get(key)\n if (cached) {\n return cached\n }\n\n const result = resolveSource(sourcePath)\n cache.set(key, result)\n return result\n }\n\n // api-ref-bundler swallows resolver errors and leaves refs unresolved, so surface an\n // unreadable input document as a hard error before bundling.\n await resolver(pathOrUrl)\n\n return (await bundle(pathOrUrl, resolver)) as Document\n}\n","import { isPlainObject } from '@internals/utils'\nimport type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\nimport type { DiscriminatorObject, SchemaObject } from './types.ts'\n\n/**\n * Returns `true` when `doc` is a Swagger 2.0 document (no `openapi` key).\n *\n * @example\n * ```ts\n * if (isOpenApiV2Document(doc)) {\n * // doc is OpenAPIV2.Document\n * }\n * ```\n */\nexport function isOpenApiV2Document(doc: unknown): doc is OpenAPIV2.Document {\n return !!doc && isPlainObject(doc) && !('openapi' in doc)\n}\n\n/**\n * Returns `true` when a schema should be treated as nullable.\n *\n * Recognizes all nullable signals across OAS versions: `nullable: true` (OAS 3.0),\n * `x-nullable: true` (vendor extension), `type: 'null'`, and `type: ['null', ...]` (OAS 3.1).\n *\n * @example\n * ```ts\n * isNullable({ type: 'string', nullable: true }) // true\n * isNullable({ type: ['string', 'null'] }) // true\n * isNullable({ type: 'string' }) // false\n * ```\n */\nexport function isNullable(schema?: SchemaObject & { 'x-nullable'?: boolean }): boolean {\n const explicitNullable = schema?.nullable ?? schema?.['x-nullable']\n if (explicitNullable === true) return true\n\n const schemaType = schema?.type\n if (schemaType === 'null') return true\n if (Array.isArray(schemaType)) return schemaType.includes('null')\n\n return false\n}\n\n/**\n * Returns `true` when `obj` is an OpenAPI `$ref` pointer object.\n *\n * @example\n * ```ts\n * isReference({ $ref: '#/components/schemas/Pet' }) // true\n * isReference({ type: 'string' }) // false\n * ```\n */\nexport function isReference(obj?: unknown): obj is OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject {\n return !!obj && typeof obj === 'object' && '$ref' in obj\n}\n\n/**\n * Returns `true` when `obj` is a schema with a structured OAS 3.x `discriminator` object.\n *\n * @example\n * ```ts\n * isDiscriminator({ discriminator: { propertyName: 'type', mapping: {} } }) // true\n * isDiscriminator({ discriminator: 'type' }) // false (Swagger 2 string form)\n * ```\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: DiscriminatorObject } {\n const record = obj as Record<string, unknown>\n return !!obj && !!record['discriminator'] && typeof record['discriminator'] !== 'string'\n}\n","import path from 'node:path'\nimport { exists, mergeDeep, Url } from '@internals/utils'\nimport { Diagnostics } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { compileErrors, validate } from '@readme/openapi-parser'\nimport { parse } from 'yaml'\nimport { bundleDocument } from './bundler.ts'\nimport { MERGE_DEFAULT_TITLE, MERGE_DEFAULT_VERSION, MERGE_OPENAPI_VERSION } from './constants.ts'\nimport { isOpenApiV2Document } from './guards.ts'\nimport type { Document } from './types.ts'\n\nexport type ParseOptions = {\n canBundle?: boolean\n}\n\nexport type ValidateDocumentOptions = {\n throwOnError?: boolean\n}\n\n/**\n * Loads and dereferences an OpenAPI document, returning the raw `Document`.\n *\n * Accepts a file path string or an already-parsed document object. File paths and URLs are\n * bundled via `api-ref-bundler`, hoisting external file schemas into named `components.schemas`\n * entries so generators can emit named types and imports. Swagger 2.0 documents are\n * automatically up-converted to OpenAPI 3.0 via `swagger2openapi`.\n *\n * @example\n * ```ts\n * const document = await parseDocument('./openapi.yaml')\n * const document = await parse(rawDocumentObject, { canBundle: false })\n * ```\n */\nexport async function parseDocument(pathOrApi: string | Document, { canBundle = true }: ParseOptions = {}): Promise<Document> {\n if (typeof pathOrApi === 'string' && canBundle) {\n const bundled = await bundleDocument(pathOrApi)\n\n return parseDocument(bundled, { canBundle: false })\n }\n\n // A string here is always inline YAML/JSON content: file paths and URLs are read and parsed by\n // `bundleDocument` first. `yaml.parse` also parses JSON, since JSON is a subset of YAML.\n const document = (typeof pathOrApi === 'string' ? parse(pathOrApi) : pathOrApi) as Document\n\n if (isOpenApiV2Document(document)) {\n const { default: swagger2openapi } = await import('swagger2openapi')\n const { openapi } = await swagger2openapi.convertObj(document, {\n anchors: true,\n })\n\n return openapi as Document\n }\n\n return document\n}\n\n/**\n * Deep-merges multiple OpenAPI documents into a single `Document`.\n *\n * Each document is parsed independently, then deep-merged into one in array order.\n * Throws when the input array is empty.\n *\n * @example\n * ```ts\n * const document = await mergeDocuments(['./pets.yaml', './orders.yaml'])\n * ```\n */\nexport async function mergeDocuments(pathOrApi: Array<string | Document>): Promise<Document> {\n const documents = await Promise.all(pathOrApi.map((p) => parseDocument(p, { canBundle: false })))\n\n if (documents.length === 0) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: 'No OAS documents were provided for merging.',\n help: 'Pass at least one path or document to `input.path`.',\n location: { kind: 'config' },\n })\n }\n\n const seed: Document = {\n openapi: MERGE_OPENAPI_VERSION,\n info: { title: MERGE_DEFAULT_TITLE, version: MERGE_DEFAULT_VERSION },\n paths: {},\n components: { schemas: {} },\n } as Document\n\n const merged = documents.reduce(\n (acc, current) => mergeDeep(acc as Record<string, unknown>, current as Record<string, unknown>),\n seed as Record<string, unknown>,\n )\n\n return parseDocument(merged as Document)\n}\n\n/**\n * Creates a `Document` from an `AdapterSource`.\n *\n * Handles all three source types:\n * - `{ type: 'path' }` resolves and bundles a local file path or remote URL.\n * - `{ type: 'paths' }` merges multiple file paths into a single document.\n * - `{ type: 'data' }` parses an inline string (YAML/JSON) or raw object.\n *\n * @example\n * ```ts\n * const document = await parseFromConfig({ type: 'path', path: './openapi.yaml' })\n * const document = await parseFromConfig({ type: 'data', data: '{\"openapi\":\"3.0.0\",...}' })\n * ```\n */\nexport async function parseFromConfig(source: AdapterSource): Promise<Document> {\n if (source.type === 'data') {\n if (typeof source.data === 'object') {\n return parseDocument(structuredClone(source.data) as Document)\n }\n\n return parseDocument(source.data as string, { canBundle: false })\n }\n\n if (source.type === 'paths') {\n return mergeDocuments(source.paths)\n }\n\n // type === 'path'\n if (Url.canParse(source.path)) {\n return parseDocument(source.path)\n }\n\n const resolved = path.resolve(path.dirname(source.path), source.path)\n await assertInputExists(resolved)\n return parseDocument(resolved)\n}\n\n/**\n * Throws a coded `KUBB_INPUT_NOT_FOUND` diagnostic when a local input path does not exist.\n * URLs are skipped, and a malformed but readable file is left for `parseDocument` to surface\n * its parse error instead.\n */\nexport async function assertInputExists(input: string): Promise<void> {\n if (Url.canParse(input)) {\n return\n }\n if (!(await exists(input))) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputNotFound,\n severity: 'error',\n message: `Cannot read the file set in \\`input.path\\` (or via \\`kubb generate PATH\\`): ${input}`,\n help: 'Check that the path exists and is readable, then set it in `input.path` or pass it as `kubb generate PATH`.',\n location: { kind: 'config' },\n })\n }\n}\n\n/**\n * Validates an OpenAPI document using `@readme/openapi-parser` with colorized error output.\n *\n * @example\n * ```ts\n * await validateDocument(document)\n * ```\n */\nexport async function validateDocument(document: Document, { throwOnError = false }: ValidateDocumentOptions = {}): Promise<void> {\n try {\n // `validate` dereferences its input in place, so clone to keep the cached document intact.\n const result = await validate(structuredClone(document), {\n validate: {\n errors: { colorize: true },\n },\n })\n\n if (!result.valid) {\n throw new Error(compileErrors(result))\n }\n } catch (error) {\n if (throwOnError) {\n throw error\n }\n\n // Validation failures are non-fatal, mirror plugin-oas behavior\n }\n}\n","import { type Diagnostic, Diagnostics } from '@kubb/core'\nimport { isReference } from './guards.ts'\nimport type { Document } from './types.ts'\n\nconst _refCache = new WeakMap<Document, Map<string, unknown>>()\n\n/**\n * Resolves a local JSON pointer reference from a document.\n *\n * Accepts `#/...` refs. Returns `null` for empty or non-local refs.\n * Throws when the pointer cannot be resolved.\n *\n * @example\n * ```ts\n * resolveRef<SchemaObject>(document, '#/components/schemas/Pet') // SchemaObject | null\n * ```\n */\nexport function resolveRef<T = unknown>(document: Document, $ref: string): T | null {\n const origRef = $ref\n $ref = $ref.trim()\n if ($ref === '') {\n return null\n }\n if (!$ref.startsWith('#')) return null\n $ref = globalThis.decodeURIComponent($ref.substring(1))\n\n let docCache = _refCache.get(document)\n if (!docCache) {\n docCache = new Map()\n _refCache.set(document, docCache)\n }\n\n if (docCache.has($ref)) {\n return docCache.get($ref) as T\n }\n\n const current = $ref\n .split('/')\n .filter(Boolean)\n .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)\n\n if (!current) {\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: 'error',\n message: `Could not find a definition for ${origRef}.`,\n help: 'Add the schema under `components.schemas`, or fix the `$ref`. Run `kubb validate` to check the spec.',\n location: { kind: 'schema', pointer: origRef, ref: origRef },\n }\n // Report the unresolved ref into the active build and resolve to null, like any\n // other unresolvable ref. The build collects it and keeps going. Outside a build there is no\n // sink, so throw rather than silently returning null.\n if (!Diagnostics.report(diagnostic)) {\n throw new Diagnostics.Error(diagnostic)\n }\n return null\n }\n\n docCache.set($ref, current)\n return current as T\n}\n\n/**\n * Resolves a `$ref` object while preserving the original `$ref` field on the result.\n *\n * Useful for parser flows that need both dereferenced fields and pointer\n * identity (for naming/import purposes). Non-reference values are returned as-is.\n *\n * @example\n * ```ts\n * dereferenceWithRef(document, { $ref: '#/components/schemas/Pet' })\n * // { $ref: '#/components/schemas/Pet', type: 'object', properties: { ... } }\n * ```\n */\nexport function dereferenceWithRef<T = unknown>(document: Document, schema?: T): T {\n if (isReference(schema)) {\n return {\n ...schema,\n ...resolveRef(document, schema.$ref),\n $ref: schema.$ref,\n }\n }\n\n return schema as T\n}\n","import { ast } from '@kubb/core'\nimport { isDiscriminator, isNullable, isReference } from './guards.ts'\nimport { resolveRef } from './refs.ts'\nimport type { SchemaObject } from './types.ts'\n\n/**\n * The OpenAPI / Swagger dialect, the default used by `@kubb/adapter-oas`.\n *\n * Implements the spec-agnostic {@link ast.SchemaDialect} contract: it isolates the\n * decisions that differ between specs (nullability, `$ref`, discriminator, binary,\n * ref resolution) so the converter pipeline and dispatch rules stay shared. A\n * future adapter (e.g. AsyncAPI) ships its own dialect, `type: ['null', …]`\n * nullability, no discriminator object, binary via `contentEncoding` and reuses\n * the rest unchanged.\n *\n * Formats (`uuid`, `email`, dates, …) are intentionally NOT here: they are shared\n * JSON Schema vocabulary, so the converters keep that common case.\n *\n * @example\n * ```ts\n * const parser = createSchemaParser(context) // uses oasDialect\n * const parser = createSchemaParser(context, oasDialect) // explicit\n * ```\n */\nexport const oasDialect = ast.defineSchemaDialect({\n name: 'oas',\n isNullable,\n isReference,\n isDiscriminator,\n isBinary: (schema: SchemaObject) => schema.type === 'string' && schema.contentMediaType === 'application/octet-stream',\n resolveRef,\n})\n\n/**\n * The concrete dialect type for `@kubb/adapter-oas`. Keeps the OAS guard predicates\n * (`isReference`, `isDiscriminator`) intact so converters narrow schemas after a check.\n */\nexport type OasDialect = typeof oasDialect\n","/**\n * MIME type fragments that mark a media type as JSON-like.\n *\n * Matches the substrings used by the `oas` library's `matchesMimeType.json`, so a content type is\n * JSON when it contains any of these. The `+json` entry catches structured-syntax suffixes such as\n * `application/vnd.api+json`.\n */\nconst jsonMimeFragments = ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'] as const\n\n/**\n * Returns `true` when a media type string is JSON-like.\n *\n * @example\n * ```ts\n * isJsonMimeType('application/json') // true\n * isJsonMimeType('application/vnd.api+json') // true\n * isJsonMimeType('multipart/form-data') // false\n * ```\n */\nexport function isJsonMimeType(mimeType: string): boolean {\n return jsonMimeFragments.some((fragment) => mimeType.includes(fragment))\n}\n","import { SUPPORTED_METHODS } from './constants.ts'\nimport { isReference } from './guards.ts'\nimport { isJsonMimeType } from './mime.ts'\nimport { resolveRef } from './refs.ts'\nimport type { Document, MediaTypeObject, OperationObject, PathItemObject, ReferenceObject, RequestBodyObject, ResponseObject } from './types.ts'\n\n/**\n * A single OpenAPI operation: its URL path, HTTP method, and the raw operation object.\n *\n * `schema` is a live reference into the document, so any in-place `$ref` resolution the resolvers\n * perform is visible here too.\n */\nexport type Operation = {\n path: string\n method: string\n schema: OperationObject\n}\n\n/**\n * The document plus the operation being read. Shared by the request/response accessors so they can\n * resolve `$ref`s against the document.\n */\ntype OperationContext = {\n document: Document\n operation: Operation\n}\n\n/**\n * Slugifies a path for the `operationId` fallback: non-alphanumerics collapse to single dashes,\n * with no leading or trailing dash.\n */\nfunction slugify(value: string): string {\n return value\n .replace(/[^a-zA-Z0-9]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-|-$/g, '')\n}\n\n/**\n * Returns the operation's `operationId`, falling back to `<method>_<slugified-path>` when absent.\n */\nexport function getOperationId({ path, method, schema }: Operation): string {\n const { operationId } = schema\n if (typeof operationId === 'string' && operationId.length > 0) {\n return operationId\n }\n return `${method}_${slugify(path).toLowerCase()}`\n}\n\n/**\n * Returns the declared response status codes, skipping `x-` extensions and non-object entries.\n */\nexport function getResponseStatusCodes({ schema }: Operation): Array<string> {\n const responses = schema.responses as Record<string, unknown> | undefined\n if (!responses || isReference(responses)) {\n return []\n }\n return Object.keys(responses).filter((key) => !key.startsWith('x-') && !!responses[key] && typeof responses[key] === 'object')\n}\n\n/**\n * Returns the response object for a status code, resolving a `$ref` in place. `false` when absent.\n */\nexport function getResponseByStatusCode({ document, operation, statusCode }: OperationContext & { statusCode: string | number }): ResponseObject | false {\n const responses = operation.schema.responses as Record<string, ResponseObject | ReferenceObject> | undefined\n if (!responses || isReference(responses)) {\n return false\n }\n const response = responses[statusCode]\n if (!response) {\n return false\n }\n if (isReference(response)) {\n const resolved = resolveRef<ResponseObject>(document, response.$ref)\n responses[statusCode] = resolved as ResponseObject\n if (!resolved || isReference(resolved)) {\n return false\n }\n return resolved\n }\n return response\n}\n\n/**\n * Resolves the request body (dereferencing a `$ref` in place) and returns its content map, or\n * `undefined` when the operation has no request body.\n */\nfunction getRequestBodyContent({ document, operation }: OperationContext): Record<string, MediaTypeObject> | undefined {\n const { schema } = operation\n let requestBody = schema.requestBody as RequestBodyObject | ReferenceObject | undefined\n if (!requestBody) {\n return undefined\n }\n if (isReference(requestBody)) {\n const resolved = resolveRef<RequestBodyObject>(document, requestBody.$ref)\n ;(schema as { requestBody?: unknown }).requestBody = resolved\n if (!resolved || isReference(resolved)) {\n return undefined\n }\n requestBody = resolved\n }\n return requestBody.content\n}\n\n/**\n * Returns the request body media type. With `mediaType` set, returns that entry or `false`.\n * Otherwise picks the first JSON-like media type, then the first declared one, as a\n * `[mediaType, object]` tuple.\n */\nexport function getRequestContent({\n document,\n operation,\n mediaType,\n}: OperationContext & { mediaType?: string }): MediaTypeObject | false | [string, MediaTypeObject] {\n const content = getRequestBodyContent({ document, operation })\n if (!content) {\n return false\n }\n if (mediaType) {\n return mediaType in content ? content[mediaType]! : false\n }\n const mediaTypes = Object.keys(content)\n const available = mediaTypes.find((mt) => isJsonMimeType(mt)) ?? mediaTypes[0]\n return available ? [available, content[available]!] : false\n}\n\n/**\n * Returns the primary request content type. Prefers a JSON-like media type (the last one wins,\n * matching the previous behavior), then the first declared one, defaulting to `'application/json'`.\n */\nexport function getRequestContentType({ document, operation }: OperationContext): string {\n const content = getRequestBodyContent({ document, operation })\n const mediaTypes = content ? Object.keys(content) : []\n\n let result = mediaTypes[0] ?? 'application/json'\n for (const mt of mediaTypes) {\n if (isJsonMimeType(mt)) {\n result = mt\n }\n }\n return result\n}\n\n/**\n * Builds an `Operation` for every supported HTTP method on every path, in document order.\n * `x-` path keys and unresolvable path-item `$ref`s are skipped.\n *\n * @example\n * ```ts\n * for (const operation of getOperations(document)) {\n * parseOperation(options, operation)\n * }\n * ```\n */\nexport function getOperations(document: Document): Array<Operation> {\n const operations: Array<Operation> = []\n const paths = document.paths\n if (!paths) {\n return operations\n }\n\n for (const path of Object.keys(paths)) {\n if (path.startsWith('x-')) {\n continue\n }\n\n let pathItem = paths[path] as PathItemObject | ReferenceObject | undefined\n if (!pathItem) {\n continue\n }\n if (isReference(pathItem)) {\n const resolved = resolveRef<PathItemObject>(document, pathItem.$ref)\n ;(paths as Record<string, unknown>)[path] = resolved\n if (!resolved || isReference(resolved)) {\n continue\n }\n pathItem = resolved\n }\n\n const item = pathItem as Record<string, unknown>\n for (const method of Object.keys(item)) {\n if (!SUPPORTED_METHODS.has(method)) {\n continue\n }\n const schema = item[method]\n if (!schema || typeof schema !== 'object') {\n continue\n }\n operations.push({ path, method, schema: schema as OperationObject })\n }\n }\n\n return operations\n}\n","import { pascalCase } from '@internals/utils'\nimport { Diagnostics } from '@kubb/core'\nimport type { ast } from '@kubb/core'\nimport { formatMap, SCHEMA_REF_PREFIX, specialCasedFormats, structuralKeys } from './constants.ts'\nimport { isReference } from './guards.ts'\nimport { isJsonMimeType } from './mime.ts'\nimport { getRequestContent, getResponseByStatusCode } from './operation.ts'\nimport { dereferenceWithRef, resolveRef } from './refs.ts'\nimport type { ContentType, Document, MediaTypeObject, Operation, ParameterObject, ResponseObject, SchemaObject, ServerObject } from './types.ts'\n\n/**\n * Replaces `{variable}` placeholders in an OpenAPI server URL with provided values.\n * Resolution order: `overrides[key]` → `variable.default` → left unreplaced.\n * Throws if an override value is not in the variable's `enum` list.\n *\n * @example\n * ```ts\n * resolveServerUrl(\n * { url: 'https://{env}.api.example.com', variables: { env: { default: 'dev', enum: ['dev', 'prod'] } } },\n * { env: 'prod' },\n * )\n * // 'https://prod.api.example.com'\n * ```\n */\nexport function resolveServerUrl(server: ServerObject, overrides?: Record<string, string>): string {\n if (!server.variables) {\n return server.url\n }\n\n let url = server.url\n for (const [key, variable] of Object.entries(server.variables)) {\n const value = overrides?.[key] ?? (variable.default != null ? String(variable.default) : undefined)\n if (value === undefined) {\n continue\n }\n\n if (variable.enum?.length && !variable.enum.some((e) => String(e) === value)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidServerVariable,\n severity: 'error',\n message: `Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`,\n help: `Use one of the allowed enum values, or drop the enum on the '${key}' server variable.`,\n location: { kind: 'document', pointer: '#/servers' },\n })\n }\n\n url = url.replaceAll(`{${key}}`, value)\n }\n\n return url\n}\n\n/**\n * Returns the Kubb `SchemaType` for a given OAS `format` string, or `null` if not found.\n * Formats not in `formatMap` (e.g., `int64`, `date-time`) are handled separately by parser options.\n */\nexport function getSchemaType(format: string): ast.SchemaType | null {\n return formatMap[format as keyof typeof formatMap] ?? null\n}\n\n/**\n * Whether the parser maps `format` to a dedicated type. True for any `formatMap` entry and the\n * `specialCasedFormats` `convertFormat` handles directly. False means the format falls back to the\n * base type, which is what `KUBB_UNSUPPORTED_FORMAT` flags. Reading both sources keeps the\n * diagnostic in step with the parser as `formatMap` grows.\n */\nexport function isHandledFormat(format: string): boolean {\n return getSchemaType(format) !== null || specialCasedFormats.has(format)\n}\n\n/**\n * Converts an OAS primitive type string to its `PrimitiveSchemaType` equivalent.\n * Numeric types (`number`, `integer`, `bigint`) pass through unchanged. `boolean` maps to `'boolean'`. Everything else becomes `'string'`.\n */\nexport function getPrimitiveType(type: string | undefined): ast.PrimitiveSchemaType {\n if (type === 'number' || type === 'integer' || type === 'bigint') return type\n if (type === 'boolean') return 'boolean'\n\n return 'string'\n}\n\nexport type OperationsOptions = {\n contentType?: ContentType\n}\n\n/**\n * Returns all parameters for an operation, merging path-level and operation-level entries.\n * Operation-level parameters override path-level ones with the same `in:name` key.\n * `$ref` parameters resolve via `dereferenceWithRef` for backward compatibility.\n *\n * @example\n * ```ts\n * getParameters(document, operation)\n * // [{ name: 'petId', in: 'path', required: true, schema: { type: 'integer' } }]\n * ```\n */\nexport function getParameters(document: Document, operation: Operation): Array<ParameterObject> {\n const resolveParams = (params: Array<unknown>): Array<ParameterObject> =>\n params.map((p) => dereferenceWithRef(document, p)).filter((p): p is ParameterObject => !!p && typeof p === 'object' && 'in' in p && 'name' in p)\n\n const operationParams = resolveParams(operation.schema?.parameters || [])\n const pathItem = document.paths?.[operation.path]\n const pathLevelParams = resolveParams(pathItem && !isReference(pathItem) && pathItem.parameters ? pathItem.parameters : [])\n\n const paramMap = new Map<string, ParameterObject>()\n for (const p of pathLevelParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n for (const p of operationParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n\n return Array.from(paramMap.values())\n}\n\nfunction getResponseBody(responseBody: boolean | ResponseObject, contentType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...Array<string>] {\n if (!responseBody) return false\n if (isReference(responseBody)) return false\n\n const body = responseBody as ResponseObject\n if (!body.content) return false\n\n if (contentType) {\n if (!(contentType in body.content)) return false\n return body.content[contentType]!\n }\n\n let availableContentType: string | undefined\n const contentTypes = Object.keys(body.content)\n for (const mt of contentTypes) {\n if (isJsonMimeType(mt)) {\n availableContentType = mt\n break\n }\n }\n\n if (!availableContentType) {\n availableContentType = contentTypes[0]\n }\n\n if (availableContentType) {\n return [availableContentType, body.content[availableContentType]!, ...(body.description ? [body.description] : [])]\n }\n\n return false\n}\n\n/**\n * Returns the response schema for a given operation and HTTP status code.\n *\n * Returns an empty object `{}` when no response body schema is available.\n *\n * @example\n * ```ts\n * getResponseSchema(document, operation, 200) // SchemaObject\n * getResponseSchema(document, operation, '4XX') // {}\n * ```\n */\nexport function getResponseSchema(document: Document, operation: Operation, statusCode: string | number, options: OperationsOptions = {}): SchemaObject {\n if (operation.schema.responses) {\n const responses = operation.schema.responses\n for (const key in responses) {\n const schema = responses[key]\n if (schema && isReference(schema)) {\n responses[key] = resolveRef<any>(document, schema.$ref)\n }\n }\n }\n\n const responseBody = getResponseBody(getResponseByStatusCode({ document, operation, statusCode }), options.contentType)\n\n if (responseBody === false) {\n return {}\n }\n\n const schema = Array.isArray(responseBody) ? responseBody[1].schema : responseBody.schema\n\n if (!schema) {\n return {}\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * Returns the request body schema for an operation, or `null` when absent.\n *\n * @example\n * ```ts\n * getRequestSchema(document, operation) // SchemaObject | null\n * ```\n */\nexport function getRequestSchema(document: Document, operation: Operation, options: OperationsOptions = {}): SchemaObject | null {\n if (operation.schema.requestBody) {\n operation.schema.requestBody = dereferenceWithRef(document, operation.schema.requestBody)\n }\n\n const requestBody = getRequestContent({ document, operation, mediaType: options.contentType })\n\n if (requestBody === false) {\n return null\n }\n\n const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema\n\n if (!schema) {\n return null\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * The three component sections Kubb reads schemas from.\n */\ntype SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'\n\n/**\n * A schema annotated with its component section source and original name. Used by `resolveNameCollisions` for cross-source collision resolution.\n */\ntype SchemaWithMetadata = {\n schema: SchemaObject\n source: SchemaSourceMode\n originalName: string\n}\n\nexport type GetSchemasOptions = {\n contentType?: ContentType\n}\n\nexport type GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n nameMapping: Map<string, string>\n}\n\n/**\n * Flattens a keyword-only `allOf` into its parent schema.\n *\n * Only flattens when every member is a plain fragment, with no `$ref` and no structural keywords\n * (see `structuralKeys`). Outer schema values take precedence over fragment values.\n * Returns `null` for a `null` input, and the original schema unchanged when flattening is unsafe.\n *\n * @example\n * ```ts\n * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })\n * // { type: 'object', properties: {}, description: 'A pet' }\n *\n * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })\n * // returned unchanged, contains a $ref\n * ```\n */\n/**\n * Returns `true` when `fragment` carries any JSON Schema keyword that makes it\n * structurally significant on its own (see `structuralKeys`).\n *\n * A fragment with a structural keyword can't be safely merged into a parent schema.\n */\nfunction hasStructuralKeywords(fragment: SchemaObject): boolean {\n for (const key in fragment) {\n if (structuralKeys.has(key as 'properties')) return true\n }\n return false\n}\n\nexport function flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null\n\n const allOfFragments = schema.allOf as Array<SchemaObject>\n if (allOfFragments.some((item) => isReference(item))) return schema\n if (allOfFragments.some(hasStructuralKeywords)) return schema\n\n const merged: SchemaObject = { ...schema }\n delete merged.allOf\n\n for (const fragment of allOfFragments) {\n for (const [key, value] of Object.entries(fragment)) {\n if (merged[key as keyof typeof merged] === undefined) {\n merged[key as keyof typeof merged] = value\n }\n }\n }\n\n return merged\n}\n\n/**\n * Extracts the inline schema from a media-type `content` map.\n *\n * Prefers `preferredContentType` when given, otherwise uses the first key in the map.\n * Returns `null` when `content` is absent, the schema is missing, or the schema is a `$ref`.\n *\n * @example\n * ```ts\n * extractSchemaFromContent(operation.content, 'application/json')\n * // SchemaObject | null\n * ```\n */\nexport function extractSchemaFromContent(content: Record<string, unknown> | undefined, preferredContentType?: ContentType): SchemaObject | null {\n if (!content) return null\n\n const firstContentType = Object.keys(content)[0] ?? 'application/json'\n const targetContentType = preferredContentType ?? firstContentType\n const contentSchema = content[targetContentType] as { schema?: SchemaObject } | undefined\n const schema = contentSchema?.schema\n\n if (schema && '$ref' in schema) return null\n return schema ?? null\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.\n */\nfunction* collectRefs(schema: unknown): Generator<string, void, undefined> {\n if (Array.isArray(schema)) {\n for (const item of schema) yield* collectRefs(item)\n return\n }\n\n if (schema && typeof schema === 'object') {\n for (const key in schema) {\n const value = (schema as Record<string, unknown>)[key]\n if (!(key === '$ref' && typeof value === 'string')) {\n yield* collectRefs(value)\n continue\n }\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = value.slice(SCHEMA_REF_PREFIX.length)\n if (name) yield name\n }\n }\n }\n}\n\n/**\n * Returns a copy of `schemas` topologically sorted by `$ref` dependency.\n *\n * Referenced schemas appear before the schemas that depend on them, so code generators\n * can emit types in the correct order. Cycles are silently skipped.\n *\n * @example\n * ```ts\n * const sorted = sortSchemas({ Order: orderSchema, Pet: petSchema })\n * // Pet appears before Order when Order.$ref points at Pet\n * ```\n */\nexport function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {\n const deps = new Map<string, Array<string>>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n deps.set(name, [...new Set(collectRefs(schema))])\n }\n\n const sorted: Array<string> = []\n const visited = new Set<string>()\n\n function visit(name: string, stack: Set<string>) {\n if (visited.has(name) || stack.has(name)) return\n stack.add(name)\n for (const child of deps.get(name) ?? []) {\n if (deps.has(child)) visit(child, stack)\n }\n stack.delete(name)\n visited.add(name)\n sorted.push(name)\n }\n\n for (const name of Object.keys(schemas)) {\n visit(name, new Set())\n }\n\n const result: Record<string, SchemaObject> = {}\n for (const name of sorted) result[name] = schemas[name]!\n return result\n}\n\nconst semanticSuffixes: Record<SchemaSourceMode, string> = {\n schemas: 'Schema',\n responses: 'Response',\n requestBodies: 'Request',\n}\n\nfunction getSemanticSuffix(source: SchemaSourceMode): string {\n return semanticSuffixes[source]\n}\n\nfunction resolveSchemaRef(document: Document, schema: SchemaObject): SchemaObject {\n if (!isReference(schema)) return schema\n const resolved = resolveRef<SchemaObject>(document, schema.$ref)\n return resolved && !isReference(resolved) ? resolved : schema\n}\n\n/**\n * Collects component schemas from one or more sources and resolves name collisions.\n *\n * Sources default to `['schemas', 'requestBodies', 'responses']`. Returned schemas are\n * topologically sorted by `$ref` dependency so generators emit types in the correct order.\n *\n * When two or more schemas normalize to the same PascalCase name:\n * - Same source → numeric suffix (`2`, `3`, …).\n * - Different sources → semantic suffix (`Schema`, `Response`, `Request`).\n *\n * @example\n * ```ts\n * const { schemas, nameMapping } = getSchemas(document, { contentType: 'application/json' })\n * ```\n */\nexport function getSchemas(document: Document, { contentType }: GetSchemasOptions): GetSchemasResult {\n const components = document.components\n\n const candidates: Array<SchemaWithMetadata> = [\n ...Object.entries((components?.schemas as Record<string, SchemaObject>) ?? {}).map(([name, schema]) => ({\n schema: resolveSchemaRef(document, schema),\n source: 'schemas' as const,\n originalName: name,\n })),\n ...(['responses', 'requestBodies'] as const).flatMap((source) =>\n Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {\n const schema = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)\n return schema\n ? [\n {\n schema: resolveSchemaRef(document, schema),\n source,\n originalName: name,\n },\n ]\n : []\n }),\n ),\n ]\n\n const normalizedNames = new Map<string, Array<SchemaWithMetadata>>()\n for (const item of candidates) {\n const key = pascalCase(item.originalName)\n const bucket = normalizedNames.get(key) ?? []\n bucket.push(item)\n normalizedNames.set(key, bucket)\n }\n\n const schemas: Record<string, SchemaObject> = {}\n const nameMapping = new Map<string, string>()\n\n for (const [, items] of normalizedNames) {\n const isSingle = items.length === 1\n let hasMultipleSources = false\n if (!isSingle) {\n const firstSource = items[0]!.source\n for (let i = 1; i < items.length; i++) {\n if (items[i]!.source !== firstSource) {\n hasMultipleSources = true\n break\n }\n }\n }\n\n items.forEach((item, index) => {\n const suffix = isSingle ? '' : hasMultipleSources ? getSemanticSuffix(item.source) : index === 0 ? '' : String(index + 1)\n const uniqueName = item.originalName + suffix\n schemas[uniqueName] = item.schema\n nameMapping.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas), nameMapping }\n}\n\n/**\n * Resolves the AST type descriptor for a date/time format, honoring the `dateType` option.\n * Returns `null` when `dateType: false`, signalling the format should fall through to `string`.\n */\nexport function getDateType(\n options: ast.ParserOptions,\n format: 'date-time' | 'date' | 'time',\n): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | null {\n if (!options.dateType) {\n return null\n }\n\n if (format === 'date-time') {\n if (options.dateType === 'date') {\n return { type: 'date', representation: 'date' }\n }\n if (options.dateType === 'stringOffset') {\n return { type: 'datetime', offset: true }\n }\n if (options.dateType === 'stringLocal') {\n return { type: 'datetime', local: true }\n }\n return { type: 'datetime', offset: false }\n }\n\n if (format === 'date') {\n return {\n type: 'date',\n representation: options.dateType === 'date' ? 'date' : 'string',\n }\n }\n\n // time\n return {\n type: 'time',\n representation: options.dateType === 'date' ? 'date' : 'string',\n }\n}\n\n/**\n * Collects the shared metadata fields passed to every `createSchema` call.\n */\nexport function buildSchemaNode(schema: SchemaObject, name: string | null | undefined, nullable: true | undefined, defaultValue: unknown) {\n return {\n name,\n nullable,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n default: defaultValue,\n example: schema.example,\n format: schema.format,\n } as const\n}\n\n/**\n * Returns all request body content type keys for an operation.\n *\n * The requestBody is dereferenced in place when it is a `$ref` (the same mutation that\n * `getRequestSchema` already performs), so the returned list accurately reflects the\n * available content types even for referenced bodies.\n *\n * @example\n * ```ts\n * getRequestBodyContentTypes(document, operation)\n * // ['application/json', 'multipart/form-data']\n * ```\n */\nexport function getRequestBodyContentTypes(document: Document, operation: Operation): Array<string> {\n if (operation.schema.requestBody) {\n operation.schema.requestBody = dereferenceWithRef(document, operation.schema.requestBody)\n }\n\n const body = operation.schema.requestBody as { content?: Record<string, unknown> } | undefined\n if (!body) return []\n\n // dereferenceWithRef keeps $ref but spreads all resolved fields (including `content`).\n // Do not bail out on isReference, the content is already present on the merged object.\n return body.content ? Object.keys(body.content) : []\n}\n\n/**\n * Returns all response content type keys for an operation at a given status code.\n *\n * Response `$ref`s are resolved in place first (the same mutation `getResponseSchema` performs),\n * so the returned list reflects the available content types even for referenced responses.\n *\n * @example\n * ```ts\n * getResponseBodyContentTypes(document, operation, 200)\n * // ['application/json', 'application/xml']\n * ```\n */\nexport function getResponseBodyContentTypes(document: Document, operation: Operation, statusCode: string | number): Array<string> {\n if (operation.schema.responses) {\n const responses = operation.schema.responses\n for (const key in responses) {\n const schema = responses[key]\n if (schema && isReference(schema)) {\n responses[key] = resolveRef<any>(document, schema.$ref)\n }\n }\n }\n\n const responseObj = getResponseByStatusCode({ document, operation, statusCode })\n if (!responseObj || typeof responseObj !== 'object' || isReference(responseObj)) return []\n\n const body = responseObj as { content?: Record<string, unknown> }\n return body.content ? Object.keys(body.content) : []\n}\n","import { pascalCase } from '@internals/utils'\nimport { childName, enumPropName, extractRefName, findDiscriminator } from '@kubb/ast/utils'\nimport { ast } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS, enumExtensionKeys, SCHEMA_REF_PREFIX, typeOptionMap } from './constants.ts'\nimport { oasDialect, type OasDialect } from './dialect.ts'\nimport { getOperationId, getOperations, getRequestContentType, getResponseByStatusCode, getResponseStatusCodes } from './operation.ts'\nimport {\n buildSchemaNode,\n flattenSchema,\n getDateType,\n getParameters,\n getPrimitiveType,\n getRequestBodyContentTypes,\n getRequestSchema,\n getResponseBodyContentTypes,\n getResponseSchema,\n getSchemas,\n getSchemaType,\n} from './resolvers.ts'\nimport type { ContentType, Document, Operation, ReferenceObject, SchemaObject } from './types.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and optional content-type override.\n *\n * Passed to schema and operation converters to access the full specification\n * and handle content negotiation when multiple media types are available.\n */\nexport type OasParserContext = {\n document: Document\n contentType?: ContentType\n}\n\n/**\n * The object returned by {@link createSchemaParser}.\n * Contains parser functions bound to a specific document.\n */\nexport type SchemaParser = {\n parseSchema: (entry: { schema: SchemaObject; name?: string | null }, options?: Partial<ast.ParserOptions>) => ast.SchemaNode\n parseOperation: (options: ast.ParserOptions, operation: Operation) => ast.OperationNode\n parseParameter: (options: ast.ParserOptions, param: Record<string, unknown>) => ast.ParameterNode\n}\n\n/**\n * Pre-computed per-schema context passed to every schema converter.\n *\n * Centralizes schema derivations (type resolution, defaults, options) to avoid repeated\n * computation across all conversion branches. The `type` field is normalized from OAS 3.1\n * multi-type arrays to a single string.\n */\ntype SchemaContext = {\n schema: SchemaObject\n name: string | null | undefined\n nullable: true | undefined\n defaultValue: unknown\n /**\n * Normalized single type string (first element when OAS 3.1 multi-type array).\n */\n type: string | undefined\n rawOptions: Partial<ast.ParserOptions> | undefined\n options: ast.ParserOptions\n}\n\n/**\n * One entry in the ordered schema rule table: a predicate paired with a converter. A rule whose\n * `match` returns `true` may still `convert` to `null` to defer to the next rule (e.g. a `format`\n * that is not convertible falls through to plain `type` handling).\n */\ntype SchemaRule = {\n /** Identifies the rule when reading the table or debugging which branch ran. */\n name: string\n /** Returns `true` when this rule is responsible for the given context. */\n match: (context: SchemaContext) => boolean\n /** Produces a node for the context, or `null` to fall through to the next rule. */\n convert: (context: SchemaContext) => ast.SchemaNode | null\n}\n\n/**\n * Normalizes malformed `{ type: 'array', enum: [...] }` schemas by moving enum values into items.\n *\n * This pattern violates the OpenAPI spec but appears in real specs. The fix moves enum values\n * from the array to its items sub-schema, making them valid for downstream processing.\n *\n * @note This is a defensive measure for robustness with non-compliant specs.\n */\nfunction normalizeArrayEnum(schema: SchemaObject): SchemaObject {\n const isItemsObject = typeof schema.items === 'object' && !Array.isArray(schema.items)\n const normalizedItems: SchemaObject = {\n ...(isItemsObject ? (schema.items as SchemaObject) : {}),\n enum: schema.enum,\n }\n const { enum: _enum, ...schemaWithoutEnum } = schema\n\n return { ...schemaWithoutEnum, items: normalizedItems } as SchemaObject\n}\n\n/**\n * Factory function that creates schema and operation converters for a given OpenAPI context.\n *\n * Returns closures that share mutable state (`resolvingRefs` set for cycle detection).\n * Each converter branch (`convertRef`, `convertAllOf`, etc.) mutually recursively calls `parseSchema`,\n * made possible by hoisting of function declarations.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: OasParserContext, dialect: OasDialect = oasDialect) {\n const document = ctx.document\n\n // Branch handlers, each converts one OAS schema pattern to a SchemaNode.\n\n /**\n * Tracks `$ref` paths that are currently being resolved to prevent infinite\n * recursion when schemas contain circular references (e.g. `Pet → parent → Pet`).\n */\n const resolvingRefs = new Set<string>()\n\n /**\n * Cache of `$ref` schemas already resolved in this parser instance, keyed by ref path.\n *\n * Without it, a shared schema (e.g. `customer`) is re-expanded for every `$ref` that points at\n * it. In cross-referenced specs like Stripe (~1400 schemas) that becomes exponential blowup,\n * since one schema can be referenced from dozens of parents, each re-walking its whole subtree.\n * Memoizing by ref path drops the work from O(2^depth) to O(N) unique schema names.\n */\n const resolvedRefCache = new Map<string, ast.SchemaNode | null>()\n\n /**\n * Converts a `$ref` schema into a `RefSchemaNode`.\n *\n * The resolved schema is stored in `node.schema`. Usage-site sibling fields\n * (description, readOnly, nullable, etc.) are stored directly on the ref node.\n * Use `syncSchemaRef(node)` in printers to get a merged view of both.\n * Circular refs are detected via `resolvingRefs` and leave `schema` as `undefined`.\n */\n function convertRef({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n let resolvedSchema: ast.SchemaNode | null = null\n const refPath = schema.$ref\n if (refPath && !resolvingRefs.has(refPath)) {\n if (!resolvedRefCache.has(refPath)) {\n try {\n const referenced = dialect.resolveRef<SchemaObject>(document, refPath)\n if (referenced) {\n resolvingRefs.add(refPath)\n resolvedSchema = parseSchema({ schema: referenced }, rawOptions)\n resolvingRefs.delete(refPath)\n }\n } catch {\n // Ref cannot be resolved in this document (e.g. unit tests with minimal documents).\n }\n resolvedRefCache.set(refPath, resolvedSchema)\n }\n resolvedSchema = resolvedRefCache.get(refPath) ?? null\n }\n\n return ast.createSchema({\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n type: 'ref',\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n schema: resolvedSchema,\n })\n }\n\n /**\n * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.\n */\n function convertAllOf({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n if (\n schema.allOf!.length === 1 &&\n !schema.properties &&\n !(Array.isArray(schema.required) && schema.required.length) &&\n schema.additionalProperties === undefined\n ) {\n const [memberSchema] = schema.allOf as Array<SchemaObject | ReferenceObject>\n const memberNode = parseSchema({ schema: memberSchema! as SchemaObject, name }, rawOptions)\n const { kind: _kind, ...memberNodeProps } = memberNode\n const mergedNullable = nullable || memberNode.nullable || undefined\n const mergedDefault = schema.default === null && mergedNullable ? undefined : (schema.default ?? memberNode.default)\n\n return ast.createSchema({\n ...memberNodeProps,\n name,\n title: schema.title ?? memberNode.title,\n description: schema.description ?? memberNode.description,\n deprecated: schema.deprecated ?? memberNode.deprecated,\n nullable: mergedNullable,\n readOnly: schema.readOnly ?? memberNode.readOnly,\n writeOnly: schema.writeOnly ?? memberNode.writeOnly,\n default: mergedDefault,\n example: schema.example ?? memberNode.example,\n pattern: schema.pattern ?? ('pattern' in memberNode ? memberNode.pattern : undefined),\n format: schema.format ?? memberNode.format,\n } as ast.DistributiveOmit<ast.SchemaNode, 'kind'>)\n }\n\n const filteredDiscriminantValues: Array<{\n propertyName: string\n value: string\n }> = []\n const allOfMembers: Array<ast.SchemaNode> = (schema.allOf as Array<SchemaObject | ReferenceObject>)\n .filter((item) => {\n if (!dialect.isReference(item) || !name) return true\n const deref = dialect.resolveRef<SchemaObject>(document, item.$ref)\n if (!deref || !dialect.isDiscriminator(deref)) return true\n const parentUnion = deref.oneOf ?? deref.anyOf\n if (!parentUnion) return true\n const childRef = `${SCHEMA_REF_PREFIX}${name}`\n const inOneOf = parentUnion.some((oneOfItem) => dialect.isReference(oneOfItem) && oneOfItem.$ref === childRef)\n const inMapping = Object.values(deref.discriminator.mapping ?? {}).some((v) => v === childRef)\n if (inOneOf || inMapping) {\n const discriminatorValue = findDiscriminator(deref.discriminator.mapping, childRef)\n if (discriminatorValue) {\n filteredDiscriminantValues.push({\n propertyName: deref.discriminator.propertyName,\n value: discriminatorValue,\n })\n }\n return false\n }\n return true\n })\n .map((s) => parseSchema({ schema: s as SchemaObject, name }, rawOptions))\n\n const syntheticStart = allOfMembers.length\n\n if (Array.isArray(schema.required) && schema.required.length) {\n const outerKeys = schema.properties ? new Set(Object.keys(schema.properties)) : new Set<string>()\n const missingRequired = schema.required.filter((key) => !outerKeys.has(key))\n\n if (missingRequired.length) {\n const resolvedMembers = (schema.allOf as Array<SchemaObject | ReferenceObject>).flatMap((item) => {\n if (!dialect.isReference(item)) return [item as SchemaObject]\n const deref = dialect.resolveRef<SchemaObject>(document, item.$ref)\n return deref && !dialect.isReference(deref) ? [deref] : []\n })\n\n for (const key of missingRequired) {\n for (const resolved of resolvedMembers) {\n if (resolved.properties?.[key]) {\n allOfMembers.push(\n parseSchema(\n {\n schema: {\n properties: { [key]: resolved.properties[key] },\n required: [key],\n } as SchemaObject,\n name,\n },\n rawOptions,\n ),\n )\n break\n }\n }\n }\n }\n }\n\n if (schema.properties) {\n const { allOf: _allOf, ...schemaWithoutAllOf } = schema\n // Don't pass `name` here, the result must stay anonymous so it can be merged with the\n // adjacent synthetic object in `mergeAdjacentObjectsLazy`. Nested enum qualification\n // happens upstream via `convertObject`'s `setEnumName` propagation.\n allOfMembers.push(parseSchema({ schema: schemaWithoutAllOf }, rawOptions))\n }\n\n for (const { propertyName, value } of filteredDiscriminantValues) {\n allOfMembers.push(ast.createDiscriminantNode({ propertyName, value }))\n }\n\n return ast.createSchema({\n type: 'intersection',\n members: [...ast.mergeAdjacentObjectsLazy(allOfMembers.slice(0, syntheticStart)), ...ast.mergeAdjacentObjectsLazy(allOfMembers.slice(syntheticStart))],\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n */\n function convertUnion({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n function pickDiscriminatorPropertyNode(node: ast.SchemaNode, propertyName: string): ast.SchemaNode | null {\n const objectNode = ast.narrowSchema(node, 'object')\n const discriminatorProperty = objectNode?.properties?.find((property) => property.name === propertyName)\n\n if (!discriminatorProperty) {\n return null\n }\n\n return ast.createSchema({\n type: 'object',\n primitive: 'object',\n properties: [discriminatorProperty],\n })\n }\n\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const unionBase = {\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n discriminatorPropertyName: dialect.isDiscriminator(schema) ? schema.discriminator.propertyName : undefined,\n strategy,\n }\n const discriminator = dialect.isDiscriminator(schema) ? schema.discriminator : undefined\n const sharedPropertiesNode = schema.properties\n ? (() => {\n const { oneOf: _oneOf, anyOf: _anyOf, ...schemaWithoutUnion } = schema\n const memberBaseSchema: SchemaObject = discriminator\n ? (Object.fromEntries(Object.entries(schemaWithoutUnion).filter(([key]) => key !== 'discriminator')) as SchemaObject)\n : schemaWithoutUnion\n return parseSchema({ schema: memberBaseSchema, name }, rawOptions)\n })()\n : undefined\n\n if (sharedPropertiesNode || discriminator?.mapping) {\n const members = unionMembers.map((s) => {\n const ref = dialect.isReference(s) ? s.$ref : undefined\n const discriminatorValue = findDiscriminator(discriminator?.mapping, ref)\n const memberNode = parseSchema({ schema: s as SchemaObject, name }, rawOptions)\n\n if (!discriminatorValue || !discriminator) {\n return memberNode\n }\n\n const narrowedDiscriminatorNode = sharedPropertiesNode\n ? pickDiscriminatorPropertyNode(\n ast.setDiscriminatorEnum({\n node: sharedPropertiesNode,\n propertyName: discriminator.propertyName,\n values: [discriminatorValue],\n }),\n discriminator.propertyName,\n )\n : undefined\n\n return ast.createSchema({\n type: 'intersection',\n members: [\n memberNode,\n narrowedDiscriminatorNode ??\n ast.createDiscriminantNode({\n propertyName: discriminator.propertyName,\n value: discriminatorValue,\n }),\n ],\n })\n })\n\n const unionNode = ast.createSchema({\n type: 'union',\n ...unionBase,\n members,\n })\n\n if (!sharedPropertiesNode) {\n return unionNode\n }\n\n return ast.createSchema({\n type: 'intersection',\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n members: [unionNode, sharedPropertiesNode],\n })\n }\n\n return ast.createSchema({\n type: 'union',\n ...unionBase,\n members: ast.simplifyUnion(unionMembers.map((s) => parseSchema({ schema: s as SchemaObject, name }, rawOptions))),\n })\n }\n\n /**\n * Converts an OAS 3.1 `const` schema into a null scalar or a single-value `EnumSchemaNode`.\n */\n function convertConst({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n const constValue = schema.const\n\n if (constValue === null) {\n return ast.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n format: schema.format,\n })\n }\n\n const constPrimitive = getPrimitiveType(typeof constValue === 'number' ? 'number' : typeof constValue === 'boolean' ? 'boolean' : 'string')\n return ast.createSchema({\n type: 'enum',\n primitive: constPrimitive,\n enumValues: [constValue as string | number | boolean],\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a format-annotated schema into a special-type `SchemaNode`.\n * Returns `null` when the format should fall through to string handling (`dateType: false`).\n */\n function convertFormat({ schema, name, nullable, defaultValue, options }: SchemaContext): ast.SchemaNode | null {\n const base = buildSchemaNode(schema, name, nullable, defaultValue)\n\n if (schema.format === 'int64') {\n return ast.createSchema({\n type: options.integerType === 'bigint' ? 'bigint' : 'integer',\n primitive: 'integer',\n ...base,\n min: schema.minimum,\n max: schema.maximum,\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n })\n }\n\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const dateType = getDateType(options, schema.format)\n if (!dateType) return null\n\n if (dateType.type === 'datetime') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'datetime',\n offset: dateType.offset,\n local: dateType.local,\n })\n }\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: dateType.type,\n representation: dateType.representation,\n })\n }\n\n const specialType = getSchemaType(schema.format!)\n if (!specialType) return null\n\n const specialPrimitive: ast.PrimitiveSchemaType = specialType === 'number' || specialType === 'integer' || specialType === 'bigint' ? specialType : 'string'\n\n if (specialType === 'number' || specialType === 'integer' || specialType === 'bigint') {\n return ast.createSchema({\n ...base,\n primitive: specialPrimitive,\n type: specialType,\n })\n }\n if (specialType === 'url') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'url',\n min: schema.minLength,\n max: schema.maxLength,\n })\n }\n if (specialType === 'ipv4') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'ipv4',\n })\n }\n if (specialType === 'ipv6') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: 'ipv6',\n })\n }\n if (specialType === 'uuid' || specialType === 'email') {\n return ast.createSchema({\n ...base,\n primitive: 'string' as const,\n type: specialType,\n min: schema.minLength,\n max: schema.maxLength,\n })\n }\n\n return ast.createSchema({\n ...base,\n primitive: specialPrimitive,\n type: specialType as ast.ScalarSchemaType,\n })\n }\n\n /**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n */\n function convertEnum({ schema, name, nullable, type, rawOptions }: SchemaContext): ast.SchemaNode {\n if (type === 'array') {\n return parseSchema({ schema: normalizeArrayEnum(schema), name }, rawOptions)\n }\n\n const nullInEnum = schema.enum!.includes(null)\n const filteredValues = (nullInEnum ? schema.enum!.filter((v) => v !== null) : schema.enum!) as Array<string | number | boolean>\n\n // drf-spectacular `NullEnum` ({ enum: [null] }) is just `null`. An empty enum node would\n // render as `never` (plugin-ts) / invalid `z.enum([])` (plugin-zod). Mirror the `const: null`\n // branch so it renders as a clean `null` (not `z.null().nullable()`).\n if (nullInEnum && filteredValues.length === 0) {\n return ast.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n format: schema.format,\n })\n }\n\n const enumNullable = nullable || nullInEnum || undefined\n const enumDefault = schema.default === null && enumNullable ? undefined : schema.default\n const enumPrimitive = getPrimitiveType(type)\n\n const enumBase = {\n type: 'enum' as const,\n primitive: enumPrimitive,\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable: enumNullable,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n default: enumDefault,\n example: schema.example,\n format: schema.format,\n }\n\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n if (extensionKey || enumPrimitive === 'number' || enumPrimitive === 'integer' || enumPrimitive === 'boolean') {\n const enumPrimitiveType = (enumPrimitive === 'number' || enumPrimitive === 'integer' ? 'number' : enumPrimitive === 'boolean' ? 'boolean' : 'string') as\n | 'number'\n | 'boolean'\n | 'string'\n const rawEnumNames = extensionKey ? ((schema as Record<string, unknown>)[extensionKey] as Array<string | number>) : undefined\n const uniqueValues = [...new Set(filteredValues)]\n const seenNames = new Set<string>()\n\n return ast.createSchema({\n ...enumBase,\n primitive: enumPrimitiveType,\n namedEnumValues: uniqueValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive: enumPrimitiveType,\n }))\n .filter((entry) => {\n if (seenNames.has(entry.name)) return false\n seenNames.add(entry.name)\n return true\n }),\n })\n }\n\n return ast.createSchema({\n ...enumBase,\n enumValues: [...new Set(filteredValues)],\n })\n }\n\n /**\n * Converts an object-like schema into an `ObjectSchemaNode`.\n */\n function convertObject({ schema, name, nullable, defaultValue, rawOptions, options }: SchemaContext): ast.SchemaNode {\n const properties: Array<ast.PropertyNode> = schema.properties\n ? Object.entries(schema.properties).map(([propName, propSchema]) => {\n const required = Array.isArray(schema.required) ? schema.required.includes(propName) : !!schema.required\n const resolvedPropSchema = propSchema as SchemaObject\n const propNullable = dialect.isNullable(resolvedPropSchema)\n\n const resolvedChildName = childName(name, propName)\n const propNode = parseSchema({ schema: resolvedPropSchema, name: resolvedChildName }, rawOptions)\n const schemaNode = (() => {\n const node = ast.setEnumName(propNode, name, propName, options.enumSuffix)\n const tupleNode = ast.narrowSchema(node, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => ast.setEnumName(item, name, propName, options.enumSuffix))\n if (namedItems.some((item, i) => item !== tupleNode.items![i])) {\n return { ...tupleNode, items: namedItems }\n }\n }\n return node\n })()\n\n return ast.createProperty({\n name: propName,\n schema: {\n ...schemaNode,\n nullable: schemaNode.type === 'null' ? undefined : propNullable || undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n const additionalPropertiesNode: ast.SchemaNode | boolean | undefined = (() => {\n if (additionalProperties === true) return true\n if (additionalProperties === false) return false\n if (additionalProperties && Object.keys(additionalProperties).length > 0) {\n return parseSchema({ schema: additionalProperties as SchemaObject }, rawOptions)\n }\n if (additionalProperties) return ast.createSchema({ type: typeOptionMap.get(options.unknownType)! })\n return undefined\n })()\n\n const rawPatternProperties = 'patternProperties' in schema ? schema.patternProperties : undefined\n\n const patternProperties = rawPatternProperties\n ? Object.fromEntries(\n Object.entries(rawPatternProperties).map(([pattern, patternSchema]) => [\n pattern,\n patternSchema === true || (typeof patternSchema === 'object' && Object.keys(patternSchema).length === 0)\n ? ast.createSchema({\n type: typeOptionMap.get(options.unknownType)!,\n })\n : parseSchema({ schema: patternSchema as SchemaObject }, rawOptions),\n ]),\n )\n : undefined\n\n const objectNode: ast.SchemaNode = ast.createSchema({\n type: 'object',\n primitive: 'object',\n properties,\n additionalProperties: additionalPropertiesNode,\n patternProperties,\n minProperties: schema.minProperties,\n maxProperties: schema.maxProperties,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n\n if (dialect.isDiscriminator(schema) && schema.discriminator.mapping) {\n const discPropName = schema.discriminator.propertyName\n const values = Object.keys(schema.discriminator.mapping)\n const enumName = name ? enumPropName(name, discPropName, options.enumSuffix) : undefined\n return ast.setDiscriminatorEnum({\n node: objectNode,\n propertyName: discPropName,\n values,\n enumName,\n })\n }\n\n return objectNode\n }\n\n /**\n * Converts an OAS 3.1 `prefixItems` tuple into a `TupleSchemaNode`.\n */\n function convertTuple({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => parseSchema({ schema: item as SchemaObject }, rawOptions))\n const rest = schema.items ? parseSchema({ schema: schema.items as SchemaObject }, rawOptions) : ast.createSchema({ type: 'any' })\n\n return ast.createSchema({\n type: 'tuple',\n primitive: 'array',\n items: tupleItems,\n rest,\n min: schema.minItems,\n max: schema.maxItems,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'array'` schema into an `ArraySchemaNode`.\n */\n function convertArray({ schema, name, nullable, defaultValue, rawOptions, options }: SchemaContext): ast.SchemaNode {\n const rawItems = schema.items as SchemaObject | undefined\n const itemName = rawItems?.enum?.length && name ? enumPropName(null, name, options.enumSuffix) : name\n const items = rawItems ? [parseSchema({ schema: rawItems, name: itemName }, rawOptions)] : []\n\n return ast.createSchema({\n type: 'array',\n primitive: 'array',\n items,\n min: schema.minItems,\n max: schema.maxItems,\n unique: schema.uniqueItems ?? undefined,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'string'` schema into a `StringSchemaNode`.\n */\n function convertString({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'number'` or `type: 'integer'` schema.\n */\n function convertNumeric({ schema, name, nullable, defaultValue }: SchemaContext, type: 'number' | 'integer'): ast.SchemaNode {\n return ast.createSchema({\n type,\n primitive: type,\n min: schema.minimum,\n max: schema.maximum,\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n multipleOf: schema.multipleOf,\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts a `type: 'boolean'` schema.\n */\n function convertBoolean({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'boolean',\n primitive: 'boolean',\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts an explicit `type: 'null'` schema.\n */\n function convertNull({ schema, name, nullable }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable,\n format: schema.format,\n })\n }\n\n /**\n * Converts a binary string schema (`type: 'string'`, `contentMediaType: 'application/octet-stream'`)\n * into a `blob` node.\n */\n function convertBlob({ schema, name, nullable, defaultValue }: SchemaContext): ast.SchemaNode {\n return ast.createSchema({\n type: 'blob',\n primitive: 'string',\n ...buildSchemaNode(schema, name, nullable, defaultValue),\n })\n }\n\n /**\n * Converts an OAS 3.1 multi-type array (e.g. `type: ['string', 'number']`) into a `UnionSchemaNode`.\n *\n * Returns `null` when only one non-`null` type remains (e.g. `['string', 'null']`), so `parseSchema`\n * falls through and handles it as that single type with nullability already folded in.\n */\n function convertMultiType({ schema, name, nullable, defaultValue, rawOptions }: SchemaContext): ast.SchemaNode | null {\n const types = schema.type as Array<string>\n const nonNullTypes = types.filter((t) => t !== 'null')\n if (nonNullTypes.length <= 1) return null\n\n const arrayNullable = types.includes('null') || nullable || undefined\n return ast.createSchema({\n type: 'union',\n members: nonNullTypes.map((t) => parseSchema({ schema: { ...schema, type: t } as SchemaObject, name }, rawOptions)),\n ...buildSchemaNode(schema, name, arrayNullable, defaultValue),\n })\n }\n\n /**\n * Ordered schema rule table. Order is significant: composition keywords (`$ref`, `allOf`,\n * `oneOf`/`anyOf`) take precedence over `const`/`format`, which take precedence over the plain\n * `type`. The first matching rule that produces a node wins. See {@link SchemaRule} for the\n * match/convert/fall-through contract.\n */\n const schemaRules: Array<SchemaRule> = [\n { name: 'ref', match: ({ schema }) => dialect.isReference(schema), convert: convertRef },\n { name: 'allOf', match: ({ schema }) => !!schema.allOf?.length, convert: convertAllOf },\n { name: 'union', match: ({ schema }) => !!(schema.oneOf?.length || schema.anyOf?.length), convert: convertUnion },\n { name: 'const', match: ({ schema }) => 'const' in schema && schema.const !== undefined, convert: convertConst },\n { name: 'format', match: ({ schema }) => !!schema.format, convert: convertFormat },\n {\n name: 'blob',\n match: ({ schema }) => dialect.isBinary(schema),\n convert: convertBlob,\n },\n { name: 'multi-type', match: ({ schema }) => Array.isArray(schema.type) && schema.type.length > 1, convert: convertMultiType },\n {\n name: 'constrained-string',\n match: ({ schema, type }) => !type && (schema.minLength !== undefined || schema.maxLength !== undefined || schema.pattern !== undefined),\n convert: convertString,\n },\n {\n name: 'constrained-number',\n match: ({ schema, type }) => !type && (schema.minimum !== undefined || schema.maximum !== undefined),\n convert: (ctx) => convertNumeric(ctx, 'number'),\n },\n { name: 'enum', match: ({ schema }) => !!schema.enum?.length, convert: convertEnum },\n {\n name: 'object',\n match: ({ schema, type }) => type === 'object' || !!schema.properties || !!schema.additionalProperties || 'patternProperties' in schema,\n convert: convertObject,\n },\n { name: 'tuple', match: ({ schema }) => 'prefixItems' in schema, convert: convertTuple },\n { name: 'array', match: ({ schema, type }) => type === 'array' || 'items' in schema, convert: convertArray },\n { name: 'string', match: ({ type }) => type === 'string', convert: convertString },\n { name: 'number', match: ({ type }) => type === 'number', convert: (ctx) => convertNumeric(ctx, 'number') },\n { name: 'integer', match: ({ type }) => type === 'integer', convert: (ctx) => convertNumeric(ctx, 'integer') },\n { name: 'boolean', match: ({ type }) => type === 'boolean', convert: convertBoolean },\n { name: 'null', match: ({ type }) => type === 'null', convert: convertNull },\n ]\n\n /**\n * Converts an OAS `SchemaObject` into a `SchemaNode`.\n *\n * Builds the per-schema context, then walks the ordered {@link schemaRules} table and returns\n * the first converter that produces a node. When none match, falls back to the configured\n * `emptySchemaType`.\n */\n function parseSchema({ schema, name }: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>): ast.SchemaNode {\n const options: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n ...rawOptions,\n }\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema && flattenedSchema !== schema) {\n return parseSchema({ schema: flattenedSchema, name }, rawOptions)\n }\n\n const nullable = dialect.isNullable(schema) || undefined\n const defaultValue = schema.default === null && nullable ? undefined : schema.default\n const type = Array.isArray(schema.type) ? schema.type[0] : schema.type\n\n const schemaCtx: SchemaContext = {\n schema,\n name,\n nullable,\n defaultValue,\n type,\n rawOptions,\n options,\n }\n\n for (const rule of schemaRules) {\n if (!rule.match(schemaCtx)) continue\n const node = rule.convert(schemaCtx)\n if (node) return node\n }\n\n const emptyType = typeOptionMap.get(options.emptySchemaType)!\n return ast.createSchema({\n type: emptyType as ast.ScalarSchemaType,\n name,\n title: schema.title,\n description: schema.description,\n format: schema.format,\n })\n }\n\n /**\n * Converts a dereferenced OAS parameter object into a `ParameterNode`.\n */\n function parseParameter(options: ast.ParserOptions, param: Record<string, unknown>, parentName?: string): ast.ParameterNode {\n const required = (param['required'] as boolean | undefined) ?? false\n const paramName = param['name'] as string\n const schemaName = parentName && paramName ? pascalCase(`${parentName} ${paramName}`) : undefined\n\n const schema: ast.SchemaNode = param['schema']\n ? parseSchema({ schema: param['schema'] as SchemaObject, name: schemaName }, options)\n : ast.createSchema({ type: typeOptionMap.get(options.unknownType)! })\n\n return ast.createParameter({\n name: paramName,\n in: param['in'] as ast.ParameterLocation,\n schema: {\n ...schema,\n description: (param['description'] as string | undefined) ?? schema.description,\n },\n required,\n })\n }\n\n /**\n * Reads the inline `requestBody` metadata (description / required) that OAS exposes\n * outside the schema itself. Returns an empty object when the request body is missing or a `$ref`.\n */\n function getRequestBodyMeta(operation: Operation): {\n description?: string\n required: boolean\n } {\n const body = operation.schema.requestBody as { description?: string; required?: boolean } | undefined\n if (!body) return { required: false }\n\n // After getRequestBodyContentTypes has run, body may still carry $ref but the\n // resolved fields (description, required, content) are already spread onto it.\n return {\n description: body.description,\n required: body.required === true,\n }\n }\n\n /**\n * Reads the inline response object (not a `$ref`) and returns its description plus its `content` map.\n */\n function getResponseMeta(responseObj: unknown): {\n description?: string\n content?: Record<string, unknown>\n } {\n if (typeof responseObj !== 'object' || responseObj === null || Array.isArray(responseObj)) return {}\n\n const inline = responseObj as {\n description?: string\n content?: Record<string, unknown>\n }\n return { description: inline.description, content: inline.content }\n }\n\n /**\n * Collects property names whose schema has a truthy boolean flag (`readOnly` or `writeOnly`).\n * `$ref` entries are skipped since their flags live on the dereferenced target.\n */\n function collectPropertyKeysByFlag(schema: SchemaObject | null, flag: 'readOnly' | 'writeOnly'): Array<string> | null {\n if (!schema?.properties) return null\n\n const keys: Array<string> = []\n for (const key in schema.properties) {\n const prop = schema.properties[key]\n if (prop && !dialect.isReference(prop) && (prop as Record<string, unknown>)[flag]) {\n keys.push(key)\n }\n }\n return keys.length ? keys : null\n }\n\n /**\n * Converts an OAS `Operation` into an `OperationNode`.\n */\n function parseOperation(options: ast.ParserOptions, operation: Operation): ast.OperationNode {\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const parameters: Array<ast.ParameterNode> = getParameters(document, operation).map((param) =>\n parseParameter(options, param as unknown as Record<string, unknown>, operationName),\n )\n\n // Determine which content types to include in requestBody.content.\n // When a global contentType is configured, restrict to that single type.\n // Otherwise include every content type declared in the spec.\n const allContentTypes = ctx.contentType ? [ctx.contentType] : getRequestBodyContentTypes(document, operation)\n\n const requestBodyMeta = getRequestBodyMeta(operation)\n const requestBodyName = operationName ? `${operationName}Request` : undefined\n\n const content = allContentTypes.flatMap((ct) => {\n const schema = getRequestSchema(document, operation, { contentType: ct })\n if (!schema) return []\n return [\n {\n contentType: ct,\n schema: ast.syncOptionality(parseSchema({ schema, name: requestBodyName }, options), requestBodyMeta.required),\n keysToOmit: collectPropertyKeysByFlag(schema, 'readOnly'),\n },\n ]\n })\n\n const requestBody =\n content.length > 0 || requestBodyMeta.description\n ? {\n description: requestBodyMeta.description,\n required: requestBodyMeta.required || undefined,\n content: content.length > 0 ? content : undefined,\n }\n : undefined\n\n const responses: Array<ast.ResponseNode> = getResponseStatusCodes(operation).map((statusCode) => {\n const responseObj = getResponseByStatusCode({ document, operation, statusCode })\n\n // Use `Status<code>` (matching plugin-ts's resolveResponseStatusName convention) so the\n // qualified names for nested enums don't collide with top-level component schemas that\n // happen to be named `<operation><statusCode>` (e.g. `GetMaintenance200`).\n const responseName = operationName ? `${operationName}Status${statusCode}` : undefined\n const { description } = getResponseMeta(responseObj)\n\n const parseEntrySchema = (contentType?: string) => {\n const raw = getResponseSchema(document, operation, statusCode, { contentType })\n const node =\n raw && Object.keys(raw).length > 0\n ? parseSchema({ schema: raw, name: responseName }, options)\n : ast.createSchema({ type: typeOptionMap.get(options.emptySchemaType)! })\n return { schema: node, keysToOmit: collectPropertyKeysByFlag(raw, 'writeOnly') }\n }\n\n // Build one entry per declared response content type so plugins can union the variants.\n // When a global contentType is configured, restrict to that single type (mirrors requestBody).\n const responseContentTypes = ctx.contentType ? [ctx.contentType] : getResponseBodyContentTypes(document, operation, statusCode)\n const content = responseContentTypes.map((contentType) => ({ contentType, ...parseEntrySchema(contentType) }))\n\n // Body-less responses keep a single fallback entry so the response still resolves to a\n // (void/any) schema, matching how `requestBody` only carries schemas inside `content`.\n if (content.length === 0) {\n content.push({ contentType: getRequestContentType({ document, operation }) || 'application/json', ...parseEntrySchema(ctx.contentType) })\n }\n\n return ast.createResponse({\n statusCode: statusCode as ast.StatusCode,\n description,\n content,\n })\n })\n\n const pathItem = document.paths?.[operation.path]\n const pathItemDoc = pathItem && !dialect.isReference(pathItem) ? (pathItem as { summary?: unknown; description?: unknown }) : undefined\n const pickDoc = (key: 'summary' | 'description'): string | undefined => {\n const own = operation.schema[key]\n if (typeof own === 'string') return own\n const fallback = pathItemDoc?.[key]\n return typeof fallback === 'string' ? fallback : undefined\n }\n\n return ast.createOperation({\n operationId,\n protocol: 'http',\n method: operation.method.toUpperCase() as ast.HttpMethod,\n path: operation.path,\n tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],\n summary: pickDoc('summary') || undefined,\n description: pickDoc('description') || undefined,\n deprecated: operation.schema.deprecated || undefined,\n parameters,\n requestBody,\n responses,\n })\n }\n\n return { parseSchema, parseOperation, parseParameter }\n}\n\n/**\n * Parses a single OpenAPI `SchemaObject` into a `SchemaNode`.\n *\n * Use this for targeted schema parsing when you don't need the full spec.\n * For complete spec parsing, use `parseOas()` instead which handles operations and all schemas together.\n *\n * @note Circular schema references are tracked via internal state and resolve appropriately.\n *\n * @example\n * ```ts\n * const document = yaml.parse(fs.readFileSync('openapi.yaml', 'utf8'))\n * const ctx = { document }\n * const schema = parseSchema(ctx, { schema: { type: 'string', format: 'uuid' } })\n * ```\n */\nexport function parseSchema(\n ctx: OasParserContext,\n { schema, name }: { schema: SchemaObject; name?: string },\n options?: Partial<ast.ParserOptions>,\n): ast.SchemaNode {\n return createSchemaParser(ctx).parseSchema({ schema, name }, options)\n}\n\n/**\n * Parses an OpenAPI specification into Kubb's universal `InputNode` AST.\n *\n * This is the main entry point for `@kubb/adapter-oas`. It converts OpenAPI/Swagger specs into a spec-agnostic tree\n * that downstream plugins (`plugin-ts`, `plugin-zod`, etc.) consume for code generation. No code is generated here, * the tree is a pure data structure representing all schemas and operations.\n *\n * Returns the AST root and a `nameMapping` for resolving schema references.\n *\n * @example\n * ```ts\n * import { parseOas } from '@kubb/adapter-oas'\n *\n * const document = await parseFromConfig(config)\n * const { root, nameMapping } = parseOas(document, { dateType: 'date', contentType: 'application/json' })\n * ```\n */\nexport function parseOas(\n document: Document,\n options: Partial<ast.ParserOptions> & { contentType?: ContentType } = {},\n): { root: ast.InputNode; nameMapping: Map<string, string> } {\n const { contentType, ...parserOptions } = options\n const mergedOptions: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n ...parserOptions,\n }\n\n const { schemas: schemaObjects, nameMapping } = getSchemas(document, {\n contentType,\n })\n const { parseSchema: _parseSchema, parseOperation: _parseOperation } = createSchemaParser({ document, contentType })\n\n const schemas: Array<ast.SchemaNode> = Object.entries(schemaObjects).map(([name, schema]) => _parseSchema({ schema, name }, mergedOptions))\n\n const operations: Array<ast.OperationNode> = getOperations(document)\n .map((operation) => _parseOperation(mergedOptions, operation))\n .filter((op): op is ast.OperationNode => op !== null)\n\n const root = ast.createInput({ schemas, operations })\n\n return { root, nameMapping }\n}\n","import { ast } from '@kubb/core'\nimport type { SchemaNodeByType } from '@kubb/ast'\n\nexport type DiscriminatorTarget = {\n propertyName: string\n enumValues: Array<string | number | boolean>\n}\n\n/**\n * Builds a map of child schema names → discriminator patch data by scanning the given\n * top-level AST schema nodes for union schemas that carry a `discriminatorPropertyName`.\n *\n * The streaming path calls this on a small pre-parsed subset of schemas (only the\n * discriminator parents) rather than on all schemas at once.\n */\nexport function buildDiscriminatorChildMap(schemas: Array<ast.SchemaNode>): Map<string, DiscriminatorTarget> {\n const childMap = new Map<string, DiscriminatorTarget>()\n\n for (const schema of schemas) {\n // Case 1: top-level schema is a union (oneOf/anyOf with discriminator)\n // Case 2: top-level schema is an intersection wrapping a union (oneOf/anyOf + shared properties)\n let unionNode = ast.narrowSchema(schema, 'union')\n\n if (!unionNode) {\n const intersectionMembers = ast.narrowSchema(schema, 'intersection')?.members\n if (intersectionMembers) {\n for (const m of intersectionMembers) {\n const u = ast.narrowSchema(m, 'union')\n if (u) {\n unionNode = u\n break\n }\n }\n }\n }\n\n if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue\n\n const { discriminatorPropertyName, members } = unionNode\n\n for (const member of members) {\n // Members with a discriminant value are intersections: [RefSchemaNode, ObjectSchemaNode]\n const intersectionNode = ast.narrowSchema(member, 'intersection')\n if (!intersectionNode?.members) continue\n\n let refNode: SchemaNodeByType['ref'] | null = null\n let objNode: SchemaNodeByType['object'] | null = null\n\n for (const m of intersectionNode.members) {\n refNode ??= ast.narrowSchema(m, 'ref')\n objNode ??= ast.narrowSchema(m, 'object')\n }\n\n if (!refNode?.name || !objNode) continue\n\n const prop = objNode.properties.find((p) => p.name === discriminatorPropertyName)\n const enumNode = prop ? ast.narrowSchema(prop.schema, 'enum') : null\n if (!enumNode?.enumValues?.length) continue\n\n const enumValues = enumNode.enumValues.filter((v): v is string | number | boolean => v !== null)\n if (!enumValues.length) continue\n\n const existing = childMap.get(refNode.name)\n if (!existing) {\n childMap.set(refNode.name, { propertyName: discriminatorPropertyName, enumValues: [...enumValues] })\n continue\n }\n existing.enumValues.push(...enumValues)\n }\n }\n\n return childMap\n}\n\n/**\n * Patches a single top-level `SchemaNode` with its discriminator entry (adds or replaces\n * the discriminant property). Used by the streaming path to apply patches inline per yield\n * without buffering all schemas.\n */\nexport function patchDiscriminatorNode(node: ast.SchemaNode, entry: { propertyName: string; enumValues: Array<string | number | boolean> }): ast.SchemaNode {\n const objectNode = ast.narrowSchema(node, 'object')\n if (!objectNode) return node\n\n const { propertyName, enumValues } = entry\n const enumSchema = ast.createSchema({ type: 'enum', enumValues })\n const newProp = ast.createProperty({ name: propertyName, required: true, schema: enumSchema })\n\n const existingIdx = objectNode.properties.findIndex((p) => p.name === propertyName)\n const newProperties = existingIdx >= 0 ? objectNode.properties.map((p, i) => (i === existingIdx ? newProp : p)) : [...objectNode.properties, newProp]\n\n return { ...objectNode, properties: newProperties }\n}\n","import { Diagnostics } from '@kubb/core'\nimport type { ast } from '@kubb/core'\nimport { isHandledFormat } from './resolvers.ts'\n\n/**\n * Reports the advisory diagnostics (`KUBB_UNSUPPORTED_FORMAT`, `KUBB_DEPRECATED`) for one\n * top-level schema. Walks the node the parser produced during `preScan`, threading the RFC 6901\n * pointer as it descends so a nested field reports against its full path\n * (`#/components/schemas/Pet/properties/owner/properties/name`). Refs are not followed, so the\n * resolved schema is reported under its own walk. Reports land in the active build run, are a\n * no-op outside one, and repeats are deduped by the build.\n */\nexport function reportSchemaDiagnostics({ node, name }: { node: ast.SchemaNode; name: string }): void {\n visit(node, `#/components/schemas/${escapePointerToken(name)}`)\n}\n\n/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * property name with those characters maps to a distinct pointer instead of colliding in the dedupe.\n */\nfunction escapePointerToken(token: string): string {\n return token.replace(/~/g, '~0').replace(/\\//g, '~1')\n}\n\nfunction visit(node: ast.SchemaNode, pointer: string): void {\n if (node.deprecated) {\n Diagnostics.report({\n code: Diagnostics.code.deprecated,\n severity: 'info',\n message: 'This schema is marked as deprecated.',\n location: { kind: 'schema', pointer },\n })\n }\n\n if (typeof node.format === 'string' && !isHandledFormat(node.format)) {\n Diagnostics.report({\n code: Diagnostics.code.unsupportedFormat,\n severity: 'warning',\n message: `Kubb does not map the format \"${node.format}\" to a specific type, so it falls back to the base type.`,\n help: `Use a format Kubb supports, or handle \"${node.format}\" with a custom parser or plugin.`,\n location: { kind: 'schema', pointer },\n })\n }\n\n if (node.type === 'object') {\n for (const property of node.properties) {\n visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`)\n }\n if (node.additionalProperties && typeof node.additionalProperties === 'object') {\n visit(node.additionalProperties, `${pointer}/additionalProperties`)\n }\n return\n }\n\n if (node.type === 'array') {\n for (const item of node.items ?? []) {\n visit(item, `${pointer}/items`)\n }\n return\n }\n\n if (node.type === 'tuple') {\n // Each tuple position has its own pointer, so index them. A shared `/items` would collapse\n // distinct diagnostics in the dedupe.\n for (const [index, item] of (node.items ?? []).entries()) {\n visit(item, `${pointer}/items/${index}`)\n }\n return\n }\n\n if (node.type === 'union' || node.type === 'intersection') {\n for (const [index, member] of (node.members ?? []).entries()) {\n visit(member, `${pointer}/members/${index}`)\n }\n }\n}\n","import { ast } from '@kubb/core'\nimport { SCHEMA_REF_PREFIX } from './constants.ts'\nimport { buildDiscriminatorChildMap, patchDiscriminatorNode } from './discriminator.ts'\nimport { getOperations } from './operation.ts'\nimport type { SchemaParser } from './parser.ts'\nimport { resolveServerUrl } from './resolvers.ts'\nimport { reportSchemaDiagnostics } from './schemaDiagnostics.ts'\nimport type { DiscriminatorTarget } from './discriminator.ts'\nimport type { AdapterOas, Document, SchemaObject } from './types.ts'\n\nexport type PreScanResult = {\n refAliasMap: Map<string, ast.SchemaNode>\n enumNames: Array<string>\n circularNames: Array<string>\n discriminatorChildMap: Map<string, DiscriminatorTarget> | null\n dedupePlan: ast.DedupePlan | null\n}\n\n/**\n * Builds the deduplication plan from the already-parsed top-level schema nodes plus a\n * single extra parse pass over operations (so duplicates in request/response bodies are seen).\n *\n * Only enums and objects are candidates, and object shapes that reference a circular schema are\n * rejected to avoid hoisting recursive structures. Inline shapes reuse their context-derived\n * name (collision-resolved against existing component names); shapes without a name stay inline.\n */\nfunction createDedupePlan({\n schemaNodes,\n operationNodes,\n schemaNames,\n circularNames,\n}: {\n schemaNodes: Array<ast.SchemaNode>\n operationNodes: Array<ast.OperationNode>\n schemaNames: Array<string>\n circularNames: Array<string>\n}): ast.DedupePlan {\n const circularSchemas = new Set(circularNames)\n const usedNames = new Set(schemaNames)\n\n return ast.buildDedupePlan([...schemaNodes, ...operationNodes], {\n isCandidate: (node) => {\n if (node.type === 'enum') return true\n if (node.type !== 'object') return false\n // Skip object shapes that are part of a circular chain, hoisting them would break the cycle.\n if (node.name && circularSchemas.has(node.name)) return false\n return !ast.containsCircularRef(node, { circularSchemas })\n },\n nameFor: (node) => {\n const base = node.name\n if (!base) return null\n\n let name = base\n let counter = 2\n while (usedNames.has(name)) {\n name = `${base}${counter++}`\n }\n usedNames.add(name)\n return name\n },\n refFor: (name) => `${SCHEMA_REF_PREFIX}${name}`,\n })\n}\n\n/**\n * Reads the server URL from the document's `servers` array at `serverIndex`,\n * interpolating any `serverVariables` into the URL template.\n *\n * Returns `null` when `serverIndex` is omitted or out of range.\n *\n * @example Resolve the first server\n * `resolveBaseUrl({ document, serverIndex: 0 })`\n *\n * @example Override a path variable\n * `resolveBaseUrl({ document, serverIndex: 0, serverVariables: { version: 'v2' } })`\n */\nexport function resolveBaseUrl({\n document,\n serverIndex,\n serverVariables,\n}: {\n document: Document\n serverIndex?: number\n serverVariables?: Record<string, string>\n}): string | null {\n const server = serverIndex !== undefined ? document.servers?.at(serverIndex) : undefined\n return server?.url ? resolveServerUrl(server, serverVariables) : null\n}\n\n/**\n * Parses every schema once to build the lookup structures that streaming needs upfront.\n *\n * Three things happen in this single pass:\n * - `refAliasMap` records schemas that are pure `$ref` aliases so the streaming pass can inline them.\n * - `enumNames` collects the names of every enum schema so plugins skip re-scanning the stream.\n * - `circularNames` runs cycle detection, which requires all nodes in memory simultaneously.\n * The `allNodes` array is local and drops out of scope as soon as this function returns.\n *\n * After this call, only `refAliasMap` and `discriminatorChildMap` stay alive in the adapter closure.\n * Both are proportional to the number of aliases or discriminator parents, not total schema count.\n *\n * Each schema is parsed again during the streaming pass. This is intentional.\n * Holding the parsed nodes in memory here would defeat the streaming memory benefit.\n *\n * @example\n * ```ts\n * const { refAliasMap, enumNames, circularNames } = preScan({\n * schemas,\n * parseSchema,\n * parserOptions,\n * discriminator: 'strict',\n * })\n * ```\n */\nexport function preScan({\n schemas,\n parseSchema,\n parseOperation,\n document,\n parserOptions,\n discriminator,\n dedupe,\n}: {\n schemas: Record<string, SchemaObject>\n parseSchema: (entry: { schema: SchemaObject; name: string }, options: ast.ParserOptions) => ast.SchemaNode\n parseOperation: SchemaParser['parseOperation']\n document: Document\n parserOptions: ast.ParserOptions\n discriminator: AdapterOas['options']['discriminator']\n dedupe: boolean\n}): PreScanResult {\n const allNodes: Array<ast.SchemaNode> = []\n const refAliasMap = new Map<string, ast.SchemaNode>()\n const enumNames: Array<string> = []\n const discriminatorParentNodes: Array<ast.SchemaNode> = []\n\n for (const [name, schema] of Object.entries(schemas)) {\n const node = parseSchema({ schema, name }, parserOptions)\n allNodes.push(node)\n reportSchemaDiagnostics({ node, name })\n if (node.type === 'ref' && node.name && node.name !== name) {\n refAliasMap.set(name, node)\n }\n if (ast.narrowSchema(node, ast.schemaTypes.enum) && node.name) {\n enumNames.push(node.name)\n }\n if (discriminator === 'inherit' && (schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const circularNames = [...ast.findCircularSchemas(allNodes)]\n const discriminatorChildMap = discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n let dedupePlan: ast.DedupePlan | null = null\n if (dedupe) {\n // One extra parse pass over operations so duplicates in request/response bodies are seen.\n // Reuses the already-parsed `allNodes` for schemas, no second schema parse.\n const operationNodes: Array<ast.OperationNode> = []\n for (const operation of getOperations(document)) {\n const operationNode = parseOperation(parserOptions, operation)\n if (operationNode) operationNodes.push(operationNode)\n }\n\n dedupePlan = createDedupePlan({ schemaNodes: allNodes, operationNodes, schemaNames: Object.keys(schemas), circularNames })\n\n for (const definition of dedupePlan.hoisted) {\n if (definition.type === 'enum' && definition.name) enumNames.push(definition.name)\n }\n }\n\n // Enum names that duplicate an earlier schema's content are never emitted, so they are not\n // advertised to plugins either.\n const aliasNames = dedupePlan?.aliasNames\n const emittedEnumNames = aliasNames && aliasNames.size > 0 ? enumNames.filter((name) => !aliasNames.has(name)) : enumNames\n\n return { refAliasMap, enumNames: emittedEnumNames, circularNames, discriminatorChildMap, dedupePlan }\n}\n\n/**\n * Creates a lazy `InputNode<true>` from already-resolved adapter state.\n *\n * The schema and operation iterables each start a fresh parse pass on every\n * `[Symbol.asyncIterator]()` call. This lets multiple plugins consume the same\n * stream object independently without sharing a cursor or holding all nodes in memory.\n *\n * Ref aliases in `refAliasMap` are inlined during iteration: an alias entry is replaced\n * with its target's parsed node (but keeps the alias name) so plugins never receive bare `ref` nodes.\n *\n * @example\n * ```ts\n * const streamNode = createInputStream({ schemas, parseSchema, parseOperation, document, parserOptions, refAliasMap, discriminatorChildMap, meta })\n * for await (const schema of streamNode.schemas) {\n * // each call to for-await restarts from the first schema\n * }\n * ```\n */\nexport function createInputStream({\n schemas,\n parseSchema,\n parseOperation,\n document,\n parserOptions,\n refAliasMap,\n discriminatorChildMap,\n dedupePlan,\n meta,\n}: {\n schemas: Record<string, SchemaObject>\n parseSchema: SchemaParser['parseSchema']\n parseOperation: SchemaParser['parseOperation']\n document: Document\n parserOptions: ast.ParserOptions\n refAliasMap: Map<string, ast.SchemaNode>\n discriminatorChildMap: Map<string, DiscriminatorTarget> | null\n dedupePlan: ast.DedupePlan | null\n meta: ast.InputMeta\n}): ast.InputNode<true> {\n // Rewrites a top-level schema against the dedupe plan: a structurally identical sibling\n // becomes a `ref` alias to the canonical one (keeping its own name); otherwise nested\n // duplicates are collapsed while the schema's own root is preserved.\n const rewriteTopLevelSchema = (node: ast.SchemaNode): ast.SchemaNode => {\n if (!dedupePlan) return node\n\n const canonical = dedupePlan.canonicalBySignature.get(ast.signatureOf(node))\n if (canonical && canonical.name !== node.name) {\n return ast.createSchema({\n type: 'ref',\n name: node.name ?? null,\n ref: canonical.ref,\n description: node.description,\n deprecated: node.deprecated,\n })\n }\n\n return ast.applyDedupe(node, dedupePlan, true)\n }\n\n const schemasIterable: AsyncIterable<ast.SchemaNode> = {\n [Symbol.asyncIterator]() {\n return (async function* () {\n // Hoisted canonical definitions are emitted first so the schema list owns the shared shapes.\n if (dedupePlan) {\n for (const definition of dedupePlan.hoisted) yield definition\n }\n\n for (const [name, schema] of Object.entries(schemas)) {\n // A top-level schema whose content duplicates an earlier one is not emitted: every\n // ref to it is repointed at the first schema with that content, so its model would\n // be dead code.\n if (dedupePlan?.aliasNames.has(name)) continue\n\n // Inline ref aliases: replace the alias entry with its target's parsed node\n // (keeping the alias name). Skip the first parse entirely for alias entries\n // since that result is never used.\n const alias = refAliasMap.get(name)\n if (alias?.name && schemas[alias.name]) {\n yield rewriteTopLevelSchema({ ...parseSchema({ schema: schemas[alias.name]!, name: alias.name }, parserOptions), name })\n continue\n }\n\n const parsed = parseSchema({ schema, name }, parserOptions)\n const node = discriminatorChildMap?.get(name) ? patchDiscriminatorNode(parsed, discriminatorChildMap.get(name)!) : parsed\n yield rewriteTopLevelSchema(node)\n }\n })()\n },\n }\n\n const operationsIterable: AsyncIterable<ast.OperationNode> = {\n [Symbol.asyncIterator]() {\n return (async function* () {\n for (const operation of getOperations(document)) {\n const node = parseOperation(parserOptions, operation)\n if (node) yield dedupePlan ? ast.applyDedupe(node, dedupePlan) : node\n }\n })()\n },\n }\n\n return ast.createStreamInput(schemasIterable, operationsIterable, meta)\n}\n","import { ast, createAdapter } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { assertInputExists, parseDocument, parseFromConfig, validateDocument } from './factory.ts'\nimport { createSchemaParser } from './parser.ts'\nimport { getSchemas } from './resolvers.ts'\nimport { createInputStream, preScan, resolveBaseUrl } from './stream.ts'\nimport type { AdapterOas, Document } from './types.ts'\nimport { collect, narrowSchema } from '@kubb/ast'\nimport { extractRefName } from '@kubb/ast/utils'\n\n/**\n * Canonical adapter name for `@kubb/adapter-oas`. Used for driver lookups.\n */\nexport const adapterOasName = 'oas' satisfies AdapterOas['name']\n\n/**\n * Default Kubb adapter for OpenAPI 2.0, 3.0, and 3.1 specifications. Reads the\n * file at `input.path`, validates it, resolves the base URL, and converts every\n * schema and operation into the universal AST that every downstream plugin\n * consumes.\n *\n * Configure once on `defineConfig`. The adapter's choices (date representation,\n * integer width, server URL) apply to every plugin in the build.\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 * serverIndex: 0,\n * discriminator: 'inherit',\n * dateType: 'date',\n * }),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport const adapterOas = createAdapter<AdapterOas>((options) => {\n const {\n validate = true,\n contentType,\n serverIndex,\n serverVariables,\n discriminator = 'strict',\n dedupe = true,\n dateType = DEFAULT_PARSER_OPTIONS.dateType,\n integerType = DEFAULT_PARSER_OPTIONS.integerType,\n unknownType = DEFAULT_PARSER_OPTIONS.unknownType,\n enumSuffix = DEFAULT_PARSER_OPTIONS.enumSuffix,\n emptySchemaType = unknownType || DEFAULT_PARSER_OPTIONS.emptySchemaType,\n } = options\n\n const parserOptions: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n }\n\n let nameMapping = new Map<string, string>()\n let parsedDocument: Document | null = null\n\n // Cache per source and per document so one adapter instance reused across a `defineConfig` array\n // parses each config's spec instead of replaying the first one. Keying the document by its source\n // object still collapses a config's concurrent `stream()` (build) and `parse()` (studio) calls,\n // which share one source object, onto a single parse. The document-derived caches key off the\n // resulting document, so distinct configs (distinct documents) stay isolated.\n const documentCache = new WeakMap<AdapterSource, Promise<Document>>()\n const schemasCache = new WeakMap<Document, Promise<ReturnType<typeof getSchemas>['schemas']>>()\n const schemaParserCache = new WeakMap<Document, ReturnType<typeof createSchemaParser>>()\n const preScanCache = new WeakMap<Document, ReturnType<typeof preScan>>()\n\n function ensureDocument(source: AdapterSource): Promise<Document> {\n const cached = documentCache.get(source)\n if (cached) return cached\n\n const promise = (async () => {\n const fresh = await parseFromConfig(source)\n if (validate) await validateDocument(fresh)\n parsedDocument = fresh\n return fresh\n })()\n documentCache.set(source, promise)\n return promise\n }\n\n function ensureSchemas(document: Document): Promise<ReturnType<typeof getSchemas>['schemas']> {\n const cached = schemasCache.get(document)\n if (cached) return cached\n\n const promise = Promise.resolve().then(() => {\n const result = getSchemas(document, { contentType })\n nameMapping = result.nameMapping\n return result.schemas\n })\n schemasCache.set(document, promise)\n return promise\n }\n\n function ensureSchemaParser(document: Document): ReturnType<typeof createSchemaParser> {\n const cached = schemaParserCache.get(document)\n if (cached) return cached\n\n const parser = createSchemaParser({ document, contentType })\n schemaParserCache.set(document, parser)\n return parser\n }\n\n function ensurePreScan(\n document: Document,\n schemas: ReturnType<typeof getSchemas>['schemas'],\n parseSchema: ReturnType<typeof ensureSchemaParser>['parseSchema'],\n parseOperation: ReturnType<typeof ensureSchemaParser>['parseOperation'],\n ): ReturnType<typeof preScan> {\n const cached = preScanCache.get(document)\n if (cached) return cached\n\n const result = preScan({ schemas, parseSchema, parseOperation, document, parserOptions, discriminator, dedupe })\n preScanCache.set(document, result)\n return result\n }\n\n async function createStream(source: AdapterSource): Promise<ast.InputNode<true>> {\n const document = await ensureDocument(source)\n const schemas = await ensureSchemas(document)\n const { parseSchema, parseOperation } = ensureSchemaParser(document)\n const { refAliasMap, enumNames, circularNames, discriminatorChildMap, dedupePlan } = ensurePreScan(document, schemas, parseSchema, parseOperation)\n\n return createInputStream({\n schemas,\n parseSchema,\n parseOperation,\n document,\n parserOptions,\n refAliasMap,\n discriminatorChildMap,\n dedupePlan,\n meta: {\n title: document.info?.title,\n description: document.info?.description,\n version: document.info?.version,\n baseURL: resolveBaseUrl({ document, serverIndex, serverVariables }),\n circularNames,\n enumNames,\n },\n })\n }\n\n return {\n name: adapterOasName,\n get options() {\n return {\n validate,\n contentType,\n serverIndex,\n serverVariables,\n discriminator,\n dedupe,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n nameMapping,\n }\n },\n get document() {\n return parsedDocument\n },\n async validate(input, options) {\n await assertInputExists(input)\n const document = await parseDocument(input)\n await validateDocument(document, options)\n },\n getImports(node, resolve) {\n return collect(node, {\n schema(schemaNode) {\n const schemaRef = narrowSchema(schemaNode, 'ref')\n if (!schemaRef?.ref) return null\n\n const rawName = extractRefName(schemaRef.ref)\n const schemaName = nameMapping.get(rawName) ?? rawName\n const result = resolve(schemaName)\n if (!result) return null\n\n return ast.createImport({ name: [result.name], path: result.path })\n },\n })\n },\n async parse(source) {\n const streamNode = await createStream(source)\n\n const [schemas, operations] = await Promise.all([Array.fromAsync(streamNode.schemas), Array.fromAsync(streamNode.operations)])\n\n return ast.createInput({ schemas, operations, meta: streamNode.meta })\n },\n stream: createStream,\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;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